It's not the queries and filters you should be escaping – after all the complete queries and filters do have special characters in them and escaping them would cause the query or filter to break. Instead, you should sanitize the data coming directly from the user, here the username
.
As you don't specify the programming language, it's hard to give examples on how this should be done, but if the language has some LDAP encoding functions, you should use them instead of implementing your own.
Although the distinguished name DN has less attack surface than the filters, it still has some special characters: according to OWASP LDAP Injection Prevention Cheat Sheet:
There are certain characters that are considered special characters in
a DN.
The exhaustive list is the following: \ # + < > , ; " =
and leading or
trailing spaces.
Some "special" characters that are allowed in Distinguished Names and
do not need to be escaped include:
* ( ) . & - _ [ ] ` ~ | @ $ % ^ ? : { } ! '
E.g. with your "cn=" + username + ", dc=example, dc=com"
one could descend
to organization units below the intended OU using "username" aiyan, ou=Administrators, ou=Secret
, which would then find the user in
cn=aiyan, ou=Administrators, ou=Secret, dc=example, dc=com