Ldap Injection in APIs
What is Ldap Injection?
LDAP (Lightweight Directory Access Protocol) injection is a server-side injection vulnerability that occurs when an application constructs LDAP queries using untrusted user input without proper sanitization. Attackers can manipulate these queries to access, modify, or delete directory information, bypass authentication, or extract sensitive data.
The vulnerability arises because LDAP query syntax uses special characters like parentheses ( ), asterisks *, ampersands &, and pipes | as logical operators. When user input containing these characters is concatenated directly into LDAP filters, attackers can alter the query logic.
For example, consider this vulnerable code:
username = request.getParameter("username");
filter = "(uid=" + username + ")";
// LDAP query becomes: (uid=john)If an attacker submits john)(uid=*)* as the username, the filter becomes:
(uid=john)(uid=*)This effectively returns all entries where uid exists, potentially exposing the entire directory.
How Ldap Injection Affects APIs
APIs that interact with LDAP directories are particularly vulnerable when they use user input to construct search filters, bind operations, or modify directory entries. Common API endpoints that may be affected include authentication services, user profile lookups, and directory search functions.
Attackers can exploit LDAP injection in APIs to:
- Bypass authentication: By manipulating the filter to always return true, attackers can authenticate as any user without knowing the password
- Extract sensitive directory information: Enumerate all users, groups, or other directory objects
- Modify directory data: If the API allows write operations, attackers could alter user attributes, group memberships, or permissions
- Perform denial of service: Craft queries that consume excessive resources
- Access internal systems: Many organizations use LDAP for internal authentication, making this a potential entry point to corporate networks
A particularly dangerous scenario occurs when APIs use LDAP for authentication but fail to properly handle the Distinguished Name (DN) construction. An attacker might submit a crafted username that includes additional LDAP operations, effectively becoming any user in the directory.
How to Detect Ldap Injection
Detecting LDAP injection requires both static code analysis and dynamic testing. Here's what to look for:
- Input concatenation in LDAP filters: Search for code that builds LDAP queries by concatenating user input without validation
- Special character usage: Look for unescaped parentheses, asterisks, and other LDAP metacharacters in user input
- Dynamic DN construction: Code that builds Distinguished Names from user input is particularly risky
Dynamic testing involves sending payloads with LDAP metacharacters and observing the responses:
Payloads to test:
- * - matches any value
- )( - breaks filter logic
- & - logical AND
- | - logical OR
- ! - logical NOT
- *admin* - wildcard search
- john)(cn=*
middleBrick scans for LDAP injection by testing API endpoints that accept parameters likely used in LDAP queries. The scanner sends a battery of LDAP metacharacter payloads and analyzes responses for signs of injection, such as unexpected data disclosure or authentication bypass. For authenticated APIs, middleBrick tests both unauthenticated and authenticated endpoints to ensure comprehensive coverage of the attack surface.
The scanner also checks for proper error handling—LDAP injection often causes backend errors that leak information about the directory structure or query syntax.
Prevention & Remediation
Preventing LDAP injection requires a defense-in-depth approach:
- Use parameterized LDAP queries: Most LDAP libraries support parameterized queries that separate code from data. This is the most effective prevention method.
- Input validation and sanitization: Implement strict validation of user input. Only allow expected characters and reject or escape special LDAP characters.
- Escape special characters: Use your LDAP library's escaping functions for any dynamic input that must be included in queries.
- Principle of least privilege: Ensure the LDAP account used by the API has only the minimum permissions necessary.
- Input length limits: Impose reasonable limits on input length to prevent resource exhaustion attacks.
Here's a secure implementation using parameterized queries:
// Secure approach using parameterized queries
SearchControls controls = new SearchControls();
String filter = "(uid={0})"; // {0} is a placeholder
String[] params = { username }; // User input as a parameter
NamingEnumeration<SearchResult> results = ctx.search(baseDN, filter, params, controls);
If parameterized queries aren't available, use proper escaping:
// Escaping special characters
String escapedUsername = escapeLDAPFilter(username);
String filter = "(uid=" + escapedUsername + ")";
// Example escape function
public static String escapeLDAPFilter(String input) {
StringBuilder sb = new StringBuilder();
for (char c : input.toCharArray()) {
switch (c) {
case '\u0000': sb.append("\\00"); break;
case '(': sb.append("\\28"); break;
case ')': sb.append("\\29"); break;
case '*': sb.append("\\2a"); break;
case '\': sb.append("\\5c"); break;
default: sb.append(c); break;
}
}
return sb.toString();
}
Always validate input against a whitelist of allowed characters when possible, and implement proper error handling that doesn't reveal LDAP query structure or directory information.
Real-World Impact
LDAP injection vulnerabilities have been documented in numerous enterprise applications and APIs. While specific high-profile breaches are rarely disclosed in detail, the vulnerability class is well-understood and actively exploited in penetration testing engagements.
The OWASP API Security Top 10 includes "API1: Broken Object Level Authorization" which encompasses LDAP injection as a specific instance where directory access controls are bypassed. CVE-2021-39382 documented an LDAP injection vulnerability in a popular enterprise application that could allow attackers to bypass authentication and access sensitive directory information.
The impact of successful LDAP injection can be severe:
- Data breach: Exposure of user credentials, personal information, and organizational structure
- Authentication bypass: Complete compromise of directory-based authentication systems
- Privilege escalation: Modification of group memberships or role assignments
- Compliance violations: Breaches of GDPR, HIPAA, or other regulations due to unauthorized data access
Organizations should treat LDAP injection as a critical vulnerability requiring immediate remediation, especially in APIs that handle authentication or access sensitive directory information.