# XPath Injection

#### XPath Injection

**Example 1: Java**

**Vulnerable Code:**

```java
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:**

```java
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:**

```python
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:**

```python
pythonCopy codeexpression = "/users/user[username/text()=$username]"
result = tree.xpath(expression, username=username)
```

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

***

### Java Example

#### Vulnerable Code:

```java
javaCopyimport javax.xml.xpath.*;
import org.w3c.dom.*;

public class UserLookup {
    public String findUser(String username, String password) throws Exception {
        String xpathExpr = "//user[username='" + username + "' and password='" + password + "']/role/text()";
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        return (String) xpath.evaluate(xpathExpr, xmlDocument, XPathConstants.STRING);
    }
}
```

#### Reason for Vulnerability:

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

#### Fixed Code:

```java
javaCopyimport javax.xml.xpath.*;
import org.w3c.dom.*;

public class UserLookup {
    public String findUser(String username, String password) throws Exception {
        String xpathExpr = "//user[username=$username and password=$password]/role/text()";
        XPathFactory xpathFactory = XPathFactory.newInstance();
        XPath xpath = xpathFactory.newXPath();
        
        SimpleBindings bindings = new SimpleBindings();
        bindings.put("username", username);
        bindings.put("password", password);
        
        return (String) xpath.evaluate(xpathExpr, xmlDocument, XPathConstants.STRING, bindings);
    }
}
```

#### Reason for Fix:

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

***

### PHP Example

#### Vulnerable Code:

```php
phpCopy<?php
$xpath = new DOMXPath($xml);
$query = "//user[username/text()='" . $_POST['username'] . "' and password/text()='" . $_POST['password'] . "']";
$nodes = $xpath->query($query);
?>
```

#### Reason for Vulnerability:

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

#### Fixed Code:

```php
phpCopy<?php
$xpath = new DOMXPath($xml);
$query = "//user[username/text()=? and password/text()=?]";
$nodes = $xpath->query($query, array($_POST['username'], $_POST['password']));
?>
```

#### Reason for Fix:

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

### C# Example

#### Vulnerable Code:

```csharp
csharpCopyusing System.Xml.XPath;

public string GetUserRole(string username, string password)
{
    XPathNavigator nav = xmlDoc.CreateNavigator();
    string query = $"string(//user[username='{username}' and password='{password}']/role)";
    return nav.Evaluate(query).ToString();
}
```

#### Reason for Vulnerability:

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

#### Fixed Code:

```csharp
csharpCopyusing System.Xml.XPath;

public string GetUserRole(string username, string password)
{
    XPathNavigator nav = xmlDoc.CreateNavigator();
    XPathExpression expr = nav.Compile("string(//user[username=@u and password=@p]/role)");
    expr.SetContext(new XPathContext { {"u", username}, {"p", password} });
    return nav.Evaluate(expr).ToString();
}
```

#### Reason for Fix:

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://playbook.sidthoviti.com/devsecops/secure-coding/code-review-examples/xpath-injection.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
