From ee39fd5c90ea07980bd9f9cc50d6be9da7ab82a4 Mon Sep 17 00:00:00 2001 From: Martin Date: Sat, 5 Nov 2022 12:43:28 +0100 Subject: [PATCH] Allow for DN's to have {x} prefix on first RDN (#5450) * Allow for DN's to have {x} prefix on first RDN * Update changelogs/fragments/5450-allow-for-xordered-dns.yaml Co-authored-by: Felix Fontein * Assign attrs to throw-away var * Update plugins/module_utils/ldap.py Co-authored-by: Felix Fontein * Escape DN before creating filter Co-authored-by: Felix Fontein --- .../5450-allow-for-xordered-dns.yaml | 2 ++ plugins/module_utils/ldap.py | 24 ++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 changelogs/fragments/5450-allow-for-xordered-dns.yaml diff --git a/changelogs/fragments/5450-allow-for-xordered-dns.yaml b/changelogs/fragments/5450-allow-for-xordered-dns.yaml new file mode 100644 index 0000000000..1bb1d9c761 --- /dev/null +++ b/changelogs/fragments/5450-allow-for-xordered-dns.yaml @@ -0,0 +1,2 @@ +minor_changes: + - ldap_attrs - allow for DNs to have ``{x}`` prefix on first RDN (https://github.com/ansible-collections/community.general/issues/977, https://github.com/ansible-collections/community.general/pull/5450). diff --git a/plugins/module_utils/ldap.py b/plugins/module_utils/ldap.py index daf89f16d1..03acaa58c5 100644 --- a/plugins/module_utils/ldap.py +++ b/plugins/module_utils/ldap.py @@ -15,6 +15,8 @@ from ansible.module_utils.common.text.converters import to_native try: import ldap + import ldap.dn + import ldap.filter import ldap.sasl HAS_LDAP = True @@ -48,7 +50,6 @@ class LdapGeneric(object): self.module = module self.bind_dn = self.module.params['bind_dn'] self.bind_pw = self.module.params['bind_pw'] - self.dn = self.module.params['dn'] self.referrals_chasing = self.module.params['referrals_chasing'] self.server_uri = self.module.params['server_uri'] self.start_tls = self.module.params['start_tls'] @@ -58,6 +59,9 @@ class LdapGeneric(object): # Establish connection self.connection = self._connect_to_ldap() + # Try to find the X_ORDERed version of the DN + self.dn = self._find_dn() + def fail(self, msg, exn): self.module.fail_json( msg=msg, @@ -65,6 +69,24 @@ class LdapGeneric(object): exception=traceback.format_exc() ) + def _find_dn(self): + dn = self.module.params['dn'] + + explode_dn = ldap.dn.explode_dn(dn) + + if len(explode_dn) > 1: + try: + escaped_value = ldap.filter.escape_filter_chars(explode_dn[0]) + filterstr = "(%s)" % escaped_value + dns = self.connection.search_s(','.join(explode_dn[1:]), + ldap.SCOPE_ONELEVEL, filterstr) + if len(dns) == 1: + dn, dummy = dns[0] + except Exception: + pass + + return dn + def _connect_to_ldap(self): if not self.verify_cert: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)