Preventing LDAP Injection
What you'll learn: How to protect LDAP queries from injection attacks through validation, parameterization, escaping, and secure API usage.
Now that you understand how LDAP injection works and how to detect it, it's time to learn the defenses. Just like SQL injection requires careful handling of user input, LDAP injection demands similar vigilance when constructing LDAP queries.
Core Defense Strategies
Input Validation is your first line of defense. Whitelist acceptable characters and reject anything suspicious. For usernames, allow only alphanumeric characters, hyphens, and underscores. Reject special LDAP characters like *, (, ), \, and | unless absolutely necessary.
Parameterized Queries (when supported by your LDAP library) separate data from query structure, preventing attackers from manipulating the query logic. Unfortunately, not all LDAP APIs offer parameterized queries like SQL databases do, so escaping becomes critical.
DN Escaping ensures that Distinguished Names are properly escaped. Special characters like commas, plus signs, quotes, and backslashes must be escaped according to RFC 4514. For example, a username containing John, Smith should become John\, Smith.
Filter Escaping protects LDAP search filters by escaping metacharacters according to RFC 4515. Characters like *, (, ), \, and null bytes must be escaped using their hex representation (e.g., * becomes \2a).
Secure LDAP API Usage means using library functions specifically designed to escape LDAP input rather than building queries with string concatenation. Many modern LDAP libraries provide helper functions like ldap_escape_filter_value() that handle escaping correctly.
Defense in Depth
Combine multiple defenses: validate input strictly, use secure API functions for escaping, apply the principle of least privilege to LDAP service accounts, and implement logging to detect attack attempts.
Key Takeaway: Prevent LDAP injection by validating all user input, using parameterized queries or proper escaping functions for both DNs and filters, and leveraging secure LDAP APIs instead of manual string concatenation.