Python ldap3.ALL_ATTRIBUTES Examples

The following are 30 code examples of ldap3.ALL_ATTRIBUTES(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module ldap3 , or try the search function .
Example #1
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_11_simple_not_simple_less_condition(self):
        dn = "cn=bob,ou=example,o=test"
        s = "(!(oid<=2))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn)

        dn = "cn=manager,ou=example,o=test"
        s = "(!(accountExpires<=9223372036854775807))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn) 
Example #2
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_25_add_user(self):
        dn = "cn=John Smith,ou=example,o=test"
        data = { "sn" : "Smith",
                "cn" : "John Smith",
                "userPassword": "S3cr3t",
                }
        classes = ["top", "inetOrgPerson"]
        s = "(&(cn=John Smith)(objectClass=top))"

        r = self.c.add(dn, classes, data)
        self.assertTrue(r)

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn) 
Example #3
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_16_simple_or_simple_less_condition(self):
        dn = "cn=manager,ou=example,o=test"
        s = "(|(oid<=1))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn)

        dn = "cn=mini,ou=example,o=test"
        s = "(|(accountExpires<=100))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn) 
Example #4
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_15_simple_or_simple_greater_condition(self):
        dn = "cn=bob,ou=example,o=test"
        s = "(|(oid>=3))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn)

        dn = "cn=manager,ou=example,o=test"
        s = "(|(accountExpires>=9223372036854775808))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn) 
Example #5
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_12_multi_not(self):
        dn = "cn=alice,ou=example,o=test"
        dn1 = "cn=bob,ou=example,o=test"
        dn2 = "cn=manager,ou=example,o=test"
        s = "(!(&(sn~=Cooper)(cn=mini)))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 3)
        self.assertTrue(self.c.response[0].get("dn") == dn)
        self.assertTrue(self.c.response[1].get("dn") == dn1)
        self.assertTrue(self.c.response[2].get("dn") == dn2)

        dn = "cn=mini,ou=example,o=test"
        s = "(!(|(cn~=bob)(sn=*le*)(accountExpires>=100)))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn) 
Example #6
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_10_simple_not_simple_greater_condition(self):
        dn = "cn=manager,ou=example,o=test"
        s = "(!(oid>=2))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn)

        dn = "cn=mini,ou=example,o=test"
        s = "(!(accountExpires>=1))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn) 
Example #7
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_06_simple_and_simple_less_condition(self):
        dn = "cn=manager,ou=example,o=test"
        s = "(&(oid<=1))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn)

        dn = "cn=alice,ou=example,o=test"
        dn1 = "cn=mini,ou=example,o=test"
        s = "(&(accountExpires<=9223372036854775805))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 2)
        self.assertTrue(self.c.response[0].get("dn") == dn)
        self.assertTrue(self.c.response[1].get("dn") == dn1) 
Example #8
Source File: __init__.py    From ldapdomaindump with MIT License 6 votes vote down vote up
def getAllUsers(self):
        if self.config.minimal:
            self.connection.extend.standard.paged_search('%s' % (self.root), '(&(objectCategory=person)(objectClass=user))', attributes=MINIMAL_USERATTRIBUTES, paged_size=500, generator=False)
        else:
            self.connection.extend.standard.paged_search('%s' % (self.root), '(&(objectCategory=person)(objectClass=user))', attributes=ldap3.ALL_ATTRIBUTES, paged_size=500, generator=False)
        return self.connection.entries

    #Get all computers in the domain 
Example #9
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_00_wrong_basedn(self):

        s = "(&(cn=*))"
        base = "o=invalid"
        self.c.search(search_base=base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 0)

        s = "(!(cn=*))"
        base = "o=invalid"
        self.c.search(search_base=base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 0)

        s = "(|(cn=*)(sn=*))"
        base = "o=invalid"
        self.c.search(search_base=base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 0) 
Example #10
Source File: __init__.py    From ldapdomaindump with MIT License 5 votes vote down vote up
def getAllComputers(self):
        if self.config.minimal:
            self.connection.extend.standard.paged_search('%s' % (self.root), '(&(objectClass=computer)(objectClass=user))', attributes=MINIMAL_COMPUTERATTRIBUTES, paged_size=500, generator=False)
        else:
            self.connection.extend.standard.paged_search('%s' % (self.root), '(&(objectClass=computer)(objectClass=user))', attributes=ldap3.ALL_ATTRIBUTES, paged_size=500, generator=False)
        return self.connection.entries

    #Get all user SPNs 
Example #11
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_20_simple_not_multi_value_attribute(self):

        dn = "cn=bob,ou=example,o=test"
        dn1 = "cn=manager,ou=example,o=test"
        s = "(!(mobile=45678))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 2)
        self.assertTrue(self.c.response[0].get("dn") == dn)
        self.assertTrue(self.c.response[1].get("dn") == dn1) 
Example #12
Source File: __init__.py    From ldapdomaindump with MIT License 5 votes vote down vote up
def getAllUserSpns(self):
        if self.config.minimal:
            self.connection.extend.standard.paged_search('%s' % (self.root), '(&(objectCategory=person)(objectClass=user)(servicePrincipalName=*))', attributes=MINIMAL_USERATTRIBUTES, paged_size=500, generator=False)
        else:
            self.connection.extend.standard.paged_search('%s' % (self.root), '(&(objectCategory=person)(objectClass=user)(servicePrincipalName=*))', attributes=ldap3.ALL_ATTRIBUTES, paged_size=500, generator=False)
        return self.connection.entries

    #Get all defined groups 
Example #13
Source File: __init__.py    From ldapdomaindump with MIT License 5 votes vote down vote up
def getAllGroups(self):
        if self.config.minimal:
            self.connection.extend.standard.paged_search(self.root, '(objectClass=group)', attributes=MINIMAL_GROUPATTRIBUTES, paged_size=500, generator=False)
        else:
            self.connection.extend.standard.paged_search(self.root, '(objectClass=group)', attributes=ldap3.ALL_ATTRIBUTES, paged_size=500, generator=False)
        return self.connection.entries

    #Get the domain policies (such as lockout policy) 
Example #14
Source File: activedirectory.py    From activedirectory with Apache License 2.0 5 votes vote down vote up
def get_users(self, new_filter=None, attrlist=ldap3.ALL_ATTRIBUTES):
        # removed (mail=*) filter form default set
        # attrlist default used to be ["sAMAccountName"] instead of all.
        if not new_filter:
            new_filter = ""
        filter = "(&%s(sAMAccountName=*)(samAccountType=805306368)%s)" % (self.filter, new_filter)
        rets = OrderedDict()
        for x in self.search_ext_s(filterstr=filter, attrlist=attrlist):
            # if ret and ret[0] and isinstance(ret[0][1], dict):
            username = x['attributes']["sAMAccountName"][0]
            rets[username] = self.__compress_attributes(x['attributes'])
        return rets 
Example #15
Source File: __init__.py    From ldapdomaindump with MIT License 5 votes vote down vote up
def getAllSecurityGroups(self):
        self.connection.search(self.root, '(groupType:1.2.840.113556.1.4.803:=2147483648)', attributes=ldap3.ALL_ATTRIBUTES)
        return self.connection.entries

    #Get the SID of the root object 
Example #16
Source File: models.py    From realms-wiki with GNU General Public License v2.0 5 votes vote down vote up
def bind_search(self):
        logger = logging.getLogger("realms.auth.ldap")
        bind_dn = self.config.get('BIND_DN') or None
        base_dn = self.config['USER_SEARCH']['base']
        filtr = self.config['USER_SEARCH']['filter'] % {'username': self.userid}
        scope = self.config['USER_SEARCH'].get('scope', 'subtree').lower().strip()
        if scope == "level":
            scope = ldap3.LEVEL
        elif scope == "base":
            scope = ldap3.BASE
        else:
            scope = ldap3.SUBTREE

        self.conn = ldap3.Connection(
            self.server,
            user=bind_dn,
            password=self.config.get('BIND_AUTH') or None,
            version=self.version
        )

        if not self.start_tls():
            return None

        if not self.conn.bind():
            logger.error("Can't bind to the LDAP server with provided credentials ({})'".format(bind_dn))
            return None

        logger.debug("Successfull BIND for '{}'".format(bind_dn))

        try:
            if not self.conn.search(base_dn, filtr, attributes=ldap3.ALL_ATTRIBUTES, search_scope=scope):
                logger.info("User was not found in LDAP: '{}'".format(self.userid))
                return None
            user_dn = self.conn.response[0]['dn']
            attrs = self._get_attributes(self.conn.response)
            # the user was found in LDAP, now let's try a BIND to check the password
            return attrs if self.conn.rebind(user=user_dn, password=self.password) else None
        finally:
            self.close() 
Example #17
Source File: models.py    From realms-wiki with GNU General Public License v2.0 5 votes vote down vote up
def direct_bind(self):
        logger = logging.getLogger("realms.auth.ldap")
        bind_dn = self.config['BIND_DN'] % {'username': self.userid}
        self.conn = ldap3.Connection(
            self.server,
            user=bind_dn,
            password=self.password,
            version=self.version
        )
        if not self.start_tls():
            # START_TLS was required but it failed
            return None
        if not self.conn.bind():
            logger.info("Invalid credentials for '{}'".format(self.userid))
            return None

        logger.debug("Successfull BIND for '{}'".format(bind_dn))

        try:
            attrs = {}
            if self.conn.search(
                bind_dn,                                       # base: the user DN
                "({})".format(bind_dn.split(",", 1)[0]),       # filter: (uid=...)
                attributes=ldap3.ALL_ATTRIBUTES,
                search_scope=ldap3.BASE
            ):
                attrs = self._get_attributes(self.conn.response)
            return attrs
        finally:
            self.close() 
Example #18
Source File: Active_Directory_Query.py    From content with MIT License 5 votes vote down vote up
def free_search(default_base_dn, page_size):

    args = demisto.args()

    search_filter = args.get('filter')
    size_limit = int(args.get('size-limit', '0'))
    time_limit = int(args.get('time-limit', '0'))
    search_base = args.get('base-dn') or default_base_dn
    attributes = args.get('attributes')
    context_output = args.get('context-output')

    search_filter = convert_special_chars_to_unicode(search_filter)

    # if ALL was specified - get all the object's attributes, else expect a string of comma separated values
    if attributes:
        attributes = ALL_ATTRIBUTES if attributes == 'ALL' else attributes.split(',')

    entries = search_with_paging(
        search_filter,
        search_base,
        attributes=attributes,
        size_limit=size_limit,
        time_limit=time_limit,
        page_size=page_size
    )

    ec = {} if context_output == 'no' else {'ActiveDirectory.Search(obj.dn == val.dn)': entries['flat']}
    demisto_entry = {
        'ContentsFormat': formats['json'],
        'Type': entryTypes['note'],
        'Contents': entries['raw'],
        'ReadableContentsFormat': formats['markdown'],
        'HumanReadable': tableToMarkdown("Active Directory Search", entries['flat']),
        'EntryContext': ec
    }
    demisto.results(demisto_entry) 
Example #19
Source File: __init__.py    From ldapdomaindump with MIT License 5 votes vote down vote up
def getDomainPolicy(self):
        self.connection.search(self.root, '(objectClass=domain)', attributes=ldap3.ALL_ATTRIBUTES)
        return self.connection.entries

    #Get domain trusts 
Example #20
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_24_filter_containing_spaces(self):
        dn = "cn=bob,ou=example,o=test"
        s = "(&(description=Bobs Account))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn) 
Example #21
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_22_two_levels_of_filter(self):
        dn = "cn=alice,ou=example,o=test"
        dn1 = "cn=bob,ou=example,o=test"
        dn2 = "cn=manager,ou=example,o=test"
        s = "(|(accountExpires>=9223372036854775807)(!(accountExpires=0)))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 3)
        self.assertTrue(self.c.response[0].get("dn") == dn)
        self.assertTrue(self.c.response[1].get("dn") == dn1)
        self.assertTrue(self.c.response[2].get("dn") == dn2)

        dn = "cn=alice,ou=example,o=test"
        s = "(&(accountExpires<=9223372036854775806)(!(accountExpires=0)))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn)

        dn = "cn=bob,ou=example,o=test"
        s = "(&(cn=*)(objectGUID~=%s))" % trim_objectGUID(objectGUIDs[2])

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn) 
Example #22
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_21_not_multi_or_multi_value_attribute(self):
        dn = "cn=bob,ou=example,o=test"
        dn1 = "cn=manager,ou=example,o=test"
        s = "(!(|(mobile=1234)(mobile=45678)))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 2)
        self.assertTrue(self.c.response[0].get("dn") == dn)
        self.assertTrue(self.c.response[1].get("dn") == dn1) 
Example #23
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_19_simple_or_multi_value_attribute(self):

        dn1 = "cn=alice,ou=example,o=test"
        dn2 = "cn=mini,ou=example,o=test"
        s = "(|(mobile=45678))"
        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 2)
        self.assertTrue(self.c.response[0].get("dn") == dn1)
        self.assertTrue(self.c.response[1].get("dn") == dn2) 
Example #24
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_18_simple_and_multi_value_attribute(self):

        dn1 = "cn=alice,ou=example,o=test"
        dn2 = "cn=mini,ou=example,o=test"
        s = "(&(mobile=45678))"
        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 2)
        self.assertTrue(self.c.response[0].get("dn") == dn1)
        self.assertTrue(self.c.response[1].get("dn") == dn2) 
Example #25
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_05_simple_and_simple_greater_condition(self):
        dn = "cn=bob,ou=example,o=test"
        s = "(&(oid>=3))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn)

        dn = "cn=manager,ou=example,o=test"
        s = "(&(accountExpires>=9223372036854775808))"

        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 1)
        self.assertTrue(self.c.response[0].get("dn") == dn) 
Example #26
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_02_invalid_search_string(self):

        s = "(&cn=*))"
        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 0)

        s = "(&(cn=*)sn=*)"
        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 0) 
Example #27
Source File: test_mock_ldap3.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_01_invalid_attribute(self):

        s = "(&(invalid=*))"
        self.c.search(search_base=self.base, search_filter=s, search_scope=ldap3.SUBTREE,
                attributes = ldap3.ALL_ATTRIBUTES, paged_size = 5)

        self.assertTrue(len(self.c.response) == 0) 
Example #28
Source File: auth.py    From django-cas-server with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, username):
        if not ldap3:
            raise RuntimeError("Please install ldap3 before using the LdapAuthUser backend")
        if not settings.CAS_LDAP_BASE_DN:
            raise ValueError(
                "You must define CAS_LDAP_BASE_DN for using the ldap authentication backend"
            )
        # in case we got deconnected from the database, retry to connect 2 times
        for retry_nb in range(3):
            try:
                conn = self.get_conn()
                if conn.search(
                    settings.CAS_LDAP_BASE_DN,
                    settings.CAS_LDAP_USER_QUERY % ldap3.utils.conv.escape_bytes(username),
                    attributes=ldap3.ALL_ATTRIBUTES
                ) and len(conn.entries) == 1:
                    # try the new ldap3>=2 API
                    try:
                        user = conn.entries[0].entry_attributes_as_dict
                        # store the user dn
                        user["dn"] = conn.entries[0].entry_dn
                    # fallback to ldap3<2 API
                    except (
                        ldap3.core.exceptions.LDAPKeyError,  # ldap3<1 exception
                        ldap3.core.exceptions.LDAPAttributeError  # ldap3<2 exception
                    ):
                        user = conn.entries[0].entry_get_attributes_dict()
                        # store the user dn
                        user["dn"] = conn.entries[0].entry_get_dn()
                    if user.get(settings.CAS_LDAP_USERNAME_ATTR):
                        self.user = user
                        super(LdapAuthUser, self).__init__(user[settings.CAS_LDAP_USERNAME_ATTR][0])
                    else:
                        super(LdapAuthUser, self).__init__(username)
                else:
                    super(LdapAuthUser, self).__init__(username)
                break
            except ldap3.core.exceptions.LDAPCommunicationError:
                if retry_nb == 2:
                    raise 
Example #29
Source File: action.py    From insightconnect-plugins with MIT License 5 votes vote down vote up
def run(self, params={}):
        conn = self.connection.conn
        query = params.get('search_filter')

        query = ADUtils.dn_normalize(query)
        temp_list = ADUtils.dn_escape_and_split(query)
        query_list = [s for s in temp_list if 'DC' in s]
        query = ','.join(query_list)
        escaped_query = ','.join(temp_list)
        escaped_query = escaped_query.replace("\\>=", ">=")
        escaped_query = escaped_query.replace("\\<=", "<=")

        # find pars of `(` `)`
        pairs = ADUtils.find_parentheses_pairs(escaped_query)

        # replace ( and ) when they are part of a name rather than a search parameter
        for key, value in pairs.items():
            tempstring = escaped_query
            if tempstring.find('=', key, value) == -1:
                escaped_query = escaped_query[:value] + '\\29' + escaped_query[value + 1:]
                escaped_query = escaped_query[:key] + '\\28' + escaped_query[key + 1:]
        self.logger.info(f"Escaped query: {escaped_query}")

        conn.search(search_base=params.get('search_base'),
                    search_filter=escaped_query,
                    attributes=[ldap3.ALL_ATTRIBUTES, ldap3.ALL_OPERATIONAL_ATTRIBUTES]
                    )

        result_list_json = conn.response_to_json()
        result_list_object = json.loads(result_list_json)
        entries = result_list_object["entries"]

        for entry in entries:
            if entry.get("dn"):
                entry["dn"] = entry["dn"].replace("\\", "")

            if entry.get("attributes") and entry.get("attributes").get("distinguishedName"):
                entry.get("attributes")["distinguishedName"] = \
                    entry.get("attributes").get("distinguishedName").replace("\\", "")

        return {'results': entries} 
Example #30
Source File: auth.py    From django-cas-server with GNU General Public License v3.0 4 votes vote down vote up
def test_password(self, password):
        """
            Tests ``password`` against the user-supplied password.

            :param unicode password: a clear text password as submited by the user.
            :return: ``True`` if :attr:`username<AuthUser.username>` is valid and ``password`` is
                correct, ``False`` otherwise.
            :rtype: bool
        """
        if self.user and settings.CAS_LDAP_PASSWORD_CHECK == "bind":
            try:
                conn = ldap3.Connection(
                    settings.CAS_LDAP_SERVER,
                    self.user["dn"],
                    password,
                    auto_bind=True
                )
                try:
                    # fetch the user attribute
                    if conn.search(
                        settings.CAS_LDAP_BASE_DN,
                        settings.CAS_LDAP_USER_QUERY % ldap3.utils.conv.escape_bytes(self.username),
                        attributes=ldap3.ALL_ATTRIBUTES
                    ) and len(conn.entries) == 1:
                        # try the ldap3>=2 API
                        try:
                            attributes = conn.entries[0].entry_attributes_as_dict
                            # store the user dn
                            attributes["dn"] = conn.entries[0].entry_dn
                        # fallback to ldap<2 API
                        except (
                            ldap3.core.exceptions.LDAPKeyError,  # ldap3<1 exception
                            ldap3.core.exceptions.LDAPAttributeError  # ldap3<2 exception
                        ):
                            attributes = conn.entries[0].entry_get_attributes_dict()
                            attributes["dn"] = conn.entries[0].entry_get_dn()
                        # cache the attributes locally as we wont have access to the user password
                        # later.
                        user = UserAttributes.objects.get_or_create(username=self.username)[0]
                        user.attributs = attributes
                        user.save()
                finally:
                    conn.unbind()
                return True
            except (
                ldap3.core.exceptions.LDAPBindError,
                ldap3.core.exceptions.LDAPCommunicationError
            ):
                return False
        elif self.user and self.user.get(settings.CAS_LDAP_PASSWORD_ATTR):
            return check_password(
                settings.CAS_LDAP_PASSWORD_CHECK,
                password,
                self.user[settings.CAS_LDAP_PASSWORD_ATTR][0],
                settings.CAS_LDAP_PASSWORD_CHARSET
            )
        else:
            return False