XPath Injection

XPath Injection

Example 1: Java

Vulnerable Code:

javaCopy codeString expression = "/users/user[username/text()='" + username + "']";
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);

Reason for vulnerability: User input is directly used in the XPath expression, allowing XPath injection.

Fixed Code:

javaCopy codeXPathExpression expr = xpath.compile("/users/user[username/text()=$username]");
Map<String, String> variables = new HashMap<>();
variables.put("username", username);
XPathVariableResolver resolver = new SimpleVariableResolver(variables);
xpath.setXPathVariableResolver(resolver);
NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);

Reason for fix: Use parameterized XPath expressions to prevent injection.

Example 2: Python

Vulnerable Code:

pythonCopy codeexpression = "/users/user[username/text()='{}']".format(username)
result = tree.xpath(expression)

Reason for vulnerability: User input is directly used in the XPath expression, allowing XPath injection.

Fixed Code:

Reason for fix: Use parameterized XPath expressions to prevent injection.


Java Example

Vulnerable Code:

Reason for Vulnerability:

This code directly incorporates user input into an XPath expression, allowing injection of malicious XPath.

Fixed Code:

Reason for Fix:

The fixed code uses XPath parameter binding to separate the query from user input, preventing XPath injection.


PHP Example

Vulnerable Code:

Reason for Vulnerability:

This code directly incorporates user input into an XPath query, allowing injection of malicious XPath.

Fixed Code:

Reason for Fix:

The fixed code uses parameterized queries to separate the XPath query from user input.

C# Example

Vulnerable Code:

Reason for Vulnerability:

This code directly incorporates user input into an XPath query, allowing injection of malicious XPath.

Fixed Code:

Reason for Fix:

The fixed code uses parameterized XPath queries to separate the query from user input.

Last updated