Go: Add html/template as XSS queries sanitizer

This commit is contained in:
Michael B. Gale
2023-04-26 21:20:58 +01:00
parent fc66aacf92
commit 1aa1153ed6
3 changed files with 25 additions and 0 deletions

View File

@@ -127,4 +127,20 @@ module SharedXss {
)
}
}
/**
* A `Template` from `html/template` will HTML-escape data automatically
* and therefore acts as a sanitizer for XSS vulnerabilities.
*/
class HtmlTemplateSanitizer extends Sanitizer, DataFlow::Node {
HtmlTemplateSanitizer() {
exists(Method m, DataFlow::CallNode call | m = call.getCall().getTarget() |
m.hasQualifiedName("html/template", "Template", "ExecuteTemplate") and
call.getArgument(2) = this
or
m.hasQualifiedName("html/template", "Template", "Execute") and
call.getArgument(1) = this
)
}
}
}

View File

@@ -3,16 +3,22 @@ package main
import (
"fmt"
"html"
"html/template"
"net/http"
)
func serve1() {
var template template.Template
http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
username := r.Form.Get("username")
if !isValidUsername(username) {
// GOOD: a request parameter is escaped before being put into the response
fmt.Fprintf(w, "%q is an unknown user", html.EscapeString(username))
// GOOD: using html/template escapes values for us
template.Execute(w, username)
template.ExecuteTemplate(w, "test", username)
} else {
// TODO: do something exciting
}

View File

@@ -2,15 +2,18 @@ package main
import (
"html"
"html/template"
"io"
"io/ioutil"
"net/http"
)
func ListFiles1(w http.ResponseWriter, r *http.Request) {
var template template.Template
files, _ := ioutil.ReadDir(".")
for _, file := range files {
io.WriteString(w, html.EscapeString(file.Name())+"\n")
template.Execute(w, file.Name())
}
}