Improper Neutralization of Special Elements used in an LDAP Query ('LDAP Injection')
Description
LDAP Injection is a vulnerability that occurs when software constructs all or part of an LDAP query using externally-influenced input from an upstream component, but does not neutralize or incorrectly neutralizes special elements that could modify the intended LDAP query. LDAP (Lightweight Directory Access Protocol) is widely used for authentication, authorization, and directory services in enterprise environments. Attackers exploit this vulnerability by injecting LDAP metacharacters such as parentheses (), asterisks *, pipes |, ampersands &, and equals signs = to manipulate queries. This can enable authentication bypass, unauthorized data access, information disclosure about directory structure, and in some cases modification of directory entries.
Risk
LDAP injection poses significant risks in enterprise environments where LDAP directories often contain sensitive organizational data including user credentials, group memberships, access permissions, and personal information. Successful attacks can bypass authentication mechanisms, allowing unauthorized access to protected resources. Attackers can enumerate directory contents to map organizational structure, identify high-value targets, and discover privileged accounts. In writable LDAP scenarios, attackers may modify directory entries to escalate privileges, create backdoor accounts, or alter access controls. The prevalence of Active Directory in corporate environments makes LDAP injection a high-value target for attackers seeking domain compromise.
Solution
Use parameterized LDAP queries or APIs that automatically escape special characters. When constructing LDAP filters, encode all LDAP special characters including *, (, ), \, and null characters using their escaped representations (e.g., * becomes \2a, ( becomes \28). Implement strict input validation using allowlists for expected data formats. Validate that usernames, search terms, and other inputs conform to expected patterns before use in queries. Apply the principle of least privilege to LDAP service accounts, limiting their permissions to only what is necessary. Consider using LDAP libraries that provide built-in injection protection.
Common Consequences
| Impact | Details |
|---|---|
| Confidentiality | Scope: Confidentiality Attackers can extract sensitive directory information including user details, group memberships, organizational structure, and potentially password hashes. |
| Access Control | Scope: Access Control Authentication bypass through LDAP injection enables unauthorized access to protected systems and resources without valid credentials. |
| Integrity | Scope: Integrity In directories with write access, attackers can modify entries, change group memberships, alter access controls, or create unauthorized accounts. |
Example Code + Solution Code
Vulnerable Code
// VULNERABLE: Direct string concatenation in LDAP query
public boolean authenticate(String username, String password) {
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.example.com:389");
try {
DirContext ctx = new InitialDirContext(env);
// VULNERABLE: User input directly in filter
// Attack: username=*)(uid=*))(|(uid=*
// Results in: (&(uid=*)(uid=*))(|(uid=*)(userPassword=...))
String filter = "(&(uid=" + username + ")(userPassword=" + password + "))";
SearchControls controls = new SearchControls();
NamingEnumeration<SearchResult> results = ctx.search("ou=users,dc=example,dc=com", filter, controls);
return results.hasMore();
} catch (NamingException e) {
return false;
}
}
Fixed Code
public boolean authenticate(String username, String password) {
// Validate input format
if (!username.matches("^[a-zA-Z0-9._-]+$")) {
throw new IllegalArgumentException("Invalid username format");
}
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://ldap.example.com:389");
try {
DirContext ctx = new InitialDirContext(env);
// SAFE: Escape LDAP special characters
String safeUsername = escapeLDAPSearchFilter(username);
String safePassword = escapeLDAPSearchFilter(password);
String filter = "(&(uid=" + safeUsername + ")(userPassword=" + safePassword + "))";
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setReturningAttributes(new String[]{"uid"});
NamingEnumeration<SearchResult> results = ctx.search("ou=users,dc=example,dc=com", filter, controls);
return results.hasMore();
} catch (NamingException e) {
return false;
}
}
// LDAP special character escaping function
public static String escapeLDAPSearchFilter(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();
}
Exploited in the Wild
Corporate Directory Enumeration Attacks (Enterprise, Ongoing)
LDAP injection is frequently used by attackers during reconnaissance phases of targeted attacks against enterprises using Active Directory. Attackers exploit LDAP injection in web applications that authenticate against AD to enumerate users, groups, and organizational units, gathering intelligence for subsequent attacks.
Authentication Bypass in Enterprise Applications (Various, Historical)
Multiple enterprise applications including CRM systems, HR platforms, and identity management solutions have been found vulnerable to LDAP injection, enabling authentication bypass and unauthorized access to sensitive business data.
Tools to test/exploit
-
Burp Suite — web security testing platform with capabilities for testing LDAP injection through parameter manipulation.
-
LDAP Injection Payloads — collection of LDAP injection payloads for various attack scenarios.
-
ldapsearch — command-line tool for manual LDAP query testing and injection verification.
CVE Examples
-
CVE-2023-2825 — GitLab LDAP injection allowing unauthorized access to user information.
-
CVE-2021-45105 — Apache Log4j LDAP injection related to JNDI lookup functionality.
References
-
MITRE. "CWE-90: Improper Neutralization of Special Elements used in an LDAP Query." https://cwe.mitre.org/data/definitions/90.html
-
OWASP. "LDAP Injection Prevention Cheat Sheet." https://cheatsheetseries.owasp.org/cheatsheets/LDAP_Injection_Prevention_Cheat_Sheet.html
-
OWASP. "LDAP Injection." https://owasp.org/www-community/attacks/LDAP_Injection