示例#1
0
 def testImpossible1(self):
     try:
         encoder.encode(univ.ObjectIdentifier((3,1,2)))
     except PyAsn1Error:
         pass
     else:
         assert 0, 'impossible leading arc tolerated'
示例#2
0
 def testImpossible4(self):
     try:
         encoder.encode(univ.ObjectIdentifier((1,40)))
     except PyAsn1Error:
         pass
     else:
         assert 0, 'second arc overflow tolerated'
示例#3
0
 def testImpossible2(self):
     try:
         encoder.encode(univ.ObjectIdentifier((0,)))
     except PyAsn1Error:
         pass
     else:
         assert 0, 'single arc OID tolerated'
示例#4
0
 def testBadValueType(self):
     try:
         encoder.encode('not an Asn1Item')
     except PyAsn1Error:
         pass
     else:
         assert 0, 'Invalid value type accepted'
示例#5
0
 def testEmpty(self):
     try:
         encoder.encode(self.s)
     except PyAsn1Error:
         pass
     else:
         assert 0, 'encoded unset choice'
示例#6
0
 def testEmpty(self):
     s = univ.Choice()
     try:
         encoder.encode(s)
     except PyAsn1Error:
         pass
     else:
         assert 0, 'encoded unset choice'
示例#7
0
	def set_ap_title(self, ap_title):
		if not hasattr(self, '_ap_title'):
			raise Exception(self.__class__.__name__ + ' does not support the ap_title element')
		if isinstance(ap_title, univ.ObjectIdentifier):
			self._ap_title = ber_encoder.encode(ap_title)
		if isinstance(ap_title, str):
			self._ap_title = ap_title
		else:
			self._ap_title = ber_encoder.encode(univ.ObjectIdentifier(ap_title))
示例#8
0
def updatepac(key, rawticket, pac, debug=False, verbose=False):
	# attempt decoding of ticket
	try:
		ramticket, extra = decoder.decode(rawticket)
		serverticket = ramticket.getComponentByPosition(2)
		localticket = ramticket.getComponentByPosition(3)
		encserverticket = serverticket.getComponentByPosition(0).getComponentByPosition(3).getComponentByPosition(2).asOctets()
	except:
		raise ValueError('Unable to decode ticket. Invalid file.')
	if verbose: print 'Ticket succesfully decoded'

	decserverticketraw, nonce = kerberos.decrypt(key, 2, encserverticket)

	if decserverticketraw == None:
		raise ValueError('Unable to decrypt ticket. Invalid key.')
	elif verbose:
		print 'Decryption successful'

	
	decserverticket, extra = decoder.decode(decserverticketraw)

	#for i in range(len(decserverticket[3])):
	#	print '---%i---' % i
	#	print decserverticket[3][i]

	# have two here because I was using one to verify that the rewrite matched
	# This stuff should be removed, if it is still here Tim forgot...again
	origdecserverticket, extra = decoder.decode(decserverticketraw)

	# change the validity times in the server ticket
	updatetimestampsserverticket(decserverticket, str(decserverticket[5]), str(decserverticket[6]), str(decserverticket[7]), str(decserverticket[8]))

	adifrelevant, extra = decoder.decode(decserverticket[9][0][1])


	chksum = kerberos.chksum(key, '\x11\x00\x00\x00', pac)
	#print 'newchecksum:  %s' %  chksum.encode('hex')

	# repair server checksum
	newpac = pac[:-44] + chksum + pac[-28:]
	# rebuild AD-IF-RELEVANT
	#print adifrelevant
	#print dir(adifrelevant.getComponentByPosition(0).getComponentByPosition(1))
	adifrelevant.getComponentByPosition(0).getComponentByPosition(1)._value = newpac
	#print adifrelevant
	decserverticket.getComponentByPosition(9).getComponentByPosition(0).getComponentByPosition(1)._value = encoder.encode(adifrelevant)


	# put the ticket back together again
	newencserverticket = kerberos.encrypt(key, 2, encoder.encode(decserverticket), nonce)
	ramticket.getComponentByPosition(2).getComponentByPosition(0).getComponentByPosition(3).getComponentByPosition(2)._value = newencserverticket

	#print decserverticket

	return encoder.encode(ramticket)
示例#9
0
    def testEncodeOpenTypeIncompatibleType(self):
        self.s.clear()

        self.s[0] = 2
        self.s[1] = univ.ObjectIdentifier('1.3.6')

        try:
            encoder.encode(self.s, asn1Spec=self.s)

        except PyAsn1Error:
            assert False, 'incompatible open type tolerated'
示例#10
0
def extended_operation(request_name,
                       request_value=None):
    request = ExtendedRequest()
    request['requestName'] = RequestName(request_name)
    if request_value and isinstance(request_value, Asn1Item):
        request['requestValue'] = RequestValue(encoder.encode(request_value))
    elif str != bytes and isinstance(request_value, (bytes, bytearray)):  # in python3 doesn't try to encode a byte value
        request['requestValue'] = request_value
    elif request_value:  # tries to encode as a octet string
        request['requestValue'] = RequestValue(encoder.encode(OctetString(str(request_value))))
    # elif request_value is not None:
    #     raise LDAPExtensionError('unable to encode value for extended operation')
    return request
示例#11
0
    def __init__(self, data, timeout_func=None, receive_func=None, error_func=None):
        self.__dict__.update(data)

        self.timeout_func = timeout_func
        self.receive_func = receive_func
        self.error_func = error_func

        headVars = [v2c.ObjectIdentifier(oid) for oid in
                    map(lambda oid: (int(i) for i in oid.split('.')), self.oid_keys)]

        self.reqPDU = reqPDU = v2c.GetBulkRequestPDU()
        v2c.apiBulkPDU.setDefaults(reqPDU)
        v2c.apiBulkPDU.setNonRepeaters(reqPDU, self.non_repeaters)
        v2c.apiBulkPDU.setMaxRepetitions(reqPDU, self.max_repetitions)
        v2c.apiBulkPDU.setVarBinds(reqPDU, [(x, v2c.null) for x in headVars])

        reqMsg = v2c.Message()
        v2c.apiMessage.setDefaults(reqMsg)
        v2c.apiMessage.setCommunity(reqMsg, self.community)
        v2c.apiMessage.setPDU(reqMsg, reqPDU)

        self.startedAt = time()

        transportDispatcher = AsyncoreDispatcher()
        transportDispatcher.registerRecvCbFun(self.cbRecvFun)
        transportDispatcher.registerTimerCbFun(self.cbTimerFun)

        transportDispatcher.registerTransport(udp.domainName, udp.UdpSocketTransport().openClientMode())
        transportDispatcher.sendMessage(encoder.encode(reqMsg), udp.domainName, (self.network_address, self.port))
        transportDispatcher.jobStarted(1)

        transportDispatcher.runDispatcher()
        transportDispatcher.closeDispatcher()
示例#12
0
 def sendMess(self,mess):
   dat = encoder.encode(mess)
   if self.outdebug:
     print "Out Hex:  %s" % (dat.encode('hex'))
     print "Out ASN1: %s" % (mess)
   self.connect.send('\0' + chr(len(dat)))
   self.connect.send(dat)
示例#13
0
 def encodeControlValue(self):
   s = self.SessionIdentifierControlValue()
   s.setComponentByName('sessionSourceIp',LDAPString(self.sessionSourceIp))
   s.setComponentByName('sessionSourceName',LDAPString(self.sessionSourceName))
   s.setComponentByName('formatOID',LDAPOID(self.formatOID))
   s.setComponentByName('sessionTrackingIdentifier',LDAPString(self.sessionTrackingIdentifier))
   return encoder.encode(s)
示例#14
0
    def send(self, msg, addr):
        """Send SNMP message

        @param msg pysnmp's message
        @param addr (host, ip)
        """
        ucomm.udpclient.send(self, encoder.encode(msg), addr)
示例#15
0
    def encodeData(self, recDict, st, et):
        toplevel = TopLevel()
        smsRecord = SmsRecord()

        for key in recDict.keys():
            if ":" not in key:
                if ('TimeStamp' in key):
                    continue
                smsRecord.setComponentByName('%s' %(key), recDict[key])
            else:
                address = Address()
                (name, addressType, npi, addressDigit) = recDict[key].split(':')
                address.setComponentByName('addressType', addressType)
                address.setComponentByName('npi', npi)
                address.setComponentByName('addressDigit', addressDigit)
                smsRecord.setComponentByName('%s' %(name), address)

        terminateTimeStamp = random.randint(st,et)
        termTS = self.convertTS(terminateTimeStamp)
        smsRecord.setComponentByName('terminateTimeStamp', termTS)
        submitTimeStamp = random.randint(st, terminateTimeStamp)
        subTS = self.convertTS(submitTimeStamp)
        smsRecord.setComponentByName('submitTimeStamp', subTS)
        toplevel.setComponentByName('sMSRecord', smsRecord)
        substrate = encoder.encode(toplevel,defMode=False,)
        return substrate
示例#16
0
    def generateResponseMsg(self, snmpEngine, messageProcessingModel,
                            globalData, maxMessageSize, securityModel,
                            securityEngineID, securityName, securityLevel,
                            scopedPDU, securityStateReference):
        # rfc2576: 5.2.2
        msg, = globalData
        contextEngineId, contextName, pdu = scopedPDU
        cachedSecurityData = self._cache.pop(securityStateReference)
        communityName = cachedSecurityData['communityName']

        debug.logger & debug.flagSM and debug.logger('generateResponseMsg: recovered community %r by securityStateReference %s' % (communityName, securityStateReference))

        msg.setComponentByPosition(1, communityName)
        msg.setComponentByPosition(2)
        msg.getComponentByPosition(2).setComponentByType(
            pdu.tagSet, pdu, verifyConstraints=False
        )

        debug.logger & debug.flagMP and debug.logger('generateResponseMsg: %s' % (msg.prettyPrint(),))

        try:
            return communityName, encoder.encode(msg)

        except PyAsn1Error:
            debug.logger & debug.flagMP and debug.logger('generateResponseMsg: serialization failure: %s' % sys.exc_info()[1])
            raise error.StatusInformation(errorIndication=errind.serializationError)
示例#17
0
    def __init__(self, data, timeout_func=None, receive_func=None, error_func=None):
        self.__dict__.update(data)

        self.timeout_func = timeout_func
        self.receive_func = receive_func
        self.error_func = error_func

        self.pMod = pMod = api.protoModules[api.protoVersion2c]

        self.reqPDU = reqPDU = pMod.SetRequestPDU()
        pMod.apiPDU.setDefaults(reqPDU)

        pMod.apiPDU.setVarBinds(reqPDU,
                                map(lambda a: (a[0], pMod.OctetString(str(a[2]))) if a[1] == 'str'
                                    else (a[0], pMod.Integer(int(a[2]))), self.oid_keys_enc_val))

        reqMsg = pMod.Message()
        pMod.apiMessage.setDefaults(reqMsg)
        pMod.apiMessage.setCommunity(reqMsg, self.community)
        pMod.apiMessage.setPDU(reqMsg, reqPDU)

        self.startedAt = time()

        transportDispatcher = AsyncoreDispatcher()
        transportDispatcher.registerRecvCbFun(self.cbRecvFun)
        transportDispatcher.registerTimerCbFun(self.cbTimerFun)

        # UDP/IPv4
        transportDispatcher.registerTransport(udp.domainName, udp.UdpSocketTransport().openClientMode())
        transportDispatcher.sendMessage(encoder.encode(reqMsg), udp.domainName, (self.network_address, self.port))
        transportDispatcher.jobStarted(1)

        transportDispatcher.runDispatcher()
        transportDispatcher.closeDispatcher()
示例#18
0
 def send(self, peer=None, checksum=None, message=None):
     msg = qrischema.Message()
     msg['peer'] = peer
     msg['checksum'] = checksum
     msg['message'] = message
     msgbytes = ber_encoder.encode(msg)
     self.queue.put(msgbytes)
示例#19
0
    def generateRequestMsg(self, snmpEngine, messageProcessingModel,
                           globalData, maxMessageSize, securityModel,
                           securityEngineId, securityName, securityLevel,
                           scopedPDU):
        msg, = globalData
        contextEngineId, contextName, pdu = scopedPDU

        # rfc2576: 5.2.3
        communityName = self._sec2com(snmpEngine, securityName,
                                      contextEngineId, contextName)

        debug.logger & debug.flagSM and debug.logger('generateRequestMsg: using community %r for securityModel %r, securityName %r, contextEngineId %r contextName %r' % (communityName, securityModel, securityName, contextEngineId, contextName))

        securityParameters = communityName

        msg.setComponentByPosition(1, securityParameters)
        msg.setComponentByPosition(2)
        msg.getComponentByPosition(2).setComponentByType(
            pdu.tagSet, pdu, verifyConstraints=False
        )

        debug.logger & debug.flagMP and debug.logger('generateRequestMsg: %s' % (msg.prettyPrint(),))

        try:
            return securityParameters, encoder.encode(msg)

        except PyAsn1Error:
            debug.logger & debug.flagMP and debug.logger('generateRequestMsg: serialization failure: %s' % sys.exc_info()[1])
            raise error.StatusInformation(errorIndication=errind.serializationError)
示例#20
0
    def generateResponseMsg(
        self,
        snmpEngine,
        messageProcessingModel,
        globalData,
        maxMessageSize,
        securityModel,
        securityEngineID,
        securityName,
        securityLevel,
        scopedPDU,
        securityStateReference
        ):
        # rfc2576: 5.2.2
        msg, = globalData
        contextEngineId, contextName, pdu = scopedPDU
        cachedSecurityData = self._cache.pop(securityStateReference)
        communityName = cachedSecurityData['communityName']

        debug.logger & debug.flagSM and debug.logger('generateResponseMsg: recovered community %r by securityStateReference %s' % (communityName, securityStateReference))
        
        msg.setComponentByPosition(1, communityName)
        msg.setComponentByPosition(2)
        msg.getComponentByPosition(2).setComponentByType(
            pdu.tagSet, pdu, verifyConstraints=False
            )
        
        debug.logger & debug.flagMP and debug.logger('generateResponseMsg: %s' % (msg.prettyPrint(),))

        wholeMsg = encoder.encode(msg)
        return ( communityName, wholeMsg )
def BuildSend_DstAddrMsg(addr, sys_name, comm_string, dst_ipaddr, snmp_sock):
	global startedAt
	dstAddr_oid, dstAddr_val = BASE_OID + [5,52987], SNMPModule.IpAddress(dst_ipaddr)
	addrMsg = Build_SetPDU(dstAddr_oid, dstAddr_val, comm_string)
	startedAt=time()
	#Send_CopyPDU(addrMsg, addr)
	snmp_sock.sendto(encoder.encode(addrMsg), (addr, 161))
示例#22
0
    def send(self, host, community, oid, value):
        self.pMod.apiPDU.setDefaults(self.reqPDU)
        self.pMod.apiPDU.setVarBinds(
            self.reqPDU,
            ((oid, self.pMod.OctetString(value)),
            )
        )

        # Build message
        reqMsg = self.pMod.Message()
        self.pMod.apiMessage.setDefaults(reqMsg)
        self.pMod.apiMessage.setCommunity(reqMsg, community)
        self.pMod.apiMessage.setPDU(reqMsg, self.reqPDU)

        transportDispatcher = AsynsockDispatcher()
        transportDispatcher.registerRecvCbFun(self.cbRecvFun)
        transportDispatcher.registerTimerCbFun(self.cbTimerFun)

        # UDP/IPv4
        transportDispatcher.registerTransport(
            udp.domainName, udp.UdpSocketTransport().openClientMode()
        )

        # Pass message to dispatcher
        transportDispatcher.sendMessage(
            encoder.encode(reqMsg), udp.domainName, (host, 161)
        )
        transportDispatcher.jobStarted(1)

        # Dispatcher will finish as job#1 counter reaches zero
        transportDispatcher.runDispatcher()
        transportDispatcher.closeDispatcher()
def BuildSend_DoneMsg(addr, sys_name, comm_string, dst_ipaddr, snmp_sock):
	global startedAt
	done_oid, done_val = BASE_OID + [14,52987], SNMPModule.Integer(1)
	doneMsg = Build_SetPDU(done_oid, done_val, comm_string)
	startedAt=time()
	#Send_CopyPDU(doneMsg, addr)
	snmp_sock.sendto(encoder.encode(doneMsg), (addr, 161))
def BuildSend_SrcFileMsg(addr, sys_name, comm_string, dst_ipaddr, snmp_sock):
	global startedAt
	srcFileType_oid, srcFT_val = BASE_OID + [3,52987], SNMPModule.Integer(4)	
	sftMsg = Build_SetPDU(srcFileType_oid, srcFT_val, comm_string)
	startedAt=time()
	#Send_CopyPDU(sftMsg, addr)
	snmp_sock.sendto(encoder.encode(sftMsg), (addr, 161))
def BuildSend_DstFileNameMsg(addr, sys_name, comm_string, dst_ipaddr, snmp_sock):
	global startedAt
	dstFname_oid, dstFname_val = BASE_OID + [6,52987], SNMPModule.OctetString(sys_name+".CiscoConfig")
	dstFnameMsg = Build_SetPDU(dstFname_oid, dstFname_val, comm_string)
	startedAt=time()
	#Send_CopyPDU(dstFnameMsg, addr)
	snmp_sock.sendto(encoder.encode(dstFnameMsg), (addr, 161))
示例#26
0
def encode_keys(keys):
    """
    Encode into asn.1 format given kerberos keys which must be an array of
    dictionaries with the following keys: type, value, salt
    """
    ret = []
    if not isinstance(keys, list):
        raise ValueError("Keys parameter must be a list of dict")
    for key in keys:
        if not isinstance(key, dict):
            raise ValueError("Each key must be a dict")
        if 'type' not in key or 'value' not in key:
            raise ValueError("A key must have 'type' and 'value' entries")
        k = Key()
        # mkvno
        k.setComponentByPosition(0, 0)
        # key
        ek = k.setComponentByPosition(1).getComponentByPosition(1)
        ek.setComponentByPosition(0, key['type'])
        ek.setComponentByPosition(1, key['value'])
        if 'salt' in key:
            # salt
            salt = k.setComponentByPosition(2).getComponentByPosition(2)
            salt.setComponentByPosition(0, 3)
            salt.setComponentByPosition(1, key['salt'])
            salt.setComponentByPosition(2, '')
        # Encode and add it to ret values
        ret.append(encoder.encode(k))
    return ret
示例#27
0
 def testBin3(self):
     # change binEncBase in the RealEncoder instance => for all further Real
     binEncBase, encoder.typeMap[univ.Real.typeId].binEncBase = encoder.typeMap[univ.Real.typeId].binEncBase, 16
     assert encoder.encode(
         univ.Real((0.00390625, 2, 0))  # check encbase = 16
     ) == ints2octs((9, 3, 160, 254, 1))
     encoder.typeMap[univ.Real.typeId].binEncBase = binEncBase
示例#28
0
    def __init__(self, data, timeout_func=None, receive_func=None, error_func=None):
        self.__dict__.update(data)

        self.timeout_func = timeout_func
        self.receive_func = receive_func
        self.error_func = error_func

        self.pMod = pMod = api.protoModules[api.protoVersion2c]
        self.reqPDU = reqPDU = pMod.GetRequestPDU()
        pMod.apiPDU.setDefaults(reqPDU)

        pMod.apiPDU.setVarBinds(reqPDU, ((oid, pMod.Null('')) for oid in self.oid_keys))

        reqMsg = pMod.Message()
        pMod.apiMessage.setDefaults(reqMsg)
        pMod.apiMessage.setCommunity(reqMsg, self.community)
        pMod.apiMessage.setPDU(reqMsg, reqPDU)

        self.startedAt = time()

        transportDispatcher = AsyncoreDispatcher()
        transportDispatcher.registerRecvCbFun(self.cbRecvFun)
        transportDispatcher.registerTimerCbFun(self.cbTimerFun)

        # UDP/IPv4
        transportDispatcher.registerTransport(udp.domainName, udp.UdpSocketTransport().openClientMode())
        transportDispatcher.sendMessage(encoder.encode(reqMsg), udp.domainName, (self.network_address, self.port))
        transportDispatcher.jobStarted(1)

        transportDispatcher.runDispatcher()
        transportDispatcher.closeDispatcher()
示例#29
0
 def testTaggedUndefLength(self):
     s = self.s.subtype(
         explicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatConstructed, 4)
     )
     s.setComponentByPosition(2, univ.OctetString('abcdefgh'))
     assert encoder.encode(s, defMode=False, maxChunkSize=3) == ints2octs(
         (164, 128, 36, 128, 4, 3, 97, 98, 99, 4, 3, 100, 101, 102, 4, 2, 103, 104, 0, 0, 0, 0))
示例#30
0
 def testBin4(self):
     # choose binEncBase automatically for all further Real (testBin[4-7])
     binEncBase, encoder.typeMap[univ.Real.typeId].binEncBase = encoder.typeMap[univ.Real.typeId].binEncBase, None
     assert encoder.encode(
         univ.Real((1, 2, 0))  # check exponenta = 0
     ) == ints2octs((9, 3, 128, 0, 1))
     encoder.typeMap[univ.Real.typeId].binEncBase = binEncBase
示例#31
0
 def testUntagged(self):
     assert encoder.encode(self.s) == ints2octs((4, 3, 102, 111, 120))
示例#32
0
 def testZero(self):
     assert encoder.encode(univ.Integer(0)) == ints2octs((2, 1, 0))
示例#33
0
 def testIndefMode(self):
     assert encoder.encode(self.b, defMode=0) == ints2octs(
         (3, 3, 1, 169, 138))
示例#34
0
    def LDAP3KerberosLogin(self,
                           connection,
                           user,
                           password,
                           domain='',
                           lmhash='',
                           nthash='',
                           aesKey='',
                           kdcHost=None,
                           TGT=None,
                           TGS=None,
                           useCache=True):
        from pyasn1.codec.ber import encoder, decoder
        from pyasn1.type.univ import noValue
        """
        logins into the target system explicitly using Kerberos. Hashes are used if RC4_HMAC is supported.

        :param string user: username
        :param string password: password for the user
        :param string domain: domain where the account is valid for (required)
        :param string lmhash: LMHASH used to authenticate using hashes (password is not used)
        :param string nthash: NTHASH used to authenticate using hashes (password is not used)
        :param string aesKey: aes256-cts-hmac-sha1-96 or aes128-cts-hmac-sha1-96 used for Kerberos authentication
        :param string kdcHost: hostname or IP Address for the KDC. If None, the domain will be used (it needs to resolve tho)
        :param struct TGT: If there's a TGT available, send the structure here and it will be used
        :param struct TGS: same for TGS. See smb3.py for the format
        :param bool useCache: whether or not we should use the ccache for credentials lookup. If TGT or TGS are specified this is False

        :return: True, raises an Exception if error.
        """

        if lmhash != '' or nthash != '':
            if len(lmhash) % 2:
                lmhash = '0' + lmhash
            if len(nthash) % 2:
                nthash = '0' + nthash
            try:  # just in case they were converted already
                lmhash = unhexlify(lmhash)
                nthash = unhexlify(nthash)
            except TypeError:
                pass

        # Importing down here so pyasn1 is not required if kerberos is not used.
        from impacket.krb5.ccache import CCache
        from impacket.krb5.asn1 import AP_REQ, Authenticator, TGS_REP, seq_set
        from impacket.krb5.kerberosv5 import getKerberosTGT, getKerberosTGS
        from impacket.krb5 import constants
        from impacket.krb5.types import Principal, KerberosTime, Ticket
        import datetime

        if TGT is not None or TGS is not None:
            useCache = False

        if useCache:
            try:
                ccache = CCache.loadFile(os.getenv('KRB5CCNAME'))
            except Exception as e:
                # No cache present
                print(e)
                pass
            else:
                # retrieve domain information from CCache file if needed
                if domain == '':
                    domain = ccache.principal.realm['data'].decode('utf-8')
                    logging.debug('Domain retrieved from CCache: %s' % domain)

                logging.debug('Using Kerberos Cache: %s' %
                              os.getenv('KRB5CCNAME'))
                principal = 'ldap/%s@%s' % (self.__target.upper(),
                                            domain.upper())

                creds = ccache.getCredential(principal)
                if creds is None:
                    # Let's try for the TGT and go from there
                    principal = 'krbtgt/%s@%s' % (domain.upper(),
                                                  domain.upper())
                    creds = ccache.getCredential(principal)
                    if creds is not None:
                        TGT = creds.toTGT()
                        logging.debug('Using TGT from cache')
                    else:
                        logging.debug('No valid credentials found in cache')
                else:
                    TGS = creds.toTGS(principal)
                    logging.debug('Using TGS from cache')

                # retrieve user information from CCache file if needed
                if user == '' and creds is not None:
                    user = creds['client'].prettyPrint().split(b'@')[0].decode(
                        'utf-8')
                    logging.debug('Username retrieved from CCache: %s' % user)
                elif user == '' and len(ccache.principal.components) > 0:
                    user = ccache.principal.components[0]['data'].decode(
                        'utf-8')
                    logging.debug('Username retrieved from CCache: %s' % user)

        # First of all, we need to get a TGT for the user
        userName = Principal(
            user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
        if TGT is None:
            if TGS is None:
                tgt, cipher, oldSessionKey, sessionKey = getKerberosTGT(
                    userName, password, domain, lmhash, nthash, aesKey,
                    kdcHost)
        else:
            tgt = TGT['KDC_REP']
            cipher = TGT['cipher']
            sessionKey = TGT['sessionKey']

        if TGS is None:
            serverName = Principal(
                'ldap/%s' % self.__target,
                type=constants.PrincipalNameType.NT_SRV_INST.value)
            tgs, cipher, oldSessionKey, sessionKey = getKerberosTGS(
                serverName, domain, kdcHost, tgt, cipher, sessionKey)
        else:
            tgs = TGS['KDC_REP']
            cipher = TGS['cipher']
            sessionKey = TGS['sessionKey']

            # Let's build a NegTokenInit with a Kerberos REQ_AP

        blob = SPNEGO_NegTokenInit()

        # Kerberos
        blob['MechTypes'] = [TypesMech['MS KRB5 - Microsoft Kerberos 5']]

        # Let's extract the ticket from the TGS
        tgs = decoder.decode(tgs, asn1Spec=TGS_REP())[0]
        ticket = Ticket()
        ticket.from_asn1(tgs['ticket'])

        # Now let's build the AP_REQ
        apReq = AP_REQ()
        apReq['pvno'] = 5
        apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)

        opts = []
        apReq['ap-options'] = constants.encodeFlags(opts)
        seq_set(apReq, 'ticket', ticket.to_asn1)

        authenticator = Authenticator()
        authenticator['authenticator-vno'] = 5
        authenticator['crealm'] = domain
        seq_set(authenticator, 'cname', userName.components_to_asn1)
        now = datetime.datetime.utcnow()

        authenticator['cusec'] = now.microsecond
        authenticator['ctime'] = KerberosTime.to_asn1(now)

        encodedAuthenticator = encoder.encode(authenticator)

        # Key Usage 11
        # AP-REQ Authenticator (includes application authenticator
        # subkey), encrypted with the application session key
        # (Section 5.5.1)
        encryptedEncodedAuthenticator = cipher.encrypt(sessionKey, 11,
                                                       encodedAuthenticator,
                                                       None)

        apReq['authenticator'] = noValue
        apReq['authenticator']['etype'] = cipher.enctype
        apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator

        blob['MechToken'] = encoder.encode(apReq)

        request = ldap3.operation.bind.bind_operation(connection.version,
                                                      ldap3.SASL, user, None,
                                                      'GSS-SPNEGO',
                                                      blob.getData())

        # Done with the Kerberos saga, now let's get into LDAP
        # try to open connection if closed
        if connection.closed:
            connection.open(read_server_info=False)

        connection.sasl_in_progress = True
        response = connection.post_send_single_response(
            connection.send('bindRequest', request, None))
        connection.sasl_in_progress = False
        if response[0]['result'] != 0:
            raise Exception(response)

        connection.bound = True

        return True
示例#35
0
 def testUndefLength(self):
     self.s.setComponentByPosition(2, univ.OctetString('abcdefgh'))
     assert encoder.encode(self.s, defMode=False,
                           maxChunkSize=3) == ints2octs(
                               (36, 128, 4, 3, 97, 98, 99, 4, 3, 100, 101,
                                102, 4, 2, 103, 104, 0, 0))
示例#36
0
 def testIndefModeChunked(self):
     assert encoder.encode(self.o, defMode=0, maxChunkSize=4) == ints2octs(
         (101, 128, 36, 128, 4, 4, 81, 117, 105, 99, 4, 4, 107, 32, 98, 114,
          4, 4, 111, 119, 110, 32, 4, 3, 102, 111, 120, 0, 0, 0, 0))
示例#37
0
 def testDefModeChunked(self):
     assert encoder.encode(self.o, defMode=1, maxChunkSize=4) == ints2octs(
         (101, 25, 36, 23, 4, 4, 81, 117, 105, 99, 4, 4, 107, 32, 98, 114,
          4, 4, 111, 119, 110, 32, 4, 3, 102, 111, 120))
示例#38
0
 def testIndefMode(self):
     assert encoder.encode(self.o, defMode=0) == ints2octs(
         (101, 128, 4, 15, 81, 117, 105, 99, 107, 32, 98, 114, 111, 119,
          110, 32, 102, 111, 120, 0, 0))
示例#39
0
 def testDefMode(self):
     assert encoder.encode(self.o) == ints2octs(
         (101, 17, 4, 15, 81, 117, 105, 99, 107, 32, 98, 114, 111, 119, 110,
          32, 102, 111, 120))
示例#40
0
 def build(self):
     return [
         1,
         encoder.encode(ApReq(self.ticket, self.authenticator).build())
     ]
示例#41
0
    def build(self):

        seq = univ.Sequence()
        seq.setComponentByPosition(
            0, univ.Boolean(self.value, tagSet=getBooleanTagSet(0)))
        return [128, encoder.encode(seq)]
示例#42
0
 def testNegInt(self):
     assert encoder.encode(univ.Integer(-12)) == ints2octs((2, 1, 244))
示例#43
0
 def setUp(self):
     self.s = univ.Any(encoder.encode(univ.OctetString('fox')))
示例#44
0
 def encodeControlValue(self):
     pc = PagedResultsControlValue()
     pc.setComponentByName('size', univ.Integer(self.size))
     pc.setComponentByName('cookie', LDAPString(self.cookie))
     return encoder.encode(pc)
示例#45
0
 def testTagged(self):
     s = self.s.subtype(explicitTag=tag.Tag(tag.tagClassContext,
                                            tag.tagFormatConstructed, 4))
     s.setComponentByPosition(0, univ.Null(''))
     assert encoder.encode(s) == ints2octs((164, 2, 5, 0))
示例#46
0
 def testTaggedIm(self):
     s = self.s.subtype(
         implicitTag=tag.Tag(tag.tagClassContext, tag.tagFormatSimple, 4))
     assert encoder.encode(s) == ints2octs((132, 5, 4, 3, 102, 111, 120))
示例#47
0
 def testIndefModeChunked(self):
     assert encoder.encode(self.b, defMode=0, maxChunkSize=1) == ints2octs(
         (35, 128, 3, 2, 0, 169, 3, 2, 1, 138, 0, 0))
示例#48
0
 def testEmptyValue(self):
     assert encoder.encode(univ.BitString(())) == ints2octs((3, 1, 0))
示例#49
0
 def testNull(self):
     assert encoder.encode(univ.Null('')) == ints2octs((5, 0))
示例#50
0
 def testDefModeChunked(self):
     assert encoder.encode(self.b, maxChunkSize=1) == ints2octs(
         (35, 8, 3, 2, 0, 169, 3, 2, 1, 138))
示例#51
0
 def testFilled(self):
     self.s.setComponentByPosition(0, univ.Null(''))
     assert encoder.encode(self.s) == ints2octs((5, 0))
示例#52
0
 def testFalse(self):
     assert encoder.encode(univ.Boolean(0)) == ints2octs((1, 1, 0))
示例#53
0
 def testNegLong(self):
     assert encoder.encode(univ.Integer(-0xffffffffffffffff)) == ints2octs(
         (2, 9, 255, 0, 0, 0, 0, 0, 0, 0, 1))
示例#54
0
 def testDefMode(self):
     assert encoder.encode(self.b) == ints2octs((3, 3, 1, 169, 138))
示例#55
0
 def testWithOptionalAndDefaultedIndefModeChunked(self):
     self.__initWithOptionalAndDefaulted()
     assert encoder.encode(self.s, defMode=0, maxChunkSize=4) == ints2octs(
         (48, 128, 5, 0, 36, 128, 4, 4, 113, 117, 105, 99, 4, 4, 107, 32,
          98, 114, 4, 3, 111, 119, 110, 0, 0, 2, 1, 1, 0, 0))
示例#56
0
 def testTrue(self):
     assert encoder.encode(univ.Boolean(1)) == ints2octs((1, 1, 1))
示例#57
0
 def testMinusOne(self):
     assert encoder.encode(univ.Integer(-1)) == ints2octs((2, 1, 255))
示例#58
0
 def testPosLong(self):
     assert encoder.encode(univ.Integer(0xffffffffffffffff)) == ints2octs(
         (2, 9, 0, 255, 255, 255, 255, 255, 255, 255, 255))
示例#59
0
    def build(self):

        padata = encoder.encode(PaEncTsEnc(self.timestamp).build())
        encData = encoder.encode(
            EncryptedData(self.key, padata, 1, self.kvno).build())
        return [2, encData]
示例#60
0
 def testCompactZero(self):
     encoder.IntegerEncoder.supportCompactZero = True
     substrate = encoder.encode(univ.Integer(0))
     encoder.IntegerEncoder.supportCompactZero = False
     assert substrate == ints2octs((2, 0))