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. Learn more about Cross-site Scripting vulnerability concepts.Documentation Index
Fetch the complete documentation index at: https://docs.semgrep.dev/llms.txt
Use this file to discover all available pages before exploring further.
Mitigation summary
In general, always use the template engine provided by Django usingrender(). If you need HTML escaping, use mark_safe() combined with format_html() and review each individual usage carefully. Once reviewed, mark with # nosem. Beware of putting data in dangerous locations in templates. And as always, run a security checker continuously on your code.
Semgrep ruleset for this cheatsheet: https://semgrep.dev/p/minusworld.django-xss
Check your project using Semgrep
1. Server code: Marking “safe” content, which does not escape HTML
1.A. Using mark_safe()
mark_safe() marks the returned content as “safe to render.” This instructs the template engine to bypass HTML escaping, creating the possibility of a XSS vulnerability.
Example:
References:
Mitigation
Banmark_safe(). Alternatively, if needed, use in combination with format_html() and review each usage carefully. Create an exemption with # nosem.
Semgrep rule
python.django.security.audit.avoid-mark-safe.avoid-mark-safe
1.B. Using the SafeString class directly
TheSafeString class is how Django determines which variables should be escaped and which should not. Elements passed to mark_safe() are returned as a SafeString. Invoking SafeString directly will bypass HTML escaping which could create a XSS vulnerabliity.
Example:
References:
Mitigation
BanSafeString(). Alternatively, prefer mark_safe() if necessary.
1.C. Registering a custom filter with is_safe=True
Registering a filter withis_safe=True indicates to Django that the filter absolutely does not introduce any unsafe HTML characters. The value returned from the filter will be marked as “safe” when the input is also marked “safe”. Generally, this is acceptable, but if you cannot be certain the filter is safe, it may introduce a XSS vulnerability.
Example:
References:
Mitigation
Do not mark filters withis_safe=True. Alternatively, prefer mark_safe() if necessary.
Semgrep rule
python.django.security.audit.xss.filter-with-is-safe1.D. Use of the html magic method in a class
The__html__ magic method is used by the Django template engine to determine whether the object should be escaped. If available, the value returned by the method will not be escaped and could introduce a XSS vulnerability.
Example:
References:
Mitigation
Ban__html__ in classes. Alternatively, prefer mark_safe() if necessary.
Semgrep rule
python.django.security.audit.xss.html-magic-method.html-magic-method
1.E. Using html_safe()
Thehtml_safe() decorator adds the __html__ magic method to the supplied class. The added __html__ magic method returns the exact string representation of the class (for example str(self)). Because objects with the __html__ method are not escaped, this could create a XSS vulnerability.
Example:
References:
Mitigation:
Banhtml_safe(). Alternatively, prefer mark_safe() if necessary.
Semgrep rule
python.django.security.audit.xss.html-safe.html-safe
2. Server code: Bypassing the template engine
2.A. Directly writing a response using HttpResponse or similar classes
Writing results directly toHttpResponse or similar classes bypasses the Django template engine. This also bypasses the HTML escaping built into the template engine and creates the possibility of a XSS vulnerability. Use render() with a template instead.
Example:
References:
Mitigation:
BanHttpResponse and similar classes. Alternatively, use render().
Semgrep rule
python.django.security.audit.xss.direct-use-of-httpresponse
2.B. Globally disabling autoescape
Autoescaping can be globally disabled in Django settings. This should never be done if you are rendering HTML; now, every response returned to the user will need to be audited to ensure it is free of XSS vulnerabilities. Example:References:
Mitigation:
Ban globally disabling autoescape. Alternatively, do not globally disable escaping. If HTML escaping is necessary, usemark_safe().
Semgrep rule
python.django.security.audit.xss.global-autoescape-off.global-autoescape-off
2.C. Setting autoescape=False in a template context
Settingautoescape=False in a template context will disable HTML escaping for that template. Any data rendered in that template could be a XSS vulnerability.
Example:
References:
- Context source code
Template.render()documentationrender_to_string()documentationrender()documentation
Mitigation:
description: “Banautoescape=False in template contexts”
alternative: “Use mark_safe() if necessary”
rule: “python.django.security.audit.xss.context-autoescape-off.context-autoescape-off”
3. Templates: unescaped variables
3.A. Use of the | safe filter
The| safe filter marks the content as “safe for rendering.” This has the same effect as mark_safe() in Python code. This will permit direct rendering of HTML and create a possible XSS vulnerability.
Example:
References:
Mitigation:
Ban| safe. Alternatively, use mark_safe() in Python if necessary.
Semgrep rule
python.flask.security.xss.audit.template-unescaped-with-safe.template-unescaped-with-safe
3.B. Use of the | safeseq filter
The| safeseq filter marks the content as “safe for rendering.” This has the same effect as mark_safe() in Python code. This will permit direct rendering of HTML and create a possible XSS vulnerability.
Example:
References:
Mitigation:
“Ban| safeseq. Alternatively, use mark_safe() in Python if necessary.
Semgrep rule
python.django.security.audit.xss.template-var-unescaped-with-safeseq.template-var-unescaped-with-safeseq
3.C. The {% autoescape off %} block
The{$ autoescape off %} block disables autoescaping for whole portions of the template. Disabling autoescaping allows HTML characters to be rendered directly onto the page which could create XSS vulnerabilities.
Example:
References:
Mitigation:
Ban{% autoescape off %}. Alternatively, use mark_safe() in Python if necessary.
Semgrep rule
python.django.security.audit.xss.template-autoescape-off.template-autoescape-off
4. Templates: Variable in dangerous location”
4.A. Unquoted variable in HTML attribute
Unquoted template variables rendered into HTML attributes is a potential XSS vector because an attacker could inject JavaScript handlers which do not require HTML characters. An example handler might look like:onmouseover=alert(1). HTML escaping will not mitigate this. The variable must be quoted to avoid this.
Example:
References:
Mitigation:
Flag unquoted HTML attributes with Jinja expressions. Alternatively, always use quotes around HTML attributes.Semgrep rule
python.flask.security.xss.audit.template-unquoted-attribute-var.template-unquoted-attribute-var
4.B. Variable in href attribute
Template variables in ahref value could still accept the javascript: URI. This could be a XSS vulnerability. HTML escaping will not prevent this. Use url_for to generate links.
Example:
References:
Mitigation:
Flag template variables inhref attributes. Alternatively, use url_for to generate links.
Semgrep rule
python.django.security.audit.xss.template-href-var.template-href-var
4.C. Variable in <script> block
Template variables placed directly into JavaScript or similar are now directly in a code execution context. Normal HTML escaping will not prevent the possibility of code injection because code can be written without HTML characters. This creates the potential for XSS vulnerabilities, or worse.References:
- Template engines: Why default encoders are not enough
- Safely including data for JavaScript in a Django template
json_scriptdocumentation
Mitigation:
Ban template variables in<script> blocks. Alternatively, use the json_script template tag and read the data in JavaScript using the element ID.