| name | cwe-643-xpath-injection |
| description | Use this skill when you need to remediate CWE-643 (XPath Injection) vulnerabilities in Java code. Triggers on SAST findings, security reviews, or when fixing xpath injection issues. |
| version | 1.0.0 |
| license | MIT |
| tags | ["security","java","cwe-643","remediation","sast","xpath-injection","xml","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
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
String username = request.getParameter("user");
XPath xPath = XPathFactory.newInstance().newXPath();
xPath.setXPathVariableResolver(new XPathVariableResolver() {
@Override
public Object resolveVariable(QName variableName) {
if ("username".equals(variableName.getLocalPart())) {
return username;
}
return null;
}
});
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:
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
| 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