ldap search_filter escape specific charter

260 views Asked by At

I retrieve members of a group and their sAMAccountName (NT Accounts) I run the following code takes from: ldap3 python search members of a group and retrieve their sAMAcountName (Active Directory)

I'm getting user name as output but after few responses I'm getting the error bellow:

ldap_conn.search(search_base='DC=DOMAIN,DC=com',search_filter=f'(distinguishedName={member})',attributes=['sAMAccountName']) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/ldap3/core/connection.py", line 838, in search request = search_operation(search_base, File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/ldap3/operation/search.py", line 371, in search_operation request['filter'] = compile_filter(parse_filter(search_filter, schema, auto_escape, auto_encode, validator, check_names).elements[0]) # parse the searchFilter string and compile it starting from the root node File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/ldap3/operation/search.py", line 214, in parse_filter raise LDAPInvalidFilterError('malformed filter') ldap3.core.exceptions.LDAPInvalidFilterError: malformed filter

it failed once try to retrieve user who have ( ) , ? , # , é charters in CN, how can escape to avoid from malformed filter error ?

base = "CN=mygroup,OU=Security Group,OU=Resources,OU=Global,DC=Domain,DC=com"
ldap_conn.search(search_base = base,search_filter = '(objectClass=group)',search_scope='SUBTREE',attributes = ['member'])

for entry in ldap_conn.entries:
    for member in entry.member.values:
        ldap_conn.search(search_base='OU=Global,DC=Domain,DC=com',search_filter=f'(distinguishedName={member})',attributes=['sAMAccountName'])
        user_sAMAccountName = ldap_conn.entries[0].sAMAccountName.values
        print(user_sAMAccountName)
1

There are 1 answers

0
user1686 On

Depending on the LDAP client module (you seem to be using ldap3):

  • For ldap3, use ldap3.utils.conv.escape_filter_chars(member).
  • For python-ldap, use ldap.filter.escape_filter_chars(member).