|
| 1 | +package rules |
| 2 | + |
| 3 | +import ( |
| 4 | + "go/ast" |
| 5 | + "regexp" |
| 6 | + |
| 7 | + "github.com/securego/gosec/v2" |
| 8 | +) |
| 9 | + |
| 10 | +type traversal struct { |
| 11 | + pattern *regexp.Regexp |
| 12 | + gosec.MetaData |
| 13 | +} |
| 14 | + |
| 15 | +func (r *traversal) ID() string { |
| 16 | + return r.MetaData.ID |
| 17 | +} |
| 18 | + |
| 19 | +func (r *traversal) Match(n ast.Node, ctx *gosec.Context) (*gosec.Issue, error) { |
| 20 | + switch node := n.(type) { |
| 21 | + case *ast.CallExpr: |
| 22 | + return r.matchCallExpr(node, ctx) |
| 23 | + } |
| 24 | + return nil, nil |
| 25 | +} |
| 26 | + |
| 27 | +func (r *traversal) matchCallExpr(assign *ast.CallExpr, ctx *gosec.Context) (*gosec.Issue, error) { |
| 28 | + for _, i := range assign.Args { |
| 29 | + if basiclit, ok1 := i.(*ast.BasicLit); ok1 { |
| 30 | + if fun, ok2 := assign.Fun.(*ast.SelectorExpr); ok2 { |
| 31 | + if x, ok3 := fun.X.(*ast.Ident); ok3 { |
| 32 | + string := x.Name + "." + fun.Sel.Name + "(" + basiclit.Value + ")" |
| 33 | + if r.pattern.MatchString(string) { |
| 34 | + return gosec.NewIssue(ctx, assign, r.ID(), r.What, r.Severity, r.Confidence), nil |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + return nil, nil |
| 41 | +} |
| 42 | + |
| 43 | +// NewDirectoryTraversal attempts to find the use of http.Dir("/") |
| 44 | +func NewDirectoryTraversal(id string, conf gosec.Config) (gosec.Rule, []ast.Node) { |
| 45 | + pattern := `http\.Dir\("\/"\)|http\.Dir\('\/'\)` |
| 46 | + if val, ok := conf["G101"]; ok { |
| 47 | + conf := val.(map[string]interface{}) |
| 48 | + if configPattern, ok := conf["pattern"]; ok { |
| 49 | + if cfgPattern, ok := configPattern.(string); ok { |
| 50 | + pattern = cfgPattern |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + return &traversal{ |
| 56 | + pattern: regexp.MustCompile(pattern), |
| 57 | + MetaData: gosec.MetaData{ |
| 58 | + ID: id, |
| 59 | + What: "Potential directory traversal", |
| 60 | + Confidence: gosec.Medium, |
| 61 | + Severity: gosec.Medium, |
| 62 | + }, |
| 63 | + }, []ast.Node{(*ast.CallExpr)(nil)} |
| 64 | +} |
0 commit comments