Join our Newsletter — 33% off our NHI Course
Home› Guides› CAPEC-136 LDAP Injection: How the Attack Pattern Works…
Guide Web & API Security

CAPEC-136 LDAP Injection: How the Attack Pattern Works and How to Defend

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 14 November 2026 14 min read
On this page

LDAP injection happens when an application pastes untrusted input into a directory query, so a login box or search field can change what the directory is asked and who it thinks is authenticating. MITRE CAPEC-136 describes the pattern, rates its likelihood of attack and typical severity as High, and classes it as a Standard pattern under Command Injection. It matters because LDAP still sits behind login forms, staff directories, self-service portals, VPN and appliance authentication, and many internal tools that were written before parameterised directory APIs were common. This guide is for developers, application security engineers and assessors: how the pattern works at the level needed to defend it, where it appears, how to find it, how to fix it, and how to measure that it stays fixed. It does not repeat directory hardening (signing, channel binding, bind types), which is covered in the LDAP Security Deep Dive Guide.

Key takeaways

  • It is a query construction flaw, not a directory flaw. CAPEC-136 requires an application that accepts a string, fails to neutralise characters with special meaning in LDAP, and inserts the string into a query the server processes.
  • Two contexts need two encoders. Search filters are escaped under RFC 4515 and distinguished names under RFC 4514; using the wrong one, or hand-written escaping, leaves gaps.
  • Parameterised builders beat string building. JNDI filter arguments, Spring LDAP's parameterised filter form and library encoders such as ldap3's escape_filter_chars remove most of the risk at the source.
  • The bind account sets the blast radius. OWASP lists least privilege on the LDAP binding account as a core additional defence, which makes this an identity problem as much as a coding one.
  • Empty passwords are a separate trap. RFC 4513 warns that a name with a zero-length password is an unauthenticated bind, so a "successful" bind can prove nothing about the user.

How the attack pattern works

An LDAP search has a base DN, a scope and a filter. Filters use prefix (Polish) notation: an operator such as AND, OR or NOT wraps parenthesised assertions like attribute equals value. When code builds that filter by concatenating a username or search term into a template, the input is treated as filter syntax rather than as data. CAPEC-136 describes the outcome in plain terms: an attacker who can add LDAP syntax can disclose information, and a wildcard in a username field might return every user in the directory. MITRE notes the pattern is very similar to SQL injection in that it manipulates a query to gather information or force a particular return value.

CAPEC's execution flow follows the familiar injection arc: survey the entry points, find inputs where characters with special LDAP meaning cause syntax errors, then infer the query shape and add logic to read or alter data. For defenders the important parts are the prerequisites and the signals, not the mechanics:

  • Prerequisite: a user-controlled string reaches an LDAP filter or DN without context-correct escaping.
  • Signal: malformed filter errors, unusually broad result sets, and searches from the application's bind account that do not match the code's normal query shapes.
  • Amplifier: verbose error pages that echo the filter, and a bind account that can read or write far more of the tree than the feature needs. CAPEC's own mitigations pair strong input validation with custom error pages for this reason.

The consequences CAPEC lists span confidentiality (read data), integrity (modify data), authorisation and authentication (gain privileges, bypass protection mechanisms) and availability (unreliable execution). The corresponding weakness is CWE-90, Improper Neutralization of Special Elements used in an LDAP Query, a Base weakness and a child of CWE-943 for data query logic.

Where it shows up in real systems

OWASP gives two reasons LDAP injection remains common: the lack of safer, parameterised LDAP query interfaces, and the widespread use of LDAP to authenticate users. In practice the risky code sits in a few predictable places.

LocationHow input reaches LDAPWhat a flaw can exposePriority
Login forms that search then bindUsername inserted into a filter to find the user's DN before the bindAccount enumeration, binding as the wrong entry, authentication logic bypassHighest
Staff or customer directory searchFree-text name, department or email field placed in a filterAttributes the page never meant to show, whole-tree enumerationHigh
Password reset and self-service portalsEmail or employee ID used to locate an entryReset flows applied to the wrong accountHigh
Group membership checks for authorisationUsername or group name placed in a membership filterMembership tests that always pass or always failHigh
Provisioning and admin toolsValues used to build DNs for add, modify or move operationsEntries written to the wrong part of the treeMedium to high (depends on bind account rights)
Appliances and legacy apps with LDAP authVendor code, not visible to youSame as login forms, often with a highly privileged bind accountAssess through vendor assurance and testing

CAPEC's example instance is a DNS server whose LDAP backend did not escape queries properly, which shows the pattern is not limited to web forms: any component that turns external input into a directory query is in scope. Directory-backed AI agents and chat tools that translate natural language into LDAP lookups add a newer path, because the "input" may be text a model produced from an untrusted document.

Escaping rules: search filters versus DNs

OWASP's primary defence is to escape all variables with the right LDAP encoding function, and it stresses that distinguished names and search filters follow different rules. Avoid custom escaping code.

ContextGoverning standardCharacters that need escapingLibrary examples
Search filter assertion valueRFC 4515 section 3 (Proposed Standard, June 2006)Asterisk as \2a, left parenthesis as \28, right parenthesis as \29, backslash as \5c, NUL as \00; also any octet above 0x7F that is not part of valid UTF-8ESAPI encodeForLDAP, .NET Encoder.LdapFilterEncode, ldap3 escape_filter_chars, JNDI filter arguments
Distinguished name attribute valueRFC 4514 section 2.4 (Proposed Standard, June 2006)Double quote, plus, comma, semicolon, less than, greater than, backslash and NUL, plus a leading space or hash and a trailing space; OWASP's list also escapes equals, which the RFC permitsESAPI encodeForDN, .NET Encoder.LdapDistinguishedNameEncode
  • Escape at the point of use: encode when the value is placed into the filter or DN, not when it enters the system, so stored data stays canonical and each sink applies its own rule.
  • Normalise before validating: OWASP, citing CERT guidance, says user input should be normalised before validation or comparison takes place.
  • Do not reuse the wrong encoder: many characters that matter in a DN, such as the comma, are harmless in a filter, while the asterisk and parentheses that matter in a filter are allowed in a DN. A value that is safe in one context is not automatically safe in the other.
  • Check helper semantics: some builder methods escape and some deliberately pass text through. Spring LDAP documents that its hardcoded filter(String) method leaves input untouched and is not well suited to user input, while filter(String, String...) encodes the parameters it inserts.

How to fix and harden

The order below puts the controls that remove the flaw ahead of those that limit damage. Apply all of them; OWASP recommends the additional defences as defence in depth, not alternatives.

  1. Use parameterised construction. In Java, pass user values as filter arguments to DirContext.search with {0} placeholders rather than concatenating them. In Spring LDAP, use the where(...).is(...) builder or the parameterised filter form. In Python ldap3, the project documentation tells developers to call escape_filter_chars from ldap3.utils.conv on any user input before placing it in a search.
  2. Escape anything that cannot be parameterised. Use a maintained encoder for the exact context (filter or DN). Ban home-grown replace-character helpers in code review.
  3. Validate against an allow-list. CWE-90 recommends "accept known good" validation of length, type, range, syntax and business rules, and warns against relying on deny-lists. Usernames and employee IDs usually have tight formats; free-text name search needs escaping rather than an over-strict pattern.
  4. Reject empty passwords before binding. RFC 4513 says clients should reject empty passwords in name and password interfaces and servers should by default fail unauthenticated bind requests with unwillingToPerform. Check both the application and the directory setting.
  5. Shrink the bind account. Give the application's service identity read access only to the subtree and attributes the feature uses, no write rights for read-only features, and a separate identity for provisioning. See the Service Account Security Guide.
  6. Constrain the search itself. Fix the base DN and scope in code, never from input, and rely on server limits. OpenLDAP's default sizelimit is 500 entries and default timelimit 3600 seconds, with per-identity overrides through olcLimits, so an application identity can be held to a smaller result set than administrators.
  7. Replace detailed errors. Return a generic message and log the LDAP result code server-side, as CAPEC's custom error page mitigation recommends.

Rollback and testing: introducing escaping can break searches that relied on users typing wildcards on purpose. Ship the change behind a feature flag, run the old and new query paths side by side in a test environment against a copy of the directory, and compare result counts for a set of known searches. If a feature genuinely needs wildcards, add them in code around an escaped value instead of accepting them from input.

Finding it: review, SAST and testing

MethodWhat it findsLimits
Code reviewEvery place an LDAP API receives a filter or DN built from variables; OWASP's test is to verify each untrusted input fed into LDAP queries is escaped correctlySlow at scale; reviewers miss wrappers that hide the LDAP call
Static analysis (SAST)Taint flows from request sources to LDAP search and DN sinks; MITRE rates automated static analysis as highly effective for CWE-90Needs custom sinks and sanitisers for in-house wrappers and approved encoders
Dynamic testing (DAST)Endpoints whose behaviour changes when LDAP metacharacters are supplied; OWASP notes tools such as ZAP have modules to detect LDAP injectionBlind to code paths it cannot reach; results need manual confirmation
Authorised penetration testingBusiness-logic impact, for example whether a flaw reaches authentication or group checksPoint in time; scope and rules of engagement must cover directory-backed features
Vendor assuranceWhether appliances and SaaS connectors build LDAP queries safelyRelies on vendor evidence; ask for test results mapped to ASVS V1.2.6

A practical first step is an inventory query in your code search: list every call to the LDAP search, add, modify and rename APIs across languages, then mark each as parameterised, encoded, or concatenated. Concatenated calls on authentication paths go to the top of the fix list. For assessors, the DAST vs IAST guide explains which runtime method sees directory calls inside the application.

Where identity fits

LDAP injection always executes with the rights of whatever identity the application used to bind, so the service account decides how bad a single flaw can be. A read-only account scoped to one organisational unit limits disclosure to that unit; a domain-wide reader exposes every user's attributes; an account with write rights turns a query flaw into a directory change. Treat each LDAP bind account as a non-human identity with an owner, a documented purpose, a minimal access control entry set, a rotation schedule and monitoring of its query volume. Where the platform supports it, prefer managed or certificate-based credentials over a static password in a configuration file, and keep separate identities for search, authentication and provisioning so one flaw does not inherit all three. See the Least Privilege Techniques Guide and the Service Account Inventory Template.

Detection and measurement

  • Application logs: log LDAP result codes and counts per request with the calling feature name. Spikes in filter syntax errors (protocol or filter errors) from one client are a strong sign of probing.
  • Directory logs: baseline the searches each application bind account makes (base DN, scope, attribute list, typical result count). Alert on searches that return far more entries than the feature normally does, or hit adminLimitExceeded, which OpenLDAP returns when a size or time limit is exceeded.
  • WAF and edge: a web application firewall can flag LDAP metacharacters in fields such as usernames, but treat it as a signal and a stopgap, not a fix. See the Web Application Firewall Guide.
  • Reconnaissance overlap: broad enumeration through an injected filter looks similar to directory reconnaissance from a compromised host; the LDAP Reconnaissance Detection Guide covers those queries.

Metrics that show it is working:

  1. Percentage of LDAP call sites that are parameterised or use an approved encoder (target 100 percent on authentication paths).
  2. Open SAST findings for LDAP injection by age, with a service level for fixing them.
  3. Number of application bind accounts with write rights or tree-wide read rights that their feature does not need.
  4. Filter syntax error rate per application per day, with alerts on deviations from baseline.
  5. Share of directory-backed applications tested against ASVS V1.2.6 in the last 12 months.

Framework mapping

FrameworkReferenceHow it applies
MITRE CAPECCAPEC-136 LDAP Injection, child of CAPEC-248 Command InjectionPattern definition, prerequisites, consequences and mitigations
MITRE CWECWE-90 Improper Neutralization of Special Elements used in an LDAP QueryWeakness definition, allow-list mitigation, SAST detection
OWASP ASVS 5.0V1.2.6Verification requirement that the application protects against LDAP injection
MITRE ATT&CKT1190 Exploit Public-Facing Application; T1087.002 Domain AccountInitial access through an internet-facing app; directory enumeration as a possible outcome
NIST SP 800-53 Rev 5SI-10 Information Input Validation, SI-11 Error Handling, AC-6 Least Privilege, SA-11 Developer Testing and EvaluationValidation and encoding, generic errors, bind account scope, SAST and DAST in the build
NIST CSF 2.0PR.PS-06, DE.CM-09Secure development practices; monitoring software and runtime for adverse events

Common failure patterns

  • Escaping with the wrong rule set: applying DN escaping to a filter value, or the reverse, so the characters that matter in that context pass straight through.
  • Trusting a framework method that does not escape: using a raw filter method because it was convenient, as Spring LDAP warns against for its hardcoded filter form.
  • Treating a successful bind as proof of identity: accepting an empty password and letting an unauthenticated bind look like a login.
  • One powerful bind account for everything: search, authentication and provisioning share a domain-wide account, so any query flaw inherits its rights. The Service Account Breaches Lessons Guide shows how over-privileged service identities widen incidents.
  • Relying on a deny-list or WAF alone: filtering a few characters at the edge while the code still concatenates input, which CWE-90 explicitly warns against.
  • Verbose errors in production: returning the directory error or the filter itself, which gives an attacker the query shape.

Practitioner checklist

  • Inventory every LDAP search, add, modify and rename call across your code and mark how input reaches it.
  • Convert concatenated filters to parameterised forms, starting with login, reset and authorisation checks.
  • Use a maintained encoder for the correct context, RFC 4515 for filters and RFC 4514 for DNs, and ban custom escaping.
  • Add allow-list validation for structured identifiers such as usernames and employee IDs.
  • Reject empty passwords in the application and confirm the directory fails unauthenticated binds.
  • Split and shrink application bind accounts, fix base DN and scope in code, and set per-identity size and time limits.
  • Configure SAST with your LDAP sinks and approved encoders, and include ASVS V1.2.6 in test plans.
  • Replace detailed LDAP errors with generic messages and log result codes server-side.
  • Baseline each bind account's queries and alert on syntax error spikes and oversized result sets.

Standards and references

Related NHI Mgmt Group resources: MITRE CAPEC Guide · LDAP Security Deep Dive Guide · Input Validation and Output Encoding Guide · SQL Injection Prevention Guide · Service Account Security Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 14 November 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.