package main import ( "fmt" "go/ast" "go/token" "regexp" "strings" ) var htmlTagPattern = regexp.MustCompile(`<[A-Za-z/!]`) // htmlChecker finds HTML built by concatenation, fmt formatting or writer // calls in which a non-constant string reaches the output unescaped. A value // counts as safe when it is constant, numeric, passed through an escaper, or // built only from safe values. Parameters, fields, map reads and other // packages' results count as untrusted. type htmlChecker struct { src *pluginSource f *pluginFile fn *ast.FuncDecl params map[paramKey]int // 1 safe, 2 unsafe, 3 in progress scope *funcScope visiting map[string]bool summary map[*ast.FuncDecl]int // 1 safe, 2 unsafe, 3 in progress reported map[string]bool out []pluginRuleFinding } func checkPluginHTML(src *pluginSource) []pluginRuleFinding { var out []pluginRuleFinding summary := map[*ast.FuncDecl]int{} params := map[paramKey]int{} for _, f := range src.files { for _, decl := range f.ast.Decls { fn, ok := decl.(*ast.FuncDecl) if !ok || fn.Body == nil { continue } c := &htmlChecker{src: src, f: f, fn: fn, params: params, scope: newHTMLScope(f, fn), visiting: map[string]bool{}, summary: summary, reported: map[string]bool{}} c.checkFunc(fn.Body) out = append(out, c.out...) } } return out } func (c *htmlChecker) report(e ast.Expr) { f := pluginRuleFinding{file: c.f.rel, line: c.src.line(e), msg: fmt.Sprintf("%s reaches HTML output unescaped; wrap it in html.EscapeString or use html/template", shortExpr(e))} key := fmt.Sprintf("%d %s", f.line, f.msg) if c.reported[key] { return } c.reported[key] = true c.out = append(c.out, f) } type htmlWrite struct { call *ast.CallExpr sink string operands []ast.Expr format ast.Expr // Fprintf format, nil otherwise } func (c *htmlChecker) checkFunc(body *ast.BlockStmt) { var writes []htmlWrite ast.Inspect(body, func(n ast.Node) bool { switch x := n.(type) { case *ast.BinaryExpr: if x.Op == token.ADD { c.checkConcat(x) for _, leaf := range concatLeaves(x) { ast.Inspect(leaf, func(m ast.Node) bool { return c.visitNested(m) }) } return false } case *ast.AssignStmt: if x.Tok == token.ADD_ASSIGN && len(x.Lhs) == 1 && len(x.Rhs) == 1 { if id, ok := x.Lhs[0].(*ast.Ident); ok && c.holdsHTML(id.Name) { c.checkOperand(x.Rhs[0]) } } case *ast.CallExpr: if p, name, ok := c.f.pkgFunc(x); ok && p == "fmt" && name == "Sprintf" && len(x.Args) > 0 && isHTMLConst(x.Args[0]) { c.checkFormatArgs(x.Args[0], x.Args[1:]) } if w, ok := c.writeCall(x); ok { writes = append(writes, w) } } return true }) htmlSinks := map[string]bool{} for _, w := range writes { if w.format != nil && isHTMLConst(w.format) { htmlSinks[w.sink] = true } for _, op := range w.operands { if isHTMLConst(op) || c.isHTMLExpr(op) { htmlSinks[w.sink] = true } } } for _, w := range writes { if !htmlSinks[w.sink] { continue } if w.format != nil { c.checkFormatArgs(w.format, w.operands) continue } for _, op := range w.operands { c.checkOperand(op) } } } // holdsHTML reports whether a local is ever assigned HTML, so appending to it // with += builds HTML too. func (c *htmlChecker) holdsHTML(name string) bool { for _, v := range c.scope.assigns[name] { if v != nil && (isHTMLConst(v) || c.isHTMLExpr(v)) { return true } } return false } // visitNested continues the walk inside a concatenation operand so nested // HTML builders are checked too. func (c *htmlChecker) visitNested(n ast.Node) bool { switch x := n.(type) { case *ast.BinaryExpr: if x.Op == token.ADD { c.checkConcat(x) } case *ast.CallExpr: if p, name, ok := c.f.pkgFunc(x); ok && p == "fmt" && name == "Sprintf" && len(x.Args) > 0 && isHTMLConst(x.Args[0]) { c.checkFormatArgs(x.Args[0], x.Args[1:]) } } return true } func (c *htmlChecker) checkConcat(e *ast.BinaryExpr) { leaves := concatLeaves(e) html := false for _, l := range leaves { if isHTMLConst(l) { html = true } } if !html { return } for _, l := range leaves { c.checkOperand(l) } } // checkOperand reports an operand of HTML output that is not safe. Operands // that are themselves HTML builders are checked where they are built. func (c *htmlChecker) checkOperand(op ast.Expr) { op = unparen(op) if c.isHTMLExpr(op) { return } if b, ok := op.(*ast.BinaryExpr); ok && b.Op == token.ADD { for _, l := range concatLeaves(b) { c.checkOperand(l) } return } if !c.safe(op) { c.report(op) } } func (c *htmlChecker) checkFormatArgs(format ast.Expr, args []ast.Expr) { s, ok := stringLit(format) if !ok { return } verbs := formatVerbs(s) for i, a := range args { if verbs != nil && i < len(verbs) && strings.ContainsRune("dbcoOxXUeEfFgGtp", verbs[i]) { continue } c.checkOperand(a) } } // formatVerbs lists the verb of each argument a format consumes, or nil when // the format uses explicit argument indexes. func formatVerbs(s string) []rune { var verbs []rune for i := 0; i < len(s); i++ { if s[i] != '%' { continue } i++ for i < len(s) && strings.IndexByte("+-# 0123456789.*[]", s[i]) >= 0 { switch s[i] { case '[': return nil case '*': verbs = append(verbs, 'd') } i++ } if i < len(s) && s[i] != '%' { verbs = append(verbs, rune(s[i])) } } return verbs } // writeCall recognises writes to a builder, buffer or writer. func (c *htmlChecker) writeCall(call *ast.CallExpr) (htmlWrite, bool) { sel, ok := call.Fun.(*ast.SelectorExpr) if !ok { return htmlWrite{}, false } if p, name, isPkg := c.f.pkgSel(sel); isPkg { if len(call.Args) == 0 || isStdStream(c.f, call.Args[0]) { return htmlWrite{}, false } sink := sinkName(call.Args[0]) switch { case p == "fmt" && name == "Fprintf" && len(call.Args) >= 2: return htmlWrite{call: call, sink: sink, format: call.Args[1], operands: call.Args[2:]}, true case p == "fmt" && (name == "Fprint" || name == "Fprintln"): return htmlWrite{call: call, sink: sink, operands: call.Args[1:]}, true case p == "io" && name == "WriteString" && len(call.Args) == 2: return htmlWrite{call: call, sink: sink, operands: call.Args[1:]}, true } return htmlWrite{}, false } if (sel.Sel.Name == "WriteString" || sel.Sel.Name == "Write") && len(call.Args) == 1 { return htmlWrite{call: call, sink: sinkName(sel.X), operands: []ast.Expr{unwrapBytes(call.Args[0])}}, true } return htmlWrite{}, false } func isStdStream(f *pluginFile, e ast.Expr) bool { sel, ok := e.(*ast.SelectorExpr) if !ok { return false } p, name, isPkg := f.pkgSel(sel) return isPkg && p == "os" && (name == "Stdout" || name == "Stderr") } func sinkName(e ast.Expr) string { if u, ok := e.(*ast.UnaryExpr); ok && u.Op == token.AND { e = u.X } return exprText(e) } func unwrapBytes(e ast.Expr) ast.Expr { if call, ok := e.(*ast.CallExpr); ok && len(call.Args) == 1 { if at, ok := call.Fun.(*ast.ArrayType); ok && exprText(at.Elt) == "byte" { return call.Args[0] } } return e } func unparen(e ast.Expr) ast.Expr { for { p, ok := e.(*ast.ParenExpr) if !ok { return e } e = p.X } } func concatLeaves(e ast.Expr) []ast.Expr { e = unparen(e) if b, ok := e.(*ast.BinaryExpr); ok && b.Op == token.ADD { return append(concatLeaves(b.X), concatLeaves(b.Y)...) } return []ast.Expr{e} } func isHTMLConst(e ast.Expr) bool { s, ok := stringLit(unparen(e)) return ok && htmlTagPattern.MatchString(s) } // isHTMLExpr reports whether e builds HTML itself (a concatenation or Sprintf // with a tag in a constant), which the checker inspects separately. func (c *htmlChecker) isHTMLExpr(e ast.Expr) bool { e = unparen(e) if b, ok := e.(*ast.BinaryExpr); ok && b.Op == token.ADD { for _, l := range concatLeaves(b) { if isHTMLConst(l) { return true } } } if call, ok := e.(*ast.CallExpr); ok { if p, name, ok := c.f.pkgFunc(call); ok && p == "fmt" && name == "Sprintf" && len(call.Args) > 0 && isHTMLConst(call.Args[0]) { return true } } return false } var escaperFuncs = map[string]map[string]bool{ "html": {"EscapeString": true}, "html/template": {"HTMLEscapeString": true, "HTMLEscaper": true, "JSEscapeString": true, "URLQueryEscaper": true}, "text/template": {"HTMLEscapeString": true, "HTMLEscaper": true, "JSEscapeString": true, "URLQueryEscaper": true}, "net/url": {"QueryEscape": true, "PathEscape": true}, "github.com/a-h/templ": {"EscapeString": true}, } func (c *htmlChecker) safe(e ast.Expr) bool { switch x := unparen(e).(type) { case *ast.BasicLit, *ast.CompositeLit, *ast.FuncLit: return true case *ast.UnaryExpr: return x.Op != token.AND || c.safe(x.X) case *ast.BinaryExpr: if x.Op != token.ADD || c.isHTMLExpr(x) { return true } return c.safe(x.X) && c.safe(x.Y) case *ast.Ident: return c.safeIdent(x.Name) case *ast.SliceExpr: return c.safe(x.X) case *ast.SelectorExpr: if id, ok := x.X.(*ast.Ident); ok && c.scope.constRange[id.Name] { return true } _, _, isPkg := c.f.pkgSel(x) return isPkg case *ast.CallExpr: return c.safeCall(x) } return false } func (c *htmlChecker) safeIdent(name string) bool { switch name { case "nil", "true", "false", "iota": return true } if c.scope.constRange[name] { return true } if c.scope.opaque[name] { return !c.src.generated && c.paramSafe(name) } if xs, ok := c.scope.rangeOf[name]; ok { if c.visiting[name] { return true } c.visiting[name] = true defer delete(c.visiting, name) for _, x := range xs { if !c.safe(x) { return false } } return true } if values, ok := c.scope.assigns[name]; ok { if c.visiting[name] { return true } c.visiting[name] = true defer delete(c.visiting, name) for _, v := range values { if v != nil && !c.safe(v) { return false } } return true } if c.f.pkg.consts[name] { return true } if v, ok := c.f.pkg.vars[name]; ok { return v != nil && c.safe(v) } return false } func (c *htmlChecker) safeCall(call *ast.CallExpr) bool { allArgsSafe := func() bool { for _, a := range call.Args { if !c.safe(a) { return false } } return true } switch fn := unparen(call.Fun).(type) { case *ast.ArrayType, *ast.MapType: return allArgsSafe() case *ast.FuncLit: for _, results := range returnExprs(fn.Body) { for _, r := range results { if !c.isHTMLExpr(r) && !c.safe(r) { return false } } } return true case *ast.Ident: switch fn.Name { case "len", "cap", "min", "max": return true case "string", "append": return allArgsSafe() } if decls := c.f.pkg.funcs[fn.Name]; len(decls) > 0 { return c.funcReturnsSafe(decls) } return false case *ast.SelectorExpr: if p, name, isPkg := c.f.pkgSel(fn); isPkg { switch { case escaperFuncs[p][name], hasImportPrefix(p, pluginSDKImportPrefix) && trustedHTMLRenderers[name]: return true case p == "strconv": return !strings.HasPrefix(name, "Quote") && !strings.HasPrefix(name, "Unquote") case p == "fmt" && name == "Sprintf" && len(call.Args) > 0: if c.isHTMLExpr(call) { return true } verbs := formatVerbs(stringOr(call.Args[0])) for i, a := range call.Args[1:] { if verbs != nil && i < len(verbs) && strings.ContainsRune("dbcoOxXUeEfFgGtp", verbs[i]) { continue } if !c.safe(a) { return false } } return true case p == "fmt" && (name == "Sprint" || name == "Sprintln"), p == "strings" && name != "Builder", p == "html/template" && (name == "HTML" || name == "HTMLAttr" || name == "URL" || name == "CSS" || name == "JS"): return allArgsSafe() } return false } if fn.Sel.Name == "String" && len(call.Args) == 0 { // A builder's String() output is checked where it was written. return true } if fn.Sel.Name == "Format" && len(call.Args) == 1 && isConstValue(c.f, call.Args[0]) { return true } if decls := c.f.pkg.funcs[fn.Sel.Name]; len(decls) > 0 { return c.funcReturnsSafe(decls) } return trustedHTMLRenderers[fn.Sel.Name] } return false } // trustedHTMLRenderers are host and library methods that return sanitized // HTML: the pluginsdk content service's BlockNote renderer and bluemonday. var trustedHTMLRenderers = map[string]bool{"BlockNoteToHTML": true, "Sanitize": true} func stringOr(e ast.Expr) string { s, _ := stringLit(e) return s } // funcReturnsSafe reports whether every value the functions return is safe // or is HTML built (and checked) inside the function. func (c *htmlChecker) funcReturnsSafe(decls []*ast.FuncDecl) bool { for _, d := range decls { switch c.summary[d] { case 1, 3: continue case 2: return false } c.summary[d] = 3 inner := c.checkerFor(d) ok := true for _, results := range returnExprs(d.Body) { for _, r := range results { if !inner.isHTMLExpr(r) && !inner.safe(r) { ok = false } } } if ok { c.summary[d] = 1 } else { c.summary[d] = 2 return false } } return true } // newHTMLScope is a funcScope that also marks range variables over a table // written out in the source, such as a slice of constant structs, as safe. func newHTMLScope(f *pluginFile, fn ast.Node) *funcScope { s := newFuncScope(fn) var constTable func(e ast.Expr, depth int) bool constTable = func(e ast.Expr, depth int) bool { if depth > 3 { return false } switch x := e.(type) { case *ast.CompositeLit: for _, el := range x.Elts { if kv, ok := el.(*ast.KeyValueExpr); ok { el = kv.Value } if !isConstValue(f, el) && !constTable(el, depth+1) { return false } } return true case *ast.Ident: values := s.assigns[x.Name] if len(values) == 0 { if v, ok := f.pkg.vars[x.Name]; ok && v != nil { values = []ast.Expr{v} } } for _, v := range values { if v == nil || !constTable(v, depth+1) { return false } } return len(values) > 0 } return false } ast.Inspect(fn, func(n ast.Node) bool { if r, ok := n.(*ast.RangeStmt); ok && constTable(r.X, 0) { if id, ok := r.Value.(*ast.Ident); ok { s.constRange[id.Name] = true } } return true }) return s } type paramKey struct { fn *ast.FuncDecl index int } func (c *htmlChecker) checkerFor(d *ast.FuncDecl) *htmlChecker { f := c.src.declFile[d] return &htmlChecker{src: c.src, f: f, fn: d, params: c.params, scope: newHTMLScope(f, d), visiting: map[string]bool{}, summary: c.summary, reported: map[string]bool{}} } // paramSafe reports whether every same-package call to the current function // passes a safe value for the named parameter. Generated plugins skip this: // their parameters always count as untrusted. func (c *htmlChecker) paramSafe(name string) bool { if c.fn == nil || c.fn.Type.Params == nil { return false } index, variadic := -1, false i := 0 for _, field := range c.fn.Type.Params.List { for _, n := range field.Names { if n.Name == name { index = i _, variadic = field.Type.(*ast.Ellipsis) } i++ } if len(field.Names) == 0 { i++ } } if index < 0 { return false } key := paramKey{c.fn, index} switch c.params[key] { case 1, 3: return true case 2: return false } c.params[key] = 3 sites := c.src.callSitesOf(c.fn.Name.Name) ok := len(sites) > 0 for _, site := range sites { args := site.call.Args if index >= len(args) { continue } args = args[index : index+1] if variadic { args = site.call.Args[index:] } caller := c.checkerFor(site.decl) for _, a := range args { if !caller.isHTMLExpr(a) && !caller.safe(a) { ok = false } } } if ok { c.params[key] = 1 } else { c.params[key] = 2 } return ok }