Python ldap3.Connection() Examples
The following are 30
code examples of ldap3.Connection().
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: search.py From coldfront with GNU General Public License v3.0 | 6 votes |
def __init__(self, user_search_string, search_by): super().__init__(user_search_string, search_by) self.FREEIPA_SERVER = import_from_settings('FREEIPA_SERVER') self.FREEIPA_USER_SEARCH_BASE = import_from_settings('FREEIPA_USER_SEARCH_BASE', 'cn=users,cn=accounts') self.FREEIPA_KTNAME = import_from_settings('FREEIPA_KTNAME', '') self.server = Server('ldap://{}'.format(self.FREEIPA_SERVER), use_ssl=True, connect_timeout=1) if len(self.FREEIPA_KTNAME) > 0: logger.info('Kerberos bind enabled: %s', self.FREEIPA_KTNAME) # kerberos SASL/GSSAPI bind os.environ["KRB5_CLIENT_KTNAME"] = self.FREEIPA_KTNAME self.conn = Connection(self.server, authentication=SASL, sasl_mechanism=KERBEROS, auto_bind=True) else: # anonomous bind self.conn = Connection(self.server, auto_bind=True) if not self.conn.bind(): raise ImproperlyConfigured('Failed to bind to LDAP server: {}'.format(self.conn.result)) else: logger.info('LDAP bind successful: %s', self.conn.extend.standard.who_am_i())
Example #2
Source File: user.py From passhport with GNU Affero General Public License v3.0 | 6 votes |
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 #3
Source File: ldaprelayclient.py From krbrelayx with MIT License | 5 votes |
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 #4
Source File: admin_test.py From treadmill with Apache License 2.0 | 5 votes |
def test_add(self): """Tests add logic.""" admin_obj = admin.Admin(None, 'dc=test,dc=com') admin_obj.write_ldap = ldap3.Connection( ldap3.Server('fake'), client_strategy=ldap3.MOCK_SYNC ) admin_obj.add( 'ou=example,dc=test,dc=com', 'testClass', { 'foo': 1, 'bar': ['z', 'a'], 'lot': 2, 'exp': [3, 4] } ) call = admin_obj.write_ldap.add.call_args_list[0][0] self.assertEqual(call[0], 'ou=example,dc=test,dc=com') self.assertEqual(call[1], 'testClass') self.assertEqual( [attr for attr in six.iteritems(call[2])], [('bar', ['z', 'a']), ('exp', [3, 4]), ('foo', 1), ('lot', 2)] )
Example #5
Source File: _ldap.py From treadmill with Apache License 2.0 | 5 votes |
def _connect_to_uri(self, uri): """Create an LDAP connection to the given URI.""" try: server = ldap3.Server( uri, mode=ldap3.IP_V4_ONLY, connect_timeout=self._connect_timeout, ) if self.user and self.password: ldap_auth = { 'user': self.user, 'password': self.password } else: ldap_auth = { 'authentication': ldap3.SASL, 'sasl_mechanism': 'GSSAPI', 'sasl_credentials': (True,) } return ldap3.Connection( server, client_strategy=ldap3.RESTARTABLE, auto_bind=True, auto_encode=True, auto_escape=True, return_empty_attributes=False, **ldap_auth ) except (ldap_exceptions.LDAPSocketOpenError, ldap_exceptions.LDAPBindError, ldap_exceptions.LDAPMaximumRetriesError): _LOGGER.debug('Failed to connect to %s', uri, exc_info=True) return None
Example #6
Source File: ldaprelayclient.py From CVE-2019-1040 with MIT License | 5 votes |
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 #7
Source File: restore.py From CVE-2019-1040 with MIT License | 5 votes |
def establish_connection(self, user): domain = self.config['domain'] # First check if the server was specified explicitly if self.config['server']: server = self.config['server'] else: server = self.config['domain'] # if self.args.server: # server = self.args.server # # If not, check if the server was specified in the restore data # elif self.config['server']: # server = self.config['server'] # # Else, assume DNS is set up properly and we can connect to the domain # else: # server = self.config['domain'] #password = getpass.getpass(self.ntlm.encode('utf-8')) password = self.ntlm self.passdata[user] = password #Todo: get password from command line args # try: # password = self.passdata[user] # except KeyError: # prompt = 'Please supply the password or LM:NTLM hashes for the account %s: ' % user # password = getpass.getpass(prompt.encode('utf-8')) # # Store for further reference # self.passdata[user] = password if domain is None: domain = get_domain(user) if '@' in user or '.' in user: binduser = get_sam_name(user) else: binduser = user ldapserver = ldap3.Server(server, get_info=ldap3.DSA) connection = ldap3.Connection(ldapserver, user='%s\\%s' % (domain, binduser), password=password, authentication=ldap3.NTLM) if not connection.bind(): raise RestoreException('Failed to connect to the LDAP server as %s\\%s: %s' % (domain, binduser, str(connection.result))) return connection, user
Example #8
Source File: ldaprelayclient.py From CVE-2019-1040 with MIT License | 5 votes |
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 #9
Source File: _servers.py From treadmill with Apache License 2.0 | 5 votes |
def get_ldap_connection(self, server_info): """Gets an AD LDAP connection for the given server name. :return: The fqdn of the server :param server_info: The info attached to the server. :return: An `ldap3.Connection` to the host's domain controller """ return self._ldap_connections[server_info[DC_KEY]]
Example #10
Source File: gmsa.py From treadmill with Apache License 2.0 | 5 votes |
def _remove_dn_from_proid_group(self, conn, server_dn, proid, force=False): """Removes a placement. :param conn: The `ldap3.Connection` :param server_dn: The server server_dn :param proid: The name of the proid """ server_dn_set = self._get_server_dn_set(proid) if not force: if not self._decrement_dn(server_dn_set, server_dn): return group = self._config.get_group_dn(proid) _LOGGER.debug('Removing %r from group %r', server_dn, group) conn.modify(group, {'member': [(ldap3.MODIFY_DELETE, [server_dn])]}) if not _check_ldap3_operation(conn) and not force: self._increment_dn(server_dn_set, server_dn)
Example #11
Source File: gmsa.py From treadmill with Apache License 2.0 | 5 votes |
def _add_dn_to_proid_group(self, conn, server_dn, proid, force=False): """Adds a placement. :param conn: The `ldap3.Connection` :param server_dn: The server server_dn :param proid: The name of the proid """ server_dn_set = self._get_server_dn_set(proid) group = self._config.get_group_dn(proid) if not self._synced: _LOGGER.debug('Server %r should be in group %r', server_dn, group) self._increment_dn(server_dn_set, server_dn) return if not force: if not self._increment_dn(server_dn_set, server_dn): return _LOGGER.debug('Adding %r to group %r', server_dn, group) conn.modify(group, {'member': [(ldap3.MODIFY_ADD, [server_dn])]}) if not _check_ldap3_operation(conn) and not force: self._decrement_dn(server_dn_set, server_dn)
Example #12
Source File: gmsa.py From treadmill with Apache License 2.0 | 5 votes |
def _check_ldap3_operation(conn): """Checks that the ldap3 operation succeeded/failed. :param conn: The `ldap3.Connection` that the operation was made. :return: `True` if the operation succeed; false otherwise """ result_code = conn.result['result'] if result_code in (0, 68): return True _LOGGER.warning('Ldap operation failed %r', conn.result) return False
Example #13
Source File: admin_test.py From treadmill with Apache License 2.0 | 5 votes |
def test_init(self): """Tests init logic.""" admin_obj = admin.Admin(None, 'dc=test,dc=com') admin_obj.write_ldap = ldap3.Connection( ldap3.Server('fake'), client_strategy=ldap3.MOCK_SYNC ) admin_obj.init() dn_list = [ arg[0][0] for arg in admin_obj.write_ldap.add.call_args_list ] self.assertTrue('dc=test,dc=com' in dn_list) self.assertTrue('ou=treadmill,dc=test,dc=com' in dn_list) self.assertTrue('ou=apps,ou=treadmill,dc=test,dc=com' in dn_list)
Example #14
Source File: ldaprelayclient.py From Slackor with GNU General Public License v3.0 | 5 votes |
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 #15
Source File: __init__.py From flask-ldapconn with BSD 2-Clause "Simplified" License | 5 votes |
def connect(self, user, password, anonymous=False): auto_bind_strategy = AUTO_BIND_TLS_BEFORE_BIND authentication_policy = SIMPLE if current_app.config['LDAP_USE_TLS'] is not True: auto_bind_strategy = AUTO_BIND_NO_TLS if anonymous: authentication_policy = ANONYMOUS user = None password = None ldap_conn = Connection( self.ldap_server, auto_bind=auto_bind_strategy, client_strategy=current_app.config['LDAP_CONNECTION_STRATEGY'], raise_exceptions=current_app.config['LDAP_RAISE_EXCEPTIONS'], authentication=authentication_policy, user=user, password=password, check_names=True, read_only=current_app.config['LDAP_READ_ONLY'], ) return ldap_conn
Example #16
Source File: ldap.py From knowledge-repo with Apache License 2.0 | 5 votes |
def validate(self, user): userdn = self.app.config['LDAP_USERDN_SCHEMA'].format(user_id=user.identifier) password = request.form['password'] conn = Connection(self.server, user=userdn, password=password) return conn.bind()
Example #17
Source File: ldaprelayclient.py From krbrelayx with MIT License | 5 votes |
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 #18
Source File: gldap.py From adminset with GNU General Public License v2.0 | 5 votes |
def connect(self): server = Server(self.server) c = Connection(server, user=self.manager, password=self.passwd) c.bind() return c
Example #19
Source File: models.py From realms-wiki with GNU General Public License v2.0 | 5 votes |
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 #20
Source File: models.py From realms-wiki with GNU General Public License v2.0 | 5 votes |
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 #21
Source File: models.py From realms-wiki with GNU General Public License v2.0 | 5 votes |
def start_tls(self): assert(isinstance(self.conn, ldap3.Connection)) if self.config['START_TLS']: logger = logging.getLogger("realms.auth.ldap") try: self.conn.open() except ldap3.LDAPSocketOpenError as ex: logger.exception("Error when connecting to LDAP server") return False try: return self.conn.start_tls() except ldap3.LDAPStartTLSError as ex: logger.exception("START_TLS error") return False except Exception as ex: logger.exception("START_TLS unexpectedly failed") return False return True
Example #22
Source File: __init__.py From anima with MIT License | 5 votes |
def get_user_groups_from_ldap(ldap_connection, ldap_base_dn, login): """returns the user group names, no permissions for now :param ldap3.Connection ldap_connection: The ldap_connection as ldap3.Connection instance :param str ldap_base_dn: The domain name in LDAP format (all this CN, DN stuff) :param str login: the login to query the name of """ data = get_user_attributes_from_ldap(ldap_connection, ldap_base_dn, login, 'memberOf') return [d.split(',')[0].split("=")[1] for d in data]
Example #23
Source File: __init__.py From anima with MIT License | 5 votes |
def get_user_name_from_ldap(ldap_connection, ldap_base_dn, login): """returns the real user name from ldap :param ldap3.Connection ldap_connection: The ldap_connection as ldap3.Connection instance :param str ldap_base_dn: The domain name in LDAP format (all this CN, DN stuff) :param str login: the login to query the name of :return: """ return get_user_attributes_from_ldap(ldap_connection, ldap_base_dn, login, 'displayName')[0]
Example #24
Source File: __init__.py From anima with MIT License | 5 votes |
def get_user_attributes_from_ldap(ldap_connection, ldap_base_dn, login, attribute): """returns the user group names, no permissions for now :param ldap3.Connection ldap_connection: The ldap_client as ldap3.Connection instance :param str ldap_base_dn: The domain name in LDAP format (all this CN, DN stuff) :param str login: The login :param str attribute: The attribute to query """ result = [] if ldap_connection: ldap_filter = '(sAMAccountName=%s)' % login result = ldap_connection.search( ldap_base_dn, ldap_filter, attributes=attribute, ) if result: data = ldap_connection.response return data[0]['attributes'][attribute] return None
Example #25
Source File: __init__.py From anima with MIT License | 5 votes |
def ldap_authenticate(login, password, ldap_server_address=None, ldap_base_dn=None): """Authenticates with data from Stalker and creates a proper local session """ # check the LDAP server for login information success = False from anima import defaults if not ldap_server_address: ldap_server_address = defaults.ldap_server_address if not ldap_base_dn: ldap_base_dn = defaults.ldap_base_dn from ldap3 import Server, Connection if ldap_server_address and ldap_base_dn: ldap_server = Server(ldap_server_address) ldap_connection = Connection(server=ldap_server, user=login, password=password) success = ldap_connection.bind() logger.debug("ldap_connection.bind(): %s" % success) logger.debug("ldap_connection.extend.standard.who_am_i(): %s" % ldap_connection.extend.standard.who_am_i()) if success: result = ldap_connection.extend.standard.who_am_i() if result: create_user_with_ldap_info(ldap_connection, ldap_base_dn, login, password) ldap_connection.unbind() return success
Example #26
Source File: custom.py From eNMS with GNU General Public License v3.0 | 5 votes |
def ldap_authentication(self, user, name, password): if not hasattr(self, "ldap_server"): self.ldap_server = Server(environ.get("LDAP_ADDR")) user = f"uid={name},dc=example,dc=com" success = Connection(self.ldap_server, user=user, password=password).bind() return {"name": name, "is_admin": True} if success else False
Example #27
Source File: ldaprelayclient.py From Exchange2domain with MIT License | 5 votes |
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 #28
Source File: ldaprelayclient.py From Exchange2domain with MIT License | 5 votes |
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 #29
Source File: LDAPSearch.py From WatchAD with GNU General Public License v3.0 | 5 votes |
def __init__(self, domain): self.domain = get_netbios_domain(domain) self.con = Connection(self._get_server(), user=main_config.ldap_account[self.domain]["user"], password=main_config.ldap_account[self.domain]["password"], auto_bind=True) self.domain_dn = main_config.ldap_account[self.domain]["dn"]
Example #30
Source File: ldap.py From burp-ui with BSD 3-Clause "New" or "Revised" License | 5 votes |
def check(self, dn=None, passwd=None): """:func:`burpui.misc.auth.ldap.LdapLoader.check` authenticates a user against the LDAP server. :param dn: canonical `dn` of the user to authenticate as :type dn: str :param passwd: password of the user to authenticate as :type passwd: str :returns: True if bind was successful, otherwise False """ try: with Connection(self.server, user='{0}'.format(dn), password=passwd, raise_exceptions=True, auto_bind=self.auto_bind, authentication=SIMPLE) as con: self.logger.debug('LDAP Connection = {0}'.format(str(con))) self.logger.info('Bound as user: {0}'.format(dn)) return con.bind() except Exception as e: self.logger.error('Failed to authenticate user: {0}, {1}'.format(dn, str(e))) self.logger.error('Bind as \'{0}\' failed'.format(dn)) return False