Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

A white-list can be used to restrict input to a list of valid characters. The list of characters Characters that must not be allowed in a excluded from white-list include lists — including JNDI meta-characters and LDAP special characters . They are tabulated below:

Character

Name

' and "

Single and double quote

/ and \

Forward-slash and back-slash

\ \

Double slashes*

space

Space character at beginning or end of string

#

Hash character at the beginning of the string

< and >

Angle brackets

, and ;

Comma and semi-colon

+ and *

Addition and multiplication operators

( and )

Round braces

\u0000

Unicode NULL character

...

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 responsible for filtering used to filter the result set on the basis of for those entries that match a user name and password that supplied by the caller must supply. If When a malicious user enters specially crafted input, this elementary authentication scheme fails to confine the output of the search query to the information that for which the user is privileged to has access privileges. For example, the user may see any record beginning with "S" by supplying the values S* and * for the string variables userSN and UserPassword respectively. Consequently, an attacker can discover information about any user can be gleaned without any prior knowledge of a particular user name and password pair.

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 = sr.getAttributes();
        Attribute attr = attrs.get("cn");
        System.out.println(attr.get());
        attr = attrs.get("mail");
        System.out.println(attr.get());
      }
      dctx.close();
    } catch (NamingException e) {
      // Handle
    }
  }
}

...

This compliant solution uses a white-list to validate sanitize user input so that the filter string contains only valid characters appear in the filter string. For example, userSN may contain only letters and spaces whereas a password may contain alphanumeric characters.

Code Block
bgColor#ccccff
// String userSN = "Sherlock Holmes"; // Valid
// String userPassword = "secret2";   // Valid

sc.setSearchScope(SearchControls.SUBTREE_SCOPE);
String base = "dc=example,dc=com";
           
if(!userSN.matches("[\\w\\s]*") || !userPassword.matches("[\\w]*")) {
  throw new IllegalArgumentException("Invalid input");
} 
            	
String filter = "(&(sn = " + userSN + ")(userPassword=" + userPassword + "))";      

If it is desired to include special characters in When a database field such as a password must include special characters, it is critical to ensure that the authentic data is stored in a sanitized form in the database and also that any user input is escaped and transformed into the equivalent form, normalized before the validation or comparison takes place. The We discourage use of characters that have special meanings in JNDI and LDAP is strongly discouraged unless in the absence of a comprehensive normalization and white-listing based routine is employed to encode and escape the characters. Refer to the guideline IDS04-J. Properly encode or escape output for examples on output encoding and escaping. The special character Special characters must be transformed to a sanitized safe value before adding it values before they are added to the white-list expression against which input is required to will be validated. Likewise, sanitization normalization of user input (escaping and encoding) should occur before the validation step.

Risk Assessment

Failing Failure to sanitize untrusted input can result in information disclosure and privilege escalation.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

IDS11-J

high

likely

medium

P18

L1

Automated Detection

...

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

...