XPath injection High

Potentially unsanitized user input in XPath queries can allow an attacker to control the query in unwanted or insecure ways. This might grant the attacker access to any data, not just the data that the original query intended.

Detector ID
python/xpath-injection@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1from flask import request, app
2
3
4@app.route('/user')
5def find_users_noncompliant():
6    from flask import request
7    import xml.etree.ElementTree as ET
8    tree = ET.parse('users.xml')
9    root = tree.getroot()
10    username = request.args['username']
11    query = "./users/user/[@name='"+username+"']/location"
12    # Noncompliant: evaluating expression built from user-supplied parameter
13    # can lead to XPath injection.
14    elements = root.findall(query)
15    return 'Location %s' % list(elements)

Compliant example

1from flask import request, app
2
3
4@app.route('/user')
5def find_users_compliant():
6    from flask import request
7    from lxml import etree
8    # Compliant: disabling external entities prevents XPath injection.
9    parser = etree.XMLParser(resolve_entities=False)
10    tree = etree.parse('users.xml', parser)
11    root = tree.getroot()
12    username = request.args['username']
13    query = "/collection/users/user[@name = $parameter_name]/location/text()"
14    elements = root.xpath(query, parameter_name=username)
15    return 'Location %s' % list(elements)