user1431282
user1431282

Reputation: 6845

Using parentheses in Python LDAP's search

I am trying to perform use LDAPObject.search_s() with a search filter.

This works perfectly fine when I have a parameter without ()s but this fails when a () exists in the filter.

For example when I look for a group with

"(name=(Test Group))", a ldap.FILTER_ERROR will be raised, but when I use "(name=Test Group)" as a filter, there will be no issues.

How do I search for groups that have parens?

Reference:

http://www.python-ldap.org/doc/html/ldap.html?highlight=initialize#ldap-objects

Upvotes: 3

Views: 2707

Answers (2)

Chris
Chris

Reputation: 1697

You should use the ldap.filter module. It already contains all the rules for things that need to be escaped.

>>> import ldap.filter
>>> ldap.filter.filter_format('(cn=%s)', ['(Test Group)',])
'(cn=\\28Test Group\\29)'

Upvotes: 9

ixe013
ixe013

Reputation: 10181

[Section 3 of RFC4515][1] says that parenthesis (parenthèses) and other special chars must be escaped.

The rule ensures that the entire filter string is a valid UTF-8 string and provides that the octets that represent the ASCII characters "*" (ASCII 0x2a), "(" (ASCII 0x28), ")" (ASCII 0x29), "" (ASCII 0x5c), and NUL (ASCII 0x00) are represented as a backslash "" (ASCII 0x5c) followed by the two hexadecimal digits representing the value of the encoded octet.

Python makes encoding easy. Just escape the special char with a backslash (\). Searching for a group named "test group", your search filter will be :

'(cn=\(test group\))'

(tested with python-ldap version 2.4.10 with an OpenLDAP server) [1]: https://www.rfc-editor.org/rfc/rfc4515

Upvotes: 1

Related Questions