Link Search Menu Expand Document

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

For example, in Jinja and other template frameworks:

<li><a href="{{ url }}">{{ text }}</a></li>

It is preferable to build the link tag in Python, e.g. with link = '<a href="{}">{}</a>'.format(url, text) where link and text are user-controlled values. Then in Jinja:

<li>{{ link|safe }}</li>

References

OWASP - Cross-Site Scripting (XSS) OWASP - Code Review Guide OWASP - Cross-Site Scripting Prevention Cheat Sheet