def get_user_dn(self, username): server = ldap3.Server('ldap://' + self.ldap_server) connection = ldap3.Connection(server) connection.open() connection.search( search_base=self.dn, search_filter='(' + self.user_attr + '=' + username + ')' ) return connection.response[0]['dn']
def setUp(self): super().setUp() self._ldap_test_server = LdapServer(self.ldap_server_data) self._ldap_test_server.start() ldap3_server = ldap3.Server('localhost', port=self._ldap_test_server.config['port']) self._ldap_connection = ldap3.Connection( ldap3_server, user=self._ldap_test_server.config['bind_dn'], password=self._ldap_test_server.config['password'], auto_bind=True )
def get_connection(self, userdn, password): server = ldap3.Server(self.server_address, port=self.server_port, use_ssl=self.use_ssl) auto_bind = (self.use_ssl and ldap3.AUTO_BIND_TLS_BEFORE_BIND or ldap3.AUTO_BIND_NO_TLS) conn = ldap3.Connection(server, user=userdn, password=password, auto_bind=auto_bind) return conn
def ldap_server(): uri = config.get(section, 'uri') if not uri: return uri, _, _, _, _, extensions = parse_ldap_url(uri) if uri.scheme.startswith('ldaps'): scheme, port = 'ldaps', 636 else: scheme, port = 'ldap', 389 return ldap3.Server('%s://%s:%s' % ( scheme, uri.hostname, uri.port or port))
def getConnection(userdn, username, password): server = ldap3.Server(self.server_address, port=self.server_port, use_ssl=self.use_ssl) self.log.debug( 'Attempting to bind {username} with {userdn}'.format( username=username, userdn=userdn)) conn = ldap3.Connection(server, user=self.escape_userdn_if_needed(userdn), password=password) return conn
def ldap_auth(self, user, password, auth_conf): server = ldap3.Server(auth_conf['host'], get_info=ldap3.NONE) conn = ldap3.Connection(server, auth_conf['user_dn'].format(user), password) conn.bind() result = conn.search(auth_conf['search_base'], auth_conf['search_filter'].format(user), attributes=ldap3.ALL_ATTRIBUTES) if not result or not len(conn.entries): return (False, None) return (True, user)
def connect_server(server_uri, user_dc, password): """ :param server_uri: LDAP Server URI :param user_dc: User DC :param password: Password :return: LDAP conenction """ server = ldap3.Server(server_uri, get_info=ldap3.ALL) connection = ldap3.Connection(server, user=user_dc, password=password) return connection
def run_main(): """ get the config """ config = get_config() # start the logger for troubleshooting myDebug = config['debug'] if myDebug == '1': logger = setup_logging() # logger # starting the main logging.info('Starting the main task ...') # use user provided options or get [default] stanza options try: # lets do it logging.info('read the default options from inputs.conf...') # check [default] stanza if we need ssl logging.info('reading usessl from inputs.conf...') usessl = config['usessl'] if usessl == '1': server = ldap3.Server(host=config['server'], port=int(config['port']), use_ssl='%s' % usessl) else: server = ldap3.Server(host=config['server'], port=int(config['port']), use_ssl=False) logging.info('usessl is : %s ...' % usessl) # set timeout to 30 seconds, sizelimit to 10 and search scope base logging.info('reading basedn from inputs.conf...') timeout = '30' sizelimit = 10 scope = 'sub' except Exception, e: # get error back logging.error('ERROR: unable to get default options from inputs.conf') logging.error('ERROR: %s' % e) splunk.Intersplunk.generateErrorResults( ': unable to get default options from inputs.conf' ) # print the error into Splunk UI sys.exit() # exit on error
def get_ldap_stat(server_id): server = Server.query.get(server_id) if server: try: ldap_server = ldap3.Server('ldaps://{}:1636'.format(server.hostname)) conn = ldap3.Connection(ldap_server) if conn.bind(): return "1" except: pass return "0"
def establish_and_return_ldap_connection(host, port, use_ssl, ca_certs_file, ca_certs_data, bind_dn, bind_pw): tls = None if ca_certs_file or ca_certs_data: tls = ldap3.Tls(ca_certs_file=ca_certs_file, ca_certs_data=ca_certs_data, validate=ssl.CERT_REQUIRED) server = ldap3.Server(host=host, port=port, use_ssl=use_ssl, tls=tls) return ldap3.Connection(server, user=bind_dn, password=bind_pw, auto_bind=True)
def get_ldap_connection(): user = '******' password = '******' try: return ldap3.Connection(ldap3.Server('ldap://localhost:389'), user, password, auto_bind=True) except: return None
def ldump(): """ Searches for students, faculty, and staff, and saves them all. """ c = ldap3.Connection(ldap3.Server(ADDRESS, PORT)) c.open() entries = [] ids = set() for dept, query, in QUERIES: add_results(c, dept, query, entries, ids) write_csv_results(entries) c.unbind()
def ensure_connection(self): tls = None if self.connection is None: if self.settings_dict.get('TLS', False): tls = TLS() server = ldap3.Server(self.settings_dict['NAME'], tls=tls) self.connection = ldap3.Connection( server, user=self.settings_dict['USER'], password=self.settings_dict['PASSWORD'], auto_bind=True)
class ldapipl: server = ldap3.Server('tetsuo') conn = ldap3.Connection(server, user= LDAP_DOMAIN + "\\" + LDAP_USER, password = LDAP_PWD, authentication='NTLM') conn.bind() if not conn.bind(): print('error in bind', conn.result) print conn """conn.search(search_base = 'CN=Users,DC=XXXXXX,DC=COM', search_filter = '(objectClass=user)', search_scope = 'SUBTREE', attributes = ['cn', 'givenName','objectClass'], paged_size = 50) total_entries += len(conn.response) for entry in conn.response: try : print entry['dn'] except: print "--" + str(entry['dn'].encode("iso-8859-1" )) print entry['attributes'] cookie = conn.result['controls']['1.2.840.113556.1.4.319']['value']['cookie'] while cookie: conn.search(search_base = 'CN=Users', search_filter = '(objectClass=user)', search_scope = 'SUBTREE', attributes = ['cn', 'givenName','objectClass'], paged_size = 50, paged_cookie = cookie) total_entries += len(conn.response) cookie = conn.result['controls']['1.2.840.113556.1.4.319']['value']['cookie'] for entry in conn.response: try : print entry['dn'] except: print "--" + str(entry['dn'].encode("iso-8859-1" )) print entry['attributes'] print('Total entries retrieved:', total_entries) #conn.add('cn=testpython,cn=users,dc=xxxxxxx,dc=com', ['top','person','organizationalPerson','user'], {'sn': 'Young'}) conn.add('cn=testpython,cn=users,dc=xxxxxxx,dc=com', ['top','group'])""" if conn.search('CN=Thierry ETA,CN=Users,DC=xxxxxxx,DC=com', '(objectclass=person)'): print 'ok' else : print 'pas ok' print(conn.result) # close the connection conn.unbind()
def clear(): import ldap3 # Connecting to a fake server with a fake account: server = ldap3.Server(BIND_HOST, port=BIND_PORT) conn = ldap3.Connection(server, user=BIND_DN, password=BIND_PW, auto_bind=True) conn.delete(fakeuser['dn']) conn.delete(BASE_DN) conn.delete(DOMAIN_DN) conn.close()
def _ldap_bind(self, action_result=None): """ returns phantom.APP_SUCCESS if connection succeeded, else phantom.APP_ERROR. If an action_result is passed in, method will appropriately use it. Otherwise just return APP_SUCCESS/APP_ERROR """ if self._ldap_connection and \ self._ldap_connection.bound and \ not self._ldap_connection.closed: return True elif self._ldap_connection is not None: self._ldap_connection.unbind() try: server_param = { "use_ssl": self._ssl, "port": self._ssl_port, "host": self._server, "get_info": ldap3.ALL } self._ldap_server = ldap3.Server(**server_param) self.save_progress("configured server {}...".format(self._server)) self._ldap_connection = ldap3.Connection(self._ldap_server, user=self._username, password=self._password, raise_exceptions=True) self.save_progress("binding to directory...") if not self._ldap_connection.bind(): if action_result: return action_result.set_status( phantom.APP_ERROR, self._ldap_connection.result['description']) else: return phantom.APP_ERROR if action_result: return action_result.set_status(phantom.APP_SUCCESS) else: return phantom.APP_SUCCESS except Exception as e: self.debug_print("[DEBUG] ldap_bind, e = {}".format(e)) if action_result: return action_result.set_status(phantom.APP_ERROR, status_message="", exception=e) else: return phantom.APP_ERROR
def __init__(self, cfg): self.sleeper = cfg['LDAP_THROTTLE'] self.server_addr = cfg['LDAP_SERVER'] self.user = cfg['LDAP_USER'] self.passw = cfg['LDAP_PASSWORD'] self.user_grp = cfg['LDAP_USERGROUP'] self.server = ldap3.Server(self.server_addr) self.conn = ldap3.Connection( self.server, 'cn={0},ou={1},dc=brown,dc=edu'.format( self.user, self.user_grp), self.passw, auto_bind=True)
def authenticate(address, username, password): try: if len(password) == 0: password = "******" server = ldap3.Server("ldap://192.168.4.222") conn = ldap3.Connection(server) # conn.search() except Exception: raise "Wrong username or password"
def __init__(self): self.server_pool = ldap3.ServerPool( servers=[ldap3.Server(s, use_ssl=AD_USE_TLS) for s in SERVER_LIST], pool_strategy=ldap3.POOLING_STRATEGY_FIRST, active=True) self.connection = ldap3.Connection( self.server_pool, user=AD_USER, password=AD_PASSWD, auto_bind=ldap3.AUTO_BIND_NO_TLS ) # use_ssl=True above makes it use TLS, so we don't have to use the StartTLS command in the connection. self.connection.raise_exceptions = True
def __init__(self, app): self.app = app self.host = app.config['LDAP_HOST'] self.bind = app.config['LDAP_BIND'] self.password = app.config['LDAP_PASSWORD'] tls = ldap3.Tls(validate=ssl.CERT_REQUIRED) server = ldap3.Server(self.host, port=636, use_ssl=True, get_info=ldap3.ALL, tls=tls) self.server = server
def __init__(self, hostname, port, timeout, ssl=False): self.hostname = hostname self.port = port self.timeout = timeout self.ssl = ssl self.server = ldap3.Server(self.hostname, port=self.port, get_info=ldap3.ALL, connect_timeout=self.timeout, use_ssl=self.ssl) self.conn = None
def __connect(self): if not self.__conn: s = ldap3.Server(self.SERVER, port=636, use_ssl=True, get_info=ldap3.ALL) self.__conn = ldap3.Connection(s, auto_bind=True, user=self.USERNAME, password=self.PASSWORD, client_strategy=ldap3.SYNC, authentication=ldap3.SIMPLE)
def _get_LDAP_connection(): """ Return a LDAP connection """ ldap_server = base.get_config('LDAP_SERVER_FOR_SEARCH') ldap_base = base.get_config('LDAP_BASE_DN') server = ldap3.Server('ldap://' + ldap_server) connection = ldap3.Connection(server) connection.open() return connection, ldap_base
def bind(self, use_ssl=True, force=False): setattr(base.current_app, self.__class__.__name__, self) base.logIt("Bind to database") if Config.mappingLocations['default'] == 'ldap': self.moddb = BackendTypes.LDAP elif Config.mappingLocations['default'] == 'rdbm': self.read_jans_schema() if Config.rdbm_type == 'mysql': self.moddb = BackendTypes.MYSQL elif Config.rdbm_type == 'pgsql': self.moddb = BackendTypes.PGSQL elif Config.rdbm_type == 'spanner': self.moddb = BackendTypes.SPANNER self.spanner = Spanner() else: self.moddb = BackendTypes.COUCHBASE if not hasattr(self, 'ldap_conn') or force: for group in Config.mappingLocations: if Config.mappingLocations[group] == 'ldap': base.logIt("Making LDAP Conncetion") ldap_server = ldap3.Server(Config.ldap_hostname, port=int(Config.ldaps_port), use_ssl=use_ssl) self.ldap_conn = ldap3.Connection( ldap_server, user=Config.ldap_binddn, password=Config.ldapPass, ) base.logIt( "Making LDAP Connection to host {}:{} with user {}". format(Config.ldap_hostname, Config.ldaps_port, Config.ldap_binddn)) self.ldap_conn.bind() break if not self.session or force: for group in Config.mappingLocations: if Config.mappingLocations[group] == 'rdbm': if Config.rdbm_type in ('mysql', 'pgsql'): base.logIt("Making MySql Conncetion") result = self.mysqlconnection() if not result[0]: print("{}FATAL: {}{}".format( colors.FAIL, result[1], colors.ENDC)) break self.set_cbm() self.default_bucket = Config.couchbase_bucket_prefix
def authenticate(self, handler, data): username = data['username'] password = data['password'] # Protect against invalid usernames as well as LDAP injection attacks if not re.match(self.valid_username_regex, username): self.log.warn('Invalid username') return None # No empty passwords! if password is None or password.strip() == '': self.log.warn('Empty password') return None userdn = self.bind_dn_template.format(username=username) server = ldap3.Server(self.server_address, port=self.server_port, use_ssl=self.use_ssl) conn = ldap3.Connection(server, user=userdn, password=password) if conn.bind(): if self.allowed_groups: if self.lookup_dn: # In some cases, like AD, we don't bind with the DN, and need to discover it. conn.search(search_base=self.user_search_base, search_scope=ldap3.SUBTREE, search_filter='({userattr}={username})'.format( userattr=self.user_attribute, username=username), attributes=[self.user_attribute]) if len(conn.response) == 0: self.log.warn( 'User with {userattr}={username} not found in directory' .format(userattr=self.user_attribute, username=username)) return None userdn = conn.response[0]['dn'] for group in self.allowed_groups: if conn.search(group, search_scope=ldap3.BASE, search_filter='(member={userdn})'.format( userdn=userdn), attributes=['member']): return username else: return username else: self.log.warn('Invalid password') return None
def test_init(self): """Tests init logic.""" admin_obj = admin.Admin(None, 'dc=test,dc=com') admin_obj.ldap = ldap3.Connection(ldap3.Server('fake'), client_strategy=ldap3.MOCK_SYNC) admin_obj.init() dn_list = [arg[0][0] for arg in admin_obj.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)
def connection(self): # pragma: no cover """Establish LDAP connection.""" # self.server allows us to fetch server info # (including LDAP schema list) if we wish to # add this feature later self.server = ldap3.Server(self.host, port=self.port, get_info=ldap3.ALL) self.conn = ldap3.Connection( self.server, user=self.user_dn, password=self.user_pw, auto_bind=True, lazy=True, receive_timeout=1)
def poc(arg): check_port = lambda x: x if re.match(r"(.*?):(\d+)$", x) else x + ':389' host, port = check_port(arg).split(':') timeout = 5 try: server = ldap3.Server(host, get_info=ldap3.ALL, connect_timeout=timeout) conn = ldap3.Connection(server, auto_bind=True) if len(server.info.naming_contexts) > 0: return True except Exception: return
def auth(username, password): conf = conf_path() LDAP_SERVER = conf.ladp_server LDAP_DOMAIN = conf.ladp_domain c = ldap3.Connection(ldap3.Server(LDAP_SERVER, get_info=ldap3.ALL), user=username + '@' + LDAP_DOMAIN, password=password) ret = c.bind() if ret: c.unbind() return True else: return False
def connect_gssapi(host): serv = ldap3.Server(host, tls=ldap3.Tls(validate=ssl.CERT_REQUIRED), get_info="DSA") conn = ldap3.Connection(serv, authentication="SASL", sasl_mechanism="GSSAPI") conn.open() if not conn.start_tls(): raise Exception("start_tls failed", conn.result) if not conn.bind(): raise Exception("bind failed", conn.result) return conn