Go

Go

Made by DeepSource

Audit the usage of unescaped data in HTML templates GSC-G203

Security
Major
a03 cwe-79 sans top 25 owasp top 10

Potential unescaped data in HTML template.

Do not use external values in the template without escaping as it will not auto-escape HTML and could lead to code injection attacks.

Recommendations:

  • template.JS: Using JS to include valid but untrusted JSON is not safe. A safe alternative is to parse the JSON with json.Unmarshal and then pass the resultant object into the template, where it will be converted to sanitized JSON when presented in a JavaScript context.
  • template.HTML: Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.
  • template.HTMLAttr: Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.
  • template.URL: Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.

Bad practice

package main

import (
    "fmt"
    "html/template"
    "os"
)

func main() {
    // Tainted untrusted JSON
    a := `{"name": "untrusted"}`
    t := template.Must(template.New("x").Parse(""))
    v := map[string]interface{}{
        "Body": template.JS(a),
    }

    if err := t.Execute(os.Stdout, v); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

Recommended

package main

import (
    "fmt"
    "html/template"
    "os"
)

func main() {
    // We assume that hardcoded template strings are safe as the programmer would
    // need to be explicitly shooting themselves in the foot (as below)
    t := template.Must(template.New("x").Parse(""))
    v := map[string]interface{}{
        "Body": template.JS(`{"name": "trusted"}`),
    }

    if err := t.Execute(os.Stdout, v); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

References