XPath injection: when input becomes part of an XML query

XPath injection happens when an application builds an XPath expression from user input without keeping the input apart from the query. The XML processor then selects nodes the developer did not intend. It turns up where XML files or XML services stand in for a database, such as a user list or a configuration store, and it is prevented by passing values as variables, not by splicing them into the string.

Section Web attacks Updated Weakness CWE-643

Quick facts

Weakness
CWE-643, improper neutralization of data within XPath expressions; child of CWE-91 (XML injection) and CWE-943
OWASP category
A05:2025 Injection
OWASP description
XPath Injection on the OWASP community site
Language
XPath 1.0, W3C Recommendation of 16 November 1999; XPath 3.1 is the later line
Access control
None inside XPath: OWASP notes there is no access control level, so a query can reach the whole document
Main fix
Compile the expression once with variable references and bind user values to them, validate the expected type, and give the process the least access to the XML it needs

The weakness entry and its mitigations come from CWE-643. The consequences and the point about access control come from the OWASP page above. Claims about the language itself are checked against the W3C text.

What XPath does

XPath is a language for addressing parts of an XML document. A path such as /users/user[name='ann'] walks the tree from the root, picks user elements, and keeps those whose name child equals the text between the quotes. Predicates in square brackets can combine conditions with and and or, compare values, and call functions such as count() or substring(). The expression returns nodes, a string, a number or a boolean.

Two properties of the language shape every injection flaw. First, XPath is a query language and 1.0 has no way to change a document, so the realistic harm is reading, not writing. Second, an expression is an ordinary string handed to an XPath engine. If part of that string came from a request, the engine cannot tell the application's text from the visitor's.

The versions matter a little. XPath 3.1 is a later line that adds maps, arrays and a far larger function library, and it defines functions such as doc() that return a document for a given URI. Whether a processor lets an expression load another resource is a setting of that processor, so a team should find out which engine and which options it actually runs.

The same family as SQL injection

The mechanism is the one behind SQL injection and LDAP injection: data and instructions share one string. The OWASP page points out that XPath has no access control, and that the syntax is the same across implementations. That second point means a single probe works against any engine, and automation is easy. There is also no permission layer to limit what a successful change in the query can see.

Where input reaches the expression

The flaw requires an application that stores data as XML and queries it with XPath built at runtime. That is less common than SQL, which makes it easy to forget in an audit. Look at these places.

  • XML user files. A small application keeps accounts in an XML file and finds the entry for the typed login name with a path expression. The login name sits between two quotes. OWASP uses this setup as its example of privilege escalation.
  • XML-backed services. A SOAP or REST service that keeps documents in an XML database or in memory may let a request parameter select a node by name, id or attribute.
  • Search and filter boxes. A catalogue stored as XML takes a search term and turns it into a predicate.
  • Configuration and routing lookups. A page picks a record from an XML file by a parameter such as a section name.
  • XSLT and templating. A stylesheet that builds a path from a parameter value has the same exposure. See XXE for the neighbouring class of XML parser problems.

Values stored earlier and used later count too. A profile field written by one page and placed into an expression by another is untrusted at the point of use.

What goes wrong

OWASP lists four consequences: the XML structure is exposed, data outside the user's permissions can be read, privileges can be raised when XML holds authentication data, and the whole document can be retrieved because the language has no access control. Which of these applies depends on what the application does with the result.

In a sign-in flow, the failure is a lookup that matches an entry it should not, or any entry at all, so the check passes without the right credentials. In a search box, the result is a larger set of nodes than the page was meant to show, including fields that were never rendered before. Where an application returns only a yes or no, a visitor can still learn about the document by asking many true-or-false questions and watching how the response differs. OWASP lists this as a related attack, blind XPath injection, and the slow, repetitive request pattern it produces is useful to remember when reading logs.

Error messages help the visitor. A response that prints the engine's complaint about a malformed expression shows how the query is built. OWASP advises custom error pages for this reason.

Repeated probing of a sign-in also looks like brute force attacks in the logs, and the controls differ: attempt limits for the second, query construction for the first.

Why escaping is a weak fix

With SQL and LDAP, a well-known escape routine exists for each context. XPath is awkward here. In the XPath 1.0 grammar, a string literal is either a double quote, any characters except a double quote, and a double quote, or the same with single quotes. A literal cannot contain its own delimiter and there is no backslash or doubling convention to include it. A value that contains one kind of quote can sit inside the other kind. A value that contains both cannot be written as a single literal at all and has to be assembled with the concat() function.

That has two consequences. Escaping rules borrowed from other languages do not work, and a custom routine that mishandles the mixed-quote case leaves a hole at exactly the characters an attacker would choose. OWASP describes escaping the quote as a possible measure and calls precompiled, parameterised queries the better option, because with them nobody needs to enumerate dangerous characters. CWE-643 lists parameterised XPath first for the same reason.

Prevention

  1. Use variable references. XPath 1.0 defines a variable reference as a dollar sign followed by a name. The expression is written once with $name in place of the value, and the application binds the value separately. Libraries expose this: Java has XPathVariableResolver, and the xpath() method in lxml for Python takes variables as arguments. Check your own library's documentation for the equivalent.
  2. Never build the expression by concatenation. If a library offers no variable binding, treat that as a reason to look at another library, not to write an escape function.
  3. Validate the type. If a parameter is an integer or a fixed set of names, reject anything else before it reaches the query. OWASP notes that parameterisation also restricts input to the expected type.
  4. Return one generic failure message. Do not print the engine's error text, and do not tell a caller which part of a lookup failed.
  5. Reduce what the query can reach. Keep secrets such as password hashes out of the document that a search feature queries. If the data needs real permissions, a database with access control is a better home than a file XPath can read in full.
  6. Harden the XML parser. Disable external entity resolution and, where the engine allows it, document-loading functions that the feature does not need.
  7. Test the code path. Review every place an expression is assembled, and run the checks against test data and a staging copy.

Where a WAF helps and where it does not

A request filter sees the HTTP request: the query string, form fields, a JSON or XML body, headers. Quote characters, brackets and XPath function names in a login field or a search parameter have a recognisable shape there, and an injection rule can flag them before the application sees them. The OWASP Top 10 page on injection describes the general case.

The limits are real. The WAF does not see the expression the application passes to the XML engine, so it cannot tell whether variables were used. Quotes, brackets and the word and are ordinary in legitimate text, and a name like O'Brien arrives with an apostrophe in the normal course of business, so an eager rule will flag real people. Values stored earlier never pass the filter at the moment of use. Encodings the filter does not decode can carry the same characters through. And blind probing sends requests that each look harmless; only the pattern across many of them gives it away.

The three modes fit this uncertainty. In off nothing is inspected. In monitor a match is recorded and the request is still served, so the activity log shows which parameters carry quote and bracket characters and from which clients. Read it first, add exceptions for fields that legitimately take apostrophes, and sort out false positives. Then move to block, where matching requests are refused and still recorded. The route is described in monitor mode.

The filter reduces exposure while the code is fixed; it does not repair the code. Parameterised expressions are the fix, and a WAF does not replace them.

Questions

What is XPath injection?

XPath injection is an attack in which user input changes the meaning of an XPath expression because the application built the expression by joining strings. The XML processor then selects nodes the developer did not intend. It is tracked as CWE-643.

How do you prevent XPath injection?

Write the expression once with variable references and bind user values to them, as CWE-643 and OWASP recommend. Validate the expected type of each value, hide error details, and keep sensitive data out of documents that a search feature can query.

Why can't I just escape quotes in XPath?

In XPath 1.0 a string literal cannot contain its own delimiter, and the language has no backslash escape. A value with both kinds of quote cannot be written as one literal and needs concat(). Parameterised queries avoid the problem.

Is XPath injection the same as SQL injection?

It is the same kind of flaw aimed at a different interpreter, since both mix data and instructions in one string. XPath has no access control, so a changed query can reach the whole document. See SQL injection for the comparison.

Can a WAF stop XPath injection?

A WAF can flag quote and bracket patterns in request parameters, and monitor mode shows what would be blocked before block is enabled. It cannot see the expression the application builds, so the fix remains parameterised XPath in the code.