Overview
LDAP Injection is an attack that exploits applications that construct LDAP (Lightweight Directory Access Protocol) queries from user-supplied input. If an application fails to sanitize this input, an attacker can inject LDAP metacharacters (*, (, ), &, |, etc.) to modify the query. This can lead to bypassing authentication, escalating privileges, or disclosing sensitive information from the directory.
Business Impact
Since LDAP directories are often the central source of truth for user authentication and authorization in an enterprise, a successful LDAP Injection attack can be catastrophic. It can allow an attacker to bypass login controls for critical applications, grant themselves administrative privileges, or exfiltrate the entire corporate user directory.Reference Details
CWE ID: CWE-90
OWASP Top 10 (2021): A03:2021 - Injection
Severity: High
Framework-Specific Analysis and Remediation
The core of LDAP Injection is identical to SQL Injection: mixing untrusted data with code (in this case, the LDAP filter syntax). The universal defense is to always escape or sanitize user-supplied input before it is placed within an LDAP filter. All special characters in the input must be properly escaped so they are treated as literal values, not as operators.- Python
- Java
- .NET(C#)
- PHP
- Node.js
- Ruby
Framework Context
Django applications typically use thepython-ldap library for LDAP integration. This library provides a utility for escaping, but developers often forget to use it when building filters manually.Vulnerable Scenario 1: User Authentication
A custom authentication backend attempts to bind to an LDAP server by constructing a filter from the username.Vulnerable Scenario 2: Employee Search Feature
An internal portal allows searching for employees by their common name (cn).Mitigation and Best Practices
Use theldap.filter.escape_filter_chars() function on all user input that will be part of an LDAP filter. This correctly escapes special characters like *, (, ), \, etc.Secure Code Example
Testing Strategy
Write unit tests for the authentication/search function. Pass payloads containing LDAP metacharacters (e.g.,testuser*, admin)(uid=*, *) and assert that the function behaves as expected (e.g., fails authentication, returns no results) rather than executing the modified filter.
