Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def addChild(self, rdn, attributes):
"""TODO ugly API. Returns the created entry."""
rdn = distinguishedname.RelativeDistinguishedName(rdn)
rdn_str = rdn.toWire()
if rdn_str in self._children:
raise ldaperrors.LDAPEntryAlreadyExists(self._children[rdn_str].dn)
dn = distinguishedname.DistinguishedName(
listOfRDNs=(rdn,) + self.dn.split())
e = ReadOnlyInMemoryLDAPEntry(dn, attributes)
e._parent = self
self._children[rdn_str] = e
return e
def lookup(self, dn):
dn = distinguishedname.DistinguishedName(dn)
if not self.dn.contains(dn):
return defer.fail(ldaperrors.LDAPNoSuchObject(dn))
if dn == self.dn:
return defer.succeed(self)
it = dn.split()
me = self.dn.split()
assert len(it) > len(me)
assert ((len(me) == 0) or (it[-len(me):] == me))
rdn = it[-len(me)-1]
path = os.path.join(self.path, '%s.dir' % rdn)
entry = os.path.join(self.path, '%s.ldif' % rdn)
if not os.path.isdir(path) and not os.path.isfile(entry):
return defer.fail(ldaperrors.LDAPNoSuchObject(dn))
else:
childDN = distinguishedname.DistinguishedName(listOfRDNs=(rdn,)+me)
c = self.__class__(path, childDN)
return c.lookup(dn)
'Extended request PasswordModify '
'received unexpected item.')
if self.boundUser is None:
raise ldaperrors.LDAPStrongAuthRequired()
if (userIdentity is not None
and userIdentity != self.boundUser.dn):
log.msg('User %(actor)s tried to change password of %(target)s' % {
'actor': self.boundUser.dn.toWire(),
'target': userIdentity.toWire(),
})
raise ldaperrors.LDAPInsufficientAccessRights()
if (oldPasswd is not None
or newPasswd is None):
raise ldaperrors.LDAPOperationsError(
'Password does not support this case.')
self.boundUser.setPassword(newPasswd)
d = self.boundUser.commit()
def cb_(result):
if result:
return pureldap.LDAPExtendedResponse(
resultCode=ldaperrors.Success.resultCode,
responseName=self.extendedRequest_LDAPPasswordModifyRequest.oid)
else:
raise ldaperrors.LDAPOperationsError('Internal error.')
d.addCallback(cb_)
return d
def _addChild(self, rdn, attributes):
rdn = distinguishedname.RelativeDistinguishedName(rdn)
for c in self._sync_children():
if c.dn.split()[0] == rdn:
raise ldaperrors.LDAPEntryAlreadyExists(c.dn)
dn = distinguishedname.DistinguishedName(
listOfRDNs=(rdn,) + self.dn.split())
e = entry.BaseLDAPEntry(dn, attributes)
if not os.path.exists(self.path):
os.mkdir(self.path)
fileName = os.path.join(self.path, '%s' % rdn)
tmp = fileName + '.' + str(uuid.uuid4()) + '.tmp'
f = open(tmp, 'wb')
f.write(str(e).encode('ascii'))
f.close()
os.rename(tmp, fileName+'.ldif')
dirName = os.path.join(self.path, '%s.dir' % rdn)
e = self.__class__(dirName, dn)
return e
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)
def _cb(entry):
"""
Called when BIND operation was successful.
"""
self.boundUser = entry
msg = pureldap.LDAPBindResponse(
resultCode=ldaperrors.Success.resultCode,
matchedDN=str(entry.dn))
return msg
d.addCallback(_cb)
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""LDAP protocol client"""
from ldaptor.protocols import pureldap, pureber
from ldaptor.protocols.ldap import ldaperrors
from twisted.python import log
from twisted.python.failure import Failure
from twisted.internet import protocol, defer, ssl, reactor
class LDAPClientConnectionLostException(ldaperrors.LDAPException):
def __str__(self):
return 'Connection lost'
class LDAPStartTLSBusyError(ldaperrors.LDAPOperationsError):
def __init__(self, onwire, message=None):
self.onwire = onwire
ldaperrors.LDAPOperationsError.__init__(self, message=message)
def __str__(self):
return 'Cannot STARTTLS while operations on wire: %r' % self.onwire
class LDAPClient(protocol.Protocol):
"""An LDAP client"""
debug = True
def __init__(self):
self.onwire = {}
self.buffer = ''
self.connected = None
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")
x.nt_version = 5
x.lmnt_token = 0xffff
x.lm20_token = 0xffff
#print ndr.ndr_print(x)
y = ndr.ndr_pack(x)
attrs = [('netlogon', [ str(y) ])]
print binascii.hexlify(str(y))
result = ''
result += str(pureldap.LDAPMessage(pureldap.LDAPSearchResultEntry(
objectName='',
attributes=attrs),
id=msgId))
result += str(pureldap.LDAPMessage(pureldap.LDAPSearchResultDone(
resultCode=ldaperrors.Success.resultCode),
id=msgId))
return result
elif isinstance(
value,
pureldap.LDAPPasswordModifyRequest_oldPasswd):
if oldPasswd is not None:
raise ldaperrors.LDAPProtocolError(
'Extended request PasswordModify '
'received oldPasswd twice.')
oldPasswd = value.value
elif isinstance(value, pureldap.LDAPPasswordModifyRequest_newPasswd):
if newPasswd is not None:
raise ldaperrors.LDAPProtocolError(
'Extended request PasswordModify '
'received newPasswd twice.')
newPasswd = value.value
else:
raise ldaperrors.LDAPProtocolError(
'Extended request PasswordModify '
'received unexpected item.')
if self.boundUser is None:
raise ldaperrors.LDAPStrongAuthRequired()
if (userIdentity is not None
and userIdentity != self.boundUser.dn):
log.msg('User %(actor)s tried to change password of %(target)s' % {
'actor': self.boundUser.dn.toWire(),
'target': userIdentity.toWire(),
})
raise ldaperrors.LDAPInsufficientAccessRights()
if (oldPasswd is not None
or newPasswd is None):
raise ldaperrors.LDAPOperationsError(