51 lines
1.6 KiB
Plaintext
51 lines
1.6 KiB
Plaintext
![]() |
=== How to fix it in Java SE
|
||
|
|
||
|
The following non-compliant code is vulnerable to LDAP injections because untrusted data is
|
||
|
concatenated to an LDAP query without prior sanitization or validation.
|
||
|
|
||
|
[cols="a"]
|
||
|
|===
|
||
|
h| Non-compliant code example
|
||
|
|
|
||
|
[source,java]
|
||
|
----
|
||
|
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()); // Noncompliant
|
||
|
return results.hasMore();
|
||
|
}
|
||
|
----
|
||
|
h| Compliant solution
|
||
|
|
|
||
|
[source,java]
|
||
|
----
|
||
|
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 automatically.
|
||
|
|
||
|
|
||
|
In the compliant solution example, the `search` function allows to safely parameterize the query.
|