Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: removed compilation bug

...

Code Block
bgColor#FFCCCC
// 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.

...