include::../description.adoc[]

== Noncompliant Code Example

----
public boolean authenticate(javax.servlet.http.HttpServletRequest request, DirContext ctx) throws NamingException { 
  String user = request.getParameter("user"); 
  String pass = request.getParameter("pass"); 

  String filter = "(&(uid=" + user + ")(userPassword=" + pass + "))"; // Unsafe 

  // If the special value "*)(uid=*))(|(uid=*" is passed as user, authentication is bypassed 
  // Indeed, if it is passed as a user, the filter becomes: 
  // (&(uid=*)(uid=*))(|(uid=*)(userPassword=...))
  // as uid=* match all users, it is equivalent to:
  // (|(uid=*)(userPassword=...))
  // again, as uid=* match all users, the filter becomes useless

  NamingEnumeration<SearchResult> results = ctx.search("ou=system", filter, new SearchControls()); // Noncompliant
  return results.hasMore();
}
----

== Compliant Solution

----
public boolean authenticate(javax.servlet.http.HttpServletRequest request, DirContext ctx) throws NamingException { 
  String user = request.getParameter("user"); 
  String pass = request.getParameter("pass"); 

  String filter = "(&(uid={0})(userPassword={1}))"; // Safe

  NamingEnumeration<SearchResult> results = ctx.search("ou=system", filter, new String[]{user, pass}, new SearchControls());
  return results.hasMore();
}
----

== See

* https://owasp.org/Top10/A03_2021-Injection/[OWASP Top 10 2021 Category A3] - Injection
* https://www.owasp.org/index.php/Top_10-2017_A1-Injection[OWASP Top 10 2017 Category A1] - Injection
* https://www.ietf.org/rfc/rfc4514.txt[RFC 4514] - LDAP: String Representation of Distinguished Names
* https://www.ietf.org/rfc/rfc4515.txt[RFC 4515] - LDAP: String Representation of Search Filters
* https://cwe.mitre.org/data/definitions/90.html[MITRE, CWE-90] - Improper Neutralization of Special Elements used in an LDAP Query ('LDAP Injection')
* https://wiki.sei.cmu.edu/confluence/x/bjZGBQ[CERT, IDS54-J.] - Prevent LDAP injection

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

include::../message.adoc[]

'''
== Comments And Links
(visible only on this page)

include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]
