Cross-Site Scripting in Python
Prevention
Remediation depends on the actual framework or template engine used, but in all cases, it is implemented by escaping the HTML code using HTML entities.
In vanilla Python, this can be accomplished by using the html.method
:
html.escape('USER-CONTROLLED-DATA')
In most cases, the HTML generation task is delegated to a template engine, often performing HTML escaping automatically by default. In most cases, the programmer should refrain from disabling this feature and rely instead on static HTML generation if possible.
Jinja
In Jinja, everything is escaped by default except for values explicitly marked with the |safe
filter.
<li><a href="{{ url }}">{{ text }}</a></li>
References
OWASP - Cross-Site Scripting (XSS) OWASP - Code Review Guide OWASP - Cross-Site Scripting Prevention Cheat Sheet