Injection Attacks: The Complete 2020 Guide

LDAP Injections - Defenses

Primary LDAP defense

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;
}

Secondary LDAP Defenses

  • Use frameworks that automatically protect from LDAP injections
     
  • Allowlist input validation
     
  • Use least privileges

Escaping

The best defense: avoid putting user inputs into LDAP queries...if that's not possible, escape any untrusted data.

Escaping

  • Parentheses
  • Asterisks
  • Logical operators (AND "&", OR "|" and NOT "!")
  • Relational operators (=, <=, >=, ~=)

For example, filter:

Hash signs (#), commas, semicolons, etc...)

Frameworks

There are frameworks made to automatically escape values before handing them off to LDAP queries.

Input Validation

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.

Least Privilege

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.

Code Review

Check for any queries to LDAP.

Make sure those queries are properly escaping special characters.

Automated Tools

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.

Defending against LDAP Injections

By Christophe Limpalair

Defending against LDAP Injections

  • 413