WebApp Sec mailing list archives
Escaping LDAP queries
From: Stephen de Vries <stephen () corsaire com>
Date: Tue, 16 Aug 2005 16:04:49 +0100
Hi all,I'm looking for methods to properly escape LDAP queries in a Java environment. From the RFC's it appears that both the distinguished name (DN) and the search filter have their own sets of meta- characters. In the case of performing the query through JNDI, it is also necessary to escape any JNDI meta-characters, since java uses JNDI to perform LDAP queries. I've put together the following pieces of code and would appreciate any comment on these. Also, are there any built in functions (or available libraries) that will automatically perform the escaping instead of this manual approach?
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"); return escapedStr; } thanks, Stephen
Current thread:
- Escaping LDAP queries Stephen de Vries (Aug 16)