...
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.get()); attr = (Attribute) attrs.get("mail"); System.out.println(attr.get()); } dctx.close(); } catch (NamingException e) { // Forward to handler } } } |
Compliant Solution
This compliant solution uses a whitelist 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.
...