python.django.security.audit.xss.var-in-script-tag.var-in-script-tag
Community Favorite

Author
14,658
Download Count*
License
Detected a template variable used in a script tag. Although template variables are HTML escaped, HTML escaping does not always prevent cross-site scripting (XSS) attacks when used directly in JavaScript. If you need this data on the rendered page, consider placing it in the HTML portion (outside of a script tag). Alternatively, use a JavaScript-specific encoder, such as the one available in OWASP ESAPI. For Django, you may also consider using the 'json_script' template tag and retrieving the data in your script by using the element ID (e.g., document.getElementById
).
Run Locally
Run in CI
Defintion
rules:
- id: var-in-script-tag
languages:
- generic
severity: ERROR
message: Detected a template variable used in a script tag. Although template
variables are HTML escaped, HTML escaping does not always prevent
cross-site scripting (XSS) attacks when used directly in JavaScript. If
you need this data on the rendered page, consider placing it in the HTML
portion (outside of a script tag). Alternatively, use a
JavaScript-specific encoder, such as the one available in OWASP ESAPI. For
Django, you may also consider using the 'json_script' template tag and
retrieving the data in your script by using the element ID (e.g.,
`document.getElementById`).
patterns:
- pattern-inside: <script ...> ... </script>
- pattern: "{{ ... }}"
- pattern-not-inside: nonce = '...'
- pattern-not-inside: nonce = "..."
paths:
include:
- "*.html"
metadata:
cwe:
- "CWE-79: Improper Neutralization of Input During Web Page Generation
('Cross-site Scripting')"
owasp:
- A07:2017 - Cross-Site Scripting (XSS)
- A03:2021 - Injection
references:
- https://adamj.eu/tech/2020/02/18/safely-including-data-for-javascript-in-a-django-template/?utm_campaign=Django%2BNewsletter&utm_medium=rss&utm_source=Django_Newsletter_12A
- https://www.veracode.com/blog/secure-development/nodejs-template-engines-why-default-encoders-are-not-enough
- https://github.com/ESAPI/owasp-esapi-js
category: security
technology:
- django
cwe2022-top25: true
cwe2021-top25: true
subcategory:
- audit
likelihood: LOW
impact: MEDIUM
confidence: LOW
license: Commons Clause License Condition v1.0[LGPL-2.1-only]
Examples
var-in-script-tag.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
// ruleid: var-in-script-tag
const mydata = {{ mydata_json|safe }};
// ruleid: var-in-script-tag
const moredata = {{ mydata_json }};
</script>
<div>
<!-- ok: var-in-script-tag -->
<p>{{ this_is_fine }}</p>
</div>
<!-- ok: var-in-script-tag -->
<script nonce="{{ request.csp_nonce }}">
console.log('inline script running');
</script>
</body>
</html>
Short Link: https://sg.run/Ge7q