# LDAP Injection
**LDAP injection** is a type of *injection attack*. Injection attacks occur when maliciously crafted inputs are submitted by an attacker, causing an application to perform an unintended action. LDAP injection attacks allow an attacker to override authentication protections or manipulate data in your directory information service.
*LDAP* (Lightweight Directory Access Protocol) is a common method of querying a directory information service that contains information about users, systems and devices. The most common LDAP server is Microsoft’s Active Directory, used by Windows domain networks. Code accessing an LDAP server frequently uses parameters coming from an untrusted source to make queries against the user data.
For example: when a user attempts to log into a website, the username parameter supplied in the HTTP request may be incorporated into an LDAP query to check the user’s credentials. It is important that LDAP queries run against the directory service are constructed securely, to ensures attackers cannot inject extra statements or change the logic of an existing statement.
## LDAP Connections in Python
Consider the following Python function that connects to an LDAP server to validate a username and password:
“`python import ldapdef validate_credentials(username, password): ldap_query = f”(&(uid={username})(userPassword={password}))” connection = ldap.initialize(“ldap://127.0.0.1:389”) user = connection.search_s(“dc=example,dc=com”, ldap.SCOPE_SUBTREE, ldap_query)return user.length == 1 “` |
Since the LDAP query is built through string interpolation and the inputs are not sanitized, and attacker can supply the password parameter as `*` and it will be treated as a wildcard pattern, allowing them to bypass validation. Furthermore, either parameter may contain control characters like `(` and `)` than can be injected to change the outcome of the query.
## Mitigation
To safely construct LDAP queries from untrusted data you must remove any characters that have a special meaning in the LDAP query language. The following code snippet illustrates a secure way of escaping the username and password in such a way that an attacker cannot inject control characters:
“`python import ldap import escape_filter_chars from ldap.filterdef validate_credentials(username, password): safe_username = escape_filter_chars(username) safe_password = escape_filter_chars(password)ldap_query = f”(&(uid={safe_username})(userPassword={safe_password}))” connection = ldap.initialize(“ldap://127.0.0.1:389”) user = connection.search_s(“dc=example,dc=com”, ldap.SCOPE_SUBTREE, ldap_query) return user.length == 1 |
# CWEs
* [CWE-90](https://cwe.mitre.org/data/definitions/90.html)