DefenseCode

XPATH Injection

Risk type:LOW

Description:

XPath injection is an attack targeting websites that create XPath queries from user-supplied data. If an application embeds unprotected data into an XPath query, the query can be altered so that it is no longer parsed in the manner originally intended.

Example:

Let's consider the following XML code:

<?xml version="1.0" encoding="utf-8"?>
<Employees>
<Employee ID="1">
<FirstName>Arnold</FirstName>
<LastName>Baker</LastName>
<UserName>ABaker</UserName>
<Password>SoSecret</Password>
<Type>Admin</Type>
</Employee>
<Employee ID="2">
<FirstName>Peter</FirstName>
<LastName>Pan</LastName>
<UserName>PPan</UserName>
<Password>NotTelling</Password>
<Type>User</Type>
</Employee>
</Employees>

Vulnerable web page is using an authentication system that uses this XML data file to login users. Once a username and password have been supplied, the software might use XPath to look up the user (C# programming language):

String FindUserXPath;
FindUserXPath = "//Employee[UserName/text()='" + Request("Username") + "' And Password/text()='" + Request("Password") + "']";

The attacker can forge malicious input without knowing the username or password:

  • Username: anything' or 1=1 or 'a'='a
  • Password: anything

This translates to:

FindUserXPath = "//Employee[UserName/text()='anything' or 1=1 or 'a'='a' And Password/text()='anything']";

Only the first part of the XPath needs to be true. The password part becomes irrelevant, and the username part will match all employees.

Mitigation:

  • Escape single and double quotes if your application uses them.
  • Use precompiled XPath.

Further reading:

https://www.owasp.org/index.php/XPATH_Injection
http://www.ibm.com/developerworks/xml/library/x-xpathinjection/index.html