2018-09-04 08:55:03 +02:00
|
|
|
package rules
|
|
|
|
|
|
|
|
import (
|
|
|
|
"go/ast"
|
|
|
|
"go/types"
|
|
|
|
|
2020-04-01 22:18:39 +02:00
|
|
|
"github.com/securego/gosec/v2"
|
2023-02-15 21:44:13 +02:00
|
|
|
"github.com/securego/gosec/v2/issue"
|
2018-09-04 08:55:03 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type ssrf struct {
|
2023-02-15 21:44:13 +02:00
|
|
|
issue.MetaData
|
2018-09-04 08:55:03 +02:00
|
|
|
gosec.CallList
|
|
|
|
}
|
|
|
|
|
|
|
|
// ID returns the identifier for this rule
|
|
|
|
func (r *ssrf) ID() string {
|
|
|
|
return r.MetaData.ID
|
|
|
|
}
|
|
|
|
|
|
|
|
// ResolveVar tries to resolve the first argument of a call expression
|
|
|
|
// The first argument is the url
|
|
|
|
func (r *ssrf) ResolveVar(n *ast.CallExpr, c *gosec.Context) bool {
|
|
|
|
if len(n.Args) > 0 {
|
|
|
|
arg := n.Args[0]
|
|
|
|
if ident, ok := arg.(*ast.Ident); ok {
|
|
|
|
obj := c.Info.ObjectOf(ident)
|
2019-10-04 13:25:38 +02:00
|
|
|
if _, ok := obj.(*types.Var); ok {
|
|
|
|
scope := c.Pkg.Scope()
|
|
|
|
if scope != nil && scope.Lookup(ident.Name) != nil {
|
|
|
|
// a URL defined in a variable at package scope can be changed at any time
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
if !gosec.TryResolve(ident, c) {
|
|
|
|
return true
|
|
|
|
}
|
2018-09-04 08:55:03 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Match inspects AST nodes to determine if certain net/http methods are called with variable input
|
2023-02-15 21:44:13 +02:00
|
|
|
func (r *ssrf) Match(n ast.Node, c *gosec.Context) (*issue.Issue, error) {
|
2018-09-04 08:55:03 +02:00
|
|
|
// Call expression is using http package directly
|
2020-01-28 15:11:00 +02:00
|
|
|
if node := r.ContainsPkgCallExpr(n, c, false); node != nil {
|
2018-09-04 08:55:03 +02:00
|
|
|
if r.ResolveVar(node, c) {
|
2023-02-15 21:44:13 +02:00
|
|
|
return c.NewIssue(n, r.ID(), r.What, r.Severity, r.Confidence), nil
|
2018-09-04 08:55:03 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewSSRFCheck detects cases where HTTP requests are sent
|
2023-03-20 11:08:49 +02:00
|
|
|
func NewSSRFCheck(id string, _ gosec.Config) (gosec.Rule, []ast.Node) {
|
2018-09-04 08:55:03 +02:00
|
|
|
rule := &ssrf{
|
|
|
|
CallList: gosec.NewCallList(),
|
2023-02-15 21:44:13 +02:00
|
|
|
MetaData: issue.MetaData{
|
2018-09-04 08:55:03 +02:00
|
|
|
ID: id,
|
|
|
|
What: "Potential HTTP request made with variable url",
|
2023-02-15 21:44:13 +02:00
|
|
|
Severity: issue.Medium,
|
|
|
|
Confidence: issue.Medium,
|
2018-09-04 08:55:03 +02:00
|
|
|
},
|
|
|
|
}
|
|
|
|
rule.AddAll("net/http", "Do", "Get", "Head", "Post", "PostForm", "RoundTrip")
|
|
|
|
return rule, []ast.Node{(*ast.CallExpr)(nil)}
|
|
|
|
}
|