53 lines
2.0 KiB
Plaintext

== How to fix it in Java SE
=== Code examples
The following noncompliant code is vulnerable to LDAP injections because untrusted data is
concatenated to an LDAP query without prior sanitization or validation.
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
public boolean authenticate(HttpServletRequest req, DirContext ctx) throws NamingException {
String user = req.getParameter("user");
String pass = req.getParameter("pass");
String filter = "(&(uid=" + user + ")(userPassword=" + pass + "))";
NamingEnumeration<SearchResult> results = ctx.search("ou=system", filter, new SearchControls());
return results.hasMore();
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
public boolean authenticate(HttpServletRequest req, DirContext ctx) throws NamingException {
String user = req.getParameter("user");
String pass = req.getParameter("pass");
String filter = "(&(uid={0})(userPassword={1}))";
NamingEnumeration<SearchResult> results = ctx.search("ou=system", filter, new String[]{user, pass}, new SearchControls());
return results.hasMore();
}
----
=== How does this work?
include::../../common/fix/validation.adoc[]
For Java, OWASP's functions
https://www.javadoc.io/doc/org.owasp.esapi/esapi/latest/org/owasp/esapi/Encoder.html#encodeForDN-java.lang.String-[`encodeForDN`]
and
https://www.javadoc.io/doc/org.owasp.esapi/esapi/latest/org/owasp/esapi/Encoder.html#encodeForLDAP-java.lang.String-[`encodeForLDAP`]
allow sanitizing these characters and should be used: Remember that it is never
a good practice to reinvent the wheel and write your own encoders. +
However, if it is not possible to use these libraries,
https://github.com/bcgit/bc-java/blob/r1rv74/prov/src/main/java/org/bouncycastle/jce/provider/X509LDAPCertStoreSpi.java#L52-L70[here]
is an example of an encoder implementation for LDAP search filters, in the `Bouncy Castle Java` framework.
In the compliant solution example, the `search` function allows to safely parameterize the query.