Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using parentheses in Python LDAP's search

Tags:

python

ldap

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

like image 977
user1431282 Avatar asked Apr 08 '26 18:04

user1431282


2 Answers

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)'
like image 137
Chris Avatar answered Apr 11 '26 06:04

Chris


[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

like image 34
ixe013 Avatar answered Apr 11 '26 07:04

ixe013



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!