What is XPATH injection and how can it be prevented?
Same idea as SQL injection, but the interpreter is an XPath engine querying an XML document — break out of the query string to return data you shouldn't see. Prevent it by XML-encoding input before building the query.
XPath is the query language for XML: you give it a path through the document and it returns the matching nodes. Suppose an HR file holds staff records, salaries included:
<employees>
<employee id="AS789" firstname="John" lastname="Doo" annualsalary="70000"/>
<employee id="AS719" firstname="Isabela" lastname="Dobora" annualsalary="90000"/>
<employee id="AS219" firstname="Eric" lastname="Lambert" annualsalary="65000"/>
</employees>
The application looks one person up by building a query string:
/employees/employee[@id='EMPLOYEE_ID']
If EMPLOYEE_ID is ' or '1'='1, the assembled predicate becomes:
/employees/employee[@id='' or '1'='1']
The attacker's quote closes the intended comparison early, and the or grafts on a condition that is true for every node — '1'='1' never fails. The predicate now matches all employees, so a lookup meant to return one record dumps the whole file, salaries and all. Note the shape: identical to SQL's ' OR 1=1, because the flaw is identical — user text was concatenated into a query instead of being passed as a value.
Prevention:
- XML-encode the input before it is placed into the XPath expression, so the quote can never terminate the literal —
'becomes'and the payload is compared as the harmless string it should have been all along - Better still where the library supports it, use a parameterised XPath (variable bindings), the exact analogue of a prepared statement