Skip to content

Commit

Permalink
Recognize struct field in G601
Browse files Browse the repository at this point in the history
Signed-off-by: futuretea <1913508671@qq.com>
  • Loading branch information
futuretea committed Jun 2, 2023
1 parent 1457921 commit be2069a
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 2 deletions.
24 changes: 22 additions & 2 deletions rules/implicit_aliasing.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
}
}
Expand Down
64 changes: 64 additions & 0 deletions testutils/source.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit be2069a

Please sign in to comment.