Skip to content

Commit 63e8b1a

Browse files
committed
Update unsafe rule to match package explicitly
Unsafe is not tracked in Package.Imports(), the regexp was not explicit enough and foounsafe.Blah() would trigger an error.
1 parent 39b18a1 commit 63e8b1a

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

core/analyzer.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,6 @@ func (gas *Analyzer) process(filename string, source interface{}) error {
138138
for _, pkg := range gas.context.Pkg.Imports() {
139139
gas.context.Imports.Imported[pkg.Path()] = pkg.Name()
140140
}
141-
142141
ast.Walk(gas, root)
143142
gas.Stats.NumFiles++
144143
}
@@ -203,8 +202,8 @@ func (gas *Analyzer) Visit(n ast.Node) ast.Visitor {
203202

204203
// Track aliased and initialization imports
205204
if imported, ok := n.(*ast.ImportSpec); ok {
205+
path := strings.Trim(imported.Path.Value, `"`)
206206
if imported.Name != nil {
207-
path := strings.Trim(imported.Path.Value, `"`)
208207
if imported.Name.Name == "_" {
209208
// Initialization import
210209
gas.context.Imports.InitOnly[path] = true
@@ -213,7 +212,12 @@ func (gas *Analyzer) Visit(n ast.Node) ast.Visitor {
213212
gas.context.Imports.Aliased[path] = imported.Name.Name
214213
}
215214
}
215+
// unsafe is not included in Package.Imports()
216+
if path == "unsafe" {
217+
gas.context.Imports.Imported[path] = path
218+
}
216219
}
220+
217221
if val, ok := gas.ruleset[reflect.TypeOf(n)]; ok {
218222
for _, rule := range val {
219223
ret, err := rule.Match(n, &gas.context)

rules/unsafe.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,24 +17,25 @@ package rules
1717
import (
1818
gas "github.com/GoASTScanner/gas/core"
1919
"go/ast"
20-
"regexp"
2120
)
2221

2322
type UsingUnsafe struct {
2423
gas.MetaData
25-
pattern *regexp.Regexp
24+
pkg string
25+
calls []string
2626
}
2727

2828
func (r *UsingUnsafe) Match(n ast.Node, c *gas.Context) (gi *gas.Issue, err error) {
29-
if node := gas.MatchCall(n, r.pattern); node != nil {
29+
if _, matches := gas.MatchCallByPackage(n, c, r.pkg, r.calls...); matches {
3030
return gas.NewIssue(c, n, r.What, r.Severity, r.Confidence), nil
3131
}
3232
return nil, nil
3333
}
3434

3535
func NewUsingUnsafe(conf map[string]interface{}) (gas.Rule, []ast.Node) {
3636
return &UsingUnsafe{
37-
pattern: regexp.MustCompile(`unsafe\..*`),
37+
pkg: "unsafe",
38+
calls: []string{"Alignof", "Offsetof", "Sizeof", "Pointer"},
3839
MetaData: gas.MetaData{
3940
What: "Use of unsafe calls should be audited",
4041
Severity: gas.Low,

0 commit comments

Comments
 (0)