def search(self, base="", scope=ldap.SCOPE_BASE, filter="(objectClass=*)", attrList=None, attrsonly=0, sizelimit=0): """ Does a search on the currently bound-to server. @return (bool, [], Exception) """ self.logger.debug("Started LDAP-search.") exceptionObject = None result = [] try: resultId = self.ldapServerObject.search_ext(base, scope, filter, attrList, attrsonly, sizelimit=sizelimit) while 1: # Search with a 60 second timeout result_type, result_data = self.ldapServerObject.result( resultId, 0, 60) if (result_data == []): break else: if result_type == ldap.RES_SEARCH_ENTRY: for x in result_data: result.append(x) except ldap.TIMEOUT, e: exceptionObject = ldap.LDAPError({'desc': "Search timed out"})
def ldap_get_user(self, uid=None, isdict=False): """ 通过查询用户uid,从ldap_search_dn进一步提取所需数据,search到的是全部信息 :param uid: :return: {‘uid’:'zhangsan','mail':'*****@*****.**','cn':'张三'} """ result = None try: search = self.ldap_search_dn(value=uid, value_type="uid") if search is None: raise ldap.LDAPError('未查询到相应 id') for user in search: u = user[1]['uid'][0].decode("utf-8") if u == uid: if isdict: uu = {} for key, valueB in user[1].items(): #不获取password字段 if key not in ('userPassword', ): value = valueB[0].decode('utf-8') uu[key] = value return uu return user except Exception as e: logger.error('获取用户%s 失败,原因为: %s' % (uid, str(e))) return result
def authenticate(username, password): ldap_server = config.get("authentication", "ldap_server").strip('"') ldap_search_base = config.get("authentication", "ldap_search_base").strip('"') ldap_search_filter = config.get("authentication", "ldap_search_filter", vars={ "username": username.encode("utf-8") }).strip('"') connect = ldap.open(ldap_server) try: result = connect.search_s(ldap_search_base, ldap.SCOPE_SUBTREE, ldap_search_filter) if len(result) == 0: entity = ldap_search_filter % {'username': username} raise ldap.LDAPError("Invalid ldap entity:%s" % entity) connect.bind_s(result[0][0], password) connect.unbind_s() return True except ldap.INVALID_CREDENTIALS: # invalid user password raise OperationFailed("KCHAUTH0002E") except ldap.NO_SUCH_OBJECT: # ldap search base specified wrongly. raise OperationFailed("KCHAUTH0005E", { "item": 'ldap_search_base', "value": ldap_search_base }) except ldap.LDAPError, e: arg = {"username": username, "code": e.message} raise OperationFailed("KCHAUTH0001E", arg)
def __init__(self, lumaConnection, identStr=""): QObject.__init__(self) self.lumaConnection = lumaConnection self.logger = logging.getLogger(__name__) self.identStr = identStr self.success = False self.exception = ldap.LDAPError({"desc": "Fetch failed"})
def connect(self, username=None, password=None): """ :param username: existing username with permissions to bind to and search the LDAP service :param password: the user password :return: LDAPObject instance by opening LDAP connection to LDAP host specified by LDAP URL. """ try: self._conn = ldap.initialize(self._config.ldap_server) self._conn.protocol_version = ldap.VERSION3 self._conn.set_option(ldap.OPT_PROTOCOL_VERSION, 3) self._conn.set_option(ldap.OPT_REFERRALS, 0) distinguished_login_name = self.connection_login_string(username) password = password if password else self._config.password logger.debug('going to connect using user: {0}'.format( distinguished_login_name)) result = self._conn.simple_bind_s(distinguished_login_name, password) if result[0] != LDAP_SUCCESS_CODE: raise ldap.LDAPError('LDAP user bind failed') return self._conn except ldap.INVALID_CREDENTIALS: raise Exception( "Your username or password is incorrect: [user: {0}]".format( self._config.username)) except ldap.LDAPError as e: error_msg = [] if type(e.message) is dict: for (k, v) in e.message.iteritems(): error_msg.append("%s: %sn" % (k, v)) else: error_msg.append(e.message) raise Exception(error_msg)
def setUp(self): super(TestLDAPUserEdit, self).setUp() # Dummy for search_ldap_for_user(), returning good data. self.mock_email = '*****@*****.**' self.mock_sn = 'Shmoe' self.mock_given_name = 'Joe' self.ldap_search_dummy = Dummy(default_return=('fake_dn', { 'givenName': [self.mock_given_name], 'sn': [self.mock_sn], 'CAPPrimaryEmail': [self.mock_email], })) # Dummy for when search_ldap_for_user() should fail. self.ldap_search_dummy_error = lambda x: thrower( ldap.LDAPError('error!')) # NOQA # Dummy for when search_ldap_for_user() should return no results. self.ldap_search_dummy_no_results = Dummy(default_return=None) # Form dummy for view tests. self.form_dummy().is_valid() returns False by default. self.form_dummy = Dummy(default_return=Dummy( is_valid=Dummy(default_return=False), save=Dummy(default_return=Dummy())), ) # Messages dummy. self.messages_dummy = Dummy(error=Dummy(), success=Dummy(), button=Dummy()) # Dummies for forcing a password to be considered as usable or not. self.password_not_usable_dummy = Dummy(default_return=False) self.password_is_usable_dummy = Dummy(default_return=True)
def get_userdn(host, dn, userid): """ Get the user's dn anonomously, will not work if ldap will not allow anonymous searches. param host: LDAP host param dn: search DN param userid: userid return: if found, the user's DN """ ldap_url = 'ldaps://%s:636' % host try: log.debug('Connecting to %s' % ldap_url) l = ldap.initialize(ldap_url) filter = 'uid=%s' % userid id = l.search(dn, ldap.SCOPE_SUBTREE, filter, None) result_type, result_data = l.result(id, 1) if (result_data == []): raise ldap.LDAPError('%s not a valid user' % userid) else: userdn = result_data[0][0] log.debug('Found dn, %s for user %s', userdn, userid) return userdn except ldap.LDAPError as e: log.error(e) raise e
def authenticate(username, password): ldap_server = config.get('authentication', 'ldap_server').strip('"') ldap_search_base = config.get( 'authentication', 'ldap_search_base').strip('"') ldap_search_filter = config.get( 'authentication', 'ldap_search_filter', vars={'username': username.encode('utf-8')}, ).strip('"') connect = ldap.open(ldap_server) try: result = connect.search_s( ldap_search_base, ldap.SCOPE_SUBTREE, ldap_search_filter ) if len(result) == 0: entity = ldap_search_filter % {'username': username} raise ldap.LDAPError(f'Invalid ldap entity: {entity}') connect.bind_s(result[0][0], password) connect.unbind_s() return True except ldap.INVALID_CREDENTIALS: # invalid user password raise OperationFailed('WOKAUTH0002E') except ldap.NO_SUCH_OBJECT: # ldap search base specified wrongly. raise OperationFailed( 'WOKAUTH0005E', {'item': 'ldap_search_base', 'value': ldap_search_base} ) except ldap.LDAPError as e: arg = {'username': username, 'code': str(e)} raise OperationFailed('WOKAUTH0001E', arg)
def get_userdn(host, dn, admin, cred, userid, user_filter): """ Get the user's dn. param host: LDAP host param dn: search DN param userid: userid return: if found, the user's DN """ ldap_url = host log.debug('*** %s', user_filter) try: log.debug('Connecting to %s' % ldap_url) l = ldap.initialize(ldap_url) l.simple_bind_s(admin, cred) filter = '(& (uid=%s) (%s) )' % (userid, user_filter) id = l.search(dn, ldap.SCOPE_SUBTREE, filter, None) result_type, result_data = l.result(id, 1) if (result_data == []): raise ldap.LDAPError('%s is not a valid user' % userid) else: userdn = result_data[0][0] log.debug('Found dn, %s for user %s', userdn, userid) return userdn except ldap.LDAPError as e: log.exception(e) raise e finally: log.debug('********************* unbinding') l.unbind_s()
def setUp(self): super(TestLDAPUserCreate, self).setUp() # Dummies out search_ldap_for_user(), returning good data. self.mock_email = '*****@*****.**' self.mock_sn = 'Shmoe' self.mock_given_name = 'Joe' self.ldap_search_dummy = Dummy( default_return=('fake_dn', { 'givenName': [self.mock_given_name], 'sn': [self.mock_sn], 'CAPPrimaryEmail': [self.mock_email], }) ) # Dummy for when search_ldap_for_user() should fail. self.ldap_search_dummy_error = lambda x: thrower(ldap.LDAPError('error!')) # NOQA # Dummy for when search_ldap_for_user() should return no results. self.ldap_search_dummy_no_results = Dummy(default_return=None) # Form dummy, for view tests self.form_dummy = Dummy( default_return=Dummy( is_valid=Dummy( default_return=False ), save=Dummy( default_return=Dummy( set_unusable_password=Dummy() ) ) ), ) # Messages dummy self.messages_dummy = Dummy(error=Dummy(), success=Dummy(), button=Dummy())
def test_34_init_mock_bad(self): ''' Test that init fails when ldap dies. ''' with mock.patch.object(IAMVPNLibraryBase, '_ingest_config_from_file', return_value=self.config), \ mock.patch.object(IAMVPNLibraryLDAP, '_create_ldap_connection', side_effect=ldap.LDAPError('err')), \ self.assertRaises(RuntimeError): IAMVPNLibraryLDAP()
def set_token(host, admin, cred, dn, user): """ Using the connection parameters and username, this function sets a unique token for the LDAP user. This token will be used, in part, to verify the user requested a password recovery. :param host: hostname of the LDAP directory service :param admin: username of the administrator that has permission to update a user record in the LDAP to set the token :param cred: password of the admin user :param dn: root search DN :param user: username (typically, uid) """ try: ldap.set_option(ldap.OPT_DEBUG_LEVEL, 255) url = 'ldaps://%s:636' % host l = ldap.initialize(url) log.debug("***Connecting to %s as %s %s" % (url, admin, cred)) l.simple_bind_s(admin, cred) log.debug("***Bind successful***") filter = 'uid=%s' % user attr = ['uid', 'mail', token_attr] id = l.search(dn, ldap.SCOPE_SUBTREE, filter, attr) email = '' token = '' # The result set should only have a single, valid entry or none result_type, result_data = l.result(id, 1) if (result_data == []): raise ldap.LDAPError('%s not a valid user' % user) else: log.debug(result_data) record = result_data[0][1] userdn = result_data[0][0] log.debug('Found dn, %s for user %s', userdn, user) logging.debug(record) email = record['mail'][0] log.debug(record['mail'][0]) log.debug(record['uid'][0]) # Create a temporary token using a time stamp and the username now = datetime.datetime.utcnow().strftime(timeformat) token = base64.urlsafe_b64encode(now) if token_attr in record: mod_attrs = [(ldap.MOD_REPLACE, token_attr, token)] l.modify_s(userdn, mod_attrs) else: mod_attrs = [(ldap.MOD_ADD, token_attr, token)] l.modify_s(userdn, mod_attrs) # RLJ look into compare() function for token # RLJ consider using the _ext_s for LDAPv3, synchronous l.unbind_s() return (email, token) except ldap.LDAPError, e: # RLJ TODO log.error(e) raise e
def setup_mt(self, suffix, bename, parent=None): """Setup a suffix with the given backend-name. @param suffix @param bename @param parent - the parent suffix @param verbose - None This method does not create the matching entry in the tree, nor the given backend. Both should be created apart. Ex. setup_mt(suffix='o=addressbook1', bename='addressbook1') creates: - the mapping in "cn=mapping tree,cn=config" you have to create: - the backend - the ldap entry "o=addressbook1" *after* """ nsuffix = normalizeDN(suffix) #escapedn = escapeDNValue(nsuffix) if parent: nparent = normalizeDN(parent) else: nparent = "" filt = suffixfilt(suffix) # if suffix exists, return try: entry = self.conn.getEntry( DN_MAPPING_TREE, ldap.SCOPE_SUBTREE, filt) return entry except NoSuchEntryError: entry = None # fix me when we can actually used escaped DNs #dn = "cn=%s,cn=mapping tree,cn=config" % escapedn dn = ','.join(('cn="%s"' % nsuffix, DN_MAPPING_TREE)) entry = Entry(dn) entry.update({ 'objectclass': ['top', 'extensibleObject', 'nsMappingTree'], 'nsslapd-state': 'backend', # the value in the dn has to be DN escaped # internal code will add the quoted value - unquoted value is useful for searching 'cn': nsuffix, 'nsslapd-backend': bename }) #entry.setValues('cn', [escapedn, nsuffix]) # the value in the dn has to be DN escaped # the other value can be the unescaped value if parent: entry.setValues('nsslapd-parent-suffix', nparent) try: self.log.debug("Creating entry: %r" % entry) self.conn.add_s(entry) except ldap.LDAPError, e: raise ldap.LDAPError("Error adding suffix entry " + dn, e)
def check_user_belong_to_group(self, uid, group_cn='员工'): """ 查询 用户 是否归属于某个组 :param uid: 用户uid , Ex: 'ssoadmin' :param group_cn: 归属组cn , Ex: '黑名单' :return: True|None """ result = None try: search = self.ldap_search_dn(value=group_cn, value_type='cn') if search is None: raise ldap.LDAPError('未查询到相应 id') member_list = search[0][1].get('memberUid', []) if uid in member_list: result = True except ldap.LDAPError as e: logger.error('获取用户%s与组%s关系失败,原因为: %s' % (uid, group_cn, str(e))) return result
def test_ldap_exception_handling(self): # Set up LDAP tests to use a LdapTestConnection instead of an actual LDAP connection ldap_access.CACHED_LDAP_CONN = LdapTestConnection() c = make_logged_in_client('test', is_superuser=True) with patch( 'useradmin.test_ldap_deprecated.LdapTestConnection.find_users' ) as find_users: find_users.side_effect = ldap.LDAPError('No such object') response = c.post( reverse('useradmin:useradmin.views.add_ldap_users'), dict(username_pattern='moe', password1='test', password2='test'), follow=True) assert_true( b'There was an error when communicating with LDAP' in response.content, response)
def __connectLdap(self): ''' Tries to connect to LDAP Raises an exception if not found: dns.resolver.NXDOMAIN ldap.LDAPError ''' servers = reversed( sorted(dns.resolver.query('_ldap._tcp.' + self._domain, 'SRV'), key=lambda i: i.priority * 10000 + i.weight)) for server in servers: _str = '' try: uri = "%s://%s:%d" % ('ldap', str( server.target)[:-1], server.port) logger.debug('URI: {0}'.format(uri)) ldap.set_option( ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) # Disable certificate check l = ldap.initialize(uri=uri) l.set_option(ldap.OPT_REFERRALS, 0) l.network_timeout = l.timeout = 5 l.protocol_version = ldap.VERSION3 account = self._account if account.find('@') == -1: account += '@' + self._domain logger.debug('Account data: {0}, {1}, {2}, {3}'.format( self._account, self._domain, account, self._password)) l.simple_bind_s(who=account, cred=self._password) return l except ldap.LDAPError as e: _str = self.__getLdapError(e) raise ldap.LDAPError(_str)
def fetch_dn(self, base_dn, search_string): """Fetch and return a single DN. Raises either ldap.NO_RESULTS_RETURNED if no DN could be found or ldap.LDAPError if multiple DNs were found. """ result = self.search(base_dn, search_string, []) if not result: raise ldap.NO_RESULTS_RETURNED({ 'desc': 'No DN found with filter {0} in base DN {1}'.format( search_string, base_dn) }) elif len(result) > 1: raise ldap.LDAPError({ 'desc': 'Multiple DNs found with filter {0} in base DN {1}'.format( search_string, base_dn) }) return result[0][0]
def post(self): """ Queue the specific pipeline type """ user = request.form['user'] password = request.form['password'] # ip = request.remote_addr ut.pretty_print("Checking user %s" % user) # TODO : Provide proper code for special users wilee and demux if ((cfg.ACME_DEV or cfg.ACME_PROD) and (user == 'wilee' or user == 'demux')): return {'token': generate_token(user, password)} else: try: # Make sure the password is not empty to prevent LDAP anonymous bind to succeed if not password: raise ldap.LDAPError("Empty password for user %s!" % user) #check if the LDAP binding works ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) conn = ldap.initialize(cfg.LDAPS_ADDRESS) conn.set_option(ldap.OPT_REFERRALS, 0) conn.set_option(ldap.OPT_PROTOCOL_VERSION, 3) conn.set_option(ldap.OPT_X_TLS_CACERTFILE, cfg.search_cfg_file('certificate_file.cer')) conn.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND) conn.set_option(ldap.OPT_X_TLS_DEMAND, True) bind = conn.simple_bind_s("%s@%s" % user, password, cfg.COMPANY_ADDRESS) ut.pretty_print("Bind success!!") #then create a session return {'token': generate_token(user, password)} except ldap.LDAPError, e: ut.pretty_print("ERROR: authentication error: %s" % e) return "Authentication error", 401
def _get_user_dn_by_username(self, input_username): """ Return a user's DN input_username: "******" (if they are a nonhuman) or "*****@*****.**" return: str of their DN raises if there's no such user. """ if not isinstance(input_username, basestring): raise TypeError(input_username, 'Argument must be a string') res = self.conn.search_s( self.config.get('ldap_base'), ldap.SCOPE_SUBTREE, filterstr=('(' + self.config.get('ldap_user_mail_attribute') + '=' + input_username + ')'), attrlist=[] ) # res should be a list of a tuple of a string and a dict: # [ # ('[email protected],o=com,dc=mozilla', # {'mail': ['*****@*****.**']} # ) # ] # res should be a list of just one user tuple: if len(res) < 1: # If there's no user, that's a problem raise ldap.NO_SUCH_OBJECT(input_username, 'Could not find any entry in LDAP') elif len(res) > 1: # If there's more than one user with this email, that's bad. # Fail out here out of an abundance of caution. raise ldap.LDAPError(input_username, 'Multiple entries found in LDAP') # res[0] is now be a single user's (dn,attrs) tuple: # ( # '[email protected],o=com,dc=mozilla', # {'mail': ['*****@*****.**']} # ) # res[0][0] grabs just their DN return res[0][0]
def __connectLdap(self, servers=None): ''' Tries to connect to LDAP Raises an exception if not found: dns.resolver.NXDOMAIN ldap.LDAPError ''' if servers is None: servers = self.__getServerList() _str = "No servers found" for server in servers: _str = '' try: uri = "%s://%s:%d" % ('ldap', server[0], server[1]) logger.debug('URI: {0}'.format(uri)) ldap.set_option( ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) # Disable certificate check l = ldap.initialize(uri=uri) l.set_option(ldap.OPT_REFERRALS, 0) l.network_timeout = l.timeout = 5 l.protocol_version = ldap.VERSION3 account = self._account if account.find('@') == -1: account += '@' + self._domain logger.debug('Account data: {0}, {1}, {2}, {3}'.format( self._account, self._domain, account, self._password)) l.simple_bind_s(who=account, cred=self._password) return l except ldap.LDAPError as e: _str = self.__getLdapError(e) raise ldap.LDAPError(_str)
def ldapGetObject(base, searchFilter, ldapConnection=None): conn = ldapConnection try: if not ldapConnection: conn = _ldapPool.get() results_id = conn.search(base, ldap.SCOPE_SUBTREE, searchFilter, None) rType, rData = conn.result(results_id, 0) if rData == []: raise ldap.NO_SUCH_OBJECT('No object %s in base=%s' % (searchFilter, base)) if rType != ldap.RES_SEARCH_ENTRY: raise ldap.LDAPError('Unexpected search type %s data:' % (rType, rData)) result = rData[0] rType, rData = conn.result(results_id, 0) if rData != []: raise ldap.MORE_RESULTS_TO_RETURN( 'Found more than 1 result for %s in %s' % (searchFilter, base)) finally: if not ldapConnection: _ldapPool.put(conn) return (result[0], ldap.cidict.cidict(result[1]))
def __init__(self, lumaConnection, base, scope, filter, attrList, attrsonly, sizelimit, identStr=""): QObject.__init__(self) self.lumaConnection = lumaConnection self.logger = logging.getLogger(__name__) self.base = base self.scope = scope self.filter = filter self.attrList = attrList self.attrsonly = attrsonly self.sizelimit = sizelimit self.identStr = identStr self.success = False self.resultList = [] self.exception = ldap.LDAPError({"desc": "Fetch failed"})
def test_authenticate_with_ldap_error(self): """Testing LDAPBackend.authenticate with LDAP error""" self.spy_on(TestLDAPObject.bind_s, owner=TestLDAPObject, op=kgb.SpyOpRaise(ldap.LDAPError())) self.spy_on(TestLDAPObject.search_s, owner=TestLDAPObject, op=kgb.SpyOpReturn([ ('CN=Doc Dwarf,OU=MyOrg,DC=example,DC=COM', {}), ])) user = self.backend.authenticate(request=None, username='******', password='******') self.assertIsNone(user) self.assertSpyCalledWith(TestLDAPObject.bind_s, 'CN=Doc Dwarf,OU=MyOrg,DC=example,DC=COM', 'mypass') self.assertSpyCalledWith(TestLDAPObject.search_s, 'CN=admin,DC=example,DC=com', ldap.SCOPE_SUBTREE, '(uid=doc)')
def ldap_get_user(self, uid=None): """ 通过查询用户uid,从ldap_search_dn进一步提取所需数据,search到的是全部信息 :param uid: :return: {‘uid’:'zhangsan','mail':'*****@*****.**','cn':'张三'} """ result = None try: search = self.ldap_search_dn(value=uid, value_type="uid") if search is None: raise ldap.LDAPError('未查询到相应 id') for user in search: u = user[1]['uid'][0].decode("utf-8") if u == uid: # result = { # 'uid': uid, # 'mail': user[1]['mail'][0].decode("utf-8"), # 'cn': user[1]['cn'][0].decode("utf-8"), # } return user except Exception as e: logger.error('获取用户%s 失败,原因为: %s' % (uid, str(e))) return result
def create(self, suffix=None, bename=None, parent=None): ''' Create a mapping tree entry (under "cn=mapping tree,cn=config"), for the 'suffix' and that is stored in 'bename' backend. 'bename' backend must exist before creating the mapping tree entry. If a 'parent' is provided that means that we are creating a sub-suffix mapping tree. @param suffix - suffix mapped by this mapping tree entry. It will be the common name ('cn') of the entry @param benamebase - backend common name (e.g. 'userRoot') @param parent - if provided is a parent suffix of 'suffix' @return DN of the mapping tree entry @raise ldap.NO_SUCH_OBJECT - if the backend entry or parent mapping tree does not exist ValueError - if missing a parameter, ''' # Check suffix is provided if not suffix: raise ValueError("suffix is mandatory") else: nsuffix = normalizeDN(suffix) # Check backend name is provided if not bename: raise ValueError("backend name is mandatory") # Check that if the parent suffix is provided then # it exists a mapping tree for it if parent: nparent = normalizeDN(parent) filt = suffixfilt(parent) try: entry = self.conn.getEntry(DN_MAPPING_TREE, ldap.SCOPE_SUBTREE, filt) pass except NoSuchEntryError: raise ValueError("parent suffix has no mapping tree") else: nparent = "" # Check if suffix exists, return filt = suffixfilt(suffix) try: entry = self.conn.getEntry(DN_MAPPING_TREE, ldap.SCOPE_SUBTREE, filt) return entry except ldap.NO_SUCH_OBJECT: entry = None # # Now start the real work # # fix me when we can actually used escaped DNs dn = ','.join(('cn="%s"' % nsuffix, DN_MAPPING_TREE)) entry = Entry(dn) entry.update({ 'objectclass': ['top', 'extensibleObject', MT_OBJECTCLASS_VALUE], 'nsslapd-state': 'backend', # the value in the dn has to be DN escaped # internal code will add the quoted value - unquoted value is # useful for searching. MT_PROPNAME_TO_ATTRNAME[MT_SUFFIX]: nsuffix, MT_PROPNAME_TO_ATTRNAME[MT_BACKEND]: bename }) # possibly add the parent if parent: entry.setValues(MT_PROPNAME_TO_ATTRNAME[MT_PARENT_SUFFIX], nparent) try: self.log.debug("Creating entry: %s", entry.dn) self.log.info("Entry %r", entry) self.conn.add_s(entry) except ldap.LDAPError as e: raise ldap.LDAPError("Error adding suffix entry " + dn, e) ret = self.conn._test_entry(dn, ldap.SCOPE_BASE) return ret
def bind_s(ldapo, username, password): self.assertEqual(username, 'CN=Doc Dwarf,OU=MyOrg,DC=example,DC=COM') self.assertEqual(password, 'mypass') raise ldap.LDAPError()
def find_users(self, user, find_by_dn=False): raise ldap.LDAPError('No such object')
class LDAPBackendConfigurationTest(unittest2.TestCase): def test_null_bind_dn(self): self.assertRaises(ValueError, ldap_backend.LDAPAuthenticationBackend, None, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST) def test_null_bind_password(self): self.assertRaises(ValueError, ldap_backend.LDAPAuthenticationBackend, LDAP_BIND_DN, None, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST) def test_null_base_ou(self): self.assertRaises(ValueError, ldap_backend.LDAPAuthenticationBackend, LDAP_BIND_DN, LDAP_BIND_PASSWORD, None, LDAP_GROUP_DNS, LDAP_HOST) def test_null_group_dns(self): self.assertRaises(ValueError, ldap_backend.LDAPAuthenticationBackend, LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, None, LDAP_HOST) def test_null_host(self): self.assertRaises(ValueError, ldap_backend.LDAPAuthenticationBackend, LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, None) def test_null_port(self): backend = ldap_backend.LDAPAuthenticationBackend(LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, port=None) self.assertEqual(389, backend._port) backend = ldap_backend.LDAPAuthenticationBackend(LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, port=None, use_ssl=True) self.assertEqual(LDAPS_PORT, backend._port) backend = ldap_backend.LDAPAuthenticationBackend(LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, port=9090, use_ssl=True) self.assertEqual(9090, backend._port) def test_scope(self): for scope in ['base', 'onelevel', 'subtree']: backend = ldap_backend.LDAPAuthenticationBackend( LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, scope=scope) self.assertEqual(ldap_backend.SEARCH_SCOPES[scope], backend._scope) def test_bad_scope(self): self.assertRaises(ValueError, ldap_backend.LDAPAuthenticationBackend, LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, scope='foo') def test_null_id_attr(self): backend = ldap_backend.LDAPAuthenticationBackend(LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, id_attr=None) self.assertEqual('uid={username}', backend._account_pattern) def test_id_attr_and_account_pattern(self): account_pattern = '(|(username={username})(mail={username}))' backend = ldap_backend.LDAPAuthenticationBackend( LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, id_attr='user', account_pattern=account_pattern, ) self.assertEqual(account_pattern, backend._account_pattern) def test_both_ssl_tls_true(self): self.assertRaises(ValueError, ldap_backend.LDAPAuthenticationBackend, LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, use_ssl=True, use_tls=True) def test_bad_cacert_file(self): self.assertRaises(ValueError, ldap_backend.LDAPAuthenticationBackend, LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, cacert='/tmp/foobar') @mock.patch.object(ldap, 'initialize', mock.MagicMock(side_effect=ldap.LDAPError())) def test_connection_error(self): backend = ldap_backend.LDAPAuthenticationBackend(LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, id_attr=LDAP_ID_ATTR) authenticated = backend.authenticate(LDAP_USER_UID, LDAP_USER_PASSWD) self.assertFalse(authenticated) def test_chase_referrals(self): backend = ldap_backend.LDAPAuthenticationBackend(LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, id_attr=LDAP_ID_ATTR, chase_referrals=False) conn = backend._init_connection() self.assertFalse(conn.get_option(ldap.OPT_REFERRALS)) backend = ldap_backend.LDAPAuthenticationBackend(LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, id_attr=LDAP_ID_ATTR, chase_referrals=True) conn = backend._init_connection() self.assertTrue(conn.get_option(ldap.OPT_REFERRALS)) def test_client_options(self): client_options = { ldap.OPT_RESTART: 0, ldap.OPT_SIZELIMIT: 2014, ldap.OPT_DIAGNOSTIC_MESSAGE: 'test', # Not using a constant, 20482 is OPT_TIMEOUT '20482': 9 } backend = ldap_backend.LDAPAuthenticationBackend( LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, id_attr=LDAP_ID_ATTR, client_options=client_options) conn = backend._init_connection() for option_name, option_value in client_options.items(): self.assertEqual(conn.get_option(int(option_name)), option_value) def test_invalid_group_dns_check_option(self): expected_msg = ( 'Invalid value "invalid" for group_dns_check option. Valid ' 'values are: and, or.') self.assertRaisesRegexp(ValueError, expected_msg, ldap_backend.LDAPAuthenticationBackend, LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, group_dns_check='invalid') def test_and_is_default_group_dns_check_value(self): backend = ldap_backend.LDAPAuthenticationBackend(LDAP_BIND_DN, LDAP_BIND_PASSWORD, LDAP_BASE_OU, LDAP_GROUP_DNS, LDAP_HOST, id_attr=LDAP_ID_ATTR) self.assertEqual(backend._group_dns_check, 'and')
def _bind_fails(self, who='', cred='', **kw): raise ldap.LDAPError('LDAP connection invalid')
def bind_s(self, *args, **kwargs): if self.bindFail: raise ldap.LDAPError({'desc': 'failed to connect'})