...
This noncompliant code example allows a caller of the method searchRecord()
to search for a record in the directory using the LDAP protocol. The string filter
is used to filter the result set for those entries that match a user name and password supplied by the caller. When a malicious user enters specially crafted input, as outlined previously, this elementary authentication scheme fails to confine the output of the search query to the information for which the user has access privileges.
Code Block | ||
---|---|---|
| ||
// String userSN = "S*"; // Invalid // String userPassword = "*"; // Invalid public class LDAPInjection { private void searchRecord(String userSN, String userPassword) throws NamingException { Hashtable<String, String> env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); try { DirContext dctx = new InitialDirContext(env); SearchControls sc = new SearchControls(); String[] attributeFilter = {"cn", "mail"}; sc.setReturningAttributes(attributeFilter); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); String base = "dc=example,dc=com"; // The following resolves to (&(sn=S*)(userPassword=*)) String filter = "(&(sn=" + userSN + ")(userPassword=" + userPassword + "))"; NamingEnumeration<?> results = dctx.search(base, filter, sc); while (results.hasMore()) { SearchResult sr = (SearchResult) results.next(); Attributes attrs = (Attributes) sr.getAttributes(); Attribute attr = (Attribute) attrs.get("cn"); System.out.println(attr); attr = (Attribute) attrs.get("mail"); System.out.println(attr); } dctx.close(); } catch (NamingException e) { // Forward to handler } } } |
When a malicious user enters specially crafted input, as outlined previously, this elementary authentication scheme fails to confine the output of the search query to the information for which the user has access privileges.
Compliant Solution
This compliant solution uses a whitelist white-list to sanitize user input so that the filter
string contains only valid characters. In this code, userSN
may contain only letters and spaces, whereas a password may contain only alphanumeric characters.
...