LDAP Distinguished Names: parse paths and escape values safely
Learn how LDAP DN strings encode directory paths, which characters need escaping, and why DN comparison and filter escaping use different rules.
An LDAP Distinguished Name (DN) identifies a directory entry. Its string form joins Relative Distinguished Names (RDNs) as attribute=value pairs. RFC 4514 defines the string syntax and escaping; it does not define one canonical string form. Do not compare DNs as plain strings or use DN escaping for a search filter.
Read a DN
Example: uid=mina,ou=people,dc=example,dc=org. Commas separate RDNs; plus signs separate multiple attribute-value assertions in one RDN, such as cn=Alex+uid=apark. The displayed sequence runs from the most specific RDN toward its ancestors. Attribute names and their meaning depend on the directory schema.
Escape DN values
A comma or plus that belongs to a value must be escaped, for example cn=Park, Alex,ou=people,dc=example,dc=org. RFC 4514 also requires escaping backslash, quotation mark, semicolon, angle brackets, a leading #, leading or trailing spaces, and NUL (required) and other characters when desired (backslash plus hex octets). Use an RFC 4514 parser/encoder; do not concatenate user input into DN strings or manually double-escape values.
A fictional entry:
cn=Park\, Alex,ou=people,dc=example,dc=orgCompare and search safely
Different valid strings can represent the same DN. RFC 4514 says equality uses the LDAP distinguishedNameMatch rule (RFC 4517), not byte-for-byte string comparison. DN value encoding and LDAP filter assertion-value escaping are separate languages: RFC 4515 filter escaping uses backslash-hex for NUL, (, ), *, and backslash. Build filters with a filter-specific library API; never insert a DN-escaped value as a filter value.
Find the actual entry and DN with a directory search; do not assume a login name or email is a DN.
Keep base DN and filter separate in configuration.
Use a DN-specific API to build DNs and a filter-specific API to build search filters.
Do not treat a DN as a permanent account key: moves or renames can change it.
Where policy requires, verify returned DNs stay under an allowed base.
If special-character lookups fail, parse the DN and check escaping; if two strings differ, use matching-rule equality; if a filter errors, check that RFC 4515 escaping was used. The examples are illustrative; use mature LDAP library functions.
Sources
[RFC 4514](https://www.rfc-editor.org/rfc/rfc4514.html)
[RFC 4517](https://www.rfc-editor.org/rfc/rfc4517.html)
[RFC 4515](https://www.rfc-editor.org/rfc/rfc4515.html)