XPath injection High

Potentially unsanitized user input in XPath queries can allow an attacker to control the query in unwanted or insecure ways. This might grant the attacker access to any data, not just the data that the original query intended.

Detector ID
java/xpath-injection@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1public void evaluateExpressionNoncompliant(HttpServletRequest request, XPath xpath, Document xml)
2        throws XPathExpressionException {
3    String employeeID = request.getParameter("employeeID");
4    String expression = "/employees/" + employeeID + "/sales/monthly";
5    // Noncompliant: evaluating expression built from user-supplied parameter can lead to XPath injection.
6    xpath.evaluate(expression, xml);
7}

Compliant example

1public void evaluateExpressionCompliant(HttpServletRequest request, XPath xpath, Document xml)
2        throws XPathExpressionException {
3    String employeeID = request.getParameter("employeeID");
4    // Compliant: user-supplied parameter is sanitized before its inclusion in the expression.
5    if (!employeeID.matches("[0-9]+")) {
6        throw new IllegalArgumentException();
7    }
8    String expression = "/employees/" + employeeID + "/sales/monthly";
9    xpath.evaluate(expression, xml);
10}