def init(self): ldaphost = self.getProperty('ldaphost') ldapport = self.getProperty('ldapport') domain = self.getProperty('ldapdomain') ldapou = self.getProperty('ldapou') if ldaphost is None: logging.getLogger("HWR").error("LdapLogin: you must specify the LDAP hostname") else: if ldapport is None: logging.getLogger("HWR").debug("LdapLogin: connecting to LDAP server %s",ldaphost) self.ldapConnection=ldap.open(ldaphost) else: logging.getLogger("HWR").debug("LdapLogin: connecting to LDAP server %s:%s",ldaphost,ldapport) self.ldapConnection=ldap.open(ldaphost,int(ldapport)) logging.getLogger("HWR").debug("LdapLogin: got connection %s" % str(self.ldapConnection)) if domain is not None: domparts = domain.split(".") domstr = "" comma = "" for part in domparts: domstr += "%sdc=%s" %(comma,part) comma = "," self.domstr = domstr logging.getLogger("HWR").debug("LdapLogin: got connection %s" % str(self.ldapConnection)) else: self.domstr = "dc=esrf,dc=fr" # default is esrf.fr
def init(self): ldaphost = self.getProperty("ldaphost") ldapdc = self.getProperty("ldapdc") if ldaphost is None: logging.getLogger("HWR").error("LdapLogin: you must specify the LDAP hostname") else: ldapport = self.getProperty("ldapport") if ldapport is None: logging.getLogger("HWR").debug("LdapLogin: connecting to LDAP server %s", ldaphost) self.ldapConnection = ldap.open(ldaphost) else: logging.getLogger("HWR").debug("LdapLogin: connecting to LDAP server %s:%s", ldaphost, ldapport) self.ldapConnection = ldap.open(ldaphost, int(ldapport)) self.ldapConnection.simple_bind_s() if ldapdc is not None: parts = ldapdc.split(".") self.dcparts = "" comma = "" for part in parts: self.dcparts += "dc=%s%s" % (part, comma) comma = "," else: self.dcparts = "dc=esrf,dc=fr"
def authenticate_user_ldap(username, password): # return true if username and password correct l = None l_bind = None try: l = ldap.open(settings.LDAP_URL) searchScope = ldap.SCOPE_SUBTREE # retrieve all attributes - again adjust to your needs # see documentation for more options retrieveAttributes = None searchFilter = "uid=" + username l.protocol_version = ldap.VERSION3 result = l.search_s(settings.BASE_DN, searchScope, searchFilter, retrieveAttributes) DN = result[0][0] l_bind = ldap.open("directory.monash.edu.au") l_bind.simple_bind_s(DN, password) return True except ldap.LDAPError, e: return False
def reconnect(self): if self.ldapConnection is not None: try: self.ldapConnection.result(timeout=0) except ldap.LDAPError,err: ldaphost=self.getProperty('ldaphost') ldapport=self.getProperty('ldapport') if ldapport is None: logging.getLogger("HWR").debug("LdapLogin: reconnecting to LDAP server %s",ldaphost) self.ldapConnection=ldap.open(ldaphost) else: logging.getLogger("HWR").debug("LdapLogin: reconnecting to LDAP server %s:%s",ldaphost,ldapport) self.ldapConnection=ldap.open(ldaphost,int(ldapport))
def init(self): ldaphost=self.getProperty('ldaphost') if ldaphost is None: logging.getLogger("HWR").error("LdapLogin: you must specify the LDAP hostname") else: ldapport=self.getProperty('ldapport') if ldapport is None: logging.getLogger("HWR").debug("LdapLogin: connecting to LDAP server %s",ldaphost) self.ldapConnection=ldap.open(ldaphost) else: logging.getLogger("HWR").debug("LdapLogin: connecting to LDAP server %s:%s",ldaphost,ldapport) self.ldapConnection=ldap.open(ldaphost,int(ldapport))
def configure_user(self, user, ): username = user.username user.set_unusable_password() con = ldap.open('ldap-too.mit.edu') con.simple_bind_s("", "") dn = "dc=mit,dc=edu" fields = ['cn', 'sn', 'givenName', 'mail', ] userfilter = ldap.filter.filter_format('uid=%s', [username]) result = con.search_s('dc=mit,dc=edu', ldap.SCOPE_SUBTREE, userfilter, fields) if len(result) == 1: user.first_name = result[0][1]['givenName'][0] user.last_name = result[0][1]['sn'][0] try: user.email = result[0][1]['mail'][0] except KeyError: user.email = username + '@mit.edu' try: user.groups.add(auth.models.Group.objects.get(name='mit')) except ObjectDoesNotExist: print "Failed to retrieve mit group" else: raise ValueError, ("Could not find user with username '%s' (filter '%s')"%(username, userfilter)) try: user.groups.add(auth.models.Group.objects.get(name='autocreated')) except ObjectDoesNotExist: print "Failed to retrieve autocreated group" user.save() return user
def fetch_user_data_from_LDAP(user, ): username = user.username user.set_unusable_password() con = ldap.open('ldap.mit.edu') con.simple_bind_s("", "") dn = "dc=mit,dc=edu" fields = [ 'cn', 'sn', 'givenName', 'mail', ] userfilter = ldap.filter.filter_format('uid=%s', [username]) result = con.search_s('dc=mit,dc=edu', ldap.SCOPE_SUBTREE, userfilter, fields) print result if len(result) == 1: data = result[0][1] if 'givenName' in data: user.first_name = data['givenName'][0] if 'sn' in data: user.last_name = data['sn'][0] if 'mail' in data: user.email = data['mail'][0] user.save() user.profile.company = 'MIT' user.profile.save() else: raise ValueError, ( "Could not find user with username '%s' (filter '%s')" % (username, userfilter)) return user
def createConnector(self): try: self.ldapConnector = ldap.open(self.host) self.ldapConnector.protocol_version = ldap.VERSION3 self.ldapConnector.simple_bind(self.user, self.password) except ldap.LDAPError, e: print 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("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("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, e: arg = {"username": username, "code": e.message} raise OperationFailed("WOKAUTH0001E", arg)
def authenticate(self, authentication): """ Using the user_dn_patterns, find the user's entry, and then retrieve the password field. Encode the supplied password with the necessary hasher, and compare to the entry. """ username = self.user_dn_patterns.replace("{0}", authentication.username) baseDn = self.context_source.base() parts = username.split(",") if len(parts) > 1: username = parts[0] baseDn = ",".join(parts[1:]) + "," + baseDn (host, port) = self.context_source.server() self.logger.debug("Opening connection to server %s/%s" % (host, int(port))) l = ldap.open(host, int(port)) self.logger.debug("Searching for %s in %s" % (username, baseDn)) result_set = l.search_s(baseDn, ldap.SCOPE_SUBTREE, username, None) if len(result_set) != 1: raise BadCredentialsException("Found %s entries at %s/%s. Should only be 1." % (len(result_set), baseDn, username)) self.logger.debug("Looking for attributes...%s" % result_set[0][1]) stored_password = result_set[0][1][self.password_attr_name.lower()][0] self.logger.debug("Comparing passwords...") if self.encoder.isPasswordValid(stored_password, authentication.password, None): self.logger.debug("Successfully matched passwords!") return (result_set[0],l) else: raise BadCredentialsException("Invalid password")
def authenticate(self, username=None, password=None): scope = ldap.SCOPE_SUBTREE filter = "(&(objectclass=person) (samAccountName=%s))" % username ret = ['dn', 'mail', 'givenName', 'sn'] ldap_user = False valid_ldap_user = False # Authenticate the base user so we can search # Locate the LDAP users in one of our directories so we can then # authenticate her for service_account in ServiceAccount.objects.filter(active=True): base = service_account.base_dn try: l = ldap.open(service_account.ldap_servers) l.protocol_version = ldap.VERSION3 l.simple_bind_s(service_account.bind_dn, service_account.bind_pw) except ldap.LDAPError, e: break try: result_id = l.search(base, scope, filter, ret) result_type, result_data = l.result(result_id, 0) # If the user does not exist in LDAP, Fail. if result_data[0][0]: ldap_user = result_data[0] break except ldap.LDAPError, e: print '''Error connecting to %s: %s''' % ( service_account.ldap_servers, e )
def createLDAPConnection(host, baseDN, user=None, password=None): ldapConnector = ldap.open(host) ldapConnector.protocol_version = ldap.VERSION3 if user: retryCommand(ldapConnector.simple_bind, "%s, %s" % (user, baseDN), password) return ldapConnector
def ldap_go(options, q_in, q_out): """ Main event loop for LDAP worker """ # Load last fetched policy logging.info("Loading last fetched policy.") filename = os.path.join(options.policydir, "policy_", options.username) if os.path.exists(filename): policy = load_ldif(filename) if policy: q_in.put({"type": "policy init", "policy": policy}) domain = "dc=" + options.domain.replace(".", ", dc=") username = "******" % (options.username, domain) while True: try: conn = ldap.open(options.hostname) conn.simple_bind(username, options.password) while True: pattern = "(cn=%s)" % options.username updated, policy = fetch_policy(conn, options, domain, pattern) if updated: logging.info("LDAP policy was updated.") policy_repr = dict( zip(policy.keys(), ['...' for x in range(len(policy))])) logging.debug("New policy: %s" % policy_repr) q_in.put({"type": "policy", "policy": policy}) time.sleep(options.interval) except (ldap.SERVER_DOWN, ldap.NO_SUCH_OBJECT, IndexError): logging.warning("LDAP connection failed. Retrying in 3 seconds.") time.sleep(3)
def check_credentials(username, password, migrate=True, group_on_migration='employee'): """User authentication based on LDAP""" bind_search_string = conf_auth_ldap['bind_search_string'].format( username=username) ldap_connection = ldap.open(conf_auth_ldap['hostname']) ldap_connection.protocol_version = ldap.VERSION3 ldap_connection.simple_bind_s(bind_search_string, password) search_scope = ldap.SCOPE_SUBTREE attributes = None search_filter = conf_auth_ldap['search_filter'].format(username=username) ldap_results = ldap_connection.search_s(bind_search_string, search_scope, search_filter, attributes) # If ldap give a result, and user is not already in db, migrate the user into database if ldap_results and ldap_results[0] and ldap_results[0][ 0] == bind_search_string: ldap_result_dict = ldap_results[0][1] if migrate and not _user_exists_in_db(username): id = _migrate_user_to_db(ldap_result_dict, password, group_on_migration) if not id: cherrypy.log( 'Some error occurred migrating user from LDAP to database, please check.', context='TS.LDAP_AUTH', severity=logging.ERROR) return None else: return u"Incorrect username or password."
def authenticate(self, authentication): """Using the user_dn_patterns, find the user's entry, and then bind to the entry using supplied credentials.""" username = self.user_dn_patterns.replace("{0}", authentication.username) baseDn = self.context_source.base() parts = username.split(",") if len(parts) > 1: username = parts[0] baseDn = ",".join(parts[1:]) + "," + baseDn (host, port) = self.context_source.server() self.logger.debug("Opening connection to server %s/%s" % (host, int(port))) l = ldap.open(host, int(port)) self.logger.debug("Searching for %s in %s" % (username, baseDn)) result_set = l.search_s(baseDn, ldap.SCOPE_SUBTREE, username, None) if len(result_set) != 1: raise BadCredentialsException( "Found %s entries at %s/%s. Should only be 1." % (len(result_set), baseDn, username)) dn = result_set[0][0] self.logger.debug("Attempting to bind %s" % dn) try: l.simple_bind_s(dn, authentication.password) self.logger.debug("Successfully bound to server!") return (result_set[0], l) except Exception, e: self.logger.debug("Error %s" % e) raise BadCredentialsException("Invalid password")
def post(self): if not request.json: abort(400) # bad request # Parse the json parser = reqparse.RequestParser() try: # Check for required attributes in json document, create a dictionary parser.add_argument('username', type=str, required=True) parser.add_argument('password', type=str, required=True) request_params = parser.parse_args() except: abort(400) # bad request if request_params['username'] in session: response = {'status': 'success'} responseCode = 200 else: try: l = ldap.open(settings.LDAP_HOST) l.start_tls_s() l.simple_bind_s("uid="+request_params['username']+ ", ou=People,ou=fcs,o=unb", request_params['password']) # At this point we have sucessfully authenticated. session['username'] = request_params['username'] response = {'status': 'success'} responseCode = 201 except ldap.LDAPError, error_message: response = {'status': 'Access denied'} responseCode = 403 finally:
def __init__(self, i_user=0): User.__init__(self, 0) self.config = Config() self.ldap = ldap.open(self.config.ldap['server'], port=self.config.ldap['port']) self.ldap.protocol_version = ldap.VERSION3 self.ldap.set_option(ldap.OPT_REFERRALS, 0)
def __getitem__(self, key): # Don't return 'private' keys if key[0] != '_': if hasattr(self, key): return getattr(self, key) ld_user=ldap.open(self.domains[0]) ld_user.set_option(ldap.OPT_REFERRALS, 0) ld_user.timelimit=10 #print 'try bind',fl(self.name+'@'+self.domains[1]),password try: s=ld_user.simple_bind_s(fl(self.name+'@'+self.domains[1]),fl(password)) except: s=ld_user.simple_bind_s('testUser@ssgpo','userTest') #print 'bind',s dn=fl('DC='+self.domains[1]) #print dn fs=fl('(sAMAccountName='+self.name+')') items=ld_user.search_s(dn,2,fs,[key]) #s=ld_user.search_ext(dn,2,fs,[key]) #items=ld_user.result(s,0)[1] try: return items[0][1][key] except: pass raise "Не найден",KeyError, key
def check(self, db, uid, passwd): try: return super(users,self).check(db, uid, passwd) except security.ExceptionNoTb: # AccessDenied pass cr = pooler.get_db(db).cursor() user = self.browse(cr, 1, uid) logger = logging.getLogger('orm.ldap') if user and user.company_id.ldaps: for res_company_ldap in user.company_id.ldaps: try: l = ldap.open(res_company_ldap.ldap_server, res_company_ldap.ldap_server_port) if l.simple_bind_s(res_company_ldap.ldap_binddn, res_company_ldap.ldap_password): base = res_company_ldap.ldap_base scope = ldap.SCOPE_SUBTREE filter = filter_format(res_company_ldap.ldap_filter, (user.login,)) retrieve_attributes = None result_id = l.search(base, scope, filter, retrieve_attributes) timeout = 60 result_type, result_data = l.result(result_id, timeout) if result_data and result_type == ldap.RES_SEARCH_RESULT and len(result_data) == 1: dn = result_data[0][0] if l.bind_s(dn, passwd): l.unbind() self._uid_cache.setdefault(db, {})[uid] = passwd cr.close() return True l.unbind() except Exception, e: logger.warning('cannot check', exc_info=True) pass
def setup_ldbm(host='localhost', port=389, binddn="CN=Directory Manager", bindpw="Secret123", ldapentry=None, ldapdn=None): l = ldap.open('localhost', 389) try: l.bind(binddn, bindpw) except ldap.SERVER_DOWN, e: print("ldap server is down") return False
def authenticate(self, username=None, password=None): """ In charge of deciding if the user is authorized. @param self: Internal LDAPBackend object. @type self: LDAPBackend @param username: Username to auth. @type username: str @param password: Password to auth with. @type password: str """ if username and password: lcon = ldap.open(settings.LDAP_SERVER) try: lcon.protocol_version = ldap.VERSION3 lcon.start_tls_s() lcon.simple_bind_s(settings.LDAP_USER_BASE % username, password) return self.auth_or_make_user(username, password) except: return None else: return None
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 __init__(self, sourceConfig): """ Example OpenLDAP Configuration ( to be set in the settings/sources.json file ) { "sourceId": "openldap", "connectorClassName": "OpenLDAPCon", "ldapServer": "127.0.0.1", "baseDN": "dc=smartsheet,dc=com", "orgUnit": "ou=people", "adminUser": "******", "adminPass": "******", "searchFilter": "cn=*{}*", "retrieveAttributes": "givenName,sn,roomNumber,mail,telephoneNumber", "ldapTimeout": 0, "isStrict": false } list required fields other than 'sourceId' and 'connectorClassName' from sourceConfig entry 'sourceId' and 'connectorClassName' are required for every source, and are already being checked """ requiredFields = "ldapServer,baseDN,orgUnit,adminUser,adminPass,searchFilter,retrieveAttributes,ldapTimeout" self.ldapConfig = theConfig.validateSourceConfig(sourceConfig, logger, requiredFields) # bind to LDAP server try: self.l = ldap.open(self.ldapConfig["ldapServer"]) self.l.simple_bind_s(self.ldapConfig["adminUser"] + "," + self.ldapConfig["baseDN"],self.ldapConfig["adminPass"]) logger.info("Connected to LDAP at {}".format(self.ldapConfig["ldapServer"])) except ldap.LDAPError, error_message: logger.error("Couldn't connect to LDAP because of the following reason: {}".format(error_message), exc_info=TRUE)
def _get_ldap_connection(self): ldap_args = {} ldap_ids = self.env['ldap.configure'].search([('is_available', '=', True)]) if len(ldap_ids) == 1: for rec in ldap_ids: _logger.info(u'LDAP服务器地址:%s' % rec.ldap_server) ldap_args['ldap_server'] = rec.ldap_server.encode('utf-8') _logger.info(u'LDAP binddn:%s' % rec.ldap_binddn) ldap_args['ldap_binddn'] = rec.ldap_binddn.encode('utf-8') _logger.info(u'LDAP 密码:%s' % rec.ldap_password) ldap_args['ldap_password'] = rec.ldap_password.encode('utf-8') else: con = ldap.open(ldap_args.get('ldap_server')) con.protocol_version = ldap.VERSION3 con.set_option(ldap.OPT_REFERRALS, 0) # Bind/authenticate with a user with apropriate rights to add objects con.simple_bind_s(ldap_args.get('ldap_binddn'), ldap_args.get('ldap_password')) return con else: raise ValidationError(u'Ldap配置发生错误,仅且只能配置一个生效!') return False
def ldap_attributes(userName, userPassword): try: l = ldap.open(LDAP_SERVER) ldap_result_id = l.search( LDAP_BASE_DN, ldap.SCOPE_SUBTREE, LDAP_ATTR + userName, None ) result_type, result_data = l.result(ldap_result_id, 0) if result_type != ldap.RES_SEARCH_ENTRY or result_data == []: return user = result_data[0][0] l.simple_bind_s(user, userPassword) ldap_result_id = l.search(user, ldap.SCOPE_BASE) result_type, result_data = l.result(ldap_result_id, 0) if result_type != ldap.RES_SEARCH_ENTRY or result_data == []: return l.unbind_s() return result_data[0][1] except ldap.LDAPError, e: print e
def fetch(self, additional_filter_str=None): if additional_filter_str is None: additional_filter_str = "" filter_str = "(%s%s)" % (self.filter_str, additional_filter_str) ldap_obj = ldap.open(self.ldap_url, self.ldap_port) ldap_obj.simple_bind('', '') try: bdii_data = ldap_obj.search_s(self.base, ldap.SCOPE_SUBTREE, filter_str) except ldap.FILTER_ERROR as e: raise ValueError("LDAP filter error for '%s': %s" % (filter_str, e)) del ldap_obj out_data = {} for elarr in bdii_data: el1, el2 = elarr if el1 in out_data: raise RuntimeError("Dublicate element found: " + el1) out_data[el1] = el2 del bdii_data return out_data
def bindAdmin(self, USERNAME, PASSWORD): conn = ldap.open(self.LDAP_HOST, self.LDAP_PORT) conn.protocol_version = ldap.VERSION3 username = "******" + USERNAME + "," + self.LDAP_BASEDN logger.debug("bind admin %s" % username) conn.bind_s(username, PASSWORD) return conn
def search_LDAP_user(request): connect = ldap.open(ldap_server) attributes = request.POST.get('attributes') if attributes: attributes = attributes.replace(" ", "").split(',') search_filter = request.POST.get('filter') if not search_filter: search_filter = 'objectClass=*' scope = request.POST.get('scope') try: scope = int(scope) if scope not in range(4): raise except Exception as e: scope = ldap.SCOPE_SUBTREE base_dn = "dc=homework5,dc=mutiny,dc=codes" try: result = connect.search_s(base_dn, scope, search_filter, attributes) connect.unbind_s() return result except ldap.LDAPError as e: connect.unbind_s() return 0
def lpa(): ldap_server="10.224.210.11" username = "******" password= "******" # the following is the user_dn format provided by the ldap server user_dn = "CN="+username+",CN=Users,DC=lab,DC=local" # adjust this to your base dn for searching base_dn = "dc=lab,dc=local" connect = ldap.open(ldap_server) search_filter = "uid="+username try: #if authentication successful, get the full user data connect.bind_s("*****@*****.**",password) #result = connect.search_s(base_dn,ldap.SCOPE_SUBTREE,search_filter) # return all user data results ldap_result = connect.search(base_dn, ldap.SCOPE_SUBTREE, "(&(objectClass=Person)(cn=ann))", None) res_type, data = connect.result(ldap_result, 0) print(data) connect.unbind_s() #print result except ldap.LDAPError as e: connect.unbind_s() print e return 1
def main(): if os.getuid() != 0: print "Must be run as root." return SUCCESS try: ldap_server = sys.argv[1] ldap_user = sys.argv[2] ldap_password = sys.argv[3] ldap_base_users = sys.argv[4] ldap_base_groups = sys.argv[5] ldap_default_pw = sys.argv[6] except KeyboardInterrupt: print print "Cancelled" return FAIL except (IndexError, ValueError,): print "Usage:" print "%s serverURI userDN userPW usersDN groupsDN defaultUserPW" % sys.argv[0] print print "Example:" print "%s 127.0.0.1 cn=admin,dc=domain,dc=com qwerty dc=users,dc=domain,dc=com dc=groups,dc=domain,dc=com 1q2w3e4r5t6y" % sys.argv[0] return FAIL try: conn = ldap.open(ldap_server) conn.simple_bind_s(ldap_user, ldap_password) except ldap.LDAPError, e: print e.args[0]["desc"] return FAIL
def ldap_lookup(username): """ Performs a ldap lookup to find the email address associated with username. If none exists, it returns the empty string.""" import ldap try: conn = ldap.open("ldap.dre.vanderbilt.edu") conn.protocol_version = ldap.VERSION3 baseDN = "dc=dre,dc=vanderbilt,dc=edu" scope = ldap.SCOPE_SUBTREE attrFilter = None searchFilter = "uid=" + username result = conn.search(baseDN, scope, searchFilter, attrFilter) result_type, result_data = conn.result(result, 0) email = "" if (result_data != []) and (result_type == ldap.RES_SEARCH_ENTRY): # we have a valid result! if (result_data[0][1].has_key('mail')): email = result_data[0][1]['mail'][0] elif (result_data[0][1].has_key('svnmail')): email = result_data[0][1]['svnmail'][0] else: email = "" conn.unbind() return email except: # Some error occurred when looking this guy up. return ""
def main(srv, usr, pwd): con = ldap.open(srv) con.simple_bind_s(usr, pwd) # display a "header" line print "User ID\tUser Name\tUser Email\tManager Name\tManager Email" # do a loop here to read the input file line-by-line file = open("users.txt") while 1: line = file.readline() if not line: break # parse each line for the user id uid = line.split("\t")[0] # lookup user att = userlu(con, "sAMAccountName=" + uid) if att: mgr = att["manager"][0].replace("\\", "") mgr = mgr.split("OU=")[0].rstrip(", ") mgr = mgr.replace("(", "\(") mgr = mgr.replace(")", "\)") # lookup the manager so we can get his email and lan ID mgr_att = userlu(con, mgr) mgr_email = mgr_att["mail"][0] print "%s\t%s\t%s\t%s\t%s" % (uid, att["cn"][0], att["mail"][0], mgr.lstrip("CN="), mgr_email) else: # what we have here is a terminated employee print "%s\t\t\t\t" % (uid)
def LDAPLookup(name='', uid=''): """ Simple LDAP Lookup """ LDAPServer = 'ldap.my.org' searchBase = 'ou=People,dc=my,dc=org' searchScope = ldap.SCOPE_SUBTREE if name == '': searchName = 'uid=%s' % uid else: searchName = 'cn=*%s*' % name fieldList = ['uid', 'cn', 'mail', 'title', 'telephoneNumber', 'ou'] users = [] l = ldap.open(LDAPServer) l.simple_bind_s() # synchronous bind with no parameters = anonymous ldap_result_id = l.search(searchBase, searchScope, searchName, fieldList) while 1: result_type, result_data = l.result(ldap_result_id, 0) if (result_data == []): break else: for item in result_data: users.append(item[1]) return users
def generate_ldap_changes(giedo): todo = {'upsert': [], 'remove': []} l = ldap.open(settings.LDAP_HOST) l.bind_s(settings.LDAP_USER, settings.LDAP_PASS) try: users = Es.by_name('leden').get_members() unaccounted_for = set() in_ldap = {} for dn, entry in l.search_s(settings.LDAP_BASE, ldap.SCOPE_ONELEVEL): unaccounted_for.add(entry['uid'][0]) in_ldap[(entry['uid'][0])] = (entry['uid'][0], entry['mail'][0], entry['sn'][0], entry['cn'][0]) for u in users: uid = str(u.name) should_have = (uid, u.canonical_email, u.last_name.encode('utf-8'), unicode(u.humanName).encode('utf-8')) if uid in unaccounted_for: unaccounted_for.remove(uid) if in_ldap[uid] == should_have: continue logging.info('ldap: updating %s', uid) else: logging.info('ldap: adding %s', uid) todo['upsert'].append(should_have) for uid in unaccounted_for: todo['remove'].append(uid) logging.info('ldap: removing %s', uid) finally: l.unbind_s() return todo
def modify(self, dn, attrs): try: l = ldap.open(self.host) l.simple_bind_s(self.dn, self.password) l.modify_s(dn.encode('latin-1'), attrs) except ldap.LDAPError, error_message: raise error_message
def authenticate(self,username,password): try: l = ldap.open("ad.unsw.edu.au") l.protocol_version = ldap.VERSION3 upn = username + '@ad.unsw.edu.au' l.bind_s(upn, password) baseDN = "OU=IDM_People,OU=IDM,DC=ad,DC=unsw,DC=edu,DC=au" searchScope = ldap.SCOPE_SUBTREE retrieveAttributes = ['cn', 'displayNamePrintable', 'givenName', 'sn', 'mail'] searchFilter = "cn=" + username ldap_result = l.search(baseDN, searchScope, searchFilter, retrieveAttributes) result_type, result_data = l.result(ldap_result, 0) user_dn,attr_results = result_data[0] try: user = User.objects.get(username=attr_results['cn'][0]) return user except User.DoesNotExist: user = User(username=username, password='******') user.is_staff = False user.is_superuser = False user.first_name = attr_results['givenName'][0] user.last_name = attr_results['sn'][0] user.email = attr_results['mail'][0] user.save() return user except ldap.LDAPError, e: print e return None
def getMembersOfGroup(self, group): oldap = ldap.open(LDAP_HOST, LDAP_PORT) oldap.simple_bind_s() resultset = ['gidnumber', 'cn', 'memberuid'] if str(group).isdigit(): # Group ID filter = "(&(objectClass=posixGroup)(gidnumber=" + str(group) + "))" else: # Common Name filter = "(&(objectClass=posixGroup)(cn=" + str(group) + "))" result = oldap.search_s(LDAP_DN_GROUPS, 1, filter, resultset) v = result[0][1] if 'memberUid' in v: filter = "" for i in v['memberUid']: filter += "(uid=" + i + ")" filter = "(&(objectClass=posixAccount)(|" + filter + "))" if filter != "": return self._getMembers(filter) else: return {}
def ldapAuthen(ldapServer, user, passwd): try: # Connect to the ldap server via port 389 l = ldap.open(host=ldapServer, port=389) # Set some options to allow it to authenticate. l.protocol_version = 3 l.set_option(ldap.OPT_REFERRALS, 0) # Authenticate to the AD. l.simple_bind_s(user, passwd) print("LDAP object bound") res = l.search_s("CN=Users,DC=ctf,DC=org", ldap.SCOPE_SUBTREE, "(objectClass=User)") # Print all users. for dn, entry in res: print dn # Exit after authentication l.unbind_s() print("Unbound") # Return an array indicating successful authentication. return ([1, ""]) # If an exception is created, print a descriptive message and return an array indicating failure. except ldap.LDAPError, e: print "Exception created: " + e[0]["desc"] return ([0, e[0]["desc"]])
def authenticate(self, authentication): """Using the user_dn_patterns, find the user's entry, and then bind to the entry using supplied credentials.""" username = self.user_dn_patterns.replace("{0}", authentication.username) baseDn = self.context_source.base() parts = username.split(",") if len(parts) > 1: username = parts[0] baseDn = ",".join(parts[1:]) + "," + baseDn (host, port) = self.context_source.server() self.logger.debug("Opening connection to server %s/%s" % (host, int(port))) l = ldap.open(host, int(port)) self.logger.debug("Searching for %s in %s" % (username, baseDn)) result_set = l.search_s(baseDn, ldap.SCOPE_SUBTREE, username, None) if len(result_set) != 1: raise BadCredentialsException("Found %s entries at %s/%s. Should only be 1." % (len(result_set), baseDn, username)) dn = result_set[0][0] self.logger.debug("Attempting to bind %s" % dn) try: l.simple_bind_s(dn, authentication.password) self.logger.debug("Successfully bound to server!") return (result_set[0],l) except Exception, e: self.logger.debug("Error %s" % e) raise BadCredentialsException("Invalid password")
def configure_user(self, user, ): username = user.username user.set_unusable_password() con = ldap.open('ldap.mit.edu') con.simple_bind_s("", "") dn = "dc=mit,dc=edu" fields = ['cn', 'sn', 'givenName', 'mail', ] userfilter = ldap.filter.filter_format('uid=%s', [username]) result = con.search_s('dc=mit,dc=edu', ldap.SCOPE_SUBTREE, userfilter, fields) if len(result) == 1: user.first_name = result[0][1]['givenName'][0] user.last_name = result[0][1]['sn'][0] user.email = result[0][1]['mail'][0] try: user.groups.add(auth.models.Group.objects.get(name='MIT')) except ObjectDoesNotExist: print "Failed to retrieve mit group" else: raise ValueError, ("Could not find user with username '%s' (filter '%s')"%(username, userfilter)) try: user.groups.add(auth.models.Group.objects.get(name='autocreated')) except ObjectDoesNotExist: print "Failed to retrieve autocreated group" user.save() return user
def getAllLdapUser( ): ldapip = SETTINGS.getValue( 'ldap' ) if SETTINGS.getValue( 'ldap' ) else '10.0.99.10' l=ldap.open( ldapip ) uname="CN=ipipeline,CN=Users,DC=digitalidea,DC=co,DC=kr" password="******" l.protocol_version=ldap.VERSION3 l.simple_bind_s(uname,password) base_dn = 'CN=Users,DC=digitalidea,DC=co,DC=kr' attr = ['info','sAMAccountNAME' , 'mail' ] result = l.search_s(base_dn,ldap.SCOPE_SUBTREE ,) dict = {} depts = list(set( [ x[1].get('mail')[0] for x in result if x[1].get('mail')!= None ] )) users = [ x[1] for x in result if 'info' in x[1].keys() and 'sAMAccountName' in x[1].keys() ] for x in users: if x.get('mail') == None: if dict.get( 'Null' ) == None : dict[ 'Null' ] = [] dict[ 'Null' ].append( ( unicode( x['info'][0] ) , x['sAMAccountName'][0] ) ) else: if dict.get( x.get('mail')[0] ) == None : dict[ x.get('mail')[0] ] = [] dict[ x.get('mail')[0] ].append( ( unicode( x['info'][0] ) , x['sAMAccountName'][0] ) ) return dict
def addEntry(self, password, uid, properties): server = self.portal_properties.dipp_properties.ldap_server ou = self.portal_properties.dipp_properties.ldap_ou who = "uid=" + uid + ",ou=" + ou + ",dc=dipp,dc=nrw,dc=de" cred = password l = ldap.open(server) l.simple_bind_s(who, cred) givenName = properties['givenName'] surname = properties['surname'] cn = properties['givenName'] + " " + properties['surname'] preferredLanguage = properties['preferredLanguage'] mail = properties['email'] LOG('DiPP', INFO, mail) modlist = ldap.modlist.modifyModlist({'givenName': uid}, {'givenName': givenName}) l.modify(who, modlist) modlist = ldap.modlist.modifyModlist({'surname': uid}, {'surname': surname}) l.modify(who, modlist) modlist = ldap.modlist.modifyModlist({'cn': uid}, {'cn': cn}) l.modify(who, modlist) modlist = ldap.modlist.modifyModlist( {'preferredLanguage': uid}, {'preferredLanguage': preferredLanguage}) l.modify(who, modlist) modlist = ldap.modlist.modifyModlist({'mail': uid}, {'mail': mail}) l.modify(who, modlist) return modlist
def configure_user(self, user): username = user.username user.set_unusable_password() con = ldap.open("ldap.mit.edu") con.simple_bind_s("", "") dn = "dc=mit,dc=edu" fields = ["cn", "sn", "givenName", "mail"] userfilter = ldap.filter.filter_format("uid=%s", [username]) result = con.search_s("dc=mit,dc=edu", ldap.SCOPE_SUBTREE, userfilter, fields) if len(result) == 1: user.first_name = result[0][1]["givenName"][0] user.last_name = result[0][1]["sn"][0] user.email = result[0][1]["mail"][0] try: user.groups.add(auth.models.Group.objects.get(name="MIT")) except ObjectDoesNotExist: print "Failed to retrieve mit group" else: raise ValueError, ("Could not find user with username '%s' (filter '%s')" % (username, userfilter)) try: user.groups.add(auth.models.Group.objects.get(name="autocreated")) except ObjectDoesNotExist: print "Failed to retrieve autocreated group" user.save() return user
def ldap_fetch(username): name, mail, number = ("", ) * 3 con = ldap.open('ldap-too.mit.edu') con.simple_bind_s("", "") dn = "dc=mit,dc=edu" fields = ['cn', 'sn', 'givenName', 'mail', 'telephoneNumber'] userfilter = ldap.filter.filter_format('uid=%s', [username]) results = con.search_s('dc=mit,dc=edu', ldap.SCOPE_SUBTREE, userfilter, fields)[0][1] try: name = results['givenName'][0] + " " + results['sn'][0] except: pass try: mail = results['mail'][0] except: pass try: number = results['telephoneNumber'][0] except: pass return name, mail, number
def ldap_setpass(daan, user, password): if not password: return if not settings.LDAP_PASS: logging.warning('ldap: no credentials available, skipping') return l = ldap.open(settings.LDAP_HOST) l.bind_s(settings.LDAP_USER, settings.LDAP_PASS) udn = 'uid=%s,%s' % (user, settings.LDAP_BASE) try: # Set LDAP password l.passwd_s(udn, None, password) # Set SAMBA password entries (to support MSCHAPv2 authentication # for WiFi via FreeRADIUS via LDAP). res = l.search_s(settings.LDAP_BASE, ldap.SCOPE_ONELEVEL, 'uid=%s' % user) if not res: return _o = res[0][1] if 'sambaNTPassword' in _o: l.modify_s(udn, ldap.modlist.modifyModlist( {'sambaNTPassword': _o['sambaNTPassword'][0]}, {'sambaNTPassword': [nthash(password)]})) else: # NOTE See /doc/ldap/scheme.ldif # We added the scheme *after* the creation of the database. # Thus, the user may still miss the objectClass knAccount. l.modify_s(udn, ldap.modlist.modifyModlist( {'objectClass': _o['objectClass']}, {'objectClass': _o['objectClass'] + ['knAccount'], 'sambaNTPassword': [nthash(password)]})) finally: l.unbind_s()
def authenticate(self, username=None, password=None): base = "dc=ncsu,dc=edu" scope = ldap.SCOPE_SUBTREE filter = "(&(objectClass=ncsuPerson)(uid=%s))" % username ret = ['dn', 'givenName', 'ncsuPrimaryEMail', 'sn'] # Authenticate base user to search try: l = ldap.open(LDAP_SERVER) l.protocol_version = ldap.VERSION3 l.simple_bind_s(LDAP_USER,LDAP_PASS) except ldap.LDAPError: return None # Get info from ldap server try: result_id = l.search(base, scope, filter, ret) result_type, result_data = l.result(result_id, 0) # if user does not exist, fail if (len(result_data) != 1): return None # Bind to user's DN l.simple_bind_s(result_data[0][0], password) # Get further user info result_id = l.search(base, scope, filter, ret) result_type, result_data = l.result(result_id, 0) user_info = result_data[0][1] # If that didn't throw an exception, the user must have authed # and we can get or create a user object for the user. try: user = User.objects.get(username__exact=username) except: if 'mail' in user_info: email = user_info['mail'][0] else: email = "*****@*****.**" % username if 'givenName' in user_info: firstname = user_info['givenName'][0] else: firstname = '' if 'sn' in user_info: lastname = user_info['sn'][0] else: lastname = '' temp_pass = User.objects.make_random_password(12) user = User.objects.create_user(username, email , temp_pass) user.first_name = firstname user.last_name = lastname user.is_staff = False user.save() # We've created a a user, now we return it to Django. return user except ldap.INVALID_CREDENTIALS: # We couldn't successfully auth against the LDAP server with the # supplied username and password, so we fail. return None
def main (): # This routine expects to receive a userid, challenge, and # password on stdin as newline-separated strings: # like "yoda\n12345 abcd\nPW\n" # # Typically the inbound "password" will actually be a # site-defined hash of the real password and the challenge. # user = raw_input() challenge = raw_input() pw_hash = raw_input() # Simple username validation and early out. if not user.islower() or not is_ascii(user): return 1 LDAP_ADDR = 'od2.london.baseblack.com' LDAP_CONFIG = 'uid=%s,cn=users,dc=od1,dc=london,dc=baseblack,dc=com' % user ldsrvr = ldap.open(LDAP_ADDR) cred = pw_hash.strip() rc = 0 try: ldsrvr.simple_bind_s(LDAP_CONFIG, cred) except ldap.LDAPError, error_message: who = "uid=%s,ou=sysaccounts,o=pixar.com" % user try: ldsrvr.bind_s(LDAP_CONFIG, cred) except ldap.LDAPError, error_message: rc = 1
def verify(my, login_name, password): # replace cn=attribute with cn={login} in the config ldap_path # e.g. cn={login},o=organization,ou=server,dc=domain path = Config.get_value("security", "ldap_path") server = Config.get_value("security", "ldap_server") assert path, server my.login_name = login_name my.internal = True path = path.replace("{login}", login_name) #import ldap try: l = ldap.open(server) l.simple_bind_s(path, password) l.unbind() return True except: login = Login.get_by_login(login_name) # check if it's an external account and verify with standard approach if login and login.get_value('location', no_exception=True) == 'external': auth_class = "pyasm.security.TacticAuthenticate" authenticate = Common.create_from_class_path(auth_class) is_authenticated = authenticate.verify(login_name, password) if is_authenticated == True: my.internal = False return True elif login: auth_class = "pyasm.security.TacticAuthenticate" authenticate = Common.create_from_class_path(auth_class) is_authenticated = authenticate.verify(login_name, password) if is_authenticated == True: my.internal = False return True raise SecurityException("Login/Password combination incorrect")
def bindUser(self, USERNAME, PASSWORD): conn = ldap.open(self.LDAP_HOST, self.LDAP_PORT) conn.protocol_version = ldap.VERSION3 username = "******" + USERNAME + ", ou=users," + self.LDAP_BASEDN logger.debug("bind user %s" % username) conn.simple_bind_s(username, PASSWORD) return conn
def delete_user(self, uid): try: l = ldap.open(self.host) l.simple_bind_s(self.dn, self.password) l.delete_s("uid="+uid+",ou="+self.user_ou+","+self.base_dn) except ldap.LDAPError, error_message: print error_message
def connect(ldif=0): global connection global reconnect if connection and not reconnect: return connection if not os.path.exists(LDIF_FILE) and not ldif: # ldap connection if not os.path.exists('/etc/ldap/rootpw.conf'): pw = new_password() init_slapd('restart') else: pw = get_password() if not pw: pw = new_password() init_slapd('restart') local_ip = '127.0.0.1' local_port = listener.baseConfig.get('slapd/port', '7389').split(',')[0] connection = ldap.open(local_ip, int(local_port)) connection.simple_bind_s( 'cn=update,' + listener.baseConfig['ldap/base'], pw) else: connection = LDIFObject(LDIF_FILE) reconnect = 0 return connection
def __new__( self, filename=os.path.join("data", "user.xml"), proto=ldap.VERSION3, host="127.0.0.1", base="o=anydomain.com", search_scope=ldap.SCOPE_SUBTREE, retrieve_attr=None, ): """Constructor. Takes a filename (optional) detailing where the user file exists, in order to create the list of users. It then verifies each user via the username attribute against the LDAP (defaulting to a local implementation LDAP). @param filename: the filename of the user XML to open (default: 'I{data/user.xml}') @type filename: str """ # obtain the users from the user file _user_f = proteomics.mascot.UserXMLInputFileReader(filename) _users = _user_f.read_file() # determined verified users by querying ldap self._verified_users = [] # instantiate ldap connection logger.info("trying to initiate connection with LDAP server...") logger.debug("connecting to server {0}, using baseDN {1}".format(host, base)) try: l = ldap.open(host) l.protocol_version = proto except ldap.LDAPERROR, e: logger.exception(e)
def check_login(username, password): """ Returns whether the given credentials (username and password) are valid credential for the dkfz AD (LDAP) Server. At the moment it will only be checked in the "ad" group. (username@ad, password) TODO: Also look in all other groups Example usage: >>> check_login("thename", "mysupersecretpassword") 1 @param username: The username to check @param password: The password to check @return: 0, 1 or 2 (0 = valid combination, 1 = wrong combination, 2 = any other error, e.g. server down) """ if len(username) <= 0 or len(password) <= 0: return 1 connect = ldap.open(library.config.peachSharedConfig.get_ldap_server()) try: connect.simple_bind_s( library.config.peachSharedConfig.get_ldap_dn(username), password) return 0 except ldap.LDAPError: connect.unbind_s() return 1 except: return 2
def search(dn, filtre): """ Search in the ResEl LDAP with the given parameters >>> search('ou=machines,dc=resel,dc=enst-bretagne,dc=fr', '(Zone=User)') """ try: try: l = ldap.open('ldap.maisel.enst-bretagne.fr') l.protocol_version = ldap.VERSION3 except ldap.LDAPError, e: print(e) retrieveAttributes = None searchScope = ldap.SCOPE_SUBTREE try: ldap_result_id = l.search(dn, searchScope, filtre, retrieveAttributes) result_type, result_data = l.result(ldap_result_id, 0) if (result_data == []): sys.exit(0) else: if result_type == ldap.RES_SEARCH_ENTRY: search_results = result_data[0] return search_results except ldap.LDAPError, e: print(e)
def delete_group(self, cn): try: l = ldap.open(self.host) l.simple_bind_s(self.dn, self.password) l.delete_s("cn="+cn+",ou="+self.group_ou+","+self.base_dn) except ldap.LDAPError, error_message: print error_message
def retrieveTree(host, user, password, baseDN): dcn = 0 noError = False noResult = True searchScope = ldap.SCOPE_SUBTREE retrieveAttributes = [''] searchFilter = "" # Try 3 times to connect to LDAP server while (dcn < 3) and (not noError): ldapConnector = ldap.open(host) ldapConnector.protocol_version = ldap.VERSION3 ldapConnector.simple_bind("%s, %s" % (user, baseDN), password) try: ldap_result_id = ldapConnector.search( baseDN, searchScope) #, searchFilter, retrieveAttributes) result_set = [] while noResult: result_type, result_data = ldapConnector.result( ldap_result_id, 0) if (result_data == []): noResult = False else: if result_type == ldap.RES_SEARCH_ENTRY: result_set.append(result_data) noError = True except ldap.LDAPError, e: dcn += 1 print "error", e