Skip to main content

Free 30-min security demo  — We'll scan your real code and show live findings, no commitment Book Now

Offensive360
Academy LDAP Injection
Intermediate · 20 min

LDAP Injection

Understand how unsanitized LDAP filter strings enable authentication bypass and directory enumeration.

1 LDAP Injection Mechanics

LDAP (Lightweight Directory Access Protocol) is used for authentication in enterprise environments. When filter strings are built by concatenating user input, attackers can inject LDAP metacharacters to alter query logic.

LDAP special characters: ( ) | & = * \ NUL

Vulnerable example (Java):

String filter = "(&(uid=" + username + ")(userPassword=" + password + "))";
NamingEnumeration results = ctx.search("ou=users,dc=example,dc=com", filter, controls);

An attacker can send username admin)(&( to produce the filter (&(uid=admin)(&()(userPassword=anything)), which matches regardless of the password.

The * wildcard enables enumeration: sending a* as username matches all users starting with "a".

2 Fixing LDAP Injection

The correct fix is to escape all LDAP special characters per RFC 4515 before using user input in filter strings. Even better, use a library that supports parameterized filters.

Escape function (Java):

public static String escapeLDAP(String input) {
  StringBuilder sb = new StringBuilder();
  for (char c : input.toCharArray()) {
    switch (c) {
      case "\\": sb.append("\\5c"); break;
      case "*":  sb.append("\\2a"); break;
      case "(":  sb.append("\\28"); break;
      case ")":  sb.append("\\29"); break;
      case "\0": sb.append("\\00"); break;
      default:   sb.append(c);
    }
  }
  return sb.toString();
}

String filter = "(&(uid=" + escapeLDAP(username) + ")(userPassword=" + escapeLDAP(password) + "))";

Defense checklist:

  • Escape all LDAP metacharacters (RFC 4515)
  • Use vetted LDAP libraries with parameterized filter support
  • Apply input allowlisting (alphanumeric only for usernames)
  • Run LDAP service with least-privilege bind DN

Knowledge Check

0/3 correct
Q1

Which character in user input is most dangerous in an LDAP filter?

Q2

What RFC defines the escaping rules for LDAP filter strings?

Q3

An attacker sends username=admin)(&( — what is the goal?

Code Exercise

Sanitize LDAP Input

The function builds an LDAP filter by concatenating user input. Add an escape function that replaces ( ) * \ and null bytes with their RFC 4515 hex escapes.

javascript