What Is XPath Injection?
XPath injection is the XML/XPath counterpart to other interpreter injection flaws. The application constructs an XPath expression from untrusted input, and the input changes operators, predicates or functions in that expression instead of remaining a literal value.
MITRE tracks XPath injection as CWE-643. Consequences can include reading unauthorized XML data or bypassing application protections that rely on query results.
How Unsafe XPath Construction Happens
The risky pattern is string concatenation. Escaping mistakes are especially common because developers may reuse SQL, HTML or XML escaping functions that do not preserve XPath expression semantics.
// Risky concept
expression = "/users/user[name='" + input + "']";
// Safer concept with a library that supports XPath variables
result = xml.xpath("/users/user[name=$name]", { name: input });The second pattern keeps the expression under application control and supplies the value separately. Use the exact variable-binding mechanism provided by the selected XPath/XQuery library.
What Is Blind XPath Injection?
In a blind XPath scenario, the application does not directly return XML data or parser errors, but observable differences can still reveal whether a condition evaluated true or false. Those differences might be response content, status, timing or another business behavior.
From a defensive perspective, the lesson is the same: hiding errors does not fix injection. The XPath expression must be structurally separated from external values.
Blind XPath Injection: What Defenders Should Measure
“Blind” does not mean invisible. It means the application does not directly return the selected XML value. A vulnerable expression can still produce different observable behavior depending on whether a condition is true or false—for example a different result count, authorization outcome, status, error path or response shape.
For defensive testing, focus on whether special characters can alter the expression structure and whether logically equivalent data values produce consistent application behavior. Instrument the application so testers can observe which fixed expression was executed and which values were bound without exposing sensitive XML contents in client-facing errors.
Timing differences can occur in some systems, but defenders should not define blind XPath injection solely as a timing attack. The root weakness is external control of XPath syntax; the information channel is secondary.
XPath Injection and Authentication Logic
Legacy or XML-backed applications sometimes select an account with an XPath expression built from username and password fields. If the predicate is constructed unsafely, injected syntax can change which node matches. Authentication should not depend on a dynamically constructed XPath expression whose structure can be influenced by the user.
Use fixed lookup expressions with bound values, retrieve the intended account record, and verify credentials through the appropriate authentication mechanism. Authorization must also be enforced after data selection.
XPath Variable-Binding Examples
OWASP recommends XPath variable binding where the API supports it. When users choose a search mode or field, map that choice to a complete server-defined expression rather than inserting a user-controlled expression fragment.
const expressions = {
byId: "/catalog/item[@id=$value]",
bySku: "/catalog/item[@sku=$value]"
};
const expression = expressions[mode];
if (!expression) throw new Error("unsupported search mode");
return evaluateXPath(expression, { value: externalValue });Variables represent data values; they should not be used as a workaround for letting users supply predicates, operators or function names.
When Your XPath API Supports Variable Binding
The cleanest defense is to keep the XPath expression fixed and provide external values through the variable mechanism supported by the implementation. OWASP’s Java guidance, for example, recommends an XPathVariableResolver rather than concatenating the value into the expression string.
Library support varies, especially across older XPath 1.0 APIs. If the selected API does not provide safe variable binding, consider switching to a wrapper/query mechanism that does rather than inventing a custom escaping algorithm. Where escaping is unavoidable, it must match the XPath string-literal context and be covered by tests for quotes, Unicode and malformed input.
Also keep structural choices—element/attribute names, axes, predicates and functions—under application control. Binding a value safely does not make an attacker-controlled XPath fragment safe.
XPath Injection Prevention
- Use XPath/XQuery APIs that support variable binding and keep expressions fixed.
- Do not concatenate usernames, search terms or request values into XPath strings.
- Map user-selectable query modes to complete server-defined expressions.
- Validate values for expected type, length and business rules in addition to binding.
- Enforce authorization on the selected records; a safe query does not prove access rights.
- Keep XPath expressions, XML content and stack traces out of public error responses.
- Harden XML parsing separately against XXE and related parser risks.
XPath Injection Payload Patterns: What Defenders Should Recognize
Security tools and code reviewers do not need a library of working bypass strings to identify the weakness. The useful pattern is structural: input contains XPath metacharacters or boolean/string expressions and the application’s query shape, match count or response behavior changes because that input was interpreted as syntax rather than a bound value.
Defensive test cases should cover quotes, delimiter characters, unexpected operators and values that would be harmless when bound correctly. The pass condition is not “the scanner found no known payload”; it is that external data cannot alter the fixed XPath expression at all.
For blind cases, compare observable application behavior while keeping the test scoped to approved data. Different status codes, result presence, authorization decisions or response shapes can expose a query-construction flaw even when the selected XML value is never returned.
How to Review and Test XPath Injection
Search code for XPath evaluation and compilation calls, then trace the origin of the expression text. Every expression should be application-controlled. External values should reach the query only through supported binding or a documented safe abstraction.
Use approved test environments and assertions that demonstrate whether query structure changes. The objective is to verify binding and fixed-expression controls, not to extract directory/XML data from systems outside the assessment scope.
XPath Injection vs SQL, LDAP and XXE
| Issue | Interpreter / parser | Main defense |
|---|---|---|
| XPath injection | XPath engine | Fixed expressions + variable binding |
| SQL injection | SQL engine | Parameterized queries/prepared statements |
| LDAP injection | LDAP filter/DN parser | LDAP context-specific encoding |
| XXE | XML parser | Disable/restrict external entities and unsafe parser features |
These are distinct weaknesses even when the input is XML-related. Apply the defense at the actual interpreter boundary.
Related Ammune reading: Cross-site scripting, XML injection and SSTI and API SQL injection testing guide.
Runtime Detection Around XPath-Backed APIs
Ammune can complement secure query construction by surfacing repeated malformed search inputs and anomalous API behavior. The root control remains at the XPath sink: query syntax must stay under application control.
XPath Injection Defense Checklist
- Inventory all XPath/XQuery evaluation calls.
- Remove string concatenation from expressions.
- Use variable binding for external values.
- Map search modes to fixed server-defined expressions.
- Validate types and lengths.
- Enforce authorization after selection.
- Hide parser/query internals from clients.
- Regression-test special-character inputs.
Frequently Asked Questions
What is XPath injection?
It is an injection flaw where untrusted data changes the structure or logic of an XPath expression.
What is blind XPath injection?
It is inference-based XPath injection where the attacker learns from observable true/false behavior rather than direct XML output.
Can XPath injection bypass authentication?
Unsafe authentication expressions can be manipulated, so fixed expressions and proper credential verification are required.
How do you prevent XPath injection?
Keep expressions fixed and bind external values with a library-supported variable mechanism.
Is XPath injection the same as XXE?
No. XPath injection targets query expressions; XXE targets XML parser handling of external entities.
Primary References
Keep XML Query Structure Out of Attacker Control
Use variable binding and fixed XPath expressions, then monitor API search behavior for repeated malformed and suspicious query inputs.
