XSS prevention for Go net/http
This is a cross-site scripting (XSS) prevention cheat sheet by Semgrep, Inc. It contains code patterns of potential XSS in an application. Instead of scrutinizing code for exploitable vulnerabilities, the recommendations in this cheat sheet pave a safe road for developers that mitigate the possibility of XSS in your code. By following these recommendations, you can be reasonably sure your code is free of XSS.
Mitigation summary
The Go template engine in html/template
does automatic and contextual autoescaping, which mitigates many common XSS mistakes. Some aspects of the engine are confusingly named; therefore, proper use of the library should be enforced using code scanners. You may also consider using a stricter alternative, such as safehtml
.
Check your project using Semgrep
The following command runs an optimized set of rules for your project:
semgrep --config p/default
1. Server code: Unescaped content
1.A. Using the text/template
package
text/template
does not perform any HTML escaping.
Example:
import "text/template"
References
Mitigation
Ban text/template
. Alternatively, use html/template
, or a stricter alternative such as safehtml
.
Semgrep rule
go.lang.security.audit.xss.import-text-template.import-text-template1.B. Escaped types: template.HTML
template.HTML
is a special type which instructs the template engine not to escape the content.
Example:
content := template.HTML("<div>" + user.name + "</div>")
References
Mitigation
Ban template.HTML
. Alternatively, if necessary, review each case carefully and exempt with # nosemgrep
.