# Unsanitized User Input in XPath

## Overview

* **Rule ID**: `java_lang_xpath_injection`
* **Applicable Languages**: Java
* **Weakness ID**: CWE-643

## Description

Using unsanitized user input in XPath expressions can lead to XPath injection, allowing attackers to gain unauthorized access to sensitive information in XML documents. Ensure that all variables passed into XPath evaluation or compilation commands are properly sanitized.

## Remediation Guidelines

* **Sanitize user input** before including it in XPath queries to prevent XPath injection. This ensures that input values cannot alter the query structure.

  ```java
  public class Cls extends HttpServlet
    {
       public void handleRequest(HttpServletRequest request, HttpServletResponse response)
          {
              String userID = request.getParameter("userID");
              String sanitizedUserID = sanitize(userID); // Ensure sanitization

              javax.xml.xpath.XPathFactory xpf = javax.xml.xpath.XPathFactory.newInstance();
              javax.xml.xpath.XPath xp = xpf.newXPath();

              String expression = "/Users/User[@userID='" + sanitizedUserID + "']";
              String result = xp.evaluate(expression, xmlDocument);
          }
    }

  ```
* **Do not** directly concatenate or embed unsanitized user inputs into XPath expressions. This practice can lead to XPath injection vulnerabilities.

## References

* [**XPATH Injection**](https://owasp.org/www-community/attacks/XPATH_Injection)
* [**CWE-643: Improper Neutralization of Data within XPath Expressions ('XPath Injection')**](https://cwe.mitre.org/data/definitions/643.html)
* [**OWASP Top 10: A03:2021 - Injection**](https://owasp.org/Top10/A03_2021-Injection/)

## Configuration

To omit this rule during a scan, and to provide you with continuous 24/7 code-level scanning, you can employ our [**SAST TOOL**](https://scopy.sec1.io/login)


---

# 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://docs.sec1.io/user-docs/4-sast/2-java/unsanitized-user-input-in-xpath.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.
