The analyzer has detected that unvalidated external data is being used as code. This could lead to a code injection vulnerability.
Code injection vulnerabilities can be categorized under the OWASP Top 10 Application Security Risks 2025: A05:2025 Injection.
The example:
type Profile struct {
Name string
APIKey string
}
func reportHandler(w http.ResponseWriter, r *http.Request) {
src := r.URL.Query().Get("template")
tmpl, err := template.New("report").
Funcs(template.FuncMap{"upper": strings.ToUpper}).
Parse(src)
if err != nil {
http.Error(w, "invalid template", http.StatusBadRequest)
return
}
profile := Profile{Name: r.URL.Query().Get("name"),
APIKey: os.Getenv("API_KEY")}
tmpl.Execute(w, profile)
}
In this example, src may contain tainted data, as it comes from an external source. This data becomes the template text—that is, the code that the server will execute. Template actions can read any exported fields of the passed object and call its methods and functions registered via Funcs.
As a result, an attacker can make the server execute template logic of their choosing. For example, they can read data that is not intended to be displayed and, if suitable functions or methods are available, execute operating system commands and access files.
Tainted data example N1:
{{.APIKey}}
The template will display the API key, which the application did not intend to show to the user.
Tainted data example N2:
{{exec "cat /etc/passwd"}}
If the template functions include one that runs commands, an attacker can execute an arbitrary command on behalf of the server.
The fixed example:
const (
shortReport = "Hello, {{.Name}}!"
fullReport = "Hello, {{.Name}}! Your profile is up to date."
)
var reportTemplates = map[string]*template.Template{
"short": template.Must(template.New("short").Parse(shortReport)),
"full": template.Must(template.New("full").Parse(fullReport)),
}
func reportHandler(w http.ResponseWriter, r *http.Request) {
tmpl, ok := reportTemplates[r.URL.Query().Get("template")]
if !ok {
http.Error(w, "unknown template", http.StatusBadRequest)
return
}
tmpl.Execute(w, map[string]string{"Name": r.URL.Query().Get("name")})
}
In this case, the user selects a template from a predefined set, and their data is passed into the template only as an Execute argument.
This diagnostic rule is classified as:
|