pythonactive-directoryldapldap-querypython-ldap

How should I escape ldap special characters?


I'm using python-ldap to query Active Directory

I have this DN

CN=Whalen\, Sean,OU=Users,OU=Users and Groups,DC=example,DC=net

That works fine as a base in a query, but if I try to use it in a search filter like this

(&(objectClass=group)(memberof:1.2.840.113556.1.4.1941:=CN=Whalen\, Sean,OU=Users,OU=Users and Groups,DC=example,DC=net))

I get a Bad search filter error. From my testing, the comma in the CN seems to be the culprit, even though I escaped it with a backslash (\). But, comma isn't listed in the Microsoft documentation as a character that needs escaped in filters.

What am I missing?


Solution

  • The LDAP filter specification assigns special meaning to the following characters * ( ) \ NUL that should be escaped with a backslash followed by the two character ASCII hexadecimal representation of the character when used in a search filter (rfc2254) :

    *   \2A
    (   \28
    )   \29
    \   \5C
    Nul \00
    

    That means any backslash used for escaping a Distinguished Name' special character (including commas) must be represented by \5c in a search filter :

    (&(objectClass=group)(memberof:1.2.840.113556.1.4.1941:=CN=Whalen\5c, Sean,OU=Users,OU=Users and Groups,DC=example,DC=net))
    

    Here is the list of dn special characters that must be escaped with \, or whith \5C when used in a search filter :

        +-------------------------------+---+
        | comma                         | , |
        +-------------------------------+---+
        | Backslash character           | \ |
        +-------------------------------+---+
        | Pound sign (hash sign)        | # |
        +-------------------------------+---+
        | Plus sign                     | + |
        +-------------------------------+---+
        | Less than symbol              | < |
        +-------------------------------+---+
        | Greater than symbol           | > |
        +-------------------------------+---+
        | Semicolon                     | ; |
        +-------------------------------+---+
        | Double quote (quotation mark) | " |
        +-------------------------------+---+
        | Equal sign                    | = |
        +-------------------------------+---+
        | Leading or trailing spaces    |   |
        +-------------------------------+---+