Christophe Limpalair
Co-Founder of Cybr, and Course Author
Escape all variables using the right LDAP encoding functions
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;
}
The best defense: avoid putting user inputs into LDAP queries...if that's not possible, escape any untrusted data.
For example, filter:
Hash signs (#), commas, semicolons, etc...)
There are frameworks made to automatically escape values before handing them off to LDAP queries.
In addition to escaping, it's a good idea to perform input validation when possible.
Allowlists are not always effective or can prevent legitimate inputs. That's why they are a secondary defense option.
You should always follow the principle of least privilege.
Even if an attacker gains access, they can only do as much damage as their permissions allow.
Check for any queries to LDAP.
Make sure those queries are properly escaping special characters.
Automated tools can be implemented to scan your code before it goes out to production.
Example: OWASP ZAP contains modules that can detect LDAP injection issues.
By Christophe Limpalair