def test_bind_noMatchingServicesFound_fallback_success(self): server = self.createServer( services=['svc1', 'svc2', 'svc3', ], fallback=True, responses=[ [ pureldap.LDAPSearchResultDone(ldaperrors.Success.resultCode) ], [ pureldap.LDAPSearchResultDone(ldaperrors.Success.resultCode) ], [ pureldap.LDAPSearchResultDone(ldaperrors.Success.resultCode) ], [ pureldap.LDAPBindResponse(resultCode=ldaperrors.Success.resultCode) ], ]) server.dataReceived(str(pureldap.LDAPMessage(pureldap.LDAPBindRequest(dn='cn=jack,dc=example,dc=com', auth='s3krit'), id=4))) reactor.iterate() #TODO client = server.client client.assertSent( pureldap.LDAPSearchRequest(baseObject='dc=example,dc=com', derefAliases=0, sizeLimit=0, timeLimit=0, typesOnly=0, filter=ldapfilter.parseFilter('(&' +'(objectClass=serviceSecurityObject)' +'(owner=cn=jack,dc=example,dc=com)' +'(cn=svc1)' +('(|(!(validFrom=*))(validFrom<=%s))' % server.now) +('(|(!(validUntil=*))(validUntil>=%s))' % server.now) +')'), attributes=('1.1',)), pureldap.LDAPSearchRequest(baseObject='dc=example,dc=com', derefAliases=0, sizeLimit=0, timeLimit=0, typesOnly=0, filter=ldapfilter.parseFilter('(&' +'(objectClass=serviceSecurityObject)' +'(owner=cn=jack,dc=example,dc=com)' +'(cn=svc2)' +('(|(!(validFrom=*))(validFrom<=%s))' % server.now) +('(|(!(validUntil=*))(validUntil>=%s))' % server.now) +')'), attributes=('1.1',)), pureldap.LDAPSearchRequest(baseObject='dc=example,dc=com', derefAliases=0, sizeLimit=0, timeLimit=0, typesOnly=0, filter=ldapfilter.parseFilter('(&' +'(objectClass=serviceSecurityObject)' +'(owner=cn=jack,dc=example,dc=com)' +'(cn=svc3)' +('(|(!(validFrom=*))(validFrom<=%s))' % server.now) +('(|(!(validUntil=*))(validUntil>=%s))' % server.now) +')'), attributes=('1.1',)), pureldap.LDAPBindRequest(dn='cn=jack,dc=example,dc=com', auth='s3krit')) self.assertEquals(server.transport.value(), str(pureldap.LDAPMessage(pureldap.LDAPBindResponse(resultCode=ldaperrors.Success.resultCode), id=4)))
def search( self, filterText=None, filterObject=None, attributes=(), scope=None, derefAliases=None, sizeLimit=0, timeLimit=0, typesOnly=0, callback=None, ): if filterObject is None and filterText is None: filterObject = pureldap.LDAPFilterMatchAll elif filterObject is None and filterText is not None: filterObject = ldapfilter.parseFilter(filterText) elif filterObject is not None and filterText is None: pass elif filterObject is not None and filterText is not None: f = ldapfilter.parseFilter(filterText) filterObject = pureldap.LDAPFilter_and((f, filterObject)) if scope is None: scope = pureldap.LDAP_SCOPE_wholeSubtree if derefAliases is None: derefAliases = pureldap.LDAP_DEREF_neverDerefAliases # choose iterator: base/children/subtree if scope == pureldap.LDAP_SCOPE_wholeSubtree: iterator = self.subtree elif scope == pureldap.LDAP_SCOPE_singleLevel: iterator = self.children elif scope == pureldap.LDAP_SCOPE_baseObject: def iterateSelf(callback): callback(self) return defer.succeed(None) iterator = iterateSelf else: raise ldaperrors.LDAPProtocolError("unknown search scope: %r" % scope) results = [] if callback is None: matchCallback = results.append else: matchCallback = callback # gather results, send them def _tryMatch(entry): if entry.match(filterObject): matchCallback(entry) iterator(callback=_tryMatch) if callback is None: return defer.succeed(results) else: return defer.succeed(None)
def search( self, filterText=None, filterObject=None, attributes=(), scope=None, derefAliases=None, sizeLimit=0, timeLimit=0, typesOnly=0, callback=None, ): if filterObject is None and filterText is None: filterObject = pureldap.LDAPFilterMatchAll elif filterObject is None and filterText is not None: filterObject = ldapfilter.parseFilter(filterText) elif filterObject is not None and filterText is None: pass elif filterObject is not None and filterText is not None: f = ldapfilter.parseFilter(filterText) filterObject = pureldap.LDAPFilter_and((f, filterObject)) if scope is None: scope = pureldap.LDAP_SCOPE_wholeSubtree if derefAliases is None: derefAliases = pureldap.LDAP_DEREF_neverDerefAliases # choose iterator: base/children/subtree if scope == pureldap.LDAP_SCOPE_wholeSubtree: iterator = self.subtree elif scope == pureldap.LDAP_SCOPE_singleLevel: iterator = self.children elif scope == pureldap.LDAP_SCOPE_baseObject: def iterateSelf(callback): callback(self) return defer.succeed(None) iterator = iterateSelf else: raise ldaperrors.LDAPProtocolError, "unknown search scope: %r" % scope results = [] if callback is None: matchCallback = results.append else: matchCallback = callback # gather results, send them def _tryMatch(entry): if entry.match(filterObject): matchCallback(entry) iterator(callback=_tryMatch) if callback is None: return defer.succeed(results) else: return defer.succeed(None)
def search(self, filterText=None, filterObject=None, attributes=(), scope=None, derefAliases=None, sizeLimit=0, sizeLimitIsNonFatal=False, timeLimit=0, typesOnly=0, callback=None): self._checkState() d = defer.Deferred() if filterObject is None and filterText is None: filterObject = pureldap.LDAPFilterMatchAll elif filterObject is None and filterText is not None: filterObject = ldapfilter.parseFilter(filterText) elif filterObject is not None and filterText is None: pass elif filterObject is not None and filterText is not None: f = ldapfilter.parseFilter(filterText) filterObject = pureldap.LDAPFilter_and((f, filterObject)) if scope is None: scope = pureldap.LDAP_SCOPE_wholeSubtree if derefAliases is None: derefAliases = pureldap.LDAP_DEREF_neverDerefAliases if attributes is None: attributes = ['1.1'] results = [] if callback is None: cb = results.append else: cb = callback try: op = pureldap.LDAPSearchRequest(baseObject=str(self.dn), scope=scope, derefAliases=derefAliases, sizeLimit=sizeLimit, timeLimit=timeLimit, typesOnly=typesOnly, filter=filterObject, attributes=attributes) self.client.send_multiResponse( op, self._cbSearchMsg, d, cb, complete=not attributes, sizeLimitIsNonFatal=sizeLimitIsNonFatal) except ldapclient.LDAPClientConnectionLostException: d.errback(Failure()) else: if callback is None: d.addCallback(lambda dummy: results) return d
def search(self, filterText=None, filterObject=None, attributes=(), scope=None, derefAliases=None, sizeLimit=0, sizeLimitIsNonFatal=False, timeLimit=0, typesOnly=0, callback=None): self._checkState() d=defer.Deferred() if filterObject is None and filterText is None: filterObject=pureldap.LDAPFilterMatchAll elif filterObject is None and filterText is not None: filterObject=ldapfilter.parseFilter(filterText) elif filterObject is not None and filterText is None: pass elif filterObject is not None and filterText is not None: f=ldapfilter.parseFilter(filterText) filterObject=pureldap.LDAPFilter_and((f, filterObject)) if scope is None: scope = pureldap.LDAP_SCOPE_wholeSubtree if derefAliases is None: derefAliases = pureldap.LDAP_DEREF_neverDerefAliases if attributes is None: attributes = ['1.1'] results=[] if callback is None: cb=results.append else: cb=callback try: op = pureldap.LDAPSearchRequest( baseObject=str(self.dn), scope=scope, derefAliases=derefAliases, sizeLimit=sizeLimit, timeLimit=timeLimit, typesOnly=typesOnly, filter=filterObject, attributes=attributes) self.client.send_multiResponse( op, self._cbSearchMsg, d, cb, complete=not attributes, sizeLimitIsNonFatal=sizeLimitIsNonFatal) except ldapclient.LDAPClientConnectionLostException: d.errback(Failure()) else: if callback is None: d.addCallback(lambda dummy: results) return d
def makeFilter(name, template=None): filter=None try: filter=ldapfilter.parseFilter(name) except ldapfilter.InvalidLDAPFilter: try: filter=ldapfilter.parseFilter('('+name+')') except ldapfilter.InvalidLDAPFilter: if template is not None: try: filter=ldapfilter.parseFilter(template % {'name':name}) except ldapfilter.InvalidLDAPFilter: pass return filter
def makeFilter(name, template=None): filter = None try: filter = ldapfilter.parseFilter(name) except ldapfilter.InvalidLDAPFilter: try: filter = ldapfilter.parseFilter("(" + name + ")") except ldapfilter.InvalidLDAPFilter: if template is not None: try: filter = ldapfilter.parseFilter(template % {"name": name}) except ldapfilter.InvalidLDAPFilter: pass return filter
def makeFilter(name, template=None): filter = None try: filter = ldapfilter.parseFilter(name) except ldapfilter.InvalidLDAPFilter: try: filter = ldapfilter.parseFilter('(' + name + ')') except ldapfilter.InvalidLDAPFilter: if template is not None: try: filter = ldapfilter.parseFilter(template % {'name': name}) except ldapfilter.InvalidLDAPFilter: pass return filter
def test_cn(self): text = '(cn=Babs Jensen)' filt = pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='cn'), assertionValue=pureldap.LDAPAssertionValue(value='Babs Jensen')) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_whitespace_afterEq(self): text = r'(cn= foo)' filt = pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='cn'), assertionValue=pureldap.LDAPAssertionValue(value=' foo')) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_andornot(self): text = r'(&(!(|(cn=foo)(cn=bar)))(sn=a*b*c*d))' filt = pureldap.LDAPFilter_and([ pureldap.LDAPFilter_not( pureldap.LDAPFilter_or([ pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription( value='cn'), assertionValue=pureldap.LDAPAssertionValue( value='foo')), pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription( value='cn'), assertionValue=pureldap.LDAPAssertionValue( value='bar')), ])), pureldap.LDAPFilter_substrings( type='sn', substrings=[ pureldap.LDAPFilter_substrings_initial('a'), pureldap.LDAPFilter_substrings_any('b'), pureldap.LDAPFilter_substrings_any('c'), pureldap.LDAPFilter_substrings_final('d'), ]) ]) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_escape_backslash(self): text = r'(filename=C:\5cMyFile)' filt = pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='filename'), assertionValue=pureldap.LDAPAssertionValue(value=r'C:\MyFile')) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_escape_parens(self): text = r'(o=Parens R Us \28for all your parenthetical needs\29)' filt = pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='o'), assertionValue=pureldap.LDAPAssertionValue(value='Parens R Us (for all your parenthetical needs)')) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_escape_utf8(self): text = r'(sn=Lu\c4\8di\c4\87)' filt = pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='sn'), assertionValue=pureldap.LDAPAssertionValue( value='Lu\xc4\x8di\xc4\x87')) self.assertEquals(ldapfilter.parseFilter(text), filt)
def requestAvatarId(self, credentials): try: baseDN = self.config.getIdentityBaseDN() except config.MissingBaseDNError as e: return failure.Failure(error.UnauthorizedLogin("Disabled due configuration error: %s." % e)) if not credentials.username: return failure.Failure(error.UnauthorizedLogin("I don't support anonymous")) filtText = self.config.getIdentitySearch(credentials.username) try: filt = ldapfilter.parseFilter(filtText) except ldapfilter.InvalidLDAPFilter: return failure.Failure(error.UnauthorizedLogin("Couldn't create filter")) c = ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient) d = c.connect(baseDN, self.config.getServiceLocationOverrides()) d.addCallback(self._connected, filt, credentials) def _err(reason): reason.trap(ldaperrors.LDAPInvalidCredentials, # this happens with slapd 2.1.30 when binding # with DN but no password ldaperrors.LDAPUnwillingToPerform) return failure.Failure(error.UnauthorizedLogin()) d.addErrback(_err) return d
def test_escape_binary(self): text = r"(bin=\00\00\00\04)" filt = pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value="bin"), assertionValue=pureldap.LDAPAssertionValue(value="\00\00\00\04"), ) self.assertEqual(ldapfilter.parseFilter(text), filt)
def requestAvatarId(self, credentials): try: baseDN = self.config.getIdentityBaseDN() except config.MissingBaseDNError as e: return failure.Failure( error.UnauthorizedLogin( "Disabled due configuration error: %s." % e)) if not credentials.username: return failure.Failure( error.UnauthorizedLogin("I don't support anonymous")) filtText = self.config.getIdentitySearch(credentials.username) try: filt = ldapfilter.parseFilter(filtText) except ldapfilter.InvalidLDAPFilter: return failure.Failure( error.UnauthorizedLogin("Couldn't create filter")) c = ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient) d = c.connect(baseDN, self.config.getServiceLocationOverrides()) d.addCallback(self._connected, filt, credentials) def _err(reason): reason.trap( ldaperrors.LDAPInvalidCredentials, # this happens with slapd 2.1.30 when binding # with DN but no password ldaperrors.LDAPUnwillingToPerform) return failure.Failure(error.UnauthorizedLogin()) d.addErrback(_err) return d
def main(cfg, filter_text): from twisted.python import log log.startLogging(sys.stderr, setStdout=0) try: baseDN = cfg.getBaseDN() except config.MissingBaseDNError as e: print("{}: {}.".format(sys.argv[0], e), file=sys.stderr) sys.exit(1) if filter_text is not None: filt = ldapfilter.parseFilter(filter_text) else: filt = None c = ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient) d = c.connectAnonymously(baseDN, overrides=cfg.getServiceLocationOverrides()) d.addCallback(cbConnected, cfg, filt) d.addErrback(error) d.addBoth(lambda x: reactor.stop()) reactor.run() sys.exit(exitStatus)
def test_escape_utf8(self): text = r"(sn=Lu\c4\8di\c4\87)" filt = pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value="sn"), assertionValue=pureldap.LDAPAssertionValue(value="Lu\xc4\x8di\xc4\x87"), ) self.assertEqual(ldapfilter.parseFilter(text), filt)
def test_andornot(self): text = r"(&(!(|(cn=foo)(cn=bar)))(sn=a*b*c*d))" filt = pureldap.LDAPFilter_and( [ pureldap.LDAPFilter_not( pureldap.LDAPFilter_or( [ pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription( value="cn" ), assertionValue=pureldap.LDAPAssertionValue(value="foo"), ), pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription( value="cn" ), assertionValue=pureldap.LDAPAssertionValue(value="bar"), ), ] ) ), pureldap.LDAPFilter_substrings( type="sn", substrings=[ pureldap.LDAPFilter_substrings_initial("a"), pureldap.LDAPFilter_substrings_any("b"), pureldap.LDAPFilter_substrings_any("c"), pureldap.LDAPFilter_substrings_final("d"), ], ), ] ) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_and_or(self): text = "(&(objectClass=Person)(|(sn=Jensen)(cn=Babs J*)))" filt = pureldap.LDAPFilter_and( [ pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription( value="objectClass" ), assertionValue=pureldap.LDAPAssertionValue(value="Person"), ), pureldap.LDAPFilter_or( [ pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value="sn"), assertionValue=pureldap.LDAPAssertionValue(value="Jensen"), ), pureldap.LDAPFilter_substrings( type="cn", substrings=[ pureldap.LDAPFilter_substrings_initial(value="Babs J") ], ), ] ), ] ) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def coerce(self, *a, **kw): val = super(LDAPSearchFilter, self).coerce(*a, **kw) try: f = ldapfilter.parseFilter(val) except ldapfilter.InvalidLDAPFilter, e: raise annotate.InputError, \ "%r is not a valid LDAP search filter: %s" % (val, e)
def test_not_item(self): text = r'(!(cn=foo))' filt = pureldap.LDAPFilter_not( pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='cn'), assertionValue=pureldap.LDAPAssertionValue(value='foo'))) self.assertEquals(ldapfilter.parseFilter(text), filt) self.assertEquals(filt.asText(), text)
def test_escape_asterisk(self): text = r'(cn=*\2A*)' filt = pureldap.LDAPFilter_substrings( type='cn', substrings=[ pureldap.LDAPFilter_substrings_any(value='*'), ]) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text.lower())
def test_item_substring_any(self): text = r'(cn=*foo*)' filt = pureldap.LDAPFilter_substrings( type='cn', substrings=[pureldap.LDAPFilter_substrings_any('foo'), ]) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_not_cn(self): text = '(!(cn=Tim Howes))' filt = pureldap.LDAPFilter_not( pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='cn'), assertionValue=pureldap.LDAPAssertionValue(value='Tim Howes'))) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def coerce(self, *a, **kw): val = super().coerce(*a, **kw) try: f = ldapfilter.parseFilter(val) except ldapfilter.InvalidLDAPFilter as e: raise annotate.InputError( "{!r} is not a valid LDAP search filter: {}".format(val, e)) return f
def test_whitespace_beforeCloseParen(self): text = r"(cn=foo )" filt = pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value="cn"), assertionValue=pureldap.LDAPAssertionValue(value="foo "), ) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_item_substring_if(self): text = r'(cn=foo*bar)' filt = pureldap.LDAPFilter_substrings( type='cn', substrings=[pureldap.LDAPFilter_substrings_initial('foo'), pureldap.LDAPFilter_substrings_final('bar'), ]) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_extensible_1(self): text = '(cn:1.2.3.4.5:=Fred Flintstone)' self.assertEqual(ldapfilter.parseFilter(text), pureldap.LDAPFilter_extensibleMatch( type='cn', dnAttributes=False, matchingRule='1.2.3.4.5', matchValue='Fred Flintstone', ))
def test_extensible_3(self): text = '(o:dn:=Ace Industry)' self.assertEqual(ldapfilter.parseFilter(text), pureldap.LDAPFilter_extensibleMatch( type='o', dnAttributes=True, matchingRule=None, matchValue='Ace Industry', ))
def test_extensible_4(self): text = '(:dn:2.4.6.8.10:=Dino)' self.assertEqual(ldapfilter.parseFilter(text), pureldap.LDAPFilter_extensibleMatch( type=None, dnAttributes=True, matchingRule='2.4.6.8.10', matchValue='Dino', ))
def test_extensible_2(self): text = '(sn:dn:2.4.6.8.10:=Barney Rubble)' self.assertEqual(ldapfilter.parseFilter(text), pureldap.LDAPFilter_extensibleMatch( type='sn', dnAttributes=True, matchingRule='2.4.6.8.10', matchValue='Barney Rubble', ))
def test_not_item(self): text = r"(!(cn=foo))" filt = pureldap.LDAPFilter_not( pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value="cn"), assertionValue=pureldap.LDAPAssertionValue(value="foo"), ) ) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_extensible_3(self): text = "(o:dn:=Ace Industry)" filt = pureldap.LDAPFilter_extensibleMatch( type="o", dnAttributes=True, matchingRule=None, matchValue="Ace Industry", ) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_extensible_1(self): text = "(cn:1.2.3.4.5:=Fred Flintstone)" filt = pureldap.LDAPFilter_extensibleMatch( type="cn", dnAttributes=False, matchingRule="1.2.3.4.5", matchValue="Fred Flintstone", ) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_item_substring_any(self): text = r"(cn=*foo*)" filt = pureldap.LDAPFilter_substrings( type="cn", substrings=[ pureldap.LDAPFilter_substrings_any("foo"), ], ) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_substrings(self): text = '(o=univ*of*mich*)' filt = pureldap.LDAPFilter_substrings( type='o', substrings=[ pureldap.LDAPFilter_substrings_initial(value='univ'), pureldap.LDAPFilter_substrings_any(value='of'), pureldap.LDAPFilter_substrings_any(value='mich'), ]) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_extensible_2(self): text = "(sn:dn:2.4.6.8.10:=Barney Rubble)" filt = pureldap.LDAPFilter_extensibleMatch( type="sn", dnAttributes=True, matchingRule="2.4.6.8.10", matchValue="Barney Rubble", ) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_and_item(self): text = r'(&(cn=foo)(cn=bar))' filt = pureldap.LDAPFilter_and([ pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='cn'), assertionValue=pureldap.LDAPAssertionValue(value='foo')), pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='cn'), assertionValue=pureldap.LDAPAssertionValue(value='bar')), ]) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def search(self, ctx, scope, searchfilter, **kw): filt = [] for k, v in kw.items(): assert k.startswith("search_") if not k.startswith("search_"): continue k = k[len("search_") :] if v is None: continue v = v.strip() if v == "": continue # TODO escape ) in v # TODO handle unknown filter name right (old form open in browser etc) filter_ = config.getSearchFieldByName(k, vars={"input": v}) filt.append(ldapfilter.parseFilter(filter_)) if searchfilter: try: filt.append(ldapfilter.parseFilter(searchfilter)) except ldapfilter.InvalidLDAPFilter, e: raise annotate.ValidateError({"searchfilter": str(e)}, partialForm=inevow.IRequest(ctx).args)
def test_and_or(self): text = '(&(objectClass=Person)(|(sn=Jensen)(cn=Babs J*)))' filt = pureldap.LDAPFilter_and( [ pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='objectClass'), assertionValue=pureldap.LDAPAssertionValue(value='Person')), pureldap.LDAPFilter_or([ pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='sn'), assertionValue=pureldap.LDAPAssertionValue(value='Jensen')), pureldap.LDAPFilter_substrings( type='cn', substrings=[ pureldap.LDAPFilter_substrings_initial(value='Babs J') ]) ]), ]) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_andornot(self): text = r'(&(!(|(cn=foo)(cn=bar)))(sn=a*b*c*d))' filt = pureldap.LDAPFilter_and([ pureldap.LDAPFilter_not( pureldap.LDAPFilter_or([ pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='cn'), assertionValue=pureldap.LDAPAssertionValue(value='foo')), pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='cn'), assertionValue=pureldap.LDAPAssertionValue(value='bar')), ])), pureldap.LDAPFilter_substrings( type='sn', substrings=[pureldap.LDAPFilter_substrings_initial('a'), pureldap.LDAPFilter_substrings_any('b'), pureldap.LDAPFilter_substrings_any('c'), pureldap.LDAPFilter_substrings_final('d'), ])]) self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def test_bind_match_badAuth(self): server = self.createServer( services=['svc1', 'svc2', 'svc3', ], fallback=True, responses=[ # svc1 [ pureldap.LDAPSearchResultEntry(r'cn=svc1+owner=cn\=jack\,dc\=example\,dc\=com,dc=example,dc=com', attributes=[]), pureldap.LDAPSearchResultDone(ldaperrors.Success.resultCode) ], [ pureldap.LDAPBindResponse(resultCode=ldaperrors.LDAPInvalidCredentials.resultCode) ], # svc2 [ pureldap.LDAPSearchResultDone(ldaperrors.Success.resultCode) ], # svc3 [ pureldap.LDAPSearchResultEntry(r'cn=svc3+owner=cn\=jack\,dc\=example\,dc\=com,dc=example,dc=com', attributes=[]), pureldap.LDAPSearchResultDone(ldaperrors.Success.resultCode) ], [ pureldap.LDAPBindResponse(resultCode=ldaperrors.LDAPInvalidCredentials.resultCode) ], [ pureldap.LDAPBindResponse(resultCode=ldaperrors.LDAPInvalidCredentials.resultCode) ], ]) server.dataReceived( pureldap.LDAPMessage( pureldap.LDAPBindRequest(dn='cn=jack,dc=example,dc=com', auth='wrong-s3krit'), id=4 ).toWire() ) reactor.iterate() #TODO client = server.client client.assertSent( pureldap.LDAPSearchRequest(baseObject='dc=example,dc=com', derefAliases=0, sizeLimit=0, timeLimit=0, typesOnly=0, filter=ldapfilter.parseFilter('(&' +'(objectClass=serviceSecurityObject)' +'(owner=cn=jack,dc=example,dc=com)' +'(cn=svc1)' +('(|(!(validFrom=*))(validFrom<=%s))' % server.now) +('(|(!(validUntil=*))(validUntil>=%s))' % server.now) +')'), attributes=('1.1',)), pureldap.LDAPBindRequest(dn=r'cn=svc1+owner=cn\=jack\,dc\=example\,dc\=com,dc=example,dc=com', auth='wrong-s3krit'), pureldap.LDAPSearchRequest(baseObject='dc=example,dc=com', derefAliases=0, sizeLimit=0, timeLimit=0, typesOnly=0, filter=ldapfilter.parseFilter('(&' +'(objectClass=serviceSecurityObject)' +'(owner=cn=jack,dc=example,dc=com)' +'(cn=svc2)' +('(|(!(validFrom=*))(validFrom<=%s))' % server.now) +('(|(!(validUntil=*))(validUntil>=%s))' % server.now) +')'), attributes=('1.1',)), pureldap.LDAPSearchRequest(baseObject='dc=example,dc=com', derefAliases=0, sizeLimit=0, timeLimit=0, typesOnly=0, filter=ldapfilter.parseFilter('(&' +'(objectClass=serviceSecurityObject)' +'(owner=cn=jack,dc=example,dc=com)' +'(cn=svc3)' +('(|(!(validFrom=*))(validFrom<=%s))' % server.now) +('(|(!(validUntil=*))(validUntil>=%s))' % server.now) +')'), attributes=('1.1',)), pureldap.LDAPBindRequest(dn='cn=svc3+owner=cn\=jack\,dc\=example\,dc\=com,dc=example,dc=com', auth='wrong-s3krit'), pureldap.LDAPBindRequest(version=3, dn='cn=jack,dc=example,dc=com', auth='wrong-s3krit'), ) self.assertEqual( server.transport.value(), pureldap.LDAPMessage( pureldap.LDAPBindResponse(resultCode=ldaperrors.LDAPInvalidCredentials.resultCode), id=4 ).toWire() )
def test_escape_binary(self): text = r'(bin=\00\00\00\04)' filt = pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='bin'), assertionValue=pureldap.LDAPAssertionValue(value='\00\00\00\04')) self.assertEqual(ldapfilter.parseFilter(text), filt)
def test_escape_utf8(self): text = r'(sn=Lu\c4\8di\c4\87)' filt = pureldap.LDAPFilter_equalityMatch( attributeDesc=pureldap.LDAPAttributeDescription(value='sn'), assertionValue=pureldap.LDAPAssertionValue(value='Lu\xc4\x8di\xc4\x87')) self.assertEqual(ldapfilter.parseFilter(text), filt)
def test_item_present(self): text = r'(cn=*)' filt = pureldap.LDAPFilter_present(value='cn') self.assertEqual(ldapfilter.parseFilter(text), filt) self.assertEqual(filt.asText(), text)
def _doSearch(proto, searchFilter): searchFilter = ldapfilter.parseFilter(searchFilter) baseEntry = ldapsyntax.LDAPEntry(client=proto, dn=self.config.getBaseDN()) d=baseEntry.search(filterObject=searchFilter) return d
def search(self, filterText=None, filterObject=None, attributes=(), scope=None, derefAliases=None, sizeLimit=0, sizeLimitIsNonFatal=False, timeLimit=0, typesOnly=0, callback=None, controls=None, return_controls=False): self._checkState() d = defer.Deferred() if filterObject is None and filterText is None: filterObject = pureldap.LDAPFilterMatchAll elif filterObject is None and filterText is not None: filterObject = ldapfilter.parseFilter(filterText) elif filterObject is not None and filterText is None: pass elif filterObject is not None and filterText is not None: f = ldapfilter.parseFilter(filterText) filterObject = pureldap.LDAPFilter_and((f, filterObject)) if scope is None: scope = pureldap.LDAP_SCOPE_wholeSubtree if derefAliases is None: derefAliases = pureldap.LDAP_DEREF_neverDerefAliases if attributes is None: attributes = ['1.1'] results = [] if callback is None: cb = results.append else: cb = callback try: op = pureldap.LDAPSearchRequest( baseObject=self.dn.getText(), scope=scope, derefAliases=derefAliases, sizeLimit=sizeLimit, timeLimit=timeLimit, typesOnly=typesOnly, filter=filterObject, attributes=attributes) dsend = self.client.send_multiResponse_ex( op, controls, self._cbSearchMsg, d, cb, complete=not attributes, sizeLimitIsNonFatal=sizeLimitIsNonFatal) except ldapclient.LDAPClientConnectionLostException: d.errback(Failure()) else: if callback is None: if return_controls: d.addCallback(lambda ctls: (results, ctls)) else: d.addCallback(lambda dummy: results) def rerouteerr(e): d.errback(e) # returning None will stop the error # from being propagated and logged. dsend.addErrback(rerouteerr) return d