diff --git a/core/analyzer.go b/core/analyzer.go index c55c901..5b0b720 100644 --- a/core/analyzer.go +++ b/core/analyzer.go @@ -138,7 +138,6 @@ func (gas *Analyzer) process(filename string, source interface{}) error { for _, pkg := range gas.context.Pkg.Imports() { gas.context.Imports.Imported[pkg.Path()] = pkg.Name() } - ast.Walk(gas, root) gas.Stats.NumFiles++ } @@ -203,8 +202,8 @@ func (gas *Analyzer) Visit(n ast.Node) ast.Visitor { // Track aliased and initialization imports if imported, ok := n.(*ast.ImportSpec); ok { + path := strings.Trim(imported.Path.Value, `"`) if imported.Name != nil { - path := strings.Trim(imported.Path.Value, `"`) if imported.Name.Name == "_" { // Initialization import gas.context.Imports.InitOnly[path] = true @@ -213,7 +212,12 @@ func (gas *Analyzer) Visit(n ast.Node) ast.Visitor { gas.context.Imports.Aliased[path] = imported.Name.Name } } + // unsafe is not included in Package.Imports() + if path == "unsafe" { + gas.context.Imports.Imported[path] = path + } } + if val, ok := gas.ruleset[reflect.TypeOf(n)]; ok { for _, rule := range val { ret, err := rule.Match(n, &gas.context) diff --git a/rules/unsafe.go b/rules/unsafe.go index 3110727..861f77c 100644 --- a/rules/unsafe.go +++ b/rules/unsafe.go @@ -17,16 +17,16 @@ package rules import ( gas "github.com/GoASTScanner/gas/core" "go/ast" - "regexp" ) type UsingUnsafe struct { gas.MetaData - pattern *regexp.Regexp + pkg string + calls []string } func (r *UsingUnsafe) Match(n ast.Node, c *gas.Context) (gi *gas.Issue, err error) { - if node := gas.MatchCall(n, r.pattern); node != nil { + if _, matches := gas.MatchCallByPackage(n, c, r.pkg, r.calls...); matches { return gas.NewIssue(c, n, r.What, r.Severity, r.Confidence), nil } return nil, nil @@ -34,7 +34,8 @@ func (r *UsingUnsafe) Match(n ast.Node, c *gas.Context) (gi *gas.Issue, err erro func NewUsingUnsafe(conf map[string]interface{}) (gas.Rule, []ast.Node) { return &UsingUnsafe{ - pattern: regexp.MustCompile(`unsafe\..*`), + pkg: "unsafe", + calls: []string{"Alignof", "Offsetof", "Sizeof", "Pointer"}, MetaData: gas.MetaData{ What: "Use of unsafe calls should be audited", Severity: gas.Low,