2023-03-02 18:22:24 +01:00

54 lines
1.5 KiB
Plaintext

=== How to fix it in Java SE
The following noncompliant code is vulnerable to XPath injections because untrusted data is
concatenated to an XPath query without prior validation.
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
public boolean authenticate(HttpServletRequest req, XPath xpath, Document doc) throws XPathExpressionException {
String user = request.getParameter("user");
String pass = request.getParameter("pass");
String expression = "/users/user[@name='" + user + "' and @pass='" + pass + "']";
return (boolean)xpath.evaluate(expression, doc, XPathConstants.BOOLEAN);
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
public boolean authenticate(HttpServletRequest req, XPath xpath, Document doc) throws XPathExpressionException {
String user = request.getParameter("user");
String pass = request.getParameter("pass");
String expression = "/users/user[@name=$user and @pass=$pass]";
xpath.setXPathVariableResolver(v -> {
switch (v.getLocalPart()) {
case "user":
return user;
case "pass":
return pass;
default:
throw new IllegalArgumentException();
}
});
return (boolean)xpath.evaluate(expression, doc, XPathConstants.BOOLEAN);
}
----
=== How does this work?
include::../../common/fix/validation.adoc[]
In the example, a parameterized XPath query is created as an XPath Factory
resolver to insert untrusted data to the request in a safe way, similarly to
parametrized SQL queries.