cwe-643-xpath-injection
CWE-643 XPath Injection
Description
XPath Injection
Reference: https://cwe.mitre.org/data/definitions/643.html
OWASP Category: A03:2021 – Injection
Vulnerable Pattern
❌ Example 1: Vulnerable Pattern
// VULNERABLE: String concatenation in XPath
String username = request.getParameter("user");
String xpath = "//users/user[name='" + username + "']/password";
XPathExpression expr = xPath.compile(xpath);
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
Why it's vulnerable: This pattern is vulnerable to XPath Injection
Deterministic Fix
✅ Secure Implementation: Secure Implementation
// SECURE: Use XPath variables (parameterized)
String username = request.getParameter("user");
// Create a variable resolver
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setXPathVariableResolver(new XPathVariableResolver() {
@Override
public Object resolveVariable(QName variableName) {
if ("username".equals(variableName.getLocalPart())) {
return username; // Safely bound
}
return null;
}
});
// Use variable reference instead of concatenation
String xpath = "//users/user[name=$username]/password";
XPathExpression expr = xPath.compile(xpath);
NodeList nodes = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
Why it's secure: Implements proper protection against XPath Injection
Detection Pattern
Look for these patterns in your codebase:
# Find XPath with concatenation
grep -rn "xPath.compile\|XPathExpression" --include="*.java" | grep "\\+"
Remediation Steps
-
Use XPathVariableResolver for parameterized queries
-
Reference variables with $varname syntax
-
Validate input against expected patterns
-
Consider using typed XML libraries instead of XPath
Key Imports
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathVariableResolver;
import javax.xml.namespace.QName;
Verification
After remediation:
-
Run SAST scanner to confirm vulnerability is resolved
-
Review all instances of the vulnerable pattern
-
Add unit tests that verify the secure implementation
-
Check for similar patterns in related code
Trigger Examples
Fix CWE-643 vulnerability
Resolve XPath Injection issue
Secure this Java code against xpath injection
SAST reports CWE-643
Common Vulnerable Locations
| Layer | Files | Patterns |
|---|
| Controller | *Controller.java | User input handling |
| Service | *Service.java | Business logic |
| Repository | *Repository.java | Data access |
References
Source: Generated by Java CWE Security Skills Generator Last Updated: 2026-03-07