Skip to main content

Free 30-min security demo  — We'll scan your real code and show live findings, no commitment Book Now

Offensive360
Academy XPath Injection
Intermediate · 15 min

XPath Injection

Learn how attackers exploit XML query strings and how parameterized XPath stops data extraction.

1 XPath Injection Basics

XPath injection is analogous to SQL injection but targets XML data stores. When user input is concatenated into an XPath query string, attackers can alter the query logic to bypass authentication or extract unauthorized data.

Vulnerable example (PHP):

$username = $_POST["username"];
$password = $_POST["password"];
$xml = simplexml_load_file("users.xml");
$result = $xml->xpath("//user[username='$username' and password='$password']");

An attacker sends username ' or '1'='1 to produce:

//user[username='' or '1'='1' and password='anything']

This returns all user nodes, bypassing authentication. Attackers can also extract the entire XML document structure using techniques like ] | //* | //foo[a='.

2 Safe XPath with Variable Binding

The correct fix is to use parameterized XPath queries with variable binding. The query template is compiled separately from the data, so user input cannot alter query structure.

Safe example (Java with javax.xml.xpath):

XPath xpath = XPathFactory.newInstance().newXPath();
XPathVariableResolver resolver = varName -> {
  if ("username".equals(varName.getLocalPart())) return username;
  if ("password".equals(varName.getLocalPart())) return password;
  return null;
};
xpath.setXPathVariableResolver(resolver);
String expr = "//user[username=$username and password=$password]";
NodeList nodes = (NodeList) xpath.evaluate(expr, doc, XPathConstants.NODESET);

Defense checklist:

  • Use XPath variable binding (parameterized queries)
  • Allowlist input characters for XML contexts
  • Escape single quotes if parameterization unavailable
  • Prefer database storage over XML for sensitive data

Knowledge Check

0/3 correct
Q1

XPath injection is most similar to which other vulnerability class?

Q2

What is the recommended fix for XPath injection?

Q3

What data source does XPath injection target?

Code Exercise

Identify the XPath Injection

The code below builds an XPath expression from user input. Rewrite it to use XPath variable binding so user input cannot alter the query structure.

java