PrabaharanKathiresan
PrabaharanKathiresan

Reputation: 1129

Sanitizing the LDAP Queries in Java

can someone guide me on below 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;
   }


 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");
       escapedStr = escapedStr.replaceAll("\\\\"+Character.toString('\\u0000'), "\\\\\\\\00");
       return escapedStr;
   } 

In the above code I can understand the LDAP baseDN and searchFilter values are sanitized before going to execute but I can not understand why and how the methods will work...

Thanks in Advance!!!

Upvotes: 0

Views: 1583

Answers (1)

jwilleke
jwilleke

Reputation: 10996

Parsing a DN in a generic fashion is a daunting task. I would recommend you use a specific LDAP API like UnboundID or Apache LDAP.

If you would like to see some of the complexities check out: https://docs.ldap.com/ldap-sdk/docs/javadoc/src-html/com/unboundid/ldap/sdk/DN.html#line.280

-jim

Upvotes: 1

Related Questions