DEV Community

Cover image for Server-Side Template Injection in Go
Blue Byte
Blue Byte

Posted on

Server-Side Template Injection in Go

Server-Side Template Injection is a vulnerability that arises when user input is improperly processed by a template engine, potentially leading to remote code execution or reading of confidential files. Few people are familiar with SSTI exploitation applied to Go.

Go provides the html/template and text/template packages for rendering dynamic content. The first one is safer as it auto-escapes HTML, while the second one does not perform escaping, making it more prone to injection vulnerabilities.

A typical Go template rendering function would look like this:

func handler(w http.ResponseWriter, r *http.Request) {
    tmpl := template.Must(template.New("test").Parse("Hello, {{ . }}"))
    name := r.URL.Query().Get("name")
    tmpl.Execute(w, name)
}
Enter fullscreen mode Exit fullscreen mode

Go’s template engine does not allow arbitrary code execution like Jinja2 (unless the programmer has previously defined a function for this), but an attacker can still manipulate logic within templates, access environment variables, or disclose internal data. In this example, the 'name' parameter from the user is inserted directly into the template, making it vulnerable to SSTI. By injecting a payload like {{ . | printf "%#v" }} it would be possible to obtain information about Go internal structures.

An interesting thought is that you can think of the . character as being equivalent to _self in the case of Twig. Note that {{.}} is also a valid payload.

To prevent this type of vulnerability, it is recommended to use html/template instead of text/template, restrict functions available in the template using template.FuncMap and always sanitize user input.

Top comments (0)

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay