Reflected server-side cross-site scripting¶
ID: py/reflective-xssKind: path-problemSecurity severity: 6.1Severity: errorPrecision: highTags: - security - external/cwe/cwe-079 - external/cwe/cwe-116Query suites: - python-code-scanning.qls - python-security-extended.qls - python-security-and-quality.qls
Click to see the query in the CodeQL repository
Directly writing user input (for example, an HTTP request parameter) to a webpage without properly sanitizing the input first, allows for a cross-site scripting vulnerability.
Recommendation¶
To guard against cross-site scripting, consider escaping the input before writing user input to the page. The standard library provides escaping functions:html.escape() for Python 3.2 upwards orcgi.escape() older versions of Python. Most frameworks also provide their own escaping functions, for exampleflask.escape().
Example¶
The following example is a minimal flask app which shows a safe and unsafe way to render the given name back to the page. The first view is unsafe asfirst_name is not escaped, leaving the page vulnerable to cross-site scripting attacks. The second view is safe asfirst_name is escaped, so it is not vulnerable to cross-site scripting attacks.
fromflaskimportFlask,request,make_response,escapeapp=Flask(__name__)@app.route('/unsafe')defunsafe():first_name=request.args.get('name','')returnmake_response("Your name is "+first_name)@app.route('/safe')defsafe():first_name=request.args.get('name','')returnmake_response("Your name is "+escape(first_name))
References¶
Wikipedia:Cross-site scripting.
Python Library Reference:html.escape().
Common Weakness Enumeration:CWE-79.
Common Weakness Enumeration:CWE-116.