LDAP Injection
LDAP Injection is a critical vulnerability that exploits applications using Lightweight Directory Access Protocol for authentication and data retrieval. By manipulating LDAP queries through unsanitized user input, attackers can bypass authentication, extract sensitive directory information, and compromise enterprise systems.
What Is LDAP Injection?
LDAP Injection is a code injection attack that targets applications using the Lightweight Directory Access Protocol (LDAP) to authenticate users or query directory services. It occurs when user-supplied input is improperly sanitized before being incorporated into LDAP queries. LDAP is widely used in enterprise environments for centralized authentication, user management, and directory services through systems like Microsoft Active Directory, OpenLDAP, and Apache Directory Server.
The vulnerability arises when applications construct LDAP queries by directly concatenating user input into LDAP filter strings. Similar to SQL Injection, LDAP Injection exploits the lack of distinction between data and code. An attacker can inject LDAP metacharacters such as parentheses, asterisks, and boolean operators to alter the logical structure of the query. This can transform a legitimate authentication check into a query that always returns true, or modify search filters to extract information the attacker should not have access to.
While LDAP Injection is less commonly discussed than SQL Injection, it poses an equally serious threat to organizations. Because LDAP directories often contain highly sensitive information including employee credentials, organizational structure, email addresses, phone numbers, and group memberships, a successful LDAP Injection attack can provide attackers with a blueprint of the entire organization and a pathway to privilege escalation.
How It Works
The application presents a login form or search interface that collects credentials or search criteria from the user. This input will be used to construct an LDAP filter to authenticate a user or search the directory.
The application builds an LDAP filter by directly concatenating user input without proper sanitization or escaping. For example, a filter might be constructed as: (&(uid=USERNAME)(userPassword=PASSWORD)) where USERNAME and PASSWORD are replaced with user-supplied values.
Instead of providing a legitimate username, the attacker enters a specially crafted string such as *)(uid=*))(|(uid=* or admin)(&. These strings contain LDAP metacharacters designed to break out of the intended filter structure and inject malicious logic.
The resulting LDAP filter becomes logically different from what was intended. For instance, injecting * as a username can create a filter like (&(uid=*)(userPassword=anything)), which matches any user, or injecting admin)(& might comment out the password check entirely, creating (&(uid=admin)(&)(userPassword=...)).
The LDAP server processes the modified filter without detecting the manipulation. It may return all directory entries, authenticate an attacker without a valid password, or leak sensitive organizational data, granting unauthorized access to the system or directory information.
Vulnerable Code Example
@RestController
public class LdapAuthController {
@Autowired
private LdapTemplate ldapTemplate;
@PostMapping("/ldap-login")
public ResponseEntity<?> authenticate(@RequestBody LoginRequest req) {
// VULNERABLE: User input is directly concatenated
// into the LDAP filter string
String filter = "(&(uid=" + req.getUsername()
+ ")(userPassword=" + req.getPassword() + "))";
try {
List<Object> result = ldapTemplate.search(
"", filter, new AttributesMapper<Object>() {
public Object mapFromAttributes(Attributes attrs) {
return attrs;
}
}
);
if (!result.isEmpty()) {
return ResponseEntity.ok(Map.of("user", req.getUsername()));
}
return ResponseEntity.status(401).body("Invalid credentials");
} catch (Exception e) {
return ResponseEntity.status(500).body("Error");
}
}
}
// An attacker can bypass authentication by submitting:
// username: *
// password: anything
//
// Resulting LDAP filter:
// (&(uid=*)(userPassword=anything))
//
// The wildcard * matches any user, bypassing authentication.Secure Code Example
@RestController
public class LdapAuthController {
@Autowired
private LdapTemplate ldapTemplate;
@PostMapping("/ldap-login")
public ResponseEntity<?> authenticate(@RequestBody LoginRequest req) {
// SECURE: Use LdapQueryBuilder with proper encoding
// User input is escaped using LdapEncoder.filterEncode()
String encodedUsername = LdapEncoder.filterEncode(req.getUsername());
String encodedPassword = LdapEncoder.filterEncode(req.getPassword());
LdapQuery query = LdapQueryBuilder.query()
.where("uid").is(encodedUsername)
.and("userPassword").is(encodedPassword);
try {
List<Object> result = ldapTemplate.search(
query, new AttributesMapper<Object>() {
public Object mapFromAttributes(Attributes attrs) {
return attrs;
}
}
);
if (!result.isEmpty()) {
return ResponseEntity.ok(Map.of("user", req.getUsername()));
}
return ResponseEntity.status(401).body("Invalid credentials");
} catch (Exception e) {
return ResponseEntity.status(500).body("Error");
}
}
}
// With LdapEncoder.filterEncode(), all LDAP metacharacters
// are properly escaped. Even if an attacker submits: *
// The LDAP server looks for a user literally named: \2a
// (the escaped form of *), preventing the injection attack.Types of LDAP Injection
Authentication Bypass
The most common LDAP injection attack vector. Attackers inject wildcards (*), boolean operators, or logical tautologies into LDAP authentication filters to bypass credential checks entirely. By manipulating the filter structure, attackers can authenticate as any user, including administrators, without knowing valid passwords. For example, injecting * as a username creates a filter that matches all users, or injecting admin)(|(uid= can short-circuit password validation logic.
Data Exfiltration
Attackers modify LDAP search filters to extract sensitive directory information beyond their authorization level. By injecting carefully crafted filter logic, they can enumerate user accounts, retrieve email addresses, phone numbers, group memberships, organizational hierarchies, and other directory attributes. LDAP directories often contain a complete map of an organization's structure, making this attack particularly dangerous for reconnaissance and social engineering attacks. Techniques include wildcard injection and boolean condition manipulation to expand search results.
Blind LDAP Injection
Used when the application does not return LDAP query results or error messages directly. Attackers infer information by observing application behavior, such as response time differences or success/failure messages. By crafting filters with boolean conditions and monitoring responses, attackers can extract directory data one character at a time. For instance, testing if a username starts with 'a' versus 'b' based on whether authentication succeeds or specific error messages appear. This technique is slower but effective when direct data retrieval is not possible.
Impact
A successful LDAP Injection attack can compromise the entire authentication infrastructure of an organization. Because LDAP directories serve as the central repository for identity and access management, the consequences can be severe and far-reaching.
Attackers can gain access to any account, including administrative and privileged accounts, without knowing valid credentials. This provides immediate access to protected systems and applications that rely on the LDAP directory for authentication, enabling attackers to impersonate legitimate users across the entire organization.
LDAP directories contain highly sensitive organizational data including employee names, email addresses, phone numbers, physical locations, organizational charts, group memberships, and access permissions. Extraction of this data provides attackers with detailed intelligence for further attacks, social engineering, and lateral movement within the network.
By identifying and accessing administrative accounts or manipulating group membership queries, attackers can escalate their privileges within the directory structure. This can grant access to sensitive resources, allow modification of directory entries, and potentially compromise the entire Active Directory or LDAP infrastructure.
The information extracted from LDAP directories provides attackers with a complete organizational blueprint. This includes understanding the corporate hierarchy, identifying high-value targets like executives and system administrators, mapping network resources, and discovering relationships between users and systems. This intelligence enables sophisticated spear-phishing campaigns, targeted social engineering, and strategic network penetration.
Prevention Checklist
Always escape user input using appropriate encoding functions before incorporating it into LDAP queries. In Java, use LdapEncoder.filterEncode() or LdapEncoder.nameEncode(). In .NET, use LdapEncoder.FilterEncode(). These functions properly escape LDAP metacharacters such as * ( ) \ NUL and prevent filter manipulation. Never use string concatenation or manual escaping.
Leverage LDAP query builders and frameworks that support parameterized queries. Spring LDAP's LdapQueryBuilder, for example, automatically handles encoding and query construction safely. These abstractions separate query logic from data, similar to prepared statements in SQL, ensuring user input is treated strictly as data.
Enforce allowlists for expected input formats. Usernames should match specific patterns (e.g., alphanumeric with limited special characters), and should never contain LDAP metacharacters like * ( ) \ |. Reject any input that does not conform to expected formats. While encoding is the primary defense, input validation provides defense-in-depth.
Configure application LDAP bind accounts with minimum necessary permissions. Applications should use read-only accounts that can only search specific directory subtrees and access only required attributes. Avoid binding as administrator or using privileged accounts. This limits the scope of damage if an injection attack succeeds.
Restrict LDAP server capabilities to only what is necessary. Disable anonymous binds, limit searchable attributes, restrict base DN search scope, and configure appropriate access controls on directory entries. Enable logging of LDAP queries for security monitoring and anomaly detection to identify potential injection attempts.
Perform regular security assessments focused on LDAP query construction. Use static analysis tools (SAST) to identify unsafe LDAP filter construction patterns. Conduct penetration testing with LDAP injection payloads. Review all code that constructs LDAP queries to ensure proper encoding is applied. Include LDAP injection scenarios in automated security testing.
Real-World Examples
Cisco Prime Infrastructure
Multiple LDAP injection vulnerabilities were discovered in Cisco Prime Infrastructure that allowed remote attackers to bypass authentication and execute arbitrary LDAP queries. The vulnerabilities existed in the web interface's authentication mechanism, which improperly constructed LDAP filters using user-supplied credentials. Attackers could exploit this to gain administrative access to the network management platform.
ManageEngine ServiceDesk Plus
LDAP injection vulnerabilities were identified in ManageEngine ServiceDesk Plus, a popular IT service management platform. The flaws allowed attackers to manipulate LDAP queries in the authentication system, potentially bypassing login controls and accessing sensitive directory information. The vulnerability affected enterprise installations using LDAP for centralized authentication, exposing organizational user data.
Pulse Secure VPN
Critical LDAP injection vulnerabilities were discovered in Pulse Secure VPN appliances, which are widely deployed in enterprise environments. The vulnerabilities allowed unauthenticated attackers to bypass authentication by injecting malicious LDAP filters through the VPN authentication interface. Exploitation could lead to complete compromise of the VPN gateway and access to internal corporate networks, affecting thousands of organizations globally.
VMware vCenter Server
VMware disclosed an LDAP injection vulnerability in vCenter Server, the centralized management platform for VMware virtualization infrastructure. The vulnerability existed in the vCenter authentication mechanism when configured with LDAP/Active Directory authentication. Attackers could exploit this to bypass authentication controls and gain administrative access to virtualization infrastructure, potentially compromising entire data center environments.
Ready to Test Your Knowledge?
Put what you have learned into practice. Try identifying and fixing LDAP Injection vulnerabilities in our interactive coding challenges, or explore more security guides to deepen your understanding.