예제 #1
0
    def _cb_testSimple(self, val, client):
        client.assertSent(
            pureldap.LDAPSearchRequest(
                baseObject='dc=example,dc=com',
                scope=pureldap.LDAP_SCOPE_baseObject,
                derefAliases=pureldap.LDAP_DEREF_neverDerefAliases,
                sizeLimit=1,
                timeLimit=0,
                typesOnly=0,
                filter=pureldap.LDAPFilter_present('objectClass'),
                attributes=['subschemaSubentry']),
            pureldap.LDAPSearchRequest(
                baseObject='cn=Subschema',
                scope=pureldap.LDAP_SCOPE_baseObject,
                derefAliases=pureldap.LDAP_DEREF_neverDerefAliases,
                sizeLimit=1,
                timeLimit=0,
                typesOnly=0,
                filter=pureldap.LDAPFilter_present('objectClass'),
                attributes=['attributeTypes', 'objectClasses']),
        )
        self.failUnlessEqual(len(val), 2)

        self.failUnlessEqual([str(x) for x in val[0]],
                             [str(schema.AttributeTypeDescription(self.cn))])
        self.failUnlessEqual(
            [str(x) for x in val[1]],
            [str(schema.ObjectClassDescription(self.dcObject))])
예제 #2
0
    def _cb_testSimple(self, val, client):
        client.assertSent(
            pureldap.LDAPSearchRequest(
                baseObject="dc=example,dc=com",
                scope=pureldap.LDAP_SCOPE_baseObject,
                derefAliases=pureldap.LDAP_DEREF_neverDerefAliases,
                sizeLimit=1,
                timeLimit=0,
                typesOnly=0,
                filter=pureldap.LDAPFilter_present("objectClass"),
                attributes=["subschemaSubentry"],
            ),
            pureldap.LDAPSearchRequest(
                baseObject="cn=Subschema",
                scope=pureldap.LDAP_SCOPE_baseObject,
                derefAliases=pureldap.LDAP_DEREF_neverDerefAliases,
                sizeLimit=1,
                timeLimit=0,
                typesOnly=0,
                filter=pureldap.LDAPFilter_present("objectClass"),
                attributes=["attributeTypes", "objectClasses"],
            ),
        )
        self.failUnlessEqual(len(val), 2)

        self.failUnlessEqual(
            [to_bytes(x) for x in val[0]],
            [to_bytes(schema.AttributeTypeDescription(self.cn))],
        )
        self.failUnlessEqual(
            [to_bytes(x) for x in val[1]],
            [to_bytes(schema.ObjectClassDescription(self.dcObject))],
        )
예제 #3
0
def getNets(e, filter):
    filt = pureldap.LDAPFilter_and(
        value=(
            pureldap.LDAPFilter_present("cn"),
            pureldap.LDAPFilter_present("ipNetworkNumber"),
            pureldap.LDAPFilter_present("ipNetmaskNumber"),
        )
    )
    if filter:
        filt = pureldap.LDAPFilter_and(value=(filter, filt))

    d = e.search(
        filterObject=filt,
        attributes=[
            "cn",
            "ipNetworkNumber",
            "ipNetmaskNumber",
            "router",
            "dhcpRange",
            "winsServer",
            "domainNameServer",
            "sharedNetworkName",
        ],
    )
    d.addCallback(_cbGetNets)
    return d
예제 #4
0
def getNets(e, filter):
    filt = pureldap.LDAPFilter_and(value=(
        pureldap.LDAPFilter_present("cn"),
        pureldap.LDAPFilter_present("ipNetworkNumber"),
        pureldap.LDAPFilter_present("ipNetmaskNumber"),
    ))
    if filter:
        filt = pureldap.LDAPFilter_and(value=(filter, filt))
    d = e.search(
        filterObject=filt,
        attributes=[
            "cn",
            "ipNetworkNumber",
            "ipNetmaskNumber",
        ],
    )

    def _cbGotNets(nets):
        r = []
        for e in nets:
            net = Net(
                str(e.dn),
                str(only(e, "cn")),
                str(only(e, "ipNetworkNumber")),
                str(only(e, "ipNetmaskNumber")),
            )
            net.printZone()
            r.append(net)
        return r

    d.addCallback(_cbGotNets)
    return d
예제 #5
0
    def _tryService(self, services, baseEntry, request, controls, reply):
        try:
            serviceName = services.pop(0)
        except IndexError:
            return None
        timestamp = self.timestamp()
        d = baseEntry.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(request.dn)),
                pureldap.LDAPFilter_equalityMatch(
                    attributeDesc=pureldap.LDAPAttributeDescription('cn'),
                    assertionValue=pureldap.LDAPAssertionValue(serviceName)),
                pureldap.LDAPFilter_or([
                    # no time
                    pureldap.LDAPFilter_not(
                        pureldap.LDAPFilter_present('validFrom')),
                    # or already valid
                    pureldap.LDAPFilter_lessOrEqual(
                        attributeDesc=pureldap.LDAPAttributeDescription(
                            'validFrom'),
                        assertionValue=pureldap.LDAPAssertionValue(timestamp)),
                ]),
                pureldap.LDAPFilter_or([
                    # no time
                    pureldap.LDAPFilter_not(
                        pureldap.LDAPFilter_present('validUntil')),
                    # or still valid
                    pureldap.LDAPFilter_greaterOrEqual(
                        attributeDesc=pureldap.LDAPAttributeDescription(
                            'validUntil'),
                        assertionValue=pureldap.LDAPAssertionValue(timestamp)),
                ]),
            ]),
            attributes=('1.1', ))

        def _gotEntries(entries):
            if not entries:
                return None
            assert len(entries) == 1  #TODO
            e = entries[0]
            d = e.bind(request.auth)
            return d

        d.addCallback(_gotEntries)
        d.addCallbacks(callback=self._loopIfNone,
                       callbackArgs=(services, baseEntry, request, controls,
                                     reply),
                       errback=self._loopIfBindError,
                       errbackArgs=(services, baseEntry, request, controls,
                                    reply))
        return d
예제 #6
0
 def test_or_noMatch(self):
     o = inmemory.ReadOnlyInMemoryLDAPEntry(dn='cn=foo,dc=example,dc=com',
                                            attributes={
                                                'objectClass': ['a', 'b'],
                                                'aValue': ['a'],
                                                'bValue': ['b'],
                                            })
     result = o.match(
         pureldap.LDAPFilter_or([
             pureldap.LDAPFilter_present('cValue'),
             pureldap.LDAPFilter_present('dValue'),
         ]))
     self.assertEqual(result, False)
예제 #7
0
 def test_or_noMatch(self):
     o = inmemory.ReadOnlyInMemoryLDAPEntry(
         dn="cn=foo,dc=example,dc=com",
         attributes={
             "objectClass": ["a", "b"],
             "aValue": ["a"],
             "bValue": ["b"],
         },
     )
     result = o.match(
         pureldap.LDAPFilter_or([
             pureldap.LDAPFilter_present("cValue"),
             pureldap.LDAPFilter_present("dValue"),
         ]))
     self.assertEqual(result, False)
예제 #8
0
def getGroups(hosts, e, filter):
    """Add group info to hosts."""

    def buildFilter(hosts):
        for host in hosts:
            f = pureldap.LDAPFilter_equalityMatch(
                attributeDesc=pureldap.LDAPAttributeDescription("member"),
                assertionValue=pureber.BEROctetString(str(host.dn)),
            )
            yield f

    filt = pureldap.LDAPFilter_and(
        value=(
            # the only reason we do groups is for the bootFile,
            # so require one to be present
            pureldap.LDAPFilter_present("bootFile"),
            pureldap.LDAPFilter_or(value=list(buildFilter(hosts))),
        )
    )
    if filter:
        filt = pureldap.LDAPFilter_and(value=(filter, filt))

    d = e.search(filterObject=filt, attributes=["member", "bootFile"])

    d.addCallback(_cbGetGroups, hosts)
    return d
예제 #9
0
 def test_rootDSE(self):
     self.server.dataReceived(
         str(
             pureldap.LDAPMessage(pureldap.LDAPSearchRequest(
                 baseObject='',
                 scope=pureldap.LDAP_SCOPE_baseObject,
                 filter=pureldap.LDAPFilter_present('objectClass'),
             ),
                                  id=2)))
     self.assertEquals(
         self.server.transport.value(),
         str(
             pureldap.LDAPMessage(pureldap.LDAPSearchResultEntry(
                 objectName='',
                 attributes=[
                     ('supportedLDAPVersion', ['3']),
                     ('namingContexts', ['dc=example,dc=com']),
                     ('supportedExtension', [
                         pureldap.LDAPPasswordModifyRequest.oid,
                     ]),
                 ]),
                                  id=2)) +
         str(
             pureldap.LDAPMessage(pureldap.LDAPSearchResultDone(
                 resultCode=ldaperrors.Success.resultCode),
                                  id=2)),
     )
 def test_simple_bind(self):
     dn = 'uid=thegreathugo,cn=users,dc=test,dc=local'
     server, client = self.create_server_and_client()
     service_account_client = self.inject_service_account_server(
         [
             pureldap.LDAPBindResponse(resultCode=0),  # for service account
         ],
         [
             pureldap.LDAPSearchResultEntry(dn,
                                            [('sAMAccountName', ['hugo'])]),
             pureldap.LDAPSearchResultDone(ldaperrors.Success.resultCode),
         ])
     yield client.bind(dn, 'secret')
     # Assert that Proxy<->Backend (the actual connection) did not send anything
     server.client.assertNothingSent()
     # Assert that Proxy<->Backend (the lookup connection) did send something
     service_account_client.assertSent(
         pureldap.LDAPBindRequest(
             dn='uid=service,cn=users,dc=test,dc=local',
             auth='service-secret'),
         pureldap.LDAPSearchRequest(
             baseObject='uid=thegreathugo,cn=users,dc=test,dc=local',
             scope=0,
             derefAliases=0,
             sizeLimit=0,
             timeLimit=0,
             typesOnly=0,
             filter=pureldap.LDAPFilter_present(value='objectClass'),
             attributes=()), 'fake-unbind-by-LDAPClientTestDriver')
예제 #11
0
def getNets(e, domain, forward, reverse, filter):
    filt = pureldap.LDAPFilter_and(
        value=(
            pureldap.LDAPFilter_present("cn"),
            pureldap.LDAPFilter_present("ipNetworkNumber"),
            pureldap.LDAPFilter_present("ipNetmaskNumber"),
        )
    )
    if filter:
        filt = pureldap.LDAPFilter_and(value=(filter, filt))
    d = e.search(
        filterObject=filt,
        attributes=[
            "cn",
            "ipNetworkNumber",
            "ipNetmaskNumber",
        ],
    )

    def _cbGotNets(nets, forward, reverse):
        r = []
        for e in nets:
            net = Net(
                str(e.dn),
                str(only(e, "cn")),
                str(only(e, "ipNetworkNumber")),
                str(only(e, "ipNetmaskNumber")),
            )
            print(net.getForward(), file=forward)

            for data in reverse:
                ip = dns.aton(net.address)
                if ip & data["netmask"] == data["address"]:
                    if "file" not in data:
                        data["tempname"] = "%s.%d.tmp" % (data["filename"], os.getpid())
                        data["file"] = open(data["tempname"], "w")
                    print(net.getReverse(domain), file=data["file"])
                    net.reverseZone = data
            r.append(net)
        return r

    d.addCallback(_cbGotNets, forward, reverse)
    return d
예제 #12
0
def getHosts(e, filter):
    filt = pureldap.LDAPFilter_and(value=(
        pureldap.LDAPFilter_present("cn"),
        pureldap.LDAPFilter_present("ipHostNumber"),
    ))
    if filter:
        filt = pureldap.LDAPFilter_and(value=(filter, filt))

    d = e.search(
        filterObject=filt,
        attributes=[
            "cn",
            "ipHostNumber",
            "macAddress",
            "bootFile",
        ],
    )
    d.addCallback(_cbGetHosts)
    return d
예제 #13
0
    def handle_LDAPSearchRequest(self, request, controls, reply):
        self.checkControls(controls)

        if (request.baseObject == ''
                and request.scope == pureldap.LDAP_SCOPE_baseObject
                and request.filter == pureldap.LDAPFilter_present('objectClass')):
            return self.getRootDSE(request, reply)
        dn = distinguishedname.DistinguishedName(request.baseObject)
        root = interfaces.IConnectedLDAPEntry(self.factory)
        d = root.lookup(dn)
        d.addCallback(self._cbSearchGotBase, dn, request, reply)
        d.addErrback(self._cbSearchLDAPError)
        d.addErrback(defer.logError)
        d.addErrback(self._cbSearchOtherError)
        return d
예제 #14
0
 def test_rootDSE(self):
     """Searching for a root object"""
     self.makeSearch(baseObject='',
                     scope=pureldap.LDAP_SCOPE_baseObject,
                     filter=pureldap.LDAPFilter_present('objectClass'))
     self.assertSearchResults([{
         'objectName':
         '',
         'attributes': [
             ('supportedLDAPVersion', ['3']),
             ('namingContexts', ['dc=example,dc=com']),
             ('supportedExtension',
              [pureldap.LDAPPasswordModifyRequest.oid]),
         ]
     }])
예제 #15
0
    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
예제 #16
0
 def test_rootDSE(self):
     """Searching for a root object"""
     self.makeSearch(
         baseObject="",
         scope=pureldap.LDAP_SCOPE_baseObject,
         filter=pureldap.LDAPFilter_present("objectClass"),
     )
     self.assertSearchResults([{
         "objectName":
         "",
         "attributes": [
             ("supportedLDAPVersion", ["3"]),
             ("namingContexts", ["dc=example,dc=com"]),
             (
                 "supportedExtension",
                 [pureldap.LDAPPasswordModifyRequest.oid],
             ),
         ],
     }])
예제 #17
0
 def test_item_present(self):
     text = r'(cn=*)'
     filt = pureldap.LDAPFilter_present(value='cn')
     self.assertEquals(ldapfilter.parseFilter(text), filt)
     self.assertEquals(filt.asText(), text)
예제 #18
0
def _p_maybeSubString_present(s, l, t):
    return (lambda attr: pureldap.LDAPFilter_present(attr))
예제 #19
0
filtertype = equal | approx | greater | less
filtertype.setName('filtertype')
simple = attr + filtertype + value
simple.leaveWhitespace()
simple.setName('simple')


def _p_simple(s, l, t):
    attr, filtertype, value = t
    return filtertype(attributeDesc=pureldap.LDAPAttributeDescription(attr),
                      assertionValue=pureldap.LDAPAssertionValue(value))


simple.setParseAction(_p_simple)
present = attr + "=*"
present.setParseAction(lambda s, l, t: pureldap.LDAPFilter_present(t[0]))
initial = value.copy()
initial.setParseAction(
    lambda s, l, t: pureldap.LDAPFilter_substrings_initial(t[0]))
initial.setName('initial')
any_value = value + Suppress(Literal("*"))
any_value.setParseAction(
    lambda s, l, t: pureldap.LDAPFilter_substrings_any(t[0]))
any = Suppress(Literal("*")) + ZeroOrMore(any_value)
any.setName('any')
final = value.copy()
final.setName('final')
final.setParseAction(
    lambda s, l, t: pureldap.LDAPFilter_substrings_final(t[0]))
substring = attr + Suppress(
    Literal("=")) + Group(Optional(initial) + any + Optional(final))
예제 #20
0
 def test_item_present(self):
     text = r'*'
     filt = pureldap.LDAPFilter_present(value='cn')
     self.assertEqual(ldapfilter.parseMaybeSubstring('cn', text), filt)
예제 #21
0
class KnownValues(unittest.TestCase):
    knownValues = (  # class, args, kwargs, expected_result
        (pureldap.LDAPModifyRequest, [], {
            "object":
            'cn=foo, dc=example, dc=com',
            "modification": [
                pureber.BERSequence([
                    pureber.BEREnumerated(0),
                    pureber.BERSequence([
                        pureldap.LDAPAttributeDescription('bar'),
                        pureber.BERSet([
                            pureldap.LDAPString('a'),
                            pureldap.LDAPString('b'),
                        ]),
                    ]),
                ]),
            ],
        }, None, [0x66, 50] +
         ([0x04, 0x1a] + l("cn=foo, dc=example, dc=com") + [0x30, 20] +
          ([0x30, 18] +
           ([0x0a, 0x01, 0x00] + [0x30, 13] +
            ([0x04, len("bar")] + l("bar") + [0x31, 0x06] +
             ([0x04, len("a")] + l("a") + [0x04, len("b")] + l("b"))))))),
        (pureldap.LDAPModifyRequest, [], {
            "object":
            'cn=foo, dc=example, dc=com',
            "modification": [
                pureber.BERSequence([
                    pureber.BEREnumerated(1L),
                    pureber.BERSequence([
                        pureber.BEROctetString('bar'),
                        pureber.BERSet([]),
                    ]),
                ]),
            ],
        }, None, [0x66, 0x2c] +
         ([0x04, 0x1a] + l("cn=foo, dc=example, dc=com") + [0x30, 0x0e] +
          ([0x30, 0x0c] + ([0x0a, 0x01, 0x01] + [0x30, 0x07] +
                           ([0x04, 0x03] + l("bar") + [0x31, 0x00]))))),
        (pureldap.LDAPFilter_not, [], {
            "value": pureldap.LDAPFilter_present("foo"),
        },
         pureldap.LDAPBERDecoderContext_Filter(
             fallback=pureber.BERDecoderContext()),
         [0xa2, 0x05] + [0x87] + [len("foo")] + l("foo")),
        (
            pureldap.LDAPFilter_or,
            [],
            {
                "value": [
                    pureldap.LDAPFilter_equalityMatch(
                        attributeDesc=pureldap.LDAPAttributeDescription(
                            value='cn'),
                        assertionValue=pureldap.LDAPAssertionValue(
                            value='foo')),
                    pureldap.LDAPFilter_equalityMatch(
                        attributeDesc=pureldap.LDAPAttributeDescription(
                            value='uid'),
                        assertionValue=pureldap.LDAPAssertionValue(
                            value='foo')),
                ]
            },
            pureldap.LDAPBERDecoderContext_Filter(
                fallback=pureber.BERDecoderContext()),
            [0xa1, 23] + [0xa3, 9] + [0x04] + [len("cn")] + l("cn") + [0x04] +
            [len("foo")] + l("foo") + [0xa3, 10] + [0x04] + [len("uid")] +
            l("uid") + [0x04] + [len("foo")] + l("foo"),
        ),
        (
            pureldap.LDAPFilter_and,
            [],
            {
                "value": [
                    pureldap.LDAPFilter_equalityMatch(
                        attributeDesc=pureldap.LDAPAttributeDescription(
                            value='cn'),
                        assertionValue=pureldap.LDAPAssertionValue(
                            value='foo')),
                    pureldap.LDAPFilter_equalityMatch(
                        attributeDesc=pureldap.LDAPAttributeDescription(
                            value='uid'),
                        assertionValue=pureldap.LDAPAssertionValue(
                            value='foo')),
                ]
            },
            pureldap.LDAPBERDecoderContext_Filter(
                fallback=pureber.BERDecoderContext()),
            [0xa0, 23] + [0xa3, 9] + [0x04] + [len("cn")] + l("cn") + [0x04] +
            [len("foo")] + l("foo") + [0xa3, 10] + [0x04] + [len("uid")] +
            l("uid") + [0x04] + [len("foo")] + l("foo"),
        ),
        (pureldap.LDAPModifyDNRequest, [], {
            'entry': 'cn=foo,dc=example,dc=com',
            'newrdn': 'uid=bar',
            'deleteoldrdn': 0,
        }, None, [0x6c, 0x26] + [0x04] + [len("cn=foo,dc=example,dc=com")] +
         l("cn=foo,dc=example,dc=com") + [0x04] + [len("uid=bar")] +
         l("uid=bar") + [0x01, 0x01, 0x00]),
        (pureldap.LDAPModifyDNRequest, [], {
            'entry': 'cn=aoue,dc=example,dc=com',
            'newrdn': 'uid=aoue',
            'deleteoldrdn': 0,
            'newSuperior': 'ou=People,dc=example,dc=com',
        }, None, [0x6c, 69] + [0x04] + [len("cn=aoue,dc=example,dc=com")] +
         l("cn=aoue,dc=example,dc=com") + [0x04] + [len("uid=aoue")] +
         l("uid=aoue") + [0x01, 0x01, 0x00] + [0x80] +
         [len("ou=People,dc=example,dc=com")] +
         l("ou=People,dc=example,dc=com")),
        (
            pureldap.LDAPSearchRequest,
            [],
            {
                'baseObject': 'dc=yoja,dc=example,dc=com',
            },
            None,
            [0x63, 57] + [0x04] + [len('dc=yoja,dc=example,dc=com')] +
            l('dc=yoja,dc=example,dc=com')
            # scope
            + [0x0a, 1, 2]
            # derefAliases
            + [0x0a, 1, 0]
            # sizeLimit
            + [0x02, 1, 0]
            # timeLimit
            + [0x02, 1, 0]
            # typesOnly
            + [0x01, 1, 0]
            # filter
            + [135, 11] + l('objectClass')
            # attributes
            + [48, 0]),
        (pureldap.LDAPUnbindRequest, [], {}, None, [0x42, 0x00]),
        (
            pureldap.LDAPSearchResultDone,
            [],
            {
                'resultCode': 0,
            },
            None,
            [0x65, 0x07]
            # resultCode
            + [0x0a, 0x01, 0x00]
            # matchedDN
            + [0x04] + [len('')] + l('')
            # errorMessage
            + [0x04] + [len('')] + l('')
            # referral, TODO
            + []),
        (
            pureldap.LDAPSearchResultDone,
            [],
            {
                'resultCode': 0,
                'matchedDN': 'dc=foo,dc=example,dc=com',
            },
            None,
            [0x65, 31]
            # resultCode
            + [0x0a, 0x01, 0x00]
            # matchedDN
            + [0x04] + [len('dc=foo,dc=example,dc=com')] +
            l('dc=foo,dc=example,dc=com')
            # errorMessage
            + [0x04] + [len('')] + l('')
            # referral, TODO
            + []),
        (
            pureldap.LDAPSearchResultDone,
            [],
            {
                'resultCode': 0,
                'matchedDN': 'dc=foo,dc=example,dc=com',
                'errorMessage': 'the foobar was fubar',
            },
            None,
            [0x65, 51]
            # resultCode
            + [0x0a, 0x01, 0x00]
            # matchedDN
            + [0x04] + [len('dc=foo,dc=example,dc=com')] +
            l('dc=foo,dc=example,dc=com')
            # errorMessage
            + [0x04] + [len('the foobar was fubar')] +
            l('the foobar was fubar', )
            # referral, TODO
            + []),
        (
            pureldap.LDAPSearchResultDone,
            [],
            {
                'resultCode': 0,
                'errorMessage': 'the foobar was fubar',
            },
            None,
            [0x65, 27]
            # resultCode
            + [0x0a, 0x01, 0x00]
            # matchedDN
            + [0x04] + [len('')] + l('')
            # errorMessage
            + [0x04] + [len('the foobar was fubar')] +
            l('the foobar was fubar', )
            # referral, TODO
            + []),
        (
            pureldap.LDAPMessage,
            [],
            {
                'id': 42,
                'value': pureldap.LDAPBindRequest(),
            },
            pureldap.LDAPBERDecoderContext_TopLevel(
                inherit=pureldap.LDAPBERDecoderContext_LDAPMessage(
                    fallback=pureldap.LDAPBERDecoderContext(
                        fallback=pureber.BERDecoderContext()),
                    inherit=pureldap.LDAPBERDecoderContext(
                        fallback=pureber.BERDecoderContext()))),
            [0x30, 12]
            # id
            + [0x02, 0x01, 42]
            # value
            + l(str(pureldap.LDAPBindRequest()))),
        (
            pureldap.LDAPControl,
            [],
            {
                'controlType': '1.2.3.4',
            },
            None,
            [0x30, 9]
            # controlType
            + [0x04, 7] + l("1.2.3.4")),
        (
            pureldap.LDAPControl,
            [],
            {
                'controlType': '1.2.3.4',
                'criticality': True,
            },
            None,
            [0x30, 12]
            # controlType
            + [0x04, 7] + l("1.2.3.4")
            # criticality
            + [0x01, 1, 0xFF]),
        (
            pureldap.LDAPControl,
            [],
            {
                'controlType': '1.2.3.4',
                'criticality': True,
                'controlValue': 'silly',
            },
            None,
            [0x30, 19]
            # controlType
            + [0x04, 7] + l("1.2.3.4")
            # criticality
            + [0x01, 1, 0xFF]
            # controlValue
            + [0x04, len("silly")] + l("silly")),
        (
            pureldap.LDAPMessage,
            [],
            {
                'id':
                42,
                'value':
                pureldap.LDAPBindRequest(),
                'controls': [
                    ('1.2.3.4', None, None),
                    ('2.3.4.5', False),
                    ('3.4.5.6', True, '\x00\x01\x02\xFF'),
                ],
            },
            pureldap.LDAPBERDecoderContext_TopLevel(
                inherit=pureldap.LDAPBERDecoderContext_LDAPMessage(
                    fallback=pureldap.LDAPBERDecoderContext(
                        fallback=pureber.BERDecoderContext()),
                    inherit=pureldap.LDAPBERDecoderContext(
                        fallback=pureber.BERDecoderContext()))),
            [0x30, 59]
            # id
            + [0x02, 0x01, 42]
            # value
            + l(str(pureldap.LDAPBindRequest()))
            # controls
            + l(
                str(
                    pureldap.LDAPControls(value=[
                        pureldap.LDAPControl(controlType='1.2.3.4'),
                        pureldap.LDAPControl(controlType='2.3.4.5',
                                             criticality=False),
                        pureldap.LDAPControl(controlType='3.4.5.6',
                                             criticality=True,
                                             controlValue='\x00\x01\x02\xFF'),
                    ]))),
        ),
        (pureldap.LDAPFilter_equalityMatch, [], {
            'attributeDesc': pureldap.LDAPAttributeDescription('cn'),
            'assertionValue': pureldap.LDAPAssertionValue('foo'),
        },
         pureldap.LDAPBERDecoderContext_Filter(
             fallback=pureldap.LDAPBERDecoderContext(
                 fallback=pureber.BERDecoderContext()),
             inherit=pureldap.LDAPBERDecoderContext(
                 fallback=pureber.BERDecoderContext())),
         [0xa3, 9] + ([0x04, 2] + l('cn') + [0x04, 3] + l('foo'))),
        (pureldap.LDAPFilter_or, [[
            pureldap.LDAPFilter_equalityMatch(
                attributeDesc=pureldap.LDAPAttributeDescription('cn'),
                assertionValue=pureldap.LDAPAssertionValue('foo')),
            pureldap.LDAPFilter_equalityMatch(
                attributeDesc=pureldap.LDAPAttributeDescription('uid'),
                assertionValue=pureldap.LDAPAssertionValue('foo')),
            pureldap.LDAPFilter_equalityMatch(
                attributeDesc=pureldap.LDAPAttributeDescription('mail'),
                assertionValue=pureldap.LDAPAssertionValue('foo')),
            pureldap.LDAPFilter_substrings(
                type='mail',
                substrings=[pureldap.LDAPFilter_substrings_initial('foo@')]),
        ]], {},
         pureldap.LDAPBERDecoderContext_Filter(
             fallback=pureldap.LDAPBERDecoderContext(
                 fallback=pureber.BERDecoderContext()),
             inherit=pureldap.LDAPBERDecoderContext(
                 fallback=pureber.BERDecoderContext())), [0xA1, 52] +
         ([0xa3, 9] +
          ([0x04, 2] + l('cn') + [0x04, 3] + l('foo')) + [0xa3, 10] +
          ([0x04, 3] + l('uid') + [0x04, 3] + l('foo')) + [0xa3, 11] +
          ([0x04, 4] + l('mail') + [0x04, 3] + l('foo')) + [0xa4, 14] +
          ([0x04, 4] + l('mail') + [0x30, 6] + ([0x80, 4] + l('foo@'))))),
        (pureldap.LDAPSearchRequest, [], {
            'baseObject':
            'dc=example,dc=com',
            'scope':
            pureldap.LDAP_SCOPE_wholeSubtree,
            'derefAliases':
            pureldap.LDAP_DEREF_neverDerefAliases,
            'sizeLimit':
            1,
            'timeLimit':
            0,
            'typesOnly':
            False,
            'filter':
            pureldap.LDAPFilter_or([
                pureldap.LDAPFilter_equalityMatch(
                    attributeDesc=pureldap.LDAPAttributeDescription('cn'),
                    assertionValue=pureldap.LDAPAssertionValue('foo')),
                pureldap.LDAPFilter_equalityMatch(
                    attributeDesc=pureldap.LDAPAttributeDescription('uid'),
                    assertionValue=pureldap.LDAPAssertionValue('foo')),
                pureldap.LDAPFilter_equalityMatch(
                    attributeDesc=pureldap.LDAPAttributeDescription('mail'),
                    assertionValue=pureldap.LDAPAssertionValue('foo')),
                pureldap.LDAPFilter_substrings(
                    type='mail',
                    substrings=[
                        pureldap.LDAPFilter_substrings_initial('foo@')
                    ]),
            ]),
            'attributes': [''],
        },
         pureldap.LDAPBERDecoderContext_LDAPMessage(
             fallback=pureldap.LDAPBERDecoderContext(
                 fallback=pureber.BERDecoderContext()),
             inherit=pureldap.LDAPBERDecoderContext(
                 fallback=pureber.BERDecoderContext())), [0x63, 92] +
         ([0x04, 17] + l('dc=example,dc=com') + [0x0a, 1, 0x02] +
          [0x0a, 1, 0x00] + [0x02, 1, 0x01] + [0x02, 1, 0x00] +
          [0x01, 1, 0x00] + [0xA1, 52] +
          ([0xa3, 9] +
           ([0x04, 2] + l('cn') + [0x04, 3] + l('foo')) + [0xa3, 10] +
           ([0x04, 3] + l('uid') + [0x04, 3] + l('foo')) + [0xa3, 11] +
           ([0x04, 4] + l('mail') + [0x04, 3] + l('foo')) + [0xa4, 14] +
           ([0x04, 4] + l('mail') + [0x30, 6] +
            ([0x80, 4] + l('foo@')))) + [0x30, 2] + ([0x04, 0]))),
        (
            pureldap.LDAPMessage,
            [],
            {
                'id':
                1L,
                'value':
                pureldap.LDAPSearchRequest(
                    baseObject='dc=example,dc=com',
                    scope=pureldap.LDAP_SCOPE_wholeSubtree,
                    derefAliases=pureldap.LDAP_DEREF_neverDerefAliases,
                    sizeLimit=1,
                    timeLimit=0,
                    typesOnly=False,
                    filter=pureldap.LDAPFilter_or([
                        pureldap.LDAPFilter_equalityMatch(
                            attributeDesc=pureldap.LDAPAttributeDescription(
                                'cn'),
                            assertionValue=pureldap.LDAPAssertionValue('foo')),
                        pureldap.LDAPFilter_equalityMatch(
                            attributeDesc=pureldap.LDAPAttributeDescription(
                                'uid'),
                            assertionValue=pureldap.LDAPAssertionValue('foo')),
                        pureldap.LDAPFilter_equalityMatch(
                            attributeDesc=pureldap.LDAPAttributeDescription(
                                'mail'),
                            assertionValue=pureldap.LDAPAssertionValue('foo')),
                        pureldap.LDAPFilter_substrings(
                            type='mail',
                            substrings=[
                                pureldap.LDAPFilter_substrings_initial('foo@')
                            ]),
                    ]),
                    attributes=[''],
                ),
            },
            pureldap.LDAPBERDecoderContext_TopLevel(
                inherit=pureldap.LDAPBERDecoderContext_LDAPMessage(
                    fallback=pureldap.LDAPBERDecoderContext(
                        fallback=pureber.BERDecoderContext()),
                    inherit=pureldap.LDAPBERDecoderContext(
                        fallback=pureber.BERDecoderContext()))),
            [0x30, 97]
            # id
            + [0x02, 1, 1]
            # value
            + [0x63, 92] +
            ([0x04, 17] + l('dc=example,dc=com') + [0x0a, 1, 0x02] +
             [0x0a, 1, 0x00] + [0x02, 1, 0x01] + [0x02, 1, 0x00] +
             [0x01, 1, 0x00] + [0xA1, 52] +
             ([0xa3, 9] +
              ([0x04, 2] + l('cn') + [0x04, 3] + l('foo')) + [0xa3, 10] +
              ([0x04, 3] + l('uid') + [0x04, 3] + l('foo')) + [0xa3, 11] +
              ([0x04, 4] + l('mail') + [0x04, 3] + l('foo')) + [0xa4, 14] +
              ([0x04, 4] + l('mail') + [0x30, 6] +
               ([0x80, 4] + l('foo@')))) + [0x30, 2] + ([0x04, 0]))),
        (pureldap.LDAPExtendedRequest, [], {
            'requestName': '42.42.42',
            'requestValue': 'foo',
        }, None, [0x40 | 0x20 | 23, 1 + 1 + 8 + 1 + 1 + 3] +
         ([0x80 | 0] + [len('42.42.42')] + l('42.42.42')) +
         ([0x80 | 1] + [len('foo')] + l('foo'))),
    )

    def testToLDAP(self):
        """str(LDAPClass(...)) should give known result with known input"""
        for klass, args, kwargs, decoder, encoded in self.knownValues:
            result = klass(*args, **kwargs)
            result = str(result)
            result = map(ord, result)
            if result != encoded:
                raise AssertionError, \
                      "Class %s(*%s, **%s) doesn't encode properly: " \
                      "%s != %s" % (klass.__name__,
                                    repr(args), repr(kwargs),
                                    repr(result), repr(encoded))

    def testFromLDAP(self):
        """LDAPClass(encoded="...") should give known result with known input"""
        for klass, args, kwargs, decoder, encoded in self.knownValues:
            if decoder is None:
                decoder = pureldap.LDAPBERDecoderContext(
                    fallback=pureber.BERDecoderContext())
            m = s(*encoded)
            result, bytes = pureber.berDecodeObject(decoder, m)
            self.assertEquals(bytes, len(m))

            shouldBe = klass(*args, **kwargs)
            #TODO shouldn't use str below
            assert str(result)==str(shouldBe), \
                   "Class %s(*%s, **%s) doesn't decode properly: " \
                   "%s != %s" % (klass.__name__,
                                 repr(args), repr(kwargs),
                                 repr(result), repr(shouldBe))

    def testPartial(self):
        """LDAPClass(encoded="...") with too short input should throw BERExceptionInsufficientData"""
        for klass, args, kwargs, decoder, encoded in self.knownValues:
            if decoder is None:
                decoder = pureldap.LDAPBERDecoderContext(
                    fallback=pureber.BERDecoderContext())
            for i in xrange(1, len(encoded)):
                m = s(*encoded)[:i]
                self.assertRaises(pureber.BERExceptionInsufficientData,
                                  pureber.berDecodeObject, decoder, m)
            self.assertEquals((None, 0), pureber.berDecodeObject(decoder, ''))
예제 #22
0
 def test_item_present(self):
     text = r"*"
     filt = pureldap.LDAPFilter_present(value="cn")
     self.assertEqual(ldapfilter.parseMaybeSubstring("cn", text), filt)
예제 #23
0
 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)