This site is the archived OWASP Foundation Wiki and is no longer accepting Account Requests.
To view the new OWASP Foundation website, please visit https://owasp.org

Difference between revisions of "Preventing LDAP Injection in Java"

From OWASP
Jump to: navigation, search
 
m
Line 1: Line 1:
 
Performing LDAP queries requires correctly escaping certain meta-characters. Both the distinguished name (DN) and the search filter have their own sets of meta-characters.  In the case of Java, it is also necessary to escape any JNDI meta-characters, since java uses JNDI to perform LDAP queries.  The examples below present Java methods that could be used to perform this escaping:
 
Performing LDAP queries requires correctly escaping certain meta-characters. Both the distinguished name (DN) and the search filter have their own sets of meta-characters.  In the case of Java, it is also necessary to escape any JNDI meta-characters, since java uses JNDI to perform LDAP queries.  The examples below present Java methods that could be used to perform this escaping:
  
 +
<em>Note: This is untested code</em>
 
   public String escapeDN (String name) {
 
   public String escapeDN (String name) {
 
         //From RFC 2253 and the / character for JNDI
 
         //From RFC 2253 and the / character for JNDI

Revision as of 04:04, 3 July 2006

Performing LDAP queries requires correctly escaping certain meta-characters. Both the distinguished name (DN) and the search filter have their own sets of meta-characters. In the case of Java, it is also necessary to escape any JNDI meta-characters, since java uses JNDI to perform LDAP queries. The examples below present Java methods that could be used to perform this escaping:

Note: This is untested code

 public String escapeDN (String name) {
       //From RFC 2253 and the / character for JNDI
       final char[] META_CHARS = {'+', '"', '<', '>', ';', '/'};
       String escapedStr = new String(name);
       //Backslash is both a Java and an LDAP escape character, so escape it first
       escapedStr = escapedStr.replaceAll("\\\\","\\\\");
       //Positional characters - see RFC 2253
       escapedStr = escapedStr.replaceAll("^#","\\\\#");
       escapedStr = escapedStr.replaceAll("^ | $","\\\\ ");
       for (int i=0;i < META_CHARS.length;i++) {
           escapedStr = escapedStr.replaceAll("\\"+META_CHARS[i],"\\\\" + META_CHARS[i]);
       }
       return escapedStr;
   }

Note, that the backslash character is a Java String literal and a regular expression escape character.

  public String escapeSearchFilter (String filter) {
       //From RFC 2254
       String escapedStr = new String(filter);
       escapedStr = escapedStr.replaceAll("\\\\","\\\\5c");
       escapedStr = escapedStr.replaceAll("\\*","\\\\2a");
       escapedStr = escapedStr.replaceAll("\\(","\\\\28");
       escapedStr = escapedStr.replaceAll("\\)","\\\\29");
       return escapedStr;
   }