From bd58600acf624e94f81bf985d6bdbf2b92a34262 Mon Sep 17 00:00:00 2001 From: futuretea <1913508671@qq.com> Date: Fri, 2 Jun 2023 15:57:40 +0800 Subject: [PATCH] Recognize struct field in G601 Signed-off-by: futuretea <1913508671@qq.com> --- rules/implicit_aliasing.go | 24 ++++++++++++-- testutils/source.go | 64 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 2 deletions(-) diff --git a/rules/implicit_aliasing.go b/rules/implicit_aliasing.go index 70678e2..32e2fd2 100644 --- a/rules/implicit_aliasing.go +++ b/rules/implicit_aliasing.go @@ -28,6 +28,26 @@ func containsUnary(exprs []*ast.UnaryExpr, expr *ast.UnaryExpr) bool { return false } +func getIdentExpr(expr ast.Expr) *ast.Ident { + switch node := expr.(type) { + case *ast.Ident: + return node + case *ast.SelectorExpr: + return getIdentExpr(node.X) + case *ast.UnaryExpr: + switch e := node.X.(type) { + case *ast.Ident: + return e + case *ast.SelectorExpr: + return getIdentExpr(e.X) + default: + return nil + } + default: + return nil + } +} + func (r *implicitAliasing) Match(n ast.Node, c *gosec.Context) (*issue.Issue, error) { switch node := n.(type) { case *ast.RangeStmt: @@ -72,8 +92,8 @@ func (r *implicitAliasing) Match(n ast.Node, c *gosec.Context) (*issue.Issue, er } // If we find a unary op of & (reference) of an object within r.aliases, complain. - if ident, ok := node.X.(*ast.Ident); ok && node.Op.String() == "&" { - if _, contains := r.aliases[ident.Obj]; contains { + if identExpr := getIdentExpr(node); identExpr != nil && node.Op.String() == "&" { + if _, contains := r.aliases[identExpr.Obj]; contains { return c.NewIssue(n, r.ID(), r.What, r.Severity, r.Confidence), nil } } diff --git a/testutils/source.go b/testutils/source.go index 87d50c6..d016d21 100644 --- a/testutils/source.go +++ b/testutils/source.go @@ -3444,6 +3444,70 @@ func main() { fmt.Println(sampleString) } }`}, 0, gosec.NewConfig()}, + {[]string{` +package main + +import ( + "fmt" +) + +type sampleStruct struct { + name string +} + +func main() { + samples := []sampleStruct{ + {name: "a"}, + {name: "b"}, + } + for _, sample := range samples { + fmt.Println(sample.name) + } +}`}, 0, gosec.NewConfig()}, + {[]string{` +package main + +import ( + "fmt" +) + +type sampleStruct struct { + name string +} + +func main() { + samples := []sampleStruct{ + {name: "a"}, + {name: "b"}, + } + for _, sample := range samples { + fmt.Println(&sample.name) + } +}`}, 1, gosec.NewConfig()}, + {[]string{` +package main + +import ( + "fmt" +) + +type subStruct struct { + name string +} + +type sampleStruct struct { + sub subStruct +} + +func main() { + samples := []sampleStruct{ + {sub: subStruct{name: "a"}}, + {sub: subStruct{name: "b"}}, + } + for _, sample := range samples { + fmt.Println(&sample.sub.name) + } +}`}, 1, gosec.NewConfig()}, } // SampleCodeBuildTag - G601 build tags