From f3c8d598635e0c610bc8c2fca824e5571404c886 Mon Sep 17 00:00:00 2001 From: andyleap Date: Thu, 8 Mar 2018 15:49:49 -0800 Subject: [PATCH] Switch to valuespec instead of gendecl for hardcoded credential rule (#186) --- rules/hardcoded_credentials.go | 34 +++++++++++++--------------------- 1 file changed, 13 insertions(+), 21 deletions(-) diff --git a/rules/hardcoded_credentials.go b/rules/hardcoded_credentials.go index bbba8ca..fa84b7d 100644 --- a/rules/hardcoded_credentials.go +++ b/rules/hardcoded_credentials.go @@ -16,7 +16,6 @@ package rules import ( "go/ast" - "go/token" "regexp" "strconv" @@ -53,8 +52,8 @@ func (r *credentials) Match(n ast.Node, ctx *gas.Context) (*gas.Issue, error) { switch node := n.(type) { case *ast.AssignStmt: return r.matchAssign(node, ctx) - case *ast.GenDecl: - return r.matchGenDecl(node, ctx) + case *ast.ValueSpec: + return r.matchValueSpec(node, ctx) } return nil, nil } @@ -76,23 +75,16 @@ func (r *credentials) matchAssign(assign *ast.AssignStmt, ctx *gas.Context) (*ga return nil, nil } -func (r *credentials) matchGenDecl(decl *ast.GenDecl, ctx *gas.Context) (*gas.Issue, error) { - if decl.Tok != token.CONST && decl.Tok != token.VAR { - return nil, nil - } - for _, spec := range decl.Specs { - if valueSpec, ok := spec.(*ast.ValueSpec); ok { - for index, ident := range valueSpec.Names { - if r.pattern.MatchString(ident.Name) && valueSpec.Values != nil { - // const foo, bar = "same value" - if len(valueSpec.Values) <= index { - index = len(valueSpec.Values) - 1 - } - if val, err := gas.GetString(valueSpec.Values[index]); err == nil { - if r.ignoreEntropy || (!r.ignoreEntropy && r.isHighEntropyString(val)) { - return gas.NewIssue(ctx, valueSpec, r.What, r.Severity, r.Confidence), nil - } - } +func (r *credentials) matchValueSpec(valueSpec *ast.ValueSpec, ctx *gas.Context) (*gas.Issue, error) { + for index, ident := range valueSpec.Names { + if r.pattern.MatchString(ident.Name) && valueSpec.Values != nil { + // const foo, bar = "same value" + if len(valueSpec.Values) <= index { + index = len(valueSpec.Values) - 1 + } + if val, err := gas.GetString(valueSpec.Values[index]); err == nil { + if r.ignoreEntropy || (!r.ignoreEntropy && r.isHighEntropyString(val)) { + return gas.NewIssue(ctx, valueSpec, r.What, r.Severity, r.Confidence), nil } } } @@ -146,5 +138,5 @@ func NewHardcodedCredentials(conf gas.Config) (gas.Rule, []ast.Node) { Confidence: gas.Low, Severity: gas.High, }, - }, []ast.Node{(*ast.AssignStmt)(nil), (*ast.GenDecl)(nil)} + }, []ast.Node{(*ast.AssignStmt)(nil), (*ast.ValueSpec)(nil)} }