def example(): scp = load_settings() host = scp.get('LDAP', 'host') port = scp.getint('LDAP', 'port') basedn = scp.get('LDAP', 'basedn') binddn = scp.get('LDAP', 'binddn') bindpw = scp.get('LDAP', 'bindpw') query = '(uid=pumpkin)' print "host", host[0] c = ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient) overrides = {basedn: (host, 389)} client = yield c.connect(basedn, overrides=overrides) client = yield client.startTLS() yield client.bind(binddn, bindpw) o = ldapsyntax.LDAPEntry(client, basedn) #results = yield o.search(filterText=query, attributes=['uid', 'memberOf']) results = yield o.search(filterText=query) #results = yield o.search(filterText=query, attributes=[]) for entry in results: # Print the LDIF representation. print entry print #Access the DN print entry.dn # Print attribute values. for x in entry['uid']: print x print
def disable_dn_(self, dn, client=None): """ Deprovision subject based on DN. """ log = self.log unbind = False if client is None: client = yield self.get_ldap_client_() unbind = True with LDAPClientManager(client, active=unbind) as c: o = ldapsyntax.LDAPEntry(c, dn) results = yield o.search(filterText=self.search_filter, attributes=('userAccountControl', )) if len(results) == 1: entry = results[0] ADS_UF_ACCOUNTDISABLE = 0x00000002 user_account_control = int( list(entry['userAccountControl'])[0]) user_account_control = (user_account_control | ADS_UF_ACCOUNTDISABLE) mod = delta.ModifyOp(dn, [ delta.Replace('userAccountControl', ["{}".format(user_account_control)]), ]) l = mod.asLDAP() response = yield client.send(l)
def _fetchCb(subschemaSubentry, client): o = ldapsyntax.LDAPEntry(client=client, dn=subschemaSubentry) d = o.search(scope=pureldap.LDAP_SCOPE_baseObject, sizeLimit=1, attributes=["attributeTypes", "objectClasses"]) def handleSearchResults(l): if len(l) == 0: raise ldaperrors.LDAPOther, "No such DN" elif len(l) == 1: o = l[0] attributeTypes = [] objectClasses = [] for text in o.get("attributeTypes", []): attributeTypes.append( schema.AttributeTypeDescription(str(text))) for text in o.get("objectClasses", []): objectClasses.append(schema.ObjectClassDescription(str(text))) assert attributeTypes, "LDAP server doesn't give attributeTypes for subschemaSubentry dn=%s" % o.dn return (attributeTypes, objectClasses) else: raise ldaperrors.LDAPOther, "DN matched multiple entries" d.addCallback(handleSearchResults) return d
def get_user(self, login, password): from twisted.internet import reactor from ldaptor.protocols.ldap import ldapconnector, ldapclient, ldapsyntax if isinstance(login, unicode): login = login.encode('utf-8') if isinstance(password, unicode): password = password.encode('utf-8') server_ip = self.config.get('ldap_host', '127.0.0.1') server_port = self.config.get('ldap_port', 389) basedn = self.config.get('base_dn', 'OU=FNKC,DC=fccho-moscow,DC=ru') binddn, bindpw = login, password query = '(sAMAccountName=%s)' % login c = ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient) overrides = {basedn: (server_ip, server_port)} client = yield c.connect(basedn, overrides=overrides) try: yield client.bind(binddn, bindpw) except LDAPException as e: if e.name == 'invalidCredentials': raise EInvalidCredentials() raise o = ldapsyntax.LDAPEntry(client, basedn) results = yield o.search(filterText=query, sizeLimit=1) if not results: raise EInvalidCredentials() result = dict((name, value[0]) for name, value in results[0].items()) defer.returnValue(LdapAuthObject(result))
def fetch(client, baseObject): o = ldapsyntax.LDAPEntry(client=client, dn=baseObject) d = o.search( scope=pureldap.LDAP_SCOPE_baseObject, sizeLimit=1, attributes=["subschemaSubentry"], ) def handleSearchResults(l): if len(l) == 0: raise ldaperrors.LDAPOther("No such DN") elif len(l) == 1: o = l[0] assert "subschemaSubentry" in o, "No subschemaSubentry. TODO" subSchemas = o["subschemaSubentry"] assert ( len(subSchemas) == 1 ), "More than one subschemaSubentry is not support yet. TODO" for s in subSchemas: return s else: raise ldaperrors.LDAPOther("DN matched multiple entries") d.addCallback(handleSearchResults) d.addCallback(_fetchCb, client) return d
def example(dn_file, stats, basedn, test_starttls, test_bind, test_search, unbind): with open(dn_file, "r") as f: dns = [line.strip() for line in f] serverip = '127.0.0.1' bindpw = 'secret' for n, binddn in enumerate(dns): c = ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient) overrides = {basedn: (serverip, 10389)} client = yield c.connect(basedn, overrides=overrides) stats['attempted'] += 1 stats['att_per_s'] += 1 if test_starttls: client = yield client.startTLS() if test_bind: try: yield client.bind(binddn, bindpw) except LDAPInvalidCredentials: pass if test_search: o = ldapsyntax.LDAPEntry(client, basedn) results = yield o.search(filterText="(uid=xyzzy)", attributes=['uid']) if unbind: client.unbind() stats['successful'] += 1 stats['suc_per_s'] += 1
def data_entry(self, context, data): user = context.locate(inevow.ISession).getLoggedInRoot().loggedIn assert user entry = ldapsyntax.LDAPEntry(client=user.client, dn=self.dn) d = entry.fetch() d.addErrback(ErrorWrapper) return d
def _connected(self, client, filt, credentials): base = ldapsyntax.LDAPEntry(client, self.config.getIdentityBaseDN()) d = base.search( filterObject=filt, sizeLimit=1, attributes=[''], # TODO no attributes ) d.addCallback(self._found, credentials) return d
def _get_avatar(self, avatarId, mind): endpointstr = self._endpointstr basedn = self._basedn binddn = self._binddn bindpw = self._bindpw query = self._query_template % { 'username': escape_filter_chars(avatarId) } if self._service_based_attribs: if mind: service = mind['service'] else: service = "" if service == "" or service is None or self.service_manager is None: attributes = self._attribs else: service_entry = yield defer.maybeDeferred( self.service_manager.getMatchingService, service) if service_entry and 'attributes' in service_entry: attributes = service_entry['attributes'] else: attributes = self._attribs else: attributes = self._attribs e = clientFromString(reactor, self._endpointstr) client = yield connectProtocol(e, LDAPClient()) startTls = self._startTls startTlsHostName = self._startTlsHostName startTlsAuthority = self._startTlsAuthority if startTls: startTlsArgs = [] if startTlsHostName is not None: if startTlsAuthority is not None: ctx = optionsForClientTLS(unicode(startTlsHostName), startTlsAuthority) else: ctx = optionsForClientTLS(unicode(startTlsHostName), platformTrust()) startTlsArgs.append(ctx) client = yield client.startTLS(*startTlsArgs) yield client.bind(binddn, bindpw) o = ldapsyntax.LDAPEntry(client, basedn) results = yield o.search(filterText=query, attributes=attributes.keys()) yield client.unbind() if len(results) != 1: raise Exception("No unique account found for '%s'." % avatarId) entry = results[0] _attribs = attributes attribs = [] for key, alias in _attribs.iteritems(): if key in entry: valuelist = entry[key] for value in valuelist: attribs.append((alias, value)) user = User(avatarId, attribs) defer.returnValue(user)
def childFactory(self, context, name): entry = inevow.ISession(context).getLoggedInRoot().loggedIn filt = uriUnquote(name) e = ldapsyntax.LDAPEntry(client=entry.client, dn=self.baseObject) d = e.search(filterText=filt, sizeLimit=20) d.addCallback(ReallyMassPasswordChangePage) return d
def setUp(self): self.foo = ldapsyntax.LDAPEntry(None, dn='cn=foo,dc=example,dc=com', attributes={ 'objectClass': ['person'], 'cn': ['foo', 'thud'], 'sn': ['bar'], 'more': ['junk'], })
def _search(proto, base, connection, numOfSearches): l = [] baseEntry = ldapsyntax.LDAPEntry(client=proto, dn=base) for search in range(0, numOfSearches): d = baseEntry.search(callback=lambda x: _handle_entry(x, connection, search)) d.addErrback(error) l.append(d) dl = defer.DeferredList(l) return dl
def _bind(self): timeout = self.config.getfloat('timeout') client = yield self.creator.connect(self.config['base dn'], overrides=self.overrides, timeout=timeout) if self.config.getboolean('tls'): client = yield client.startTLS() o = ldapsyntax.LDAPEntry(client, self.config['bind dn']) yield o.bind(self.config['bind pw']) defer.returnValue(client)
def _handle_bind_success(self, x): matchedDN, serverSaslCreds = x o = ldapsyntax.LDAPEntry(client=self, dn="") d = o.search( filterText="(objectClass=*)", scope=pureldap.LDAP_SCOPE_baseObject, attributes=["namingContexts"], callback=(lambda x: self._printResults(x, self.factory.server)), ) d.chainDeferred(self.factory.deferred)
def _search(proto, base): baseEntry = ldapsyntax.LDAPEntry(client=proto, dn=base) d=baseEntry.search(scope=pureldap.LDAP_SCOPE_baseObject, sizeLimit=1) def _cb(result, proto): proto.unbind() return result d.addBoth(_cb, proto) return d
def _got_password(self, password, dn): assert len(password) == 1 password = password[0] o = ldapsyntax.LDAPEntry(client=self, dn=dn) d = o.setPassword(newPasswd=password) d.addCallbacks( callback=self._report_new_password, callbackArgs=(dn, password), errback=self._report_ldap_error, ) return d
def _nonUserEditableAttributeType_getFreeNumber(self, attributeType, context): cfg = context.locate(interfaces.ILDAPConfig) entry = context.locate(inevow.ISession).getLoggedInRoot().loggedIn client = entry.client o = ldapsyntax.LDAPEntry(client=client, dn=cfg.getBaseDN()) d = numberalloc.getFreeNumber(ldapObject=o, numberType=attributeType, min=1000) d.addCallback(lambda x, a=attributeType: (a, [str(x)])) return d
def setUp(self): self.foo = ldapsyntax.LDAPEntry( None, dn="cn=foo,dc=example,dc=com", attributes={ "objectClass": ["person"], "cn": ["foo", "thud"], "sn": ["bar"], "more": ["junk"], }, )
def _search(proto, dn, searchFilter, scope): baseEntry = ldapsyntax.LDAPEntry(client=proto, dn=dn) d=baseEntry.search(filterObject=searchFilter, scope=scope, sizeLimit=20, sizeLimitIsNonFatal=True) def _cb(result, proto): proto.unbind() return result d.addBoth(_cb, proto) return d
def search(self, searchdn, search_filter='(objectClass=*)', attributes=None, callback=None): client = yield self._bind() o = ldapsyntax.LDAPEntry(client, searchdn) results = yield o.search(filterText=search_filter, attributes=attributes) self._disconnect(client) if callback is not None: callback(results) defer.returnValue(results)
def _connected(self, client, filt, _credentials, deferred): base = ldapsyntax.LDAPEntry(client, self.config.getIdentityBaseDN()) d = base.search(filterObject=filt, sizeLimit=1, attributes=[self.uid_attrname]) def err(_failure, _deferred): log.msg(_failure.getErrorMessage()) _deferred.errback( failure.Failure(UnauthorizedLogin('Object not found'))) d.addCallback(self._found, _credentials, deferred) d.addErrback(err, deferred)
def example(): serverip = '192.168.128.21' basedn = 'dc=example,dc=com' binddn = '*****@*****.**' bindpw = 'secret' query = '(cn=Babs*)' c = ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient) overrides = {basedn: (serverip, 389)} client = yield c.connect(basedn, overrides=overrides) yield client.bind(binddn, bindpw) o = ldapsyntax.LDAPEntry(client, basedn) results = yield o.search(filterText=query) for entry in results: print(entry)
def search(client, query, basedn=None): """ Search for "query" at "basedn" :param client: LDAPClient :param query: string to search, like "(uid=kdreyer)" :param basedn: string, or None to use the default Helga LDAP basedn :returns: a deferred that when fired returns a list of LDAPEntryWithClient """ if basedn is None: basedn = settings.LDAP['basedn'] # dc=example,dc=com o = ldapsyntax.LDAPEntry(client, basedn) results = yield o.search(filterText=query) # for entry in results: # print(entry) defer.returnValue(results)
def search(client, baseDN, filt): e = ldapsyntax.LDAPEntry(client=client, dn=baseDN) d = e.search( filterObject=filt, attributes=[ "uid", "uidNumber", "gidNumber", "gecos", "cn", "homeDirectory", "loginShell", ], callback=_cbSearch, ) return d
def data_servicePasswords(self, ctx, data): user = ctx.locate(inevow.ISession).getLoggedInRoot().loggedIn config = interfaces.ILDAPConfig(ctx) e = ldapsyntax.LDAPEntry(client=user.client, dn=config.getBaseDN()) d = e.search(filterObject=pureldap.LDAPFilter_and([ pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription('objectClass'), assertionValue=pureldap.LDAPAssertionValue( 'serviceSecurityObject')), pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription('owner'), assertionValue=pureldap.LDAPAssertionValue(str(self.dn))), pureldap.LDAPFilter_present('cn'), ]), attributes=['cn']) return d
def _get_dn(self, client, username): basedn = self._basedn binddn = self._binddn bindpw = self._bindpw query = self._query_template % { 'username': escape_filter_chars(username) } try: yield client.bind(binddn, bindpw) except Exception as ex: log.err(ex) raise LDAPAdminBindError("Error binding with admin DN: %s." % binddn) o = ldapsyntax.LDAPEntry(client, basedn) results = yield o.search(filterText=query, attributes=['dn']) if len(results) != 1: raise UnauthorizedLogin() entry = results[0] defer.returnValue(entry.dn)
def resolve_attributes(self, subject): """ Return a Deferred that fires with the attributes for a subject. Atributes are a mapping of keys to a list of values. """ log = self.log attribs = {} # Connect and BIND to a directory. client = yield self.get_ldap_client() # Search for a subject. attributes = self.attributes base_dn = self.base_dn o = ldapsyntax.LDAPEntry(client, base_dn) fltr = self.filter_template.render(subject=subject) log.debug("LDAP fltr: {fltr}", fltr=fltr) try: results = yield o.search(filterText=fltr, attributes=attributes) except Exception as ex: self.log.error("Error while searching for LDAP subject {subject}", event_type='error_load_ldap_subject', subject=subject) raise finally: self.release_ldap_client_() log.debug("{classname}: Scheduled LDAP client for release.", classname=self.__class__.__name__) for n, entry in enumerate(results): if n != 0: raise Exception( "Multiple entries received for subject `{subject}`.". format(subject=subject)) # Collect the values for the relevant attributes. for name in attributes: value = entry.get(name, None) if value is not None: attribs[name] = list(value) log.debug("RESULTS: {results}", results=results) if len(results) == 0: raise Exception( "Could not find subject `{subject}` in LDAP DIT.".format( subject)) returnValue(attribs)
def start(self, ldapObject): assert 'objectClass' in ldapObject if 'posixAccount' not in ldapObject['objectClass']: raise autofill.ObjectMissingObjectClassException(ldapObject) assert 'loginShell' not in ldapObject ldapObject['loginShell'] = ['/bin/sh'] baseObject = ldapsyntax.LDAPEntry(client=ldapObject.client, dn=self.baseDN) d1 = self.freeNumberGetter(baseObject, 'uidNumber', min=1000) d2 = self.freeNumberGetter(baseObject, 'gidNumber', min=1000) d = defer.DeferredList([d1, d2], fireOnOneErrback=1) # silence the log d1.addErrback(lambda x: None) d2.addErrback(lambda x: None) d.addCallback(self._cb_gotNumbers, ldapObject) return d
def delete(self, ctx): request = inevow.IRequest(ctx) user = request.getSession().getLoggedInRoot().loggedIn e = ldapsyntax.LDAPEntry(client=user.client, dn=self.dn) d = e.delete() def cb(dummy): basedn = iwebui.ICurrentDN(ctx) while (basedn != '' and self.dn.contains(basedn)): basedn = basedn.up() u = url.URL.fromContext(ctx) u = u.parentdir().parentdir() if basedn != '': u = u.child(basedn).child('search') request.setComponent(iformless.IRedirectAfterPost, u) return _("Deleted %s.") % self.dn def eb(fail): return _("Failed: %s.") % fail.getErrorMessage() d.addCallbacks(cb, eb) return d
def move(client, fromDN, toDN): e = ldapsyntax.LDAPEntry(client=client, dn=fromDN) d = e.move(toDN) return d