def testDecodeValidInput(self): """ It can be decoded from its bytes serialization. """ knownValues=( ([], [0x30, 0x00]), ([pureber.BERInteger(2)], [0x30, 0x03, 0x02, 0x01, 2]), ([pureber.BERInteger(3)], [0x30, 0x03, 0x02, 0x01, 3]), ([pureber.BERInteger(128)], [0x30, 0x04, 0x02, 0x02, 0, 128]), ([ pureber.BERInteger(2), pureber.BERInteger(3), pureber.BERInteger(128), ], [0x30, 0x0a] + [0x02, 0x01, 2] + [0x02, 0x01, 3] + [0x02, 0x02, 0, 128]), ) for content, encoded in knownValues: m=s(*encoded) result, bytes = pureber.berDecodeObject(pureber.BERDecoderContext(), m) self.assertEqual(bytes, len(m)) self.assertIsInstance(result, pureber.BERSequence) result = result.data self.assertEqual(len(content), len(result)) for i in six.moves.range(len(content)): self.assertEqual(content[i], result[i]) self.assertEqual(content, result)
def testDecdeInvalidInput(self): """ It raises BERExceptionInsufficientData when trying to decode from data which is not valid. """ m = pureber.BERSequence([pureber.BERInteger(2)]).toWire() self.assertEqual(5, len(m)) self.assertRaises( pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:4], ) self.assertRaises( pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:3], ) self.assertRaises( pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:2], ) self.assertRaises( pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:1], ) self.assertEqual((None, 0), pureber.berDecodeObject(pureber.BERDecoderContext(), ""))
def fromBER(klass, tag, content, berdecoder=None): value, bytes = berDecodeObject(LDAPBERDecoderContext_Filter(fallback=berdecoder, inherit=berdecoder), content) assert bytes == len(content) r = klass(value=value, tag=tag) return r
def testPartialBEREnumeratedEncodings(self): """BEREnumerated(encoded="...") with too short input should throw BERExceptionInsufficientData""" m=str(pureber.BEREnumerated(42)) assert len(m)==3 self.assertRaises(pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:2]) self.assertRaises(pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:1]) self.assertEquals((None, 0), pureber.berDecodeObject(pureber.BERDecoderContext(), ''))
def testDecodeValidInput(self): """ It can be decoded from its bytes serialization. """ knownValues = ( ([], [0x30, 0x00]), ([pureber.BERInteger(2)], [0x30, 0x03, 0x02, 0x01, 2]), ([pureber.BERInteger(3)], [0x30, 0x03, 0x02, 0x01, 3]), ([pureber.BERInteger(128)], [0x30, 0x04, 0x02, 0x02, 0, 128]), ( [ pureber.BERInteger(2), pureber.BERInteger(3), pureber.BERInteger(128), ], [0x30, 0x0A] + [0x02, 0x01, 2] + [0x02, 0x01, 3] + [0x02, 0x02, 0, 128], ), ) for content, encoded in knownValues: m = s(*encoded) result, bytes = pureber.berDecodeObject( pureber.BERDecoderContext(), m) self.assertEqual(bytes, len(m)) self.assertIsInstance(result, pureber.BERSequence) result = result.data self.assertEqual(len(content), len(result)) for i in range(len(content)): self.assertEqual(content[i], result[i]) self.assertEqual(content, result)
def testPartialBERBooleanEncodings(self): """BERBoolean(encoded="...") with too short input should throw BERExceptionInsufficientData""" m = pureber.BERBoolean(42).toWire() self.assertEqual(3, len(m)) self.assertRaises(pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:2]) self.assertRaises(pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:1]) self.assertEqual((None, 0), pureber.berDecodeObject(pureber.BERDecoderContext(), ''))
def testFromBERNullKnownValues(self): """BERNull(encoded="...") should give known result with known input""" encoded=[0x05, 0x00] m=s(*encoded) result, bytes = pureber.berDecodeObject(pureber.BERDecoderContext(), m) self.assertEquals(bytes, len(m)) assert isinstance(result, pureber.BERNull) assert 0x05==result.tag
def testFromBERNullKnownValues(self): """BERNull(encoded="...") should give known result with known input""" encoded = [0x05, 0x00] m = s(*encoded) result, bytes = pureber.berDecodeObject(pureber.BERDecoderContext(), m) self.assertEqual(bytes, len(m)) self.assertIsInstance(result, pureber.BERNull) self.assertEqual(0x05, result.tag)
def testSanity(self): """BEREnumerated(encoded=BEREnumerated(n)).value==n for -1000..1000""" for n in range(-1000, 1001, 10): encoded = str(pureber.BEREnumerated(n)) result, bytes = pureber.berDecodeObject(pureber.BERDecoderContext(), encoded) self.assertEquals(bytes, len(encoded)) assert isinstance(result, pureber.BEREnumerated) result = result.value assert n==result
def fromBER(cls, criticality, control_value): ber_context = pureber.BERDecoderContext() obj, _ = pureber.berDecodeObject(ber_context, control_value) size = obj[0].value cookie = obj[1].value if size <= 0: raise ldaperrors.LDAPUnavailableCriticalExtension( 'Page size must be greater than 0') if cookie: obj, _ = pureber.berDecodeObject(ber_context, cookie) remain_count = obj[0].value last_id = obj[1].value else: remain_count = None last_id = 0 return cls(criticality, size, remain_count, last_id)
def testSanity(self): """BEROctetString(encoded=BEROctetString(n*'x')).value==n*'x' for some values of n""" for n in 0,1,2,3,4,5,6,100,126,127,128,129,1000,2000: encoded = str(pureber.BEROctetString(n*'x')) result, bytes = pureber.berDecodeObject(pureber.BERDecoderContext(), encoded) self.assertEquals(bytes, len(encoded)) assert isinstance(result, pureber.BEROctetString) result = result.value assert n*'x'==result
def testFromBERBooleanKnownValues(self): """BERBoolean(encoded="...") should give known result with known input""" for integer, encoded, canon in self.knownValues: m=s(*encoded) result, bytes = pureber.berDecodeObject(pureber.BERDecoderContext(), m) self.assertEqual(bytes, len(m)) self.assertIsInstance(result, pureber.BERBoolean) result = result.value self.assertEqual(canon, result)
def testFromBEREnumeratedKnownValues(self): """BEREnumerated(encoded="...") should give known result with known input""" for integer, encoded in self.knownValues: m=s(*encoded) result, bytes = pureber.berDecodeObject(pureber.BERDecoderContext(), m) self.assertEquals(bytes, len(m)) assert isinstance(result, pureber.BEREnumerated) result = result.value assert integer==result
def testSanity(self): """BEREnumerated(encoded=BEREnumerated(n)).value==n for -1000..1000""" for n in range(-1000, 1001, 10): encoded = pureber.BEREnumerated(n).toWire() result, bytes = pureber.berDecodeObject(pureber.BERDecoderContext(), encoded) self.assertEqual(bytes, len(encoded)) self.assertIsInstance(result, pureber.BEREnumerated) result = result.value self.assertEqual(n, result)
def testFromBERBooleanKnownValues(self): """BERBoolean(encoded="...") should give known result with known input""" for integer, encoded, canon in self.knownValues: m = s(*encoded) result, bytes = pureber.berDecodeObject( pureber.BERDecoderContext(), m) self.assertEqual(bytes, len(m)) self.assertIsInstance(result, pureber.BERBoolean) result = result.value self.assertEqual(canon, result)
def testPartialBERNullEncodings(self): """BERNull(encoded="...") with too short input should throw BERExceptionInsufficientData""" m = str(pureber.BERNull()) self.assertEqual(2, len(m)) self.assertRaises(pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:1]) self.assertEqual((None, 0), pureber.berDecodeObject(pureber.BERDecoderContext(), ''))
def testFromBEROctetStringKnownValues(self): """BEROctetString(encoded="...") should give known result with known input""" for st, encoded in self.knownValues: m=s(*encoded) result, bytes = pureber.berDecodeObject(pureber.BERDecoderContext(), m) self.assertEquals(bytes, len(m)) assert isinstance(result, pureber.BEROctetString) result = str(result) result = map(ord, result) assert encoded==result
def testPartialBERSequenceEncodings(self): """BERSequence(encoded="...") with too short input should throw BERExceptionInsufficientData""" m=str(pureber.BERSequence([pureber.BERInteger(2)])) assert len(m)==5 self.assertRaises(pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:4]) self.assertRaises(pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:3]) self.assertRaises(pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:2]) self.assertRaises(pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:1]) self.assertEquals((None, 0), pureber.berDecodeObject(pureber.BERDecoderContext(), ''))
def testSanity(self): """BEROctetString(encoded=BEROctetString(n*'x')).value==n*'x' for some values of n""" for n in 0, 1, 2, 3, 4, 5, 6, 100, 126, 127, 128, 129, 1000, 2000: encoded = pureber.BEROctetString(n * b"x").toWire() result, bytes = pureber.berDecodeObject( pureber.BERDecoderContext(), encoded) self.assertEqual(bytes, len(encoded)) self.assertIsInstance(result, pureber.BEROctetString) result = result.value self.assertEqual(n * b"x", result)
def testFromBEROctetStringKnownValues(self): """BEROctetString(encoded="...") should give known result with known input""" for st, encoded in self.knownValues: m=s(*encoded) result, bytes = pureber.berDecodeObject(pureber.BERDecoderContext(), m) self.assertEqual(bytes, len(m)) self.assertIsInstance(result, pureber.BEROctetString) result = result.toWire() result = l(result) self.assertEqual(encoded, result)
def testSanity(self): """BEREnumerated(encoded=BEREnumerated(n)).value==n for -1000..1000""" for n in range(-1000, 1001, 10): encoded = pureber.BEREnumerated(n).toWire() result, bytes = pureber.berDecodeObject( pureber.BERDecoderContext(), encoded) self.assertEqual(bytes, len(encoded)) self.assertIsInstance(result, pureber.BEREnumerated) result = result.value self.assertEqual(n, result)
def testFromBEROctetStringKnownValues(self): """BEROctetString(encoded="...") should give known result with known input""" for st, encoded in self.knownValues: m = s(*encoded) result, bytes = pureber.berDecodeObject( pureber.BERDecoderContext(), m) self.assertEqual(bytes, len(m)) self.assertIsInstance(result, pureber.BEROctetString) result = result.toWire() result = l(result) self.assertEqual(encoded, result)
def get_paged_search_cookie_(controls): """ Input: semi-parsed controls list from LDAP response; list of tuples (controlType, criticality, controlValue). Parses the controlValue and returns the cookie as a byte string. """ control_value = controls[0][2] ber_context = pureber.BERDecoderContext() ber_seq, bytes_used = pureber.berDecodeObject(ber_context, control_value) raw_cookie = ber_seq[1] cookie = raw_cookie.value return cookie
def dataReceived(self, recd): self.buffer += recd while 1: try: o, bytes = pureber.berDecodeObject(self.berdecoder, self.buffer) except pureber.BERExceptionInsufficientData: o, bytes = None, 0 self.buffer = self.buffer[bytes:] if not o: break self.handle(o)
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, ''))
def testFromBERSequenceKnownValues(self): """BERSequence(encoded="...") should give known result with known input""" for content, encoded in self.knownValues: m=s(*encoded) result, bytes = pureber.berDecodeObject(pureber.BERDecoderContext(), m) self.assertEquals(bytes, len(m)) assert isinstance(result, pureber.BERSequence) result = result.data assert len(content)==len(result) for i in xrange(len(content)): assert content[i]==result[i] assert content==result
def get_paged_search_cookie(controls): """ Input: semi-parsed controls list from LDAP response; list of tuples (controlType, criticality, controlValue). Parses the controlValue and returns the cookie as a byte string. """ control_value = controls[0][2] ber_context = pureber.BERDecoderContext() ber_seq, bytes_used = pureber.berDecodeObject(ber_context, control_value) raw_cookie = ber_seq[1] cookie = raw_cookie.value return cookie
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, ''))
def testDecdeInvalidInput(self): """ It raises BERExceptionInsufficientData when trying to decode from data which is not valid. """ m = pureber.BERSequence([pureber.BERInteger(2)]).toWire() self.assertEqual(5, len(m)) self.assertRaises(pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:4]) self.assertRaises(pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:3]) self.assertRaises(pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:2]) self.assertRaises(pureber.BERExceptionInsufficientData, pureber.berDecodeObject, pureber.BERDecoderContext(), m[:1]) self.assertEqual((None, 0), pureber.berDecodeObject(pureber.BERDecoderContext(), ''))
def buildReply(data): global lastDomain msg, bytes = pureber.berDecodeObject(berdecoder, data) msgId = msg.id print msgId msg = msg.value assert isinstance(msg, pureldap.LDAPProtocolRequest) print msg.__class__.__name__ print msg.baseObject print msg.scope domain = findDomain(msg.filter) if (domain.endswith('.')): domain = domain[0:-1] print "Received search for domain: %s" % domain lastDomain = domain.split('.') x = nbt.NETLOGON_SAM_LOGON_RESPONSE_EX() x.command = 23 x.sbz = 0 x.server_type = 0x000003fd x.domain_uuid = misc.GUID("6cb2d967-f2b7-4c93-bce1-d943eda330a1") x.forest = '.'.join(lastDomain) x.dns_domain = '.'.join(lastDomain) x.pdc_dns_name = "debian-smb." + '.'.join(lastDomain) x.domain_name = lastDomain[0].upper() x.pdc_name = "DEBIAN-SMB" #x.user_name = "" x.server_site = "Default-First-Site-Name" x.client_site = "Default-First-Site-Name" x.sockaddr_size = 0 x.sockaddr.pdc_ip = '0.0.0.0' 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
def _makeResultList(self, s): berdecoder = pureldap.LDAPBERDecoderContext_TopLevel( inherit=pureldap.LDAPBERDecoderContext_LDAPMessage( fallback=pureldap.LDAPBERDecoderContext(fallback=pureber.BERDecoderContext()), inherit=pureldap.LDAPBERDecoderContext(fallback=pureber.BERDecoderContext()))) buffer = s value = [] while 1: o, bytes = pureber.berDecodeObject(berdecoder, buffer) buffer = buffer[bytes:] if not o: break value.append(o.toWire()) return value
def buildReply(data): global lastDomain msg, bytes = pureber.berDecodeObject(berdecoder, data) msgId = msg.id print msgId msg = msg.value assert isinstance(msg, pureldap.LDAPProtocolRequest) print msg.__class__.__name__ print msg.baseObject print msg.scope domain = findDomain(msg.filter) if (domain.endswith('.')): domain = domain[0:-1] print "Received search for domain: %s" % domain lastDomain = domain.split('.') x = nbt.NETLOGON_SAM_LOGON_RESPONSE_EX() x.command = 23 x.sbz = 0 x.server_type = 0x000003fd x.domain_uuid = misc.GUID("6cb2d967-f2b7-4c93-bce1-d943eda330a1") x.forest = '.'.join(lastDomain) x.dns_domain = '.'.join(lastDomain) x.pdc_dns_name = "debian-smb." + '.'.join(lastDomain) x.domain_name = lastDomain[0].upper() x.pdc_name = "DEBIAN-SMB" #x.user_name = "" x.server_site = "Default-First-Site-Name" x.client_site = "Default-First-Site-Name" x.sockaddr_size = 0 x.sockaddr.pdc_ip = '0.0.0.0' 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
def getldappath(buff): berdecoder = pureldap.LDAPBERDecoderContext_TopLevel( inherit=pureldap.LDAPBERDecoderContext_LDAPMessage( fallback=pureldap.LDAPBERDecoderContext( fallback=pureber.BERDecoderContext()), inherit=pureldap.LDAPBERDecoderContext( fallback=pureber.BERDecoderContext()))) # buff=b'\x30\x81\xa9\x02\x01\x02c\x81\x86\x04fAaBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n\x01\x00\n\x01\x03\x02\x01\x00\x02\x01\x00\x01\x01\x00\x87\x0bobjectClass0\x00\xa0\x1b0\x19\x04\x172.16.840.1.113730.3.4.2' try: o, bytes = pureber.berDecodeObject(berdecoder, buff) return o.value.baseObject except pureber.BERExceptionInsufficientData as ex: logger.warning("get error:{}".format(ex)) return None
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.assertEqual(bytes, len(m)) shouldBe = klass(*args, **kwargs) assert result.toWire() == shouldBe.toWire(), \ "Class %s(*%s, **%s) doesn't decode properly: " \ "%s != %s" % (klass.__name__, repr(args), repr(kwargs), repr(result), repr(shouldBe))
def _makeResultList(self, s): berdecoder = pureldap.LDAPBERDecoderContext_TopLevel( inherit=pureldap.LDAPBERDecoderContext_LDAPMessage( fallback=pureldap.LDAPBERDecoderContext( fallback=pureber.BERDecoderContext()), inherit=pureldap.LDAPBERDecoderContext( fallback=pureber.BERDecoderContext()))) buffer = s value = [] while 1: try: o, bytes = pureber.berDecodeObject(berdecoder, buffer) except pureber.BERExceptionInsufficientData: o, bytes = None, 0 buffer = buffer[bytes:] if not o: break value.append(str(o)) return value
def on_recv(self): data = self.data # here we can parse and/or modify the data before send forward if data: if data.find(filthy_basedn) == -1: print strftime("%Y-%m-%d %H:%M:%S : ", gmtime()) + " LDAP request -> no filthy baseDn -> relaying to " + str(forward_to) else: test = pureldap.LDAPMessage(data) #print test.value berdecoder = pureldap.LDAPBERDecoderContext_TopLevel( inherit=pureldap.LDAPBERDecoderContext_LDAPMessage( fallback=pureldap.LDAPBERDecoderContext(fallback=pureber.BERDecoderContext()), inherit=pureldap.LDAPBERDecoderContext(fallback=pureber.BERDecoderContext()))) o, bytes = pureber.berDecodeObject(berdecoder, data) print strftime("%Y-%m-%d %H:%M:%S : ", gmtime()) + " LDAP request -> has filthy baseDn : " + o.value.baseObject o.value.baseObject = str(o.value.baseObject).replace(", ",",") print " -> converted baseDn : " + o.value.baseObject + " -> relaying to " + str(forward_to) data = str(o) self.channel[self.s].send(data)
def buildSecondReply(data): global lastDomain msg, bytes = pureber.berDecodeObject(berdecoder, data) msgId = msg.id print msgId msg = msg.value assert isinstance(msg, pureldap.LDAPProtocolRequest) print msg.__class__.__name__ print msg.baseObject print msg.scope dc = ["DC=" + x for x in lastDomain] dc = ','.join(dc) attrs = [] attrs.append(('configurationNamingContext', ['CN=Configuration,' + dc])) attrs.append(('defaultNamingContext', [dc])) attrs.append(('rootDomainNamingContext', [dc])) attrs.append(('schemaNamingContext', ['CN=Schema,CN=Configuration,' + dc])) attrs.append(('subschemaSubentry', ['CN=Aggregate,CN=Schema,CN=Configuration,' + dc])) attrs.append(('supportedCapabilities', [ '1.2.840.113556.1.4.800', '1.2.840.113556.1.4.1670', '1.2.840.113556.1.4.1791', '1.2.840.113556.1.4.1935', '1.2.840.113556.1.4.2080' ])) attrs.append(('supportedLDAPVersion', ['2', '3'])) attrs.append(('dsServiceName', [ 'CN=NTDS Settings,CN=DEBIAN-SMB,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,' + dc ])) attrs.append(('serverName', [ 'CN=DEBIAN-SMB,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,' + dc ])) attrs.append(('dnsHostName', ['debian-smb.' + '.'.join(lastDomain)])) attrs.append(('ldapServiceName', [ '.'.join(lastDomain) + ':debian-smb$@' + '.'.join(lastDomain).upper() ])) attrs.append(('supportedControl', [ '1.2.840.113556.1.4.841', '1.2.840.113556.1.4.319', '1.2.840.113556.1.4.473', '1.2.840.113556.1.4.1504', '1.2.840.113556.1.4.801', '1.2.840.113556.1.4.801', '1.2.840.113556.1.4.805', '1.2.840.113556.1.4.1338', '1.2.840.113556.1.4.529', '1.2.840.113556.1.4.417', '1.2.840.113556.1.4.2064', '1.2.840.113556.1.4.1413', '1.2.840.113556.1.4.1413', '1.2.840.113556.1.4.1413', '1.2.840.113556.1.4.1413', '1.2.840.113556.1.4.1413', '1.2.840.113556.1.4.1339', '1.2.840.113556.1.4.1340', '1.2.840.113556.1.4.1413', '1.2.840.113556.1.4.1341' ])) attrs.append(('namingContexts', [ dc, 'CN=Configuration,' + dc, 'CN=Schema,CN=Configuration,' + dc, 'DC=DomainDnsZones,' + dc, 'DC=ForestDnsZones,' + dc ])) attrs.append(('supportedSASLMechanisms', ['GSS-SPNEGO', 'GSSAPI', 'NTLM'])) 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
from ldaptor.protocols import pureber, pureldap from ldaptor.protocols.ldap import ldaperrors from samba import ndr from samba.dcerpc import nbt from samba.dcerpc import misc packet = binascii.unhexlify('3084000001040201016384000000fb04000a01000a0100020100020100010100a084000000d4a3840000001c0409446e73446f6d61696e040f6d69736b61746f6e69632e756e692ea384000000170404486f7374040f4445534b544f502d44514c4d473337a384000000250409446f6d61696e5369640418010400000000000515000000b9e81cc93f161323478e6dbca3840000001e040a446f6d61696e4775696404109833dc516c2789468b2bcf581b826058a3840000000d04054e74566572040416000000a3840000002d040b446e73486f73744e616d65041e4445534b544f502d44514c4d4733372e6d69736b61746f6e69632e756e6930840000000a04084e65746c6f676f6e') berdecoder = pureldap.LDAPBERDecoderContext_TopLevel( inherit=pureldap.LDAPBERDecoderContext_LDAPMessage( fallback=pureldap.LDAPBERDecoderContext( fallback=pureber.BERDecoderContext()), inherit=pureldap.LDAPBERDecoderContext( fallback=pureber.BERDecoderContext()))) msg, bytes = pureber.berDecodeObject(berdecoder, packet) msgId = msg.id print msgId msg = msg.value assert isinstance(msg, pureldap.LDAPProtocolRequest) print msg.__class__.__name__ print msg.baseObject print msg.scope def findDomain(filt): if isinstance(filt, pureldap.LDAPFilter_and): for x in filt: d = findDomain(x) if d != None: return d if isinstance(filt, pureldap.LDAPFilter_equalityMatch): if (filt.attributeDesc.value == 'DnsDomain'):
def buildSecondReply(data): global lastDomain msg, bytes = pureber.berDecodeObject(berdecoder, data) msgId = msg.id print msgId msg = msg.value assert isinstance(msg, pureldap.LDAPProtocolRequest) print msg.__class__.__name__ print msg.baseObject print msg.scope dc = ["DC=" + x for x in lastDomain] dc = ','.join(dc) attrs = [] attrs.append(('configurationNamingContext', ['CN=Configuration,' + dc])) attrs.append(('defaultNamingContext', [dc])) attrs.append(('rootDomainNamingContext', [dc])) attrs.append(('schemaNamingContext', ['CN=Schema,CN=Configuration,' + dc])) attrs.append(('subschemaSubentry', ['CN=Aggregate,CN=Schema,CN=Configuration,' + dc])) attrs.append(('supportedCapabilities', [ '1.2.840.113556.1.4.800', '1.2.840.113556.1.4.1670', '1.2.840.113556.1.4.1791', '1.2.840.113556.1.4.1935', '1.2.840.113556.1.4.2080' ])) attrs.append(('supportedLDAPVersion', ['2', '3'])) attrs.append(('dsServiceName', ['CN=NTDS Settings,CN=DEBIAN-SMB,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,' + dc])) attrs.append(('serverName', ['CN=DEBIAN-SMB,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,' + dc])) attrs.append(('dnsHostName', ['debian-smb.' + '.'.join(lastDomain)])) attrs.append(('ldapServiceName', ['.'.join(lastDomain) + ':debian-smb$@' + '.'.join(lastDomain).upper()])) attrs.append(('supportedControl', [ '1.2.840.113556.1.4.841', '1.2.840.113556.1.4.319', '1.2.840.113556.1.4.473', '1.2.840.113556.1.4.1504', '1.2.840.113556.1.4.801', '1.2.840.113556.1.4.801', '1.2.840.113556.1.4.805', '1.2.840.113556.1.4.1338', '1.2.840.113556.1.4.529', '1.2.840.113556.1.4.417', '1.2.840.113556.1.4.2064', '1.2.840.113556.1.4.1413', '1.2.840.113556.1.4.1413', '1.2.840.113556.1.4.1413', '1.2.840.113556.1.4.1413', '1.2.840.113556.1.4.1413', '1.2.840.113556.1.4.1339', '1.2.840.113556.1.4.1340', '1.2.840.113556.1.4.1413', '1.2.840.113556.1.4.1341' ])) attrs.append(('namingContexts', [ dc, 'CN=Configuration,' + dc, 'CN=Schema,CN=Configuration,' + dc, 'DC=DomainDnsZones,' + dc, 'DC=ForestDnsZones,' + dc ])) attrs.append(('supportedSASLMechanisms', ['GSS-SPNEGO', 'GSSAPI', 'NTLM'])) 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
def handle(self): berdecoder = pureldap.LDAPBERDecoderContext_TopLevel( inherit=pureldap.LDAPBERDecoderContext_LDAPMessage( fallback=pureldap.LDAPBERDecoderContext(fallback=pureber.BERDecoderContext()), inherit=pureldap.LDAPBERDecoderContext(fallback=pureber.BERDecoderContext()), ) ) api_key = "" buffer = self.request.recv(4096) while len(buffer): try: msg, bytes = pureber.berDecodeObject(berdecoder, buffer) except pureber.BERExceptionInsufficientData: # TODO # print "insuff" msg, bytes = None, 0 data = self.request.recv(4096) if len(data) == 0: return self.request.close() buffer = buffer + data continue if msg.value.__class__.__name__ == "LDAPBindRequest": api_key = msg.value.auth resp = pureldap.LDAPMessage(pureldap.LDAPBindResponse(resultCode=0), id=msg.id) self.request.sendall(str(resp)) buffer = self.request.recv(4096) elif msg.value.__class__.__name__ == "LDAPUnbindRequest": api_key = "" return self.request.close() elif msg.value.__class__.__name__ == "LDAPSearchRequest": cn = "" bo = msg.value.baseObject mbo = BORE.match(bo) if mbo: cn = mbo.group(1) bo = mbo.group(2) if ( bo == "" and msg.value.scope == pureldap.LDAP_SCOPE_baseObject and ( msg.value.filter == pureldap.LDAPFilter_present("objectClass") or msg.value.filter == pureldap.LDAPFilter_present("objectclass") ) ): resp = pureldap.LDAPMessage(pureldap.LDAPSearchResultDone(resultCode=0), id=msg.id) self.request.sendall(str(resp)) buffer = self.request.recv(4096) continue civiproto = config.get(bo, "protocol", "http") civihost = config.get(bo, "host") if civiproto == "http": try: civiport = config.get(bo, "port") except ConfigParser.NoOptionError: civiport = "80" elif civiproto == "https": try: civiport = config.get(bo, "port") except ConfigParser.NoOptionError: civiport = "443" civibase = config.get(bo, "base") url = civiproto + "://" + civihost + ":" + civiport + civibase civiquery = config.get(bo, "query") civikey = config.get(bo, "key") civilsfld = config.get(bo, "ldap_search_field") civicsfld = config.get(bo, "civi_search_field") civiret = config.get(bo, "return") civiserver = config.get(bo, "server") parms = {"q": civiquery, "json": "1", "api_key": api_key, "key": civikey, "return": civiret} if cn: parms["sort_name"] = cn else: filter = msg.value.filter if isinstance(filter, pureldap.LDAPFilterSet): tfilter = filter.data[0] if isinstance(tfilter, pureldap.LDAPFilterSet): filter = tfilter for fs in filter: if fs.type == civilsfld: parms[civicsfld] = fs.substrings[0].value fp = urllib.urlopen(url, urllib.urlencode(parms)) j = json.load(fp) fp.close() if j["is_error"] == 1: print j["error_message"] elif j["count"] > 0: for cid, entry in j["values"].items(): resp = pureldap.LDAPMessage( pureldap.LDAPSearchResultEntry( objectName="cn=%s,%s" % (entry["sort_name"].encode("latin1"), bo), attributes=[ ("objectClass", ["top", "inetOrgPerson", "person"]), ("homeurl", [civiserver + "/civicrm/contact/view?cid=" + cid]), ] + [(l, [entry[c].encode("latin1")]) for l, c in map.items() if c in entry], ), id=msg.id, ) # print resp self.request.sendall(str(resp)) resp = pureldap.LDAPMessage(pureldap.LDAPSearchResultDone(resultCode=0), id=msg.id) self.request.sendall(str(resp)) buffer = self.request.recv(4096) else: print "Unsupported request" buffer = self.request.recv(4096)
from samba import ndr from samba.dcerpc import nbt from samba.dcerpc import misc packet = binascii.unhexlify( '3084000001040201016384000000fb04000a01000a0100020100020100010100a084000000d4a3840000001c0409446e73446f6d61696e040f6d69736b61746f6e69632e756e692ea384000000170404486f7374040f4445534b544f502d44514c4d473337a384000000250409446f6d61696e5369640418010400000000000515000000b9e81cc93f161323478e6dbca3840000001e040a446f6d61696e4775696404109833dc516c2789468b2bcf581b826058a3840000000d04054e74566572040416000000a3840000002d040b446e73486f73744e616d65041e4445534b544f502d44514c4d4733372e6d69736b61746f6e69632e756e6930840000000a04084e65746c6f676f6e' ) berdecoder = pureldap.LDAPBERDecoderContext_TopLevel( inherit=pureldap.LDAPBERDecoderContext_LDAPMessage( fallback=pureldap.LDAPBERDecoderContext( fallback=pureber.BERDecoderContext()), inherit=pureldap.LDAPBERDecoderContext( fallback=pureber.BERDecoderContext()))) msg, bytes = pureber.berDecodeObject(berdecoder, packet) msgId = msg.id print msgId msg = msg.value assert isinstance(msg, pureldap.LDAPProtocolRequest) print msg.__class__.__name__ print msg.baseObject print msg.scope def findDomain(filt): if isinstance(filt, pureldap.LDAPFilter_and): for x in filt: d = findDomain(x) if d != None: return d if isinstance(filt, pureldap.LDAPFilter_equalityMatch):