diff --git a/scan/base.go b/scan/base.go index da3f4dd9..0148caff 100644 --- a/scan/base.go +++ b/scan/base.go @@ -19,6 +19,7 @@ package scan import ( "fmt" + "regexp" "sort" "strings" "time" @@ -165,9 +166,7 @@ func (l base) detectRunningOnAws() (ok bool, instanceID string, err error) { r := l.ssh(cmd, noSudo) if r.isSuccess() { id := strings.TrimSpace(r.Stdout) - - if id == "not found" { - // status: 0, stdout: "not found" on degitalocean or Azure + if !l.isAwsInstanceID(id) { return false, "", nil } return true, id, nil @@ -187,6 +186,9 @@ func (l base) detectRunningOnAws() (ok bool, instanceID string, err error) { r := l.ssh(cmd, noSudo) if r.isSuccess() { id := strings.TrimSpace(r.Stdout) + if !l.isAwsInstanceID(id) { + return false, "", nil + } return true, id, nil } @@ -203,6 +205,13 @@ func (l base) detectRunningOnAws() (ok bool, instanceID string, err error) { l.ServerInfo.ServerName, l.ServerInfo.Container.Name) } +// http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/resource-ids.html +var awsInstanceIDPattern = regexp.MustCompile(`^i-[0-9a-f]+$`) + +func (l base) isAwsInstanceID(str string) bool { + return awsInstanceIDPattern.MatchString(str) +} + func (l *base) convertToModel() (models.ScanResult, error) { var scoredCves, unscoredCves models.CveInfos for _, p := range l.UnsecurePackages { diff --git a/scan/base_test.go b/scan/base_test.go index c2a6ccf2..94cbc503 100644 --- a/scan/base_test.go +++ b/scan/base_test.go @@ -56,3 +56,24 @@ f570ae647edc agitated_lovelace`, } } } + +func TestIsAwsInstanceID(t *testing.T) { + var tests = []struct { + in string + expected bool + }{ + {"i-1234567a", true}, + {"i-1234567890abcdef0", true}, + {"i-1234567890abcdef0000000", true}, + {"e-1234567890abcdef0", false}, + {"i-1234567890abcdef0 foo bar", false}, + {"no data", false}, + } + + for _, tt := range tests { + actual := isAwsInstanceID(tt.in) + if tt.expected != actual { + t.Errorf("expected %t, actual %t, str: %s", tt.expected, actual, tt.in) + } + } +}