By | May 26, 2025

How To Avoid LDAP Injection

LDAP Injection is a security vulnerability that occurs when untrusted input is used to construct LDAP queries without proper validation or sanitization. Attackers can manipulate queries to access or modify unauthorized data in directory services.

How to Avoid LDAP Injection

1. Use Parameterized Queries / Prepared Statements

  • Avoid building LDAP queries by concatenating strings.
  • Use APIs or libraries that support parameterized LDAP queries.
  • This ensures user input is treated as data, not code.

2. Validate and Sanitize User Inputs

  • Restrict input to expected patterns (e.g., allow only alphanumeric characters).
  • Remove or escape special LDAP characters: * ( ) \ / \0.
  • Apply strict input validation rules before using inputs in queries.

3. Use LDAP Encoding Functions

  • Encode user inputs with LDAP-specific encoding functions.
  • Prevents special characters from altering query logic.

4. Limit LDAP Privileges

  • Use least privilege principle for LDAP accounts used by your application.
  • Prevent sensitive actions with tightly controlled access.

5. Use Strong Authentication and Access Controls

  • Protect LDAP directories with strong authentication.
  • Apply role-based access controls to limit data exposure.

6. Monitor and Log LDAP Queries

  • Detect unusual or suspicious query patterns.
  • Alert on potential injection attempts.

7. Keep LDAP Software Updated

  • Apply security patches and updates regularly.
  • Use secure protocols (e.g., LDAPS).

Example of Unsafe LDAP Query (Vulnerable to Injection)

plaintextCopyEdit(&(uid=USER_INPUT)(password=USER_PASS))

If USER_INPUT contains *)(|(uid=*)), it can manipulate the query.

Safer Approach Using Parameterized Queries (example in Java with JNDI)

javaCopyEditString searchFilter = "(&(uid={0})(password={1}))";
String[] params = { userInput, userPassword };
NamingEnumeration<SearchResult> results = ctx.search(baseDN, searchFilter, params);