Python ldap3.ALL Examples

The following are 30 code examples of ldap3.ALL(). 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: user.py    From passhport with GNU Affero General Public License v3.0 6 votes vote down vote up
def try_ldap_login(login, password):
    """ Connect to a LDAP directory to verify user login/passwords"""
    result = "Wrong login/password"
    s = Server(config.LDAPURI, port=config.LDAPPORT,
               use_ssl=False, get_info=ALL)
    # 1. connection with service account to find the user uid
    uid = useruid(s, login)
   
    if uid: 
        # 2. Try to bind the user to the LDAP
        c = Connection(s, user = uid , password = password, auto_bind = True)
        c.open()
        c.bind()
        result =  c.result["description"] # "success" if bind is ok
        c.unbind()

    return result 
Example #2
Source File: ldaprelayclient.py    From CVE-2019-1040 with MIT License 5 votes vote down vote up
def initConnection(self):
        self.server = Server("ldaps://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
        self.session = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.session.open(False)
        return True 
Example #3
Source File: ldap.py    From knowledge-repo with Apache License 2.0 5 votes vote down vote up
def init(self):

        if not self.app.config.get('LDAP_SERVER'):
            raise RuntimeError(
                "Use of LDAP authentication requires specification of the LDAP_SERVER configuration variable.")
        self.server = Server(self.app.config['LDAP_SERVER'], get_info=ALL) 
Example #4
Source File: ldaprelayclient.py    From Slackor with GNU General Public License v3.0 5 votes vote down vote up
def initConnection(self):
        self.server = Server("ldap://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
        self.session = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.session.open(False)
        return True 
Example #5
Source File: ldaprelayclient.py    From Slackor with GNU General Public License v3.0 5 votes vote down vote up
def initConnection(self):
        self.server = Server("ldaps://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
        self.session = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.session.open(False)
        return True 
Example #6
Source File: 11_6_connect_ldap_server.py    From Python-Network-Programming-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
def main(address):
    # Create the Server object with the given address.
    # Get ALL information.
    server = Server(address, get_info=ALL)
    #Create a connection object, and bind with auto bind set to true.
    conn = Connection(server, auto_bind=True)
    
    # Print the LDAP Server Information.
    print('******************Server Info**************')
    print(server.info)

    # Print the LDAP Server Detailed Schema.
    print('******************Server Schema**************')
    print(server.schema) 
Example #7
Source File: 11_7_query_ldap_server_b.py    From Python-Network-Programming-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
def main(address, dn, password):
    # Create the Server object with the given address.
    server = Server(address, get_info=ALL)
    #Create a connection object, and bind with the given DN and password.
    try: 
        conn = Connection(server, dn, password, auto_bind=True)
        print('LDAP Bind Successful.')
        # Perform a search for a pre-defined criteria.
        # Mention the search filter / filter type and attributes.
        conn.search('dc=example,dc=com', '(&(uid=euler))' , attributes=['sn'])
        # Print the resulting entries.
        print(conn.entries[0])
    except core.exceptions.LDAPBindError as e:
        # If the LDAP bind failed for reasons such as authentication failure.
        print('LDAP Bind Failed: ', e) 
Example #8
Source File: 11_7_query_ldap_server.py    From Python-Network-Programming-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
def main(address, dn, password):
    # Create the Server object with the given address.
    server = Server(address, get_info=ALL)
    #Create a connection object, and bind with the given DN and password.
    try: 
        conn = Connection(server, dn, password, auto_bind=True)
        print('LDAP Bind Successful.')
        print(conn)
    except core.exceptions.LDAPBindError as e:
        # If the LDAP bind failed for reasons such as authentication failure.
        print('LDAP Bind Failed: ', e) 
Example #9
Source File: 11_8_read_ldap_server.py    From Python-Network-Programming-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
def main():
    server = Server('ipa.demo1.freeipa.org', get_info=ALL)
    conn = Connection(server, 'uid=admin,cn=users,cn=accounts,dc=demo1,dc=freeipa,dc=org', 'Secret123', auto_bind=True)
    person = ObjectDef('person', conn)
    r = Reader(conn, person, 'ou=ldap3-tutorial,dc=demo1,dc=freeipa,dc=org')
    print(r)
    print('************')
    person+='uid'
    print(r) 
Example #10
Source File: ldaprelayclient.py    From CVE-2019-1040 with MIT License 5 votes vote down vote up
def initConnection(self):
        self.server = Server("ldap://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
        self.session = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.session.open(False)
        return True 
Example #11
Source File: ldaprelayclient.py    From krbrelayx with MIT License 5 votes vote down vote up
def initConnection(self, authdata, kdc=None):
        if not kdc:
            kdc = authdata['domain']
        self.server = Server("ldaps://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
        self.session = Connection(self.server, user="a", password="b", authentication=SASL, sasl_mechanism=KERBEROS)
        ldap_kerberos(authdata['domain'], kdc, authdata['tgt'], authdata['username'], self.session, self.targetHost) 
Example #12
Source File: 20_8_read_ldap_server.py    From Python-Network-Programming with MIT License 5 votes vote down vote up
def main():
    server = Server('ipa.demo1.freeipa.org', get_info=ALL)
    conn = Connection(server, 'uid=admin,cn=users,cn=accounts,dc=demo1,dc=freeipa,dc=org', 'Secret123', auto_bind=True)
    person = ObjectDef('person', conn)
    r = Reader(conn, person, 'ou=ldap3-tutorial,dc=demo1,dc=freeipa,dc=org')
    print(r)
    print('************')
    person+='uid'
    print(r) 
Example #13
Source File: 20_7_query_ldap_server.py    From Python-Network-Programming with MIT License 5 votes vote down vote up
def main(address, dn, password):
    # Create the Server object with the given address.
    server = Server(address, get_info=ALL)
    #Create a connection object, and bind with the given DN and password.
    try: 
        conn = Connection(server, dn, password, auto_bind=True)
        print('LDAP Bind Successful.')
        print(conn)
    except core.exceptions.LDAPBindError as e:
        # If the LDAP bind failed for reasons such as authentication failure.
        print('LDAP Bind Failed: ', e) 
Example #14
Source File: 20_7_query_ldap_server_b.py    From Python-Network-Programming with MIT License 5 votes vote down vote up
def main(address, dn, password):
    # Create the Server object with the given address.
    server = Server(address, get_info=ALL)
    #Create a connection object, and bind with the given DN and password.
    try: 
        conn = Connection(server, dn, password, auto_bind=True)
        print('LDAP Bind Successful.')
        # Perform a search for a pre-defined criteria.
        # Mention the search filter / filter type and attributes.
        conn.search('dc=example,dc=com', '(&(uid=euler))' , attributes=['sn'])
        # Print the resulting entries.
        print(conn.entries[0])
    except core.exceptions.LDAPBindError as e:
        # If the LDAP bind failed for reasons such as authentication failure.
        print('LDAP Bind Failed: ', e) 
Example #15
Source File: 20_6_connect_ldap_server.py    From Python-Network-Programming with MIT License 5 votes vote down vote up
def main(address):
    # Create the Server object with the given address.
    # Get ALL information.
    server = Server(address, get_info=ALL)
    #Create a connection object, and bind with auto bind set to true.
    conn = Connection(server, auto_bind=True)
    
    # Print the LDAP Server Information.
    print('******************Server Info**************')
    print(server.info)

    # Print the LDAP Server Detailed Schema.
    print('******************Server Schema**************')
    print(server.schema) 
Example #16
Source File: Ldap.py    From Open365 with GNU Affero General Public License v3.0 5 votes vote down vote up
def getInstance(self):
            settings = self.settings.getSettings()
            user = settings['ldap']['admin_ldap_username']
            password = settings['ldap']['admin_ldap_password']
            host = self.settings.getServiceIp('ldap')
            self.logger.debug("Connecting to " + host + " with user " + user)
            self.dn_base = settings['ldap']['ldap_cn_base']
            server = Server(host, get_info=ALL)
            self.ldapClient = Connection(server, user=user, password=password, raise_exceptions=True)
            try:
                self.ldapClient.bind()
            except ldap.LDAPSocketOpenError as e:
                self.logger.error("Could not connect to LDAP - SocketOpenError: " + str(e))
            return self 
Example #17
Source File: helper.py    From resilient-community-apps with MIT License 5 votes vote down vote up
def get_ldap_connection(self):
        try:
            server = Server(self.LDAP_SERVER, port=self.LDAP_PORT, get_info=ALL, use_ssl=self.LDAP_USE_SSL, connect_timeout=self.LDAP_CONNECT_TIMEOUT)
        
            if self.LDAP_AUTH_TYPE == "NTLM":
                connection = Connection(
                    server=server,
                    user=self.LDAP_USER_NTLM,
                    password=self.LDAP_PASSWORD,
                    authentication=NTLM,
                    return_empty_attributes=True,
                    raise_exceptions=True)

            else:
                connection = Connection(
                    server=server,
                    user=self.LDAP_USER_DN,
                    password=self.LDAP_PASSWORD,
                    authentication=self.LDAP_AUTH_TYPE,
                    return_empty_attributes=True,
                    raise_exceptions=True)

            return connection

        except Exception as err:
            raise ValueError("Cannot connect to LDAP Server. Ensure credentials are correct\n Error: {0}".format(err)) 
Example #18
Source File: ldaprelayclient.py    From PiBunny with MIT License 5 votes vote down vote up
def init_connection(self):
        self.server = Server(self.target, get_info=ALL)
        self.connection = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.connection.open(False) 
Example #19
Source File: ldaprelayclient.py    From krbrelayx with MIT License 5 votes vote down vote up
def initConnection(self, authdata, kdc=None):
        if not kdc:
            kdc = authdata['domain']
        self.server = Server("ldap://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
        self.session = Connection(self.server, user="a", password="b", authentication=SASL, sasl_mechanism=KERBEROS)
        ldap_kerberos(authdata['domain'], kdc, authdata['tgt'], authdata['username'], self.session, self.targetHost) 
Example #20
Source File: ldaprelayclient.py    From Exchange2domain with MIT License 5 votes vote down vote up
def initConnection(self):
        self.server = Server("ldaps://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
        self.session = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.session.open(False)
        return True 
Example #21
Source File: ldaprelayclient.py    From Exchange2domain with MIT License 5 votes vote down vote up
def initConnection(self):
        self.server = Server("ldap://%s:%s" % (self.targetHost, self.targetPort), get_info=ALL)
        self.session = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.session.open(False)
        return True 
Example #22
Source File: LDAPSearch.py    From WatchAD with GNU General Public License v3.0 5 votes vote down vote up
def _get_server(self):
        return Server(main_config.ldap_account[self.domain]["server"], get_info=ALL) 
Example #23
Source File: connect_ldap_server.py    From Learning-Python-Networking-Second-Edition with MIT License 5 votes vote down vote up
def main(address):
    # Create the Server object with the given address.
    # Get ALL information.
    server = Server(address, get_info=ALL)
    #Create a connection object, and bind with auto bind set to true.
    conn = Connection(server, auto_bind=True)
    
    # Print the LDAP Server Information.
    print('******************Server Info**************')
    print(server.info) 
Example #24
Source File: entries_ldap_server.py    From Learning-Python-Networking-Second-Edition with MIT License 5 votes vote down vote up
def main():
        # Create the Server object with the given address.
        server = Server(LDAP_SERVER, get_info=ALL)
        #Create a connection object, and bind with the given DN and password.
        try: 
                conn = Connection(server, LDAP_USER, LDAP_PASSWORD, auto_bind=True)
                print('LDAP Bind Successful.')
                # Perform a search for a pre-defined criteria.
                # Mention the search filter / filter type and attributes.
                conn.search('dc=demo1,dc=freeipa,dc=org', LDAP_FILTER , attributes=LDAP_ATTRS)
                # Print the resulting entries.
                for entry in conn.entries:
                        print(entry)
        except core.exceptions.LDAPBindError as e:
                # If the LDAP bind failed for reasons such as authentication failure.
                print('LDAP Bind Failed: ', e) 
Example #25
Source File: auth_ldap3.py    From bbotte.github.io with Apache License 2.0 5 votes vote down vote up
def ldap_authenticate(request,username,password,groups_allowed=True):
  #change these values to what is appropriate for your environment
  id_name="uid"
  ldap_host="192.168.0.2"
  ldap_port="389"
  bind_dn="cn=Manager,dc=bbotte,dc=com"
  bind_pass="123456"
  user_base="ou=People,dc=bbotte,dc=com"
  
  #bind with service account
  s = Server(ldap_host, port=int(ldap_port), get_info=ALL)
  c = Connection(
    s,
    authentication=SIMPLE, 
    user=bind_dn,
    password=bind_pass,
    check_names=True, 
    lazy=False, 
    client_strategy=SYNC, 
    raise_exceptions=False)
  c.open()
  c.bind()
  if c.bound:
    #once bound, check username provided and get cn, memberOf list and mail
    # get cn_name
    c.search(user_base,'(%s=%s)'%(id_name,username),attributes=['cn','mail'])
    c.unbind
    try: 
      cn_name=c.entries[0].cn
    except:
      print("user cn cannot be found")
      auth_logger.error("user cn cannot be found")
      
    session['username']=username
    return True
  else:
    auth_logger.debug('ldap bind failed')
    c.unbind()
    return False 
Example #26
Source File: ldaprelayclient.py    From cracke-dit with MIT License 5 votes vote down vote up
def init_connection(self):
        self.server = Server(self.target, get_info=ALL)
        self.connection = Connection(self.server, user="a", password="b", authentication=NTLM)
        self.connection.open(False) 
Example #27
Source File: LDAPIdResolver.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_persistent_serverpool(self, get_info=None):
        """
        Return a process-level instance of ``LockingServerPool`` for the current LDAP resolver
        configuration. Retrieve it from the app-local store. If such an instance does not exist
        yet, create one.
        :param get_info: one of ldap3.SCHEMA, ldap3.NONE, ldap3.ALL
        :return: a ``LockingServerPool`` instance
        """
        if not get_info:
            get_info = ldap3.SCHEMA
        pools = get_app_local_store().setdefault('ldap_server_pools', {})
        # Create a hashable tuple that describes the current server pool configuration
        pool_description = (self.uri,
                            self.timeout,
                            get_info,
                            repr(self.tls_context),  # this is the string representation of the TLS context
                            self.serverpool_rounds,
                            self.serverpool_skip)
        if pool_description not in pools:
            log.debug("Creating a persistent server pool instance for {!r} ...".format(pool_description))
            # Create a suitable instance of ``LockingServerPool``
            server_pool = self.create_serverpool(self.uri, self.timeout, get_info,
                                                 self.tls_context, self.serverpool_rounds, self.serverpool_skip,
                                                 pool_cls=LockingServerPool)
            # It may happen that another thread tries to add an instance to the dictionary concurrently.
            # However, only one of them will win, and the other ``LockingServerPool`` instance will be
            # garbage-collected eventually.
            return pools.setdefault(pool_description, server_pool)
        else:
            # If there is already a ``LockingServerPool`` instance, return it.
            # We never remove instances from the dictionary, so a ``KeyError`` cannot occur.
            # As a side effect, when we change the LDAP Id resolver configuration,
            # outdated ``LockingServerPool`` instances will survive until the next server restart.
            return pools[pool_description] 
Example #28
Source File: LDAPIdResolver.py    From privacyidea with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_serverpool_instance(self, get_info=None):
        """
        Return a ``ServerPool`` instance that should be used. If ``SERVERPOOL_PERSISTENT``
        is enabled, invoke ``get_persistent_serverpool`` to retrieve a per-process
        server pool instance. If it is not enabled, invoke ``create_serverpool``
        to retrieve a per-request server pool instance.
        :param get_info: one of ldap3.SCHEMA, ldap3.NONE, ldap3.ALL
        :return: a ``ServerPool``/``LockingServerPool`` instance
        """
        if self.serverpool_persistent:
            return self.get_persistent_serverpool(get_info)
        else:
            return self.create_serverpool(self.uri, self.timeout, get_info,
                                          self.tls_context, self.serverpool_rounds, self.serverpool_skip) 
Example #29
Source File: connection.py    From insightconnect-plugins with MIT License 4 votes vote down vote up
def connect(self, params):
        """
        Connect to LDAP
        """
        self.ssl = params.get('use_ssl')
        self.logger.info("Connecting to %s:%d" % (params['host'], params['port']))

        params['port'] = params.get('port') or 389

        use_ssl = False
        if params.get('use_ssl'):
            use_ssl = True

        server = ldap3.Server(
                host=params['host'],
                port=params['port'],
                use_ssl=use_ssl,
                get_info=ldap3.ALL)

        try:
            conn = ldap3.Connection(server=server,
                                    user=params.get('username_password').get('username'),
                                    password=params.get('username_password').get('password'),
                                    auto_encode=True,
                                    auto_escape=True,
                                    auto_bind=True,
                                    auto_referrals=False,
                                    authentication=ldap3.NTLM)
        except exceptions.LDAPBindError as e:
            self.logger.error(f'ldap3 returned the following error {e}')
            raise ConnectionTestException(preset=ConnectionTestException.Preset.USERNAME_PASSWORD)
        except exceptions.LDAPAuthorizationDeniedResult as e:
            self.logger.error(f'ldap3 returned the following error {e}')
            raise ConnectionTestException(preset=ConnectionTestException.Preset.UNAUTHORIZED)
        except exceptions.LDAPSocketOpenError as e:
            self.logger.error(f'ldap3 returned the following error {e}')
            raise ConnectionTestException(
                preset=ConnectionTestException.Preset.SERVICE_UNAVAILABLE)
        except:
            try:
                conn = ldap3.Connection(server=server,
                                        user=params.get('username_password').get('username'),
                                        password=params.get('username_password').get('password'),
                                        auto_referrals=False,
                                        auto_bind=True)
            except exceptions.LDAPBindError as e:
                self.logger.error(f'ldap3 returned the following error {e}')
                raise ConnectionTestException(
                    preset=ConnectionTestException.Preset.USERNAME_PASSWORD)
            except exceptions.LDAPAuthorizationDeniedResult as e:
                self.logger.error(f'ldap3 returned the following error {e}')
                raise ConnectionTestException(preset=ConnectionTestException.Preset.UNAUTHORIZED)
            except exceptions.LDAPSocketOpenError as e:
                self.logger.error(f'ldap3 returned the following error {e}')
                raise ConnectionTestException(
                    preset=ConnectionTestException.Preset.SERVICE_UNAVAILABLE)

        self.logger.info("Connected!")
        self.conn = conn 
Example #30
Source File: authentication.py    From BloodHound.py with MIT License 4 votes vote down vote up
def getLDAPConnection(self, hostname='', baseDN='', protocol='ldaps', gc=False):
        if gc:
            # Global Catalog connection
            if protocol == 'ldaps':
                # Ldap SSL
                server = Server("%s://%s:3269" % (protocol, hostname), get_info=ALL)
            else:
                # Plain LDAP
                server = Server("%s://%s:3268" % (protocol, hostname), get_info=ALL)
        else:
            server = Server("%s://%s" % (protocol, hostname), get_info=ALL)
        # ldap3 supports auth with the NT hash. LM hash is actually ignored since only NTLMv2 is used.
        if self.nt_hash != '':
            ldappass = self.lm_hash + ':' + self.nt_hash
        else:
            ldappass = self.password
        ldaplogin = '%s\\%s' % (self.domain, self.username)
        conn = Connection(server, user=ldaplogin, auto_referrals=False, password=ldappass, authentication=NTLM, receive_timeout=60, auto_range=True)

        # TODO: Kerberos auth for ldap
        if self.kdc is not None:
            logging.error('Kerberos login is not yet supported!')
            # try:
            #     logging.debug('Authenticating to LDAP server using Kerberos')
            #     conn.kerberosLogin(self.username, self.password, self.domain,
            #                        self.lm_hash, self.nt_hash, self.aes_key,
            #                        self.kdc)
            # except KerberosError as e:
            #     logging.warning('Kerberos login failed: %s' % e)
            #     return None
        else:
            logging.debug('Authenticating to LDAP server')
            if not conn.bind():
                result = conn.result
                if result['result'] == RESULT_STRONGER_AUTH_REQUIRED and protocol == 'ldap':
                    logging.warning('LDAP Authentication is refused because LDAP signing is enabled. '
                                    'Trying to connect over LDAPS instead...')
                    return self.getLDAPConnection(hostname, baseDN, 'ldaps')
                else:
                    logging.error('Failure to authenticate with LDAP! Error %s' % result['message'])
                    return None
        return conn