Exemplo n.º 1
0
    def _sync_children(self):
        children = []
        first_attr_type = self.get_first_attr_type()

        if first_attr_type.attributeType == 'ou':
            self.roles = self.access_domain.role.select_related(
                'parent').prefetch_related('user_set__userinfo_set').all()
            if first_attr_type.value == 'user':
                for user in User.get_normal_user_list().prefetch_related(
                        'userinfo_set').filter(role__in=self.roles).distinct():
                    # for role in self.roles:
                    #    for user in role.user_set.all():

                    if user.status != User.Status.NORMAL:
                        continue
                    data = self.access_domain.create_user(user)
                    dn = distinguishedname.DistinguishedName(
                        to_bytes('cn=%s,ou=user,%s' %
                                 (user.username, self.access_domain.basedn)))
                    user_dn = self.__class__(dn=dn)
                    user_dn.genrate_for_receive_data(data)
                    children.append(user_dn)
            elif first_attr_type.value == 'role':
                for role in self.roles:
                    data = self.access_domain.create_role(role)
                    dn = distinguishedname.DistinguishedName(
                        to_bytes('cn=%s,ou=role,%s' %
                                 (role.name, self.access_domain.basedn)))
                    role_dn = self.__class__(dn=dn)
                    role_dn.genrate_for_receive_data(data)
                    children.append(role_dn)
        return children
Exemplo n.º 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))],
        )
Exemplo n.º 3
0
 def _cbSearchEntry(self, callback, objectName, attributes, complete):
     attrib = {}
     for key, values in attributes:
         attrib[to_bytes(key)] = [to_bytes(x) for x in values]
     o = LDAPEntry(
         client=self.client, dn=objectName, attributes=attrib, complete=complete
     )
     callback(o)
Exemplo n.º 4
0
 def _cbSearchEntry(self, callback, objectName, attributes, complete):
     attrib = {}
     for key, values in attributes:
         attrib[to_bytes(key)] = [to_bytes(x) for x in values]
     o = LDAPEntry(client=self.client,
                   dn=objectName,
                   attributes=attrib,
                   complete=complete)
     callback(o)
Exemplo n.º 5
0
 def assertSent(self, *shouldBeSent):
     shouldBeSent = list(shouldBeSent)
     msg = '%s expected to send %r but sent %r' % (self.__class__.__name__,
                                                   shouldBeSent, self.sent)
     assert self.sent == shouldBeSent, msg
     sentStr = b''.join([to_bytes(x) for x in self.sent])
     shouldBeSentStr = b''.join([to_bytes(x) for x in shouldBeSent])
     msg = '%s expected to send data %r but sent %r' % (
         self.__class__.__name__, shouldBeSentStr, sentStr)
     assert sentStr == shouldBeSentStr, msg
Exemplo n.º 6
0
def attributeAsLDIF(attribute, value):
    attribute = to_bytes(attribute)
    value = to_bytes(value)
    if (value.startswith(b"\0") or value.startswith(b"\n")
            or value.startswith(b"\r") or value.startswith(b" ")
            or value.startswith(b":") or value.startswith(b"<")
            or value.endswith(b" ") or containsNonprintable(value)):
        return attributeAsLDIF_base64(attribute, value)
    else:
        return b"%s: %s\n" % (attribute, value)
Exemplo n.º 7
0
 def assertSent(self, *shouldBeSent):
     shouldBeSent = list(shouldBeSent)
     msg = "{} expected to send {!r} but sent {!r}".format(
         self.__class__.__name__, shouldBeSent, self.sent
     )
     assert self.sent == shouldBeSent, msg
     sentStr = b"".join([to_bytes(x) for x in self.sent])
     shouldBeSentStr = b"".join([to_bytes(x) for x in shouldBeSent])
     msg = "{} expected to send data {!r} but sent {!r}".format(
         self.__class__.__name__, shouldBeSentStr, sentStr
     )
     assert sentStr == shouldBeSentStr, msg
Exemplo n.º 8
0
 def assertSent(self, *shouldBeSent):
     shouldBeSent = list(shouldBeSent)
     msg = '%s expected to send %r but sent %r' % (
         self.__class__.__name__,
         shouldBeSent,
         self.sent)
     assert self.sent == shouldBeSent, msg
     sentStr = b''.join([to_bytes(x) for x in self.sent])
     shouldBeSentStr = b''.join([to_bytes(x) for x in shouldBeSent])
     msg = '%s expected to send data %r but sent %r' % (
         self.__class__.__name__,
         shouldBeSentStr,
         sentStr)
     assert sentStr == shouldBeSentStr, msg
Exemplo n.º 9
0
    def testSimple(self):
        d = fetchschema.fetch(self.client, 'dc=example,dc=com')
        (attributeTypes, objectClasses) = util.pumpingDeferredResult(d)

        self.failUnlessEqual(
            [to_bytes(x) for x in attributeTypes],
            [to_bytes(schema.AttributeTypeDescription(x)) for x in [
                test_schema.AttributeType_KnownValues.knownValues[0][0]]])

        self.failUnlessEqual(
            [to_bytes(x) for x in objectClasses],
            [to_bytes(schema.ObjectClassDescription(x)) for x in [
                test_schema.OBJECTCLASSES['organization'],
                test_schema.OBJECTCLASSES['organizationalUnit']]])
Exemplo n.º 10
0
def attributeAsLDIF(attribute, value):
    attribute = to_bytes(attribute)
    value = to_bytes(value)
    if value.startswith(b'\0') \
       or value.startswith(b'\n') \
       or value.startswith(b'\r') \
       or value.startswith(b' ') \
       or value.startswith(b':') \
       or value.startswith(b'<') \
       or value.endswith(b' ') \
       or containsNonprintable(value):
        return attributeAsLDIF_base64(attribute, value)
    else:
        return b'%s: %s\n' % (attribute, value)
Exemplo n.º 11
0
    def fromBER(klass, tag, content, berdecoder=None):
        l = berDecodeMultiple(content, LDAPBERDecoderContext_ModifyDNRequest(fallback=berdecoder))

        kw = {}
        try:
            kw['newSuperior'] = to_bytes(l[3].value)
        except IndexError:
            pass

        r = klass(entry=to_bytes(l[0].value),
                  newrdn=to_bytes(l[1].value),
                  deleteoldrdn=l[2].value,
                  tag=tag,
                  **kw)
        return r
Exemplo n.º 12
0
    def setPasswordMaybe_Samba(self, newPasswd):
        """

        Set the Samba password on this object if it is a
        sambaSamAccount or sambaAccount.

        @param newPasswd: A string containing the new password.

        @return: A Deferred that will complete when the operation is
        done.

        """
        if not self.complete and not self.has_key('objectClass'):
            d = self.fetch('objectClass')
            d.addCallback(lambda dummy, self=self, newPasswd=newPasswd: self.
                          setPasswordMaybe_Samba(newPasswd))
        else:
            objectClasses = [
                to_bytes(s.upper()) for s in self.get('objectClass', ())
            ]
            if b'SAMBAACCOUNT' in objectClasses:
                d = self.setPassword_Samba(newPasswd, style="sambaAccount")
            elif b'SAMBASAMACCOUNT' in objectClasses:
                d = self.setPassword_Samba(newPasswd, style="sambaSamAccount")
            else:
                d = defer.succeed(self)
        return d
Exemplo n.º 13
0
def asLDIF(dn, attributes):
    s = b'dn: %s\n' % to_bytes(dn)
    for k, vs in attributes:
        for v in vs:
            s = s + attributeAsLDIF(k, v)
    s = s + b'\n'
    return s
Exemplo n.º 14
0
 def test_bytes_object(self):
     """
     byte string is returned without changes
     if passed to to_bytes function
     """
     obj = b'bytes'
     self.assertEqual(to_bytes(obj), b'bytes')
Exemplo n.º 15
0
 def _bind(self, password):
     password = to_bytes(password)
     for key in self._user_password_keys:
         for digest in self.get(key, ()):
             digest = to_bytes(digest)
             if digest.startswith(b'{SSHA}'):
                 raw = base64.decodestring(digest[len(b'{SSHA}'):])
                 salt = raw[20:]
                 got = sshaDigest(password, salt)
                 if got == digest:
                     return self
             else:
                 # Plaintext
                 if digest == password:
                     return self
     raise ldaperrors.LDAPInvalidCredentials()
Exemplo n.º 16
0
 def test_unicode_object(self):
     """
     unicode string is encoded to utf-8 if passed
     to to_bytes function
     """
     obj = six.u('unicode')
     self.assertEqual(to_bytes(obj), b'unicode')
Exemplo n.º 17
0
 def test_wireable_object(self):
     """
     to_bytes function use object`s toWire method
     to get its bytes representation if it has one
     """
     obj = WireableObject()
     self.assertEqual(to_bytes(obj), b'wire')
Exemplo n.º 18
0
def _get(path, dn):
    path = to_bytes(path)
    dn = distinguishedname.DistinguishedName(dn)
    l = list(dn.split())
    assert len(l) >= 1
    l.reverse()

    parser = StoreParsedLDIF()

    entry = os.path.join(path, *[b'%s.dir' % rdn.toWire() for rdn in l[:-1]])
    entry = os.path.join(entry, b'%s.ldif' % l[-1].toWire())
    f = open(entry, 'rb')
    while 1:
        data = f.read(8192)
        if not data:
            break
        parser.dataReceived(data)
    parser.connectionLost(failure.Failure(error.ConnectionDone()))

    assert parser.done
    entries = parser.seen
    if len(entries) == 0:
        raise LDIFTreeEntryContainsNoEntries()
    elif len(entries) > 1:
        raise LDIFTreeEntryContainsMultipleEntries(entries)
    else:
        return entries[0]
Exemplo n.º 19
0
def _put(path, entry):
    path = to_bytes(path)
    l = list(entry.dn.split())
    assert len(l) >= 1
    l.reverse()

    entryRDN = l.pop()
    if l:
        grandParent = os.path.join(
            path, *[b'%s.dir' % rdn.toWire() for rdn in l[:-1]])
        parentEntry = os.path.join(grandParent, b'%s.ldif' % l[-1].toWire())
        parentDir = os.path.join(grandParent, b'%s.dir' % l[-1].toWire())
        if not os.path.exists(parentDir):
            if not os.path.exists(parentEntry):
                raise LDIFTreeNoSuchObject(entry.dn.up())
            try:
                os.mkdir(parentDir)
            except OSError as e:
                if e.errno == errno.EEXIST:
                    # we lost a race to create the directory, safe to ignore
                    pass
                else:
                    raise
    else:
        parentDir = path
    return _putEntry(os.path.join(parentDir, b'%s' % entryRDN.toWire()), entry)
Exemplo n.º 20
0
 def __init__(self, path, dn=None, *a, **kw):
     if dn is None:
         dn = ''
     entry.BaseLDAPEntry.__init__(self, dn, *a, **kw)
     self.path = to_bytes(path)
     if dn != '':
         self._load()
Exemplo n.º 21
0
def asLDIF(dn, attributes):
    s = b"dn: %s\n" % to_bytes(dn)
    for k, vs in attributes:
        for v in vs:
            s = s + attributeAsLDIF(k, v)
    s = s + b"\n"
    return s
Exemplo n.º 22
0
 def _bind(self, password):
     password = to_bytes(password)
     for key in self._user_password_keys:
         for digest in self.get(key, ()):
             digest = to_bytes(digest)
             if digest.startswith(b'{SSHA}'):
                 raw = base64.decodestring(digest[len(b'{SSHA}'):])
                 salt = raw[20:]
                 got = sshaDigest(password, salt)
                 if got == digest:
                     return self
             else:
                 # Plaintext
                 if digest == password:
                     return self
     raise ldaperrors.LDAPInvalidCredentials()
Exemplo n.º 23
0
    def setPasswordMaybe_Samba(self, newPasswd):
        """

        Set the Samba password on this object if it is a
        sambaSamAccount or sambaAccount.

        @param newPasswd: A string containing the new password.

        @return: A Deferred that will complete when the operation is
        done.

        """
        if not self.complete and not self.has_key('objectClass'):
            d = self.fetch('objectClass')
            d.addCallback(lambda dummy, self=self, newPasswd=newPasswd:
                          self.setPasswordMaybe_Samba(newPasswd))
        else:
            objectClasses = [to_bytes(s.upper()) for s in self.get('objectClass', ())]
            if b'SAMBAACCOUNT' in objectClasses:
                d = self.setPassword_Samba(newPasswd, style="sambaAccount")
            elif b'SAMBASAMACCOUNT' in objectClasses:
                d = self.setPassword_Samba(newPasswd, style="sambaSamAccount")
            else:
                d = defer.succeed(self)
        return d
Exemplo n.º 24
0
 def __repr__(self):
     keys = sorted((key for key in self), key=to_bytes)
     a = []
     for key in keys:
         a.append('%s: %s' % (repr(key), repr(list(self[key]))))
     attributes = ', '.join(a)
     dn = to_bytes(self.dn.getText()) if six.PY2 else self.dn.getText()
     return '%s(%s, {%s})' % (self.__class__.__name__, repr(dn), attributes)
Exemplo n.º 25
0
 def __repr__(self):
     dn = to_bytes(self.dn)
     return (self.__class__.__name__
             + '('
             + 'dn=%r' % (dn if six.PY2 else to_unicode(dn))
             + ', '
             + 'modifications=%r' % self.modifications
             + ')')
Exemplo n.º 26
0
def _putEntry(fileName, entry):
    """fileName is without extension."""
    tmp = b'%s.%s.tmp' % (fileName, to_bytes(str(uuid.uuid4())))
    f = open(tmp, 'wb')
    f.write(entry.toWire())
    f.close()
    os.rename(tmp, fileName + b'.ldif')
    return True
Exemplo n.º 27
0
    def __init__(self, text):
        self.oid = None
        self.desc = None
        self.binary_transfer_required = False
        self.human_readable = True

        if text is not None:
            self._parse(to_bytes(text))
Exemplo n.º 28
0
    def fromBER(klass, tag, content, berdecoder=None):
        l = berDecodeMultiple(
            content,
            LDAPBERDecoderContext_ModifyDNRequest(fallback=berdecoder))

        kw = {}
        try:
            kw['newSuperior'] = to_bytes(l[3].value)
        except IndexError:
            pass

        r = klass(entry=to_bytes(l[0].value),
                  newrdn=to_bytes(l[1].value),
                  deleteoldrdn=l[2].value,
                  tag=tag,
                  **kw)
        return r
Exemplo n.º 29
0
 def toWire(self):
     value = to_bytes(self.value)
     result = (
         six.int2byte(self.identification()) +
         int2berlen(len(value)) +
         value
         )
     return result
Exemplo n.º 30
0
 def toWire(self):
     message = self.message
     if message:
         return b'%s: %s' % (self.name, to_bytes(message))
     elif self.name:
         return self.name
     else:
         return b'Unknown LDAP error %r' % self
Exemplo n.º 31
0
 def toWire(self):
     value = to_bytes(self.value)
     result = (
         six.int2byte(self.identification()) +
         int2berlen(len(value)) +
         value
         )
     return result
Exemplo n.º 32
0
 def toWire(self):
     message = self.message
     if message:
         return b'%s: %s' % (self.name, to_bytes(message))
     elif self.name:
         return self.name
     else:
         return b'Unknown LDAP error %r' % self
Exemplo n.º 33
0
    def __init__(self, text):
        self.oid = None
        self.desc = None
        self.binary_transfer_required = False
        self.human_readable = True

        if text is not None:
            self._parse(to_bytes(text))
Exemplo n.º 34
0
 def __repr__(self):
     dn = self.dn.getText()
     return (self.__class__.__name__
             + '('
             + 'dn=%r' % (to_bytes(dn) if six.PY2 else dn)
             + ', '
             + 'modifications=%r' % self.modifications
             + ')')
Exemplo n.º 35
0
    def __init__(self, text):
        self.oid = None
        self.name = None
        self.desc = None
        self.obsolete = None
        self.syntax = None

        if text is not None:
            self._parse(to_bytes(text))
Exemplo n.º 36
0
    def testStringification(self):
        for want, values in self.knownValues:
            a = schema.MatchingRuleDescription(None)
            for key, val in values.items():
                setattr(a, key, val)

            want = b' '.join(want.split())
            got = b' '.join(to_bytes(a).split())
            self.assertEqual(got, want)
Exemplo n.º 37
0
    def __init__(self, text):
        self.oid = None
        self.name = None
        self.desc = None
        self.obsolete = None
        self.syntax = None

        if text is not None:
            self._parse(to_bytes(text))
Exemplo n.º 38
0
    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(to_bytes(text)))
            for text in o.get("objectClasses", []):
                objectClasses.append(
                    schema.ObjectClassDescription(to_bytes(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")
Exemplo n.º 39
0
 def genrate_for_receive_data(self, data):
     parser = StoreParsedLDIF()
     parser.dataReceived(to_bytes(data))
     parser.connectionLost(failure.Failure(error.ConnectionDone()))
     assert parser.done
     entries = parser.seen
     if len(entries) > 0:
         for k, v in entries[0].items():
             self._attributes[k] = attributeset.LDAPAttributeSet(k, v)
Exemplo n.º 40
0
    def testStringification(self):
        for want, values in self.knownValues:
            a = schema.MatchingRuleDescription(None)
            for key, val in values.items():
                setattr(a, key, val)

            want = b" ".join(want.split())
            got = b" ".join(to_bytes(a).split())
            self.assertEqual(got, want)
Exemplo n.º 41
0
    def __search(self,
                 filterText=None,
                 filterObject=None,
                 attributes=(),
                 scope=None,
                 derefAliases=None,
                 sizeLimit=0,
                 timeLimit=0,
                 typesOnly=0,
                 callback=None):
        # todo 转换 django query 限制查询
        results = []
        first_attr_type = self.get_first_attr_type()

        self.roles = self.roles or self.access_domain.role.select_related(
            'parent').prefetch_related('user_set__userinfo_set').all()
        if first_attr_type.attributeType == 'ou':
            if first_attr_type.value == 'user':
                for role in self.roles:
                    for user in role.user_set.all():
                        # for user in User.get_normal_user_list().prefetch_related('userinfo_set').filter(
                        #         role__in=self.roles).distinct():
                        data = self.access_domain.create_user(user)
                        dn = distinguishedname.DistinguishedName(
                            to_bytes(
                                'cn=%s,ou=user,%s' %
                                (user.username, self.access_domain.basedn)))
                        user_dn = self.__class__(dn=dn)
                        user_dn.genrate_for_receive_data(data)
                        results.append(user_dn)
            elif first_attr_type.value == 'role':
                for role in self.roles:
                    data = self.access_domain.create_role(role)
                    dn = distinguishedname.DistinguishedName(
                        to_bytes('cn=%s,ou=role,%s' %
                                 (role.name, self.access_domain.basedn)))
                    role_dn = self.__class__(dn=dn)
                    role_dn.genrate_for_receive_data(data)
                    results.append(role_dn)
        if callback:
            for dn in results:
                callback(dn)

        return defer.succeed(results)
Exemplo n.º 42
0
 def __repr__(self):
     keys = sorted((key for key in self), key=to_bytes)
     a = []
     for key in keys:
         a.append('%s: %s' % (repr(key), repr(list(self[key]))))
     attributes = ', '.join(a)
     dn = to_bytes(self.dn.getText()) if six.PY2 else self.dn.getText()
     return '%s(%s, {%s})' % (
         self.__class__.__name__,
         repr(dn),
         attributes)
Exemplo n.º 43
0
    def __init__(self, text):
        self.oid = None
        self.name = None
        self.desc = None
        self.obsolete = 0
        self.sup = []
        self.type = None
        self.must = []
        self.may = []

        if text is not None:
            self._parse(to_bytes(text))
Exemplo n.º 44
0
    def toWire(self):
        a = []

        for key in self._object_class_keys:
            objectClasses = list(self._attributes.get(key, []))
            objectClasses.sort(key=to_bytes)
            a.append((key, objectClasses))

        items_gen = ((key, self[key]) for key in self)
        items = sorted(items_gen, key=lambda x: to_bytes(x[0]))
        for key, values in items:
            if key.lower() not in self._object_class_lower_keys:
                vs = list(values)
                vs.sort()
                a.append((key, vs))
        return ldif.asLDIF(self.dn.getText(), a)
Exemplo n.º 45
0
    def items(self):
        a = []

        for key in self._object_class_keys:
            objectClasses = list(self._attributes.get(key, []))
            objectClasses.sort(key=to_bytes)
            if objectClasses:
                a.append((key, objectClasses))

        l = list(self._attributes.items())
        l.sort(key=lambda x: to_bytes(x[0]))
        for key, values in l:
            if key.lower() not in self._object_class_lower_keys:
                vs = list(values)
                vs.sort()
                a.append((key, vs))

        return a
Exemplo n.º 46
0
def init(**errors):
    global reverse
    reverse = {}
    for name, value in errors.items():
        if value == errors['success']:
            klass = Success
        else:
            classname = 'LDAP'+name[0].upper()+name[1:]
            klass = type(
                classname,
                (LDAPException,),
                {
                    'resultCode': value,
                    'name': to_bytes(name),
                    },
                )
            globals()[classname] = klass
        reverse[value] = klass
Exemplo n.º 47
0
    def __init__(self, text):
        self.oid = None
        self.name = None
        self.desc = None
        self.obsolete = 0
        self.sup = None
        self.equality = None
        self.ordering = None
        self.substr = None
        self.syntax = None
        self.single_value = None
        self.collective = None
        self.no_user_modification = None
        self.usage = None

        # storage for experimental terms ("X-SOMETHING"), so we can
        # output them when stringifying.
        self.x_attrs = []

        if text is not None:
            self._parse(to_bytes(text))
Exemplo n.º 48
0
 def __repr__(self):
     dn = self.dn.getText()
     return (self.__class__.__name__
             + '('
             + '%r' % (to_bytes(dn) if six.PY2 else dn)
             + ')')
Exemplo n.º 49
0
 def toWire(self):
     r = b''.join(to_bytes(x) for x in self.data)
     return six.int2byte(self.identification()) + int2berlen(len(r)) + r
Exemplo n.º 50
0
 def toWire(self):
     if self.message:
         return b'%s: %s' % (self.name, to_bytes(self.message))
     if self.name:
         return self.name
     return b'Unknown LDAP error %r' % self
Exemplo n.º 51
0
 def toWire(self):
     l = [LDAPOID(self.requestName, tag=CLASS_CONTEXT | 0)]
     if self.requestValue is not None:
         value = to_bytes(self.requestValue)
         l.append(BEROctetString(value, tag=CLASS_CONTEXT | 1))
     return BERSequence(l, tag=self.tag).toWire()
Exemplo n.º 52
0
 def toWire(self):
     codeName = b'unknownError(%d)' % self.code
     if self.message:
         return b'%s: %s' % (codeName, to_bytes(self.message))
     else:
         return codeName