This vulnerability makes it possible to temporarily execute JavaScript code in the context of the application, granting access to the session of
the victim. This is possible because user-provided data, such as URL parameters, are copied into the HTML body of the HTTP response that is sent back
to the user.
Why is this an issue?
Reflected cross-site scripting (XSS) occurs in a web application when the application retrieves data like parameters or headers from an incoming
HTTP request and inserts it into its HTTP response without first sanitizing it. The most common cause is the insertion of GET parameters.
When well-intentioned users open a link to a page that is vulnerable to reflected XSS, they are exposed to attacks that target their own
browser.
A user with malicious intent carefully crafts the link beforehand.
After creating this link, the attacker must use phishing techniques to ensure that his target users click on the link.
What is the potential impact?
A well-intentioned user opens a malicious link that injects data into the web application. This data can be text, but it can also be arbitrary code
that can be interpreted by the target user’s browser, such as HTML, CSS, or JavaScript.
Below are some real-world scenarios that illustrate some impacts of an attacker exploiting the vulnerability.
Vandalism on the front-end website
The malicious link defaces the target web application from the perspective of the user who is the victim. This may result in loss of integrity and
theft of the benevolent user’s data.
Identity spoofing
The forged link injects malicious code into the web application. The code enables identity spoofing thanks to cookie theft.
Record user activity
The forged link injects malicious code into the web application. To leak confidential information, attackers can inject code that records keyboard
activity (keylogger) and even requests access to other devices, such as the camera or microphone.
Chaining XSS with other vulnerabilities
In many cases, bug hunters and attackers chain cross-site scripting vulnerabilities with other vulnerabilities to maximize their impact.
For
example, an XSS can be used as the first step to exploit more dangerous vulnerabilities or features that require higher privileges, such as a code
injection vulnerability in the admin control panel of a web application.
How to fix it in Django
Code examples
The following code is vulnerable to cross-site scripting because it returns an HTML response that contains user input.
If you do not intend to send HTML code to clients, the vulnerability can be fixed by specifying the type of data returned in the response. For
example, you can use the JsonResponse
class to return JSON messages securely.
Noncompliant code example
from django.http import HttpResponse
import json
def index(request):
json = json.dumps({ "data": request.GET.get("input") })
return HttpResponse(json)
Compliant solution
from django.http import JsonResponse
def index(request):
json = { "data": request.GET.get("input") }
return JsonResponse(json)
It is also possible to set the content-type manually with the content_type
parameter when creating an HttpResponse
object.
Noncompliant code example
from django.http import HttpResponse
def index(request):
return HttpResponse(request.GET.get("input"))
Compliant solution
from django.http import HttpResponse
def index(request):
return HttpResponse(request.GET.get("input"), content_type="text/plain")
How does this work?
If the HTTP response consists of HTML code, it is highly recommended to use a template engine like Django’s template system to generate it. The Django template engine separates the
view from the business logic and automatically encodes the output of variables, drastically reducing the risk of cross-site scripting
vulnerabilities.
If you do not intend to send HTML code to clients, the vulnerability can be fixed by telling them what data they are receiving with the
content-type
HTTP header. This header tells the browser that the response does not contain HTML code and should not be parsed and
interpreted as HTML. Thus, the response is not vulnerable to reflected cross-site scripting.
For example, setting the Content-Type HTTP header to text/plain
allows to safely reflect user input, because browsers will not try to
parse and execute the response.
Pitfalls
Content-types
Be aware that there are more content-types than text/html
that allow to execute JavaScript code in a browser and thus are prone to
cross-site scripting vulnerabilities.
The following content-types are known to be affected:
- application/mathml+xml
- application/rdf+xml
- application/vnd.wap.xhtml+xml
- application/xhtml+xml
- application/xml
- image/svg+xml
- multipart/x-mixed-replace
- text/html
- text/rdf
- text/xml
- text/xsl
The limits of validation
Validation of user inputs is a good practice to protect against various injection attacks. But for XSS, validation on its own is not the
recommended approach.
As an example, filtering out user inputs based on a deny-list will never fully prevent XSS vulnerability from being exploited. This practice is
sometimes used by web application firewalls. It is only a matter of time for malicious users to find the exploitation payload that will defeat the
filters.
Another example is applications that allow users or third-party services to send HTML content to be used by the application. A common approach is
trying to parse HTML and strip sensitive HTML tags. Again, this deny-list approach is vulnerable by design: maintaining a list of sensitive HTML tags,
in the long run, is very difficult.
A preferred option is to use Markdown in conjunction with a parser that removes embedded HTML and restricts the use of "javascript:" URI.
Going the extra mile
Content Security Policy (CSP) Header
With a defense-in-depth security approach, the CSP response header can be added to instruct client browsers to
block loading data that does not meet the application’s security requirements. If configured correctly, this can prevent any attempt
to exploit XSS in the application.
Learn more here.
How to fix it in Django Templates
Code examples
The following code is vulnerable to cross-site scripting because auto-escaping of special HTML characters has been disabled. The recommended way to
fix this code is to move the HTML content to the template and to only inject the dynamic value. Therefore, it is not necessary to disable
auto-escaping.
Noncompliant code example
from django.shortcuts import render
def hello(request):
name = request.GET.get("name")
hello = f"<h1>Hello { name }</h1>"
return render(request, 'hello.html', {'hello': hello})
<!doctype html>
{% autoescape false %}
{{ hello }} <!-- Noncompliant -->
{% endautoescape %}
Compliant solution
from django.shortcuts import render
def hello(request):
name = request.GET.get("name")
return render(request, 'hello.html', {'name': name})
<!doctype html>
<h1>Hello {{ name }}</h1>
How does this work?
Template engines are used by web applications to build HTML content. Template files contain both static HTML and template language instructions.
These instructions allow, for example, to insert dynamic values in the document as the template is rendered. Template engines can auto-escape HTML
special characters of dynamic values in order to prevent XSS vulnerabilities.
In Django applications, the engine’s auto-escaping feature is enabled by default. XSS vulnerabilities arise when an untrusted value is injected
into the template and auto-escaping is disabled with {% autoescape false %}
or |safe
. This is often the case when a piece of
dynamic HTML is generated from code and used in a template variable.
Encode data according to the HTML context
The best approach to protect against XSS is to systematically encode data that is written to HTML documents. The goal is to leave the data intact
from the end user’s point of view but make it uninterpretable by web browsers.
XSS exploitation techniques vary depending on the HTML context where malicious input is injected. For each HTML context, there is a specific
encoding to prevent JavaScript code from being interpreted. The following table summarizes the encoding to apply for each HTML context.
Context |
Code example |
Exploit example |
Encoding |
Inbetween tags |
<!doctype html>
<div>
{ data }
</div>
|
<!doctype html>
<div>
<script>
alert(1)
</script>
</div>
|
HTML entity encoding: replace the following characters by HTML-safe sequences.
- & → &
- < → <
- > → >
- " → "
- ' → '
|
In an attribute surrounded with single or double quotes |
<!doctype html>
<div tag="{ data }">
...
</div>
|
<!doctype html>
<div tag=""
onmouseover="alert(1)">
...
</div>
|
HTML entity encoding: replace the following characters with HTML-safe sequences.
- & → &
- < → <
- > → >
- " → "
- ' → '
|
In an unquoted attribute |
<!doctype html>
<div tag={ data }>
...
</div>
|
<!doctype html>
<div tag=foo
onmouseover=alert(1)>
...
</div>
|
Dangerous context: HTML output encoding will not prevent XSS fully. |
In a URL attribute |
<!doctype html>
<a href="{ data }">
...
</a>
|
<!doctype html>
<a href="javascript:alert(1)">
...
</a>
|
Validate the URL by parsing the data. Make sure relative URLs start with a / and that absolute URLs use https
as a scheme. |
In a script block |
<!doctype html>
<script>
{ data }
</script>
|
<!doctype html>
<script>
alert(1)
</script>
|
Dangerous context: HTML output encoding will not prevent XSS fully. To pass values to a JavaScript context, the recommended way is to use a data attribute:
<!doctype html>
<script data="{ data }">
...
</script>
|
Django template auto-escaping only takes care of HTML entity encoding. It does not protect from XSS when a variable is injected into an unquoted
attribute or directly into a script block.
Auto-escaping can also be disabled at the application level and introduce XSS vulnerabilities even if {% autoescape false %}
or
|safe
are not used.
Noncompliant code example
# settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'OPTIONS': {
'autoescape': False,
],
},
},
]
Compliant solution
# settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'OPTIONS': {
'autoescape': True,
],
},
},
]
Pitfalls
Variables in script blocks
As mentioned in the section "How to fix it", injecting user-controlled values into a client-side JavaScript script
is dangerous. In
such a case it is better to add the value to an attribute.
Another option is to use the json_script
filter to insert a data structure that can then be accessed through the JavaScript code.
Noncompliant code example
<!doctype html>
<script> var name = '{{ name }}';</script>
Compliant solution
<!doctype html>
{{ name|json_script:"name-data" }}
<script> var name = JSON.parse(document.getElementById('name-data').textContent);</script>
The limits of validation
Validation of user inputs is a good practice to protect against various injection attacks. But for XSS, validation on its own is not the
recommended approach.
As an example, filtering out user inputs based on a deny-list will never fully prevent XSS vulnerability from being exploited. This practice is
sometimes used by web application firewalls. It is only a matter of time for malicious users to find the exploitation payload that will defeat the
filters.
Another example is applications that allow users or third-party services to send HTML content to be used by the application. A common approach is
trying to parse HTML and strip sensitive HTML tags. Again, this deny-list approach is vulnerable by design: maintaining a list of sensitive HTML tags,
in the long run, is very difficult.
A preferred option is to use Markdown in conjunction with a parser that removes embedded HTML and restricts the use of "javascript:" URI.
Going the extra mile
Content Security Policy (CSP) Header
With a defense-in-depth security approach, the CSP response header can be added to instruct client browsers to
block loading data that does not meet the application’s security requirements. If configured correctly, this can prevent any attempt
to exploit XSS in the application.
Learn more here.
How to fix it in Flask
Code examples
The following code is vulnerable to cross-site scripting because it returns an HTML response that contains user input.
If you do not intend to send HTML code to clients, the vulnerability can be fixed by specifying the type of data returned in the response. For
example, you can use the jsonify
class to return JSON messages safely.
Noncompliant code example
from flask import make_response, request
import json
@app.route('/')
def index():
json = json.dumps({ "data": request.args.get("input") })
return make_response(json)
Compliant solution
from flask import jsonify, request
@app.route('/')
def index():
return jsonify({ "data": request.args.get("input") })
It is also possible to set the content-type manually with the mimetype
parameter when calling the make_response
function.
Noncompliant code example
from flask import make_response, request
@app.route('/')
def index():
return make_response(request.args.get("input"))
Compliant solution
from flask import make_response, request
@app.route('/')
def index():
return make_response(request.args.get("input"), mimetype="text/plain")
How does this work?
If the HTTP response is HTML code, it is highly recommended to use a template engine like Jinja to
generate it. This template engine separates the view from the business logic and automatically encodes the output of variables, drastically reducing
the risk of cross-site scripting vulnerabilities.
If you do not intend to send HTML code to clients, the vulnerability can be fixed by specifying the type of data returned in the response with the
content-type
HTTP header. This HTTP header tells the client browser that the response does not contain HTML code and should not be parsed
and interpreted as HTML. Thus, the response is not vulnerable to reflected cross-site scripting.
For example, setting the content-type header to text/plain
allows to safely reflect user input because browsers will not try to parse
and execute the response.
Pitfalls
Content-types
Be aware that there are more content-types than text/html
that allow to execute JavaScript code in a browser and thus are prone to
cross-site scripting vulnerabilities.
The following content-types are known to be affected:
- application/mathml+xml
- application/rdf+xml
- application/vnd.wap.xhtml+xml
- application/xhtml+xml
- application/xml
- image/svg+xml
- multipart/x-mixed-replace
- text/html
- text/rdf
- text/xml
- text/xsl
The limits of validation
Validation of user inputs is a good practice to protect against various injection attacks. But for XSS, validation on its own is not the
recommended approach.
As an example, filtering out user inputs based on a deny-list will never fully prevent XSS vulnerability from being exploited. This practice is
sometimes used by web application firewalls. It is only a matter of time for malicious users to find the exploitation payload that will defeat the
filters.
Another example is applications that allow users or third-party services to send HTML content to be used by the application. A common approach is
trying to parse HTML and strip sensitive HTML tags. Again, this deny-list approach is vulnerable by design: maintaining a list of sensitive HTML tags,
in the long run, is very difficult.
A preferred option is to use Markdown in conjunction with a parser that removes embedded HTML and restricts the use of "javascript:" URI.
Going the extra mile
Content Security Policy (CSP) Header
With a defense-in-depth security approach, the CSP response header can be added to instruct client browsers to
block loading data that does not meet the application’s security requirements. If configured correctly, this can prevent any attempt
to exploit XSS in the application.
Learn more here.
How to fix it in Jinja
Code examples
The following code is vulnerable to cross-site scripting because auto-escaping of special HTML characters has been disabled. The recommended way to
fix this code is to move the HTML content to the template and to only inject the dynamic value. Therefore, it is not necessary to disable
auto-escaping.
Noncompliant code example
from flask import render_template
@app.route('/hello/<name>')
def hello(name=None):
hello = f"<h1>Hello { name }</h1>"
return render_template('hello.html', hello=hello)
<!doctype html>
{% autoescape false %}
{{ hello }} <!-- Noncompliant -->
{% endautoescape %}
Compliant solution
from flask import render_template
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
<!doctype html>
<h1>Hello {{ name }}</h1>
How does this work?
Template engines are used by web applications to build HTML content. Template files contain static HTML as well as template language instructions.
These instructions allow, for example, to insert dynamic values (variables) in the document as the template is rendered. Template engines can auto
escape HTML special characters of variables in order to prevent XSS vulnerabilities.
In Flask applications, Jinja’s auto-escaping feature is enabled by default. XSS vulnerabilities arise when an untrusted value is injected into the
template and auto-escaping is disabled with the {% autoescape false %}
or |safe
filters. This is often the case when a piece
of dynamic HTML is generated from Python code and used in a template variable.
Pitfalls
Variables in script blocks
Although auto-escaping drastically decreases the chance of introducing cross-site scripting vulnerabilities, there are still specific cases where
vulnerabilities can occur. Injecting user-controlled values inside a script
is dangerous. In such a case, the best practice is to add the
value to an attribute. Another option is to use the tojson
filter to insert a data structure in the JavaScript code at render time.
Noncompliant code example
<!doctype html>
<script> var name = '{{ name }}';</script>
Compliant solution
<!doctype html>
<script> var name = {{ name | tojson }}</script>
Going the extra mile
Content Security Policy (CSP) Header
With a defense-in-depth security approach, the CSP response header can be added to instruct client browsers to
block loading data that does not meet the application’s security requirements. If configured correctly, this can prevent any attempt
to exploit XSS in the application.
Learn more here.
Resources
Documentation
Articles & blog posts
Conference presentations
Standards