Example #1
0
    def get_db_prep_value(self, value, connection=None, prepared=False):
        if value is None:
            return None

        value = smart_str(value)

        if not self._is_encrypted(value):
            padding = self._get_padding(value)
            if padding > 0:
                value += "\0" + ''.join([
                    random.choice(string.printable)
                    for index in range(padding-1)
                ])
            if self.block_type:
                self.cipher = self.cipher_object.new(
                    self.secret_key,
                    getattr(self.cipher_object, self.block_type),
                    self.iv)
                if PYTHON3 is True:
                    value = self.prefix + binascii.b2a_hex(
                        self.iv + self.cipher.encrypt(value)).decode('utf-8')
                else:
                    value = self.prefix + binascii.b2a_hex(
                        self.iv + self.cipher.encrypt(value))
            else:
                if PYTHON3 is True:
                    print('>>>', value, '-->', len(value)/16)
                    value = self.prefix + binascii.b2a_hex(
                        self.cipher.encrypt(value)).decode('utf-8')
                else:
                    value = self.prefix + binascii.b2a_hex(
                        self.cipher.encrypt(value))
        return value
Example #2
0
def parse_ntlm_resp(msg3, seq):
    '''
    Parse the 3rd msg in NTLM handshake
    Thanks to psychomario
    '''

    if seq in challenge_acks:
        challenge = challenge_acks[seq]
    else:
        challenge = 'CHALLENGE NOT FOUND'

    if len(msg3) > 43:
        # Thx to psychomario for below
        lmlen, lmmax, lmoff, ntlen, ntmax, ntoff, domlen, dommax, domoff, userlen, usermax, useroff = struct.unpack("12xhhihhihhihhi", msg3[:44])
        lmhash = binascii.b2a_hex(msg3[lmoff:lmoff+lmlen])
        nthash = binascii.b2a_hex(msg3[ntoff:ntoff+ntlen])
        domain = msg3[domoff:domoff+domlen].replace("\0", "")
        user = msg3[useroff:useroff+userlen].replace("\0", "")
        # Original check by psychomario, might be incorrect?
        #if lmhash != "0"*48: #NTLMv1
        if ntlen == 24: #NTLMv1
            msg = '%s %s' % ('NETNTLMv1:', user+"::"+domain+":"+lmhash+":"+nthash+":"+challenge)
            return msg
        elif ntlen > 60: #NTLMv2
            msg = '%s %s' % ('NETNTLMv2:', user+"::"+domain+":"+challenge+":"+nthash[:32]+":"+nthash[32:])
            return msg
Example #3
0
def testEncodeSCCRP():
    packet = L2TPV3ControlHeader()
    packet.control_id = 0
    packet.ns = 0
    packet.nr = 0

    print binascii.b2a_hex(packet.toBinary())
Example #4
0
  def update(self,data):
    assert(len(data) == self._seedlen_bytes)
    
    #self.v = self.inc_byte_string_array(self.v)
    #temp=self.aes.encrypt(self.v)
    self.v.incr()
    temp=self.aes.encrypt(self.v.get_string())
    #print "Key: \t\t", binascii.b2a_hex(self.key), "\nVector: \t", binascii.b2a_hex(self.v), "\nAES: \t\t",  binascii.b2a_hex(temp)
    print "\nAES: \t\t",  binascii.b2a_hex(temp)

    #self.v = self.inc_byte_string_array(self.v)
    #temp+=self.aes.encrypt(self.v)
    self.v.incr()
    temp+=self.aes.encrypt(self.v.get_string())
    print "\nAES: \t\t",  binascii.b2a_hex(self.aes.encrypt(self.v.get_string()))
    #print "Key: \t\t", binascii.b2a_hex(self.key), "\nVector: \t", binascii.b2a_hex(self.v), "\nAES: \t\t",  binascii.b2a_hex(self.aes.encrypt(self.v))

    assert(len(temp) == self._seedlen_bytes)
    temp=strxor.strxor(temp,data)
    #(self.key,self.v) = (temp[0:self._keylen_bytes], temp[self._keylen_bytes:len(temp)])
    (self.key,self.v) = (temp[0:self._keylen_bytes], byte_counter(temp[self._keylen_bytes:len(temp)]))

    assert(len(self.key) == self._keylen_bytes)
    assert(len(self.v) == self._keylen_bytes)
    self.aes = AES.new(self.key,AES.MODE_ECB)
    return
Example #5
0
def testEncodeAVP():
    avp = L2TPV3AVP(True, False, 0, 0,
                    struct.pack("!H", ControlMessageTypes["SCCRQ"]))
    s = avp.toBinary()

    print str(avp)
    print binascii.b2a_hex(s)
Example #6
0
 def read_crypto_ia(self, s):
     if DEBUG:
         self._log_start()
         self.log.write('r:'+b2a_hex(s)+'(ia)\n')
         if self.buffer:
             self.log.write('r:'+b2a_hex(self.buffer)+'(buffer)\n')
     return self.read_crypto_block3done(s)
def _task_main(q):
    a = Crypto.Random.get_random_bytes(16)
    time.sleep(0.1)     # wait 100 ms
    b = Crypto.Random.get_random_bytes(16)
    q.put(binascii.b2a_hex(a))
    q.put(binascii.b2a_hex(b))
    q.put(None)      # Wait for acknowledgment
    def disrupt_data(self, dm, target, data):
        try:
            rnode, consumed_node, orig_node_val, idx = next(self.walker)
        except StopIteration:
            data.make_unusable()
            self.handover()
            return data

        new_max_runs = self.consumer.max_nb_runs_for(consumed_node)
        if self.max_runs != new_max_runs or self.current_node != consumed_node:
            self.current_node = consumed_node
            self.max_runs = new_max_runs
            self.run_num = 1
        else:
            self.run_num +=1

        data.add_info('model walking index: {:d}'.format(idx))        
        data.add_info(' |_ run: {:d} / {:d} (max)'.format(self.run_num, self.max_runs))
        data.add_info('current fuzzed separator:     %s' % self.modelwalker.consumed_node_path)
        data.add_info(' |_ value type:         %s' % consumed_node.cc.get_value_type())
        data.add_info(' |_ original separator: %s (ascii: %s)' % \
                      (binascii.b2a_hex(orig_node_val), orig_node_val))
        data.add_info(' |_ replaced by:        %s (ascii: %s)' % \
                      (binascii.b2a_hex(consumed_node.to_bytes()),
                      consumed_node.to_bytes()))

        if self.clone_node:
            exported_node = Node(rnode.name, base_node=rnode, new_env=True)
            data.update_from_node(exported_node)
        else:
            data.update_from_node(rnode)

        return data
Example #9
0
    def check_apns_error_response(self):
        """
        Check error response.
        Use blocking socket.read() and timeout when no response.

        This is experimentally workaround.
        """
        if self.apns.gateway_server._socket is None:
            return

        try:
            self.apns.gateway_server._socket.settimeout(0.6)
            error_bytes = self.apns.gateway_server.read(6)
            if len(error_bytes) < 6:
                return

            command = b2a_hex(unpack('>c', error_bytes[0:1])[0])
            if command != '08':
                logging.warn('Unknown command received %s', command)
                return
            status = b2a_hex(unpack('>c', error_bytes[1:2])[0])
            identifier = unpack('>I', error_bytes[2:6])[0]
            raise APNsError(status, identifier)

        except socket.error, e:
            if isinstance(e.args, tuple):
                if e[0] == 'The read operation timed out':
                    return  # No error response.
            logging.warn(e)
Example #10
0
def main():
        parser = argparse.ArgumentParser(description='py3-kms: KMS Server Emulator written in Python3', epilog="version: py3-kms_2018-03-01")
        parser.add_argument("ip", nargs="?", action="store", default="0.0.0.0",
                            help='The IP address to listen on. The default is \"0.0.0.0\" (all interfaces).', type=str)
        parser.add_argument("port", nargs="?", action="store", default=1688,
                            help='The network port to listen on. The default is \"1688\".', type=int)
        parser.add_argument("-e", "--epid", dest="epid", default=None,
                            help='Use this flag to manually specify an ePID to use. If no ePID is specified, a random ePID will be generated.', type=str)
        parser.add_argument("-l", "--lcid", dest="lcid", default=1033,
                            help='Use this flag to manually specify an LCID for use with randomly generated ePIDs. If an ePID is manually specified,\
this setting is ignored.', type=int)
        parser.add_argument("-c", "--client-count", dest="CurrentClientCount", default=26,
                            help='Use this flag to specify the current client count. Default is 26. A number >25 is required to enable activation.', type=int)
        parser.add_argument("-a", "--activation-interval", dest="VLActivationInterval", default=120,
                            help='Use this flag to specify the activation interval (in minutes). Default is 120 minutes (2 hours).', type=int)
        parser.add_argument("-r", "--renewal-interval", dest="VLRenewalInterval", default=1440 * 7,
                            help='Use this flag to specify the renewal interval (in minutes). Default is 10080 minutes (7 days).', type=int)
        parser.add_argument("-s", "--sqlite", dest="sqlite", action="store_const", const=True, default=False,
                            help='Use this flag to store request information from unique clients in an SQLite database.')
        parser.add_argument("-w", "--hwid", dest="hwid", action="store", default='364F463A8863D35F',
                            help='Use this flag to specify a HWID. The HWID must be an 16-character string of hex characters. \
The default is \"364F463A8863D35F\" or type \"random\" to auto generate the HWID.', type=str)   
        parser.add_argument("-v", "--loglevel", dest="loglevel", action="store", default="ERROR", choices=["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"],
                            help='Use this flag to set a Loglevel. The default is \"ERROR\".', type=str)
        parser.add_argument("-f", "--logfile", dest="logfile", action="store", default=os.path.dirname(os.path.abspath( __file__ )) + "/py3kms_server.log",
                            help='Use this flag to set an output Logfile. The default is \"pykms_server.log\".', type=str)
        
        config.update(vars(parser.parse_args()))
        # Random HWID.
        if config['hwid'] == "random":
                randomhwid = uuid.uuid4().hex
                config['hwid'] = randomhwid[:16]
        
        # Sanitize HWID.
        try:
                config['hwid'] = binascii.a2b_hex(re.sub(r'[^0-9a-fA-F]', '', config['hwid'].strip('0x')))
                if len(binascii.b2a_hex(config['hwid'])) < 16:
                        logging.error("HWID \"%s\" is invalid. Hex string is too short." % binascii.b2a_hex(config['hwid']).decode('utf-8').upper())
                        return
                elif len(binascii.b2a_hex(config['hwid'])) > 16:
                        logging.error("HWID \"%s\" is invalid. Hex string is too long." % binascii.b2a_hex(config['hwid']).decode('utf-8').upper())
                        return
        except TypeError:
                logging.error("HWID \"%s\" is invalid. Odd-length hex string." % binascii.b2a_hex(config['hwid']).decode('utf-8').upper())
                return

        logging.basicConfig(level=config['loglevel'], format='%(asctime)s %(levelname)-8s %(message)s',
                            datefmt='%a, %d %b %Y %H:%M:%S', filename=config['logfile'], filemode='w')
        
        try:
                import sqlite3
                config['dbSupport'] = True
        except:
                logging.warning("Module \"sqlite3\" is not installed, database support disabled.")
                config['dbSupport'] = False
        server = socketserver.TCPServer((config['ip'], config['port']), kmsServer)
        server.timeout = 5
        logging.info("TCP server listening at %s on port %d." % (config['ip'], config['port']))
        logging.info("HWID: %s" % binascii.b2a_hex(config['hwid']).decode('utf-8').upper())
        server.serve_forever()
Example #11
0
    def decode(self, file_input, file_output):

        f = open(file_input, 'r') #apro file di input in lettura
        o = open(file_output, 'w') #apro file di output in scrittura
        t = f.read() #leggo tutto il file
        strout = ""
        state = 0

        for c in t: #scorro tutti i caratteri contenuti nel file

            if state == 0: #state = 0 --> c e' il counter
                ba = bitarray()
                ba.frombytes(c) #dal byte mi ricavo l'oggetto bitarray
                if ba[0]: #ossia se il primo carattere della stringa di bit e' a 1 (numero > di 127) non posso convertire in string
                    ba[0] = 0 #azzero il primo carattere
                    counter_int = int(binascii.b2a_hex(ba.tostring()),16) #converto prima in esadecimale e poi in decimale
                    counter_int += 128 #aggiungo 10000000(bin) = 128(dec) che avevo tolto all'inizio
                else:
                    counter_int = int(binascii.b2a_hex(ba.tostring()),16) #converto prima in esadecimale e poi in decimale
                state = 1 #metto lo stato a 1

            else: #state = 1 --> c e' il carattere
                for i in range(0,counter_int): #per un numero counter_int di volte
                    strout += c #scrivo il carattere
                state = 0

        o.write(strout) #scrivo l'output sul file_output
        o.close() #chiudo file_output
        f.close() #chiudo file_input
Example #12
0
def try_imports_lib():
    a = imports.lazyModule('base64')

    HOOKS={ 'binascii' : ['b2a_hex'],
            'base64' : ['b64encode'],
            'oboeware.django' : ['OboeDjangoMiddleware']}

    def hook(module):
        print "hook", module.__name__

        def wrap(fn, *args, **kw):
            print "wrapped", fn.__name__
            return fn

        # wrap callables we want to wrap
        for attr in HOOKS[module.__name__]:
            setattr(module, attr, wrap(getattr(module, attr)))

        #print repr(obj)

    imports.whenImported('binascii', hook)
    imports.whenImported('base64', hook)

    from binascii import b2a_hex

    print b2a_hex('yo')

    from base64 import b64encode

    print b64encode("blah")
Example #13
0
def binLogData(data, maxlen = 64):
   ellipses = " ..."
   if len(data) > maxlen - len(ellipses):
      dd = binascii.b2a_hex(data[:maxlen]) + ellipses
   else:
      dd = binascii.b2a_hex(data)
   return dd
Example #14
0
	def __repr__(self):
		if isinstance(self._data, C1218Request):
			repr_data = repr(self._data)
		else:
			repr_data = '0x' + binascii.b2a_hex(self._data).decode('utf-8')
		crc = binascii.b2a_hex(packet_checksum(self.start + self.identity + self.control + self.sequence + self._length + self._data)).decode('utf-8')
		return '<C1218Packet data=' + repr_data + ' data_len=' + str(len(self._data)) + ' crc=0x' + crc + ' >'
Example #15
0
 def encode(self, blob):
     if 'upper' in self.dialect:
         return binascii.b2a_hex(blob).upper()
     if 'lower' in self.dialect:
         return binascii.b2a_hex(blob).lower()
     else:
         return binascii.b2a_hex(blob)
def test_srtp_auth():
    m = b"hello_rtp"
    master_key=  a2b_hex('00000000000000000000000000000000')
    master_salt= a2b_hex('0000000000000000000000000000')
    ck,sk,ak= srtp_derive_key_aes_128(master_key, master_salt)
    assert b2a_hex(ak) == b'788bcd111ecf73d4e78d2e21bef55460daacdaf7'

    ma = srtp_sign_packet(ak, m, 0)

    assert b2a_hex(ma[-10:]) == b'e60c68053178ee795142'
    assert srtp_verify_and_strip_signature(ak, ma, 0) == m
    try:
        srtp_verify_and_strip_signature(ak, ma, 1) # wrong roc should fail authentication
        assert False
    except AuthenticationFailure:
        pass

    try:
        srtp_verify_and_strip_signature(ak, b'\xff' + ma[1:], 1) # modified message should fail auth
        assert False
    except AuthenticationFailure:
        pass

    ck,sk,ak= srtp_derive_key_aes_128(master_key, master_salt, rtcp=True)
    encrypted_srtcp = True
    packet_i_srtcp = 1
    data = a2b_hex ('80cc000810feff99466c75782105000310feff990000100200001603000000090000000400000001a0573cb69ef3c96e1253')
    data2 = a2b_hex('80cc000810feff99466c75782105000310feff990000100200001603000000090000000480000002e24513e079e366eb82e6')

    assert srtcp_sign_packet(ak, data[:-14], packet_i_srtcp, not encrypted_srtcp) == data
    assert srtcp_verify_and_strip_signature(ak, data) == (data[:-14], packet_i_srtcp, not encrypted_srtcp)

    assert srtcp_sign_packet(ak, data[:-14], packet_i_srtcp+1, encrypted_srtcp) == data2
    assert srtcp_verify_and_strip_signature(ak, data2) == (data2[:-14], packet_i_srtcp+1, encrypted_srtcp)
Example #17
0
def serialize(obj):
    '''JSON serializer function for non-standard Python objects.'''

    if isinstance(obj, bytearray):
        # TODO: Decide on a single way of dumping blobs
        if False:
            # Don't dump full blobs, but merely a description of their size and
            # CRC32 hash.
            crc32 = binascii.crc32(obj)
            if crc32 < 0:
                crc32 += 0x100000000
            return 'blob(size=%u,crc32=0x%08x)' % (len(obj), crc32)
        if True:
            # Dump blobs as an array of 16byte hexadecimals
            res = []
            for i in range(0, len(obj), 16):
                res.append(binascii.b2a_hex(obj[i: i+16]))
            return res
        # Dump blobs as a single hexadecimal string
        return binascii.b2a_hex(obj)

    # If the object has a __json__ method, use it.
    try:
        method = obj.__json__
    except AttributeError:
        raise TypeError(obj)
    else:
        return method()
Example #18
0
    def __init__(self, fobject):
        """fobject is a file object advanced after the header (8 bytes)."""
        _fanout = fobject.read(FANOUT_SIZE * FANOUT_NUMBER)
        self.fanout_table = [
            struct.unpack('!i', _fanout[4*i:4*i+4])[0] for i in range(FANOUT_NUMBER)]

        self.nobjects = self.fanout_table[-1]

        self.names = []

        def foo(nobj):
            return [binascii.b2a_hex(fobject.read(20)) for j in range(nobj)]

        nobj = self.fanout_table[0]
        self.names.append(foo(nobj))
        for i in range(1, FANOUT_NUMBER):
            # Number of objects in fanout_table[i]
            nobj = self.fanout_table[i] - self.fanout_table[i-1]
            self.names.append(foo(nobj))

        self.crc32 = [struct.unpack('!i', fobject.read(4))[0] for i in range(self.nobjects)]
        self.offsets = [struct.unpack('!i', fobject.read(4))[0] for i in range(self.nobjects)]

        self.pack_checksum = binascii.b2a_hex(fobject.read(20))
        self.own_checksum = binascii.b2a_hex(fobject.read(20))

        if fobject.read():
            raise NotImplementedError("64 bits offset not supported yet")
def decrypt_file(fn, offset=0):
	key = ''.join(['\xDE', '\x72', '\xBE', '\xA0', '\xDE', '\x04', '\xBE', '\xB1', '\xDE', '\xFE', '\xBE', '\xEF', '\xDE', '\xAD', '\xBE', '\xEF'])
	bc = 0
	pb = None
	from blowfish import Blowfish
	from binascii import b2a_hex
	bf = Blowfish(key)
	printmessage("Decrypting from offset {}".format(offset))
	of = fn + ".tmp"
	with open(fn, 'rb') as f:
	    f.seek(offset)
	    with open(of, 'wb') as out:
	        while True:
	            b = f.read(8)
	            if not b:
	                break
	
	            if len(b) < 8:
	                b += '\x00' * (8 - len(b))  # pad for correct blocksize
	
	            if bc > 0:
	                db = bf.decrypt(b)
	                if pb:
	                    db = ''.join([chr(int(b2a_hex(a), 16) ^ int(b2a_hex(b), 16)) for a, b in zip(db, pb)])
	
	                pb = db
	                out.write(db)
	            bc += 1
	        return of
	return None
    def test_no_memory_arg(self):
        scram = auth.AuthScram(
            nonce='1234567890abcdef',
            kdf='argon2id13',
            salt=binascii.b2a_hex(b'1234567890abcdef'),
            iterations=4096,
            memory=512,
            password=u'p4ssw0rd',
            authid=u'username',
        )
        scram.authextra

        with self.assertRaises(ValueError) as ctx:
            challenge = types.Challenge(u'scram', {
                'nonce': u'1234567890abcdeffedcba0987654321',
                'kdf': u'argon2id-13',
                'salt': binascii.b2a_hex(b'1234567890abcdef'),
                'iterations': 4096,
                # no 'memory' key
            })
            scram.on_challenge(Mock(), challenge)
        self.assertIn(
            "requires 'memory' parameter",
            str(ctx.exception)
        )
 def before_send(self, apdu):
     self.last_vanilla_c_apdu = C_APDU(apdu)
     if (apdu.cla & 0x80 != 0x80) and (apdu.CLA & 0x0C != 0x0C):
         # Transform for SM
         apdu.CLA = apdu.CLA | 0x0C
         apdu_string = binascii.b2a_hex(apdu.render())
         new_apdu = [apdu_string[:8]]
         new_apdu.append("YY")
         
         if apdu.case() in (3,4):
             new_apdu.append("87[01")
             new_apdu.append(binascii.b2a_hex(apdu.data))
             new_apdu.append("]")
         
         if apdu.case() in (2,4):
             if apdu.Le == 0:
                 apdu.Le = 0xe7 # FIXME: Probably not the right way
             new_apdu.append("97(%02x)" % apdu.Le)
         
         new_apdu.append("8E()00")
         
         new_apdu_string = "".join(new_apdu)
         apdu = C_APDU.parse_fancy(new_apdu_string)
     
     return TCOS_Security_Environment.before_send(self, apdu)
Example #22
0
    def runTest(self):
        h = self.hashmod.new()
        h.update(self.input)

        out1 = binascii.b2a_hex(h.digest())
        out2 = h.hexdigest()

        h = self.hashmod.new(self.input)

        out3 = h.hexdigest()
        out4 = binascii.b2a_hex(h.digest())

        # PY3K: hexdigest() should return str(), and digest() bytes
        self.assertEqual(self.expected, out1)   # h = .new(); h.update(data); h.digest()
        if sys.version_info[0] == 2:
            self.assertEqual(self.expected, out2)   # h = .new(); h.update(data); h.hexdigest()
            self.assertEqual(self.expected, out3)   # h = .new(data); h.hexdigest()
        else:
            self.assertEqual(self.expected.decode(), out2)   # h = .new(); h.update(data); h.hexdigest()
            self.assertEqual(self.expected.decode(), out3)   # h = .new(data); h.hexdigest()
        self.assertEqual(self.expected, out4)   # h = .new(data); h.digest()

        # Verify that the .new() method produces a fresh hash object, except
        # for MD5 and SHA1, which are hashlib objects.  (But test any .new()
        # method that does exist.)
        if self.hashmod.__name__ not in ('Crypto.Hash.MD5', 'Crypto.Hash.SHA1') or hasattr(h, 'new'):
            h2 = h.new()
            h2.update(self.input)
            out5 = binascii.b2a_hex(h2.digest())
            self.assertEqual(self.expected, out5)
Example #23
0
	def mssql(self, ip):
		for pwd in passwd:
			try:
				pwd = pwd.replace('{user}', 'sa')
				s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
				s.connect((ip, 1433))
				husername = binascii.b2a_hex('sa')
				lusername = len('sa')
				lpassword = len(pwd)
				hpwd = binascii.b2a_hex(pwd)
				address = binascii.b2a_hex(ip) +'3a'+ binascii.b2a_hex(str(1433))
				data1 = data.replace(data[16:16+len(address)], address)
				data2 = data1.replace(data1[78:78+len(husername)], husername)
				data3 = data2.replace(data2[140:140+len(hpwd)], hpwd)
				if lusername >= 16:
					data4 = data3.replace('0X', str(hex(lusername)).replace('0x', ''))
				else:
					data4 = data3.replace('X', str(hex(lusername)).replace('0x', ''))
				if lpassword >= 16:
					data5 = data4.replace('0Y', str(hex(lpassword)).replace('0x', ''))
				else:
					data5 = data4.replace('Y', str(hex(lpassword)).replace('0x', ''))
				hladd = hex(len(ip) + len(str(1433))+1).replace('0x', '')
				data6 = data5.replace('ZZ', str(hladd))
				data7 = binascii.a2b_hex(data6)
				s.send(data7)
				if 'master' in s.recv(1024):
					print u'{}[+] {}:1433  SQLserver存在弱口令: sa  {}{}'.format(G, ip, pwd, W)
					break
			except Exception as e:
				pass
			finally:
				s.close()
Example #24
0
def _test():
    import binascii
    import time

    mt = MerkleTree([None] + [binascii.unhexlify(a) for a in [
        '999d2c8bb6bda0bf784d9ebeb631d711dbbbfe1bc006ea13d6ad0d6a2649a971',
        '3f92594d5a3d7b4df29d7dd7c46a0dac39a96e751ba0fc9bab5435ea5e22a19d',
        'a5633f03855f541d8e60a6340fc491d49709dc821f3acb571956a856637adcb6',
        '28d97c850eaf917a4c76c02474b05b70a197eaefb468d21c22ed110afe8ec9e0',
    ]])
    assert(
        b'82293f182d5db07d08acf334a5a907012bbb9990851557ac0ec028116081bd5a' ==
        binascii.b2a_hex(mt.withFirst(binascii.unhexlify('d43b669fb42cfa84695b844c0402d410213faa4f3e66cb7248f688ff19d5e5f7')))
    )

    print '82293f182d5db07d08acf334a5a907012bbb9990851557ac0ec028116081bd5a'
    txes = [binascii.unhexlify(a) for a in [
        'd43b669fb42cfa84695b844c0402d410213faa4f3e66cb7248f688ff19d5e5f7',
        '999d2c8bb6bda0bf784d9ebeb631d711dbbbfe1bc006ea13d6ad0d6a2649a971',
        '3f92594d5a3d7b4df29d7dd7c46a0dac39a96e751ba0fc9bab5435ea5e22a19d',
        'a5633f03855f541d8e60a6340fc491d49709dc821f3acb571956a856637adcb6',
        '28d97c850eaf917a4c76c02474b05b70a197eaefb468d21c22ed110afe8ec9e0',
    ]]

    s = time.time()
    mt = MerkleTree(txes)
    for x in range(100):
        y = int('d43b669fb42cfa84695b844c0402d410213faa4f3e66cb7248f688ff19d5e5f7', 16)
        #y += x
        coinbasehash = binascii.unhexlify("%x" % y)
        x = binascii.b2a_hex(mt.withFirst(coinbasehash))

    print x
    print time.time() - s
Example #25
0
def read_mapped_address(attr_type, attr_body, attr_len):
    assert attr_type in (MAPPED_ADDRESS, XOR_MAPPED_ADDRESS, '\x00\x20')
    assert attr_body[:1] == '\x00' # 最初の 8bit (1bytes) は 0 に設定しなければならない

    family_bytes = attr_body[1:2]
    port_bytes = attr_body[2:4]
    addr_bytes = attr_body[4:attr_len]
    xor = attr_type in (XOR_MAPPED_ADDRESS, '\x00\x20')

    family_text = ''
    assert family_bytes in (FAMILY_IPv4, FAMILY_IPv6)
    if family_bytes == FAMILY_IPv4:
        family_text = 'IPv4'
    elif family_bytes == FAMILY_IPv6:
        family_text = 'IPv6'

    # TODO: IPv6 に対応
    port = int(binascii.b2a_hex(port_bytes), 16)
    addr_int = int(binascii.b2a_hex(addr_bytes), 16)

    if xor:
        # port
        magicCookieHighBytesInt = int(binascii.b2a_hex(MAGIC_COOKIE[:2]), 16)
        port =  magicCookieHighBytesInt ^ port

        # addr
        magicCookieBytesInt = int(binascii.b2a_hex(MAGIC_COOKIE), 16)
        addr_int =  magicCookieBytesInt ^ addr_int

    octets = struct.pack('!I', addr_int)
    ip = '.'.join([str(ord(c)) for c in octets])
    return dict(name=STUN_ATTRIBUTE_NAMES[attr_type], ip=ip, port=port, family=family_text)
Example #26
0
    def FromSock(self):
        Str = self.__Sock.recv(4);
        if not len(Str) == 4:
            #self.__Logger.warning("To less data recv");
            return(False);
        
        self.__Logger.debug("Got Hader: %s"%binascii.b2a_hex(Str));
        self.HDRFromString(Str);
        self.__Logger.debug("Get Packet %i"%self.GetLen());
        Str = self.__Sock.recv(self.GetLen()-4);
        if not len(Str) == (self.GetLen()-4):
            self.__Logger.warning("To less data");
            return(False);

        if self.GetCMD() == JVISU_CMD_REGVAR:
            self.__Logger.debug("CMD: register var");
            FMT = "II%is"%(self.GetLen()-12);
            (self.__ID,
             self.__Rate,
             self.__DATA) = struct.unpack(FMT,Str);
            self.__Logger.debug("Add var with id %i"%self.__ID);
            return(True);
        elif self.GetCMD() == JVISU_CMD_DELVAR:
            self.__Logger.debug("CMD: unregister var");
            (self.__ID,) = struct.unpack("I",Str);
            return(True);
        elif self.GetCMD() == JVISU_CMD_SNDVAR:
            self.__Logger.debug("CMD: set value");
            FMT = "I%is"%(self.GetLen()-8);
            (self.__ID,self.__DATA) = struct.unpack(FMT,Str);
        else:
            self.__Logger.warning("Command %x not implemented"%self.GetCMD());
            self.__Logger.debug("LINE: %s"%binascii.b2a_hex(Str));
        return(False);
def readtoc(f):
    hdr = HEADER.fromfile(f)
    if hdr['magic'] != MAGIC:
        raise XARFormatError('magic %r != %r' %
                             (hdr['magic'], MAGIC))
    if hdr['version'] not in VERSIONS:
        raise XARFormatError('version %r not supported' %
                             (hdr['version'],))
    if hdr['cksum_alg'] not in CHECKSUM:
        raise XARFormatError('cksum_alg %r not supported' %
                             (hdr['cksum_alg'],))
    ztocdata = f.read(hdr['toc_length_compressed'])
    tocdata = zlib.decompress(ztocdata)
    if hdr['toc_length_uncompressed'] != len(tocdata):
        raise XARFormatError('toc_length_uncompressed %r != %r' %
                             (hdr['toc_length_uncompressed'],
                              len(tocdata)))
    digest = toc_digest(hdr, ztocdata)
    if digest:
        orig_digest = f.read(len(digest))
        if digest != orig_digest:
            raise XARFormatError('digest %r != %r' %
                                 (b2a_hex(digest),
                                  b2a_hex(orig_digest)))
    return hdr, tocdata
Example #28
0
def _compute_response_auth(urp_hash, nonce, cnonce, nonce_count, authzid,
                                                                    digest_uri):
    """Compute DIGEST-MD5 rspauth value.

    :Parameters:
        - `urp_hash`: MD5 sum of username:realm:password.
        - `nonce`: nonce value from a server challenge.
        - `cnonce`: cnonce value from the client response.
        - `nonce_count`: nonce count value.
        - `authzid`: authorization id.
        - `digest_uri`: digest-uri value.
    :Types:
        - `urp_hash`: `bytes`
        - `nonce`: `bytes`
        - `nonce_count`: `int`
        - `authzid`: `bytes`
        - `digest_uri`: `bytes`

    :return: the computed rspauth value.
    :returntype: `bytes`"""
    # pylint: disable-msg=C0103,R0913
    logger.debug("_compute_response_auth{0!r}".format((urp_hash, nonce, cnonce,
                                            nonce_count, authzid, digest_uri)))
    if authzid:
        a1 = b":".join((urp_hash, nonce, cnonce, authzid))
    else:
        a1 = b":".join((urp_hash, nonce, cnonce))
    a2 = b":" + digest_uri
    return b2a_hex(_kd_value(b2a_hex(_h_value(a1)), b":".join((
            nonce, nonce_count, cnonce, b"auth", b2a_hex(_h_value(a2))))))
Example #29
0
def start(shellcode, job):

    for line in shellcode.rsplit('\n'):
        if 'push' in line and '$0x' in line and ',' not in line and len(
                line) > 14:
            data = line.rsplit('push')[1].rsplit('$0x')[1]
            t = True
            while t:
                if _version is 2:
                    ebx_1 = binascii.b2a_hex(''.join(random.choice(chars)
                                                     for i in range(4)))
                if _version is 3:
                    ebx_1 = (binascii.b2a_hex((''.join(random.choice(
                        chars) for i in range(4))).encode('latin-1'))
                             ).decode('latin-1')
                ebx_2 = "%x" % (int(data, 16) ^ int(ebx_1, 16))
                if str('00') not in str(ebx_1) and str('00') not in str(
                        ebx_2) and len(ebx_2.replace('-', '')) > 7 and len(
                            ebx_1) > 7 and '-' not in ebx_1:
                    ebx_2 = ebx_2.replace('-', '')
                    if job == 'exec':
                        command = '\npush %%ebx\npush $0x%s\npop %%ebx\npush $0x%s\npop %%ecx\nxor %%ebx,%%ecx\npop %%ebx\npush %%ecx\n' % (
                            str(ebx_1), str(ebx_2))
                    elif job == 'add_admin' or job == 'dir_create' or job == 'download_exec':
                        command = '\npush %%ebx\npush $0x%s\npop %%ebx\npush $0x%s\npop %%ecx\nxor %%ebx,%%ecx\npop %%ebx\npush %%ecx\n' % (
                            str(ebx_1), str(ebx_2))
                    elif job == 'create_file' or job == 'disable_firewall' or job == 'download_tofile':
                        command = '\npush %%eax\npush $0x%s\npop %%eax\npush $0x%s\npop %%ecx\nxor %%eax,%%ecx\npop %%eax\npush %%ecx\n' % (
                            str(ebx_1), str(ebx_2))
                    shellcode = shellcode.replace(line, command)
                    t = False
    return shellcode
Example #30
0
 def new(self, random_iv=True): # if random_iv==False, set iv to 0
     self.key_str = binascii.b2a_hex(M2Crypto.Rand.rand_bytes(self.key_len))
     if random_iv:
         self.iv_str = binascii.b2a_hex(M2Crypto.Rand.rand_bytes(self.iv_len))
     else:
         self.iv_str = '0'*(self.iv_len*2)
     return
Example #31
0
	def updateBlock(self, newBlock, height = None, bits = None, _HBH = None):
		if newBlock == self.currentBlock[0]:
			if height in (None, self.currentBlock[1]) and bits in (None, self.currentBlock[2]):
				return
			if not self.currentBlock[2] is None:
				self.logger.error('Was working on block with wrong specs: %s (height: %d->%d; bits: %s->%s' % (
					b2a_hex(newBlock[::-1]).decode('utf8'),
					self.currentBlock[1],
					height,
					b2a_hex(self.currentBlock[2][::-1]).decode('utf8'),
					b2a_hex(bits[::-1]).decode('utf8'),
				))
		
		# Old block is invalid
		if self.currentBlock[0] != newBlock:
			self.lastBlock = self.currentBlock
		
		lastHeight = self.currentBlock[1]
		if height is None:
			height = self.currentBlock[1] + 1
		if bits is None:
			if height % self.DifficultyChangeMod == 1 or self.currentBlock[2] is None:
				self.logger.warning('New block: %s (height %d; bits: UNKNOWN)' % (b2a_hex(newBlock[::-1]).decode('utf8'), height))
				# Pretend to be 1 lower height, so we possibly retain nextMerkleRoots
				self.currentBlock = (None, height - 1, None)
				self.clearMerkleRoots = Queue(0)
				self.merkleRoots.clear()
				self.ready = False
				return
			else:
				bits = self.currentBlock[2]
		
		if _HBH is None:
			_HBH = (b2a_hex(newBlock[::-1]).decode('utf8'), b2a_hex(bits[::-1]).decode('utf8'))
		self.logger.info('New block: %s (height: %d; bits: %s)' % (_HBH[0], height, _HBH[1]))
		self.currentBlock = (newBlock, height, bits)
		
		if lastHeight != height:
			# TODO: Perhaps reuse clear merkle trees more intelligently
			if lastHeight == height - 1:
				self.curClearMerkleTree = self.nextMerkleTree
				self.clearMerkleRoots = self.nextMerkleRoots
				self.logger.debug('Adopting next-height clear merkleroots :)')
			else:
				if lastHeight:
					self.logger.warning('Change from height %d->%d; no longpoll merkleroots available!' % (lastHeight, height))
				self.curClearMerkleTree = self.createClearMerkleTree(height)
				self.clearMerkleRoots = Queue(self.WorkQueueSizeClear[1])
			self.nextMerkleTree = self.createClearMerkleTree(height + 1)
			self.nextMerkleRoots = Queue(self._MaxClearSize)
		else:
			self.logger.debug('Already using clear merkleroots for this height')
		self.currentMerkleTree = self.curClearMerkleTree
		self.merkleRoots.clear()
		
		if not self.ready:
			self.ready = True
			with self.readyCV:
				self.readyCV.notify_all()
		
		self.needMerkle = 2
		self.onBlockChange()
def b2x(b):
    return b2a_hex(b).decode('ascii')
 def gen_order_id(self):
     return str(int(time())) + b2a_hex(urandom(4)).decode
Example #34
0
 def test_wkb(self):
     "Testing WKB output."
     for g in self.geometries.hex_wkt:
         geom = fromstr(g.wkt)
         wkb = geom.wkb
         self.assertEqual(b2a_hex(wkb).decode().upper(), g.hex)
Example #35
0
 def b2a_hex(b):
     return binascii.b2a_hex(compat26Str(b))
Example #36
0
 def b2a_hex(b):
     return binascii.b2a_hex(b).decode("ascii")
Example #37
0
	def updateMerkleTree(self):
		global now
		self.logger.debug('Polling bitcoind for memorypool')
		self.nextMerkleUpdate = now + self.TxnUpdateRetryWait
		
		try:
			# First, try BIP 22 standard getblocktemplate :)
			MP = self.access.getblocktemplate(self.GBTReq)
			self.OldGMP = False
		except:
			try:
				# Failing that, give BIP 22 draft (2012-02 through 2012-07) getmemorypool a chance
				MP = self.access.getmemorypool(self.GMPReq)
			except:
				try:
					# Finally, fall back to bitcoind 0.5/0.6 getmemorypool
					MP = self.access.getmemorypool()
				except:
					MP = False
			if MP is False:
				# This way, we get the error from the BIP22 call if the old one fails too
				raise
			
			# Pre-BIP22 server (bitcoind <0.7 or Eloipool <20120513)
			if not self.OldGMP:
				self.OldGMP = True
				self.logger.warning('Upstream server is not BIP 22 compatible')
		
		oMP = deepcopy(MP)
		
		prevBlock = bytes.fromhex(MP['previousblockhash'])[::-1]
		if 'height' in MP:
			height = MP['height']
		else:
			height = self.access.getinfo()['blocks'] + 1
		bits = bytes.fromhex(MP['bits'])[::-1]
		if (prevBlock, height, bits) != self.currentBlock:
			self.updateBlock(prevBlock, height, bits, _HBH=(MP['previousblockhash'], MP['bits']))
		
		txnlist = MP['transactions']
		if len(txnlist) and isinstance(txnlist[0], dict):
			txninfo = txnlist
			txnlist = tuple(a['data'] for a in txnlist)
			txninfo.insert(0, {
			})
		elif 'transactionfees' in MP:
			# Backward compatibility with pre-BIP22 gmp_fees branch
			txninfo = [{'fee':a} for a in MP['transactionfees']]
		else:
			# Backward compatibility with pre-BIP22 hex-only (bitcoind <0.7, Eloipool <future)
			txninfo = [{}] * len(txnlist)
		# TODO: cache Txn or at least txid from previous merkle roots?
		txnlist = [a for a in map(bytes.fromhex, txnlist)]
		
		self._makeBlockSafe(MP, txnlist, txninfo)
		
		cbtxn = self.makeCoinbaseTxn(MP['coinbasevalue'])
		cbtxn.setCoinbase(b'\0\0')
		cbtxn.assemble()
		txnlist.insert(0, cbtxn.data)
		
		txnlist = [a for a in map(Txn, txnlist[1:])]
		txnlist.insert(0, cbtxn)
		txnlist = list(txnlist)
		newMerkleTree = MerkleTree(txnlist)
		if newMerkleTree.merkleRoot() != self.currentMerkleTree.merkleRoot():
			newMerkleTree.POTInfo = MP.get('POTInfo')
			newMerkleTree.oMP = oMP
			
			if (not self.OldGMP) and 'proposal' in MP.get('capabilities', ()):
				(prevBlock, height, bits) = self.currentBlock
				coinbase = self.makeCoinbase(height=height)
				cbtxn.setCoinbase(coinbase)
				cbtxn.assemble()
				merkleRoot = newMerkleTree.merkleRoot()
				MRD = (merkleRoot, newMerkleTree, coinbase, prevBlock, bits)
				blkhdr = MakeBlockHeader(MRD)
				data = assembleBlock(blkhdr, txnlist)
				propose = self.access.getblocktemplate({
					"mode": "proposal",
					"data": b2a_hex(data).decode('utf8'),
				})
				if propose is None:
					self.logger.debug('Updating merkle tree (upstream accepted proposal)')
					self.currentMerkleTree = newMerkleTree
				else:
					self.RejectedProposal = (newMerkleTree, propose)
					try:
						propose = propose['reject-reason']
					except:
						pass
					self.logger.error('Upstream rejected proposed block: %s' % (propose,))
			else:
				self.logger.debug('Updating merkle tree (no proposal support)')
				self.currentMerkleTree = newMerkleTree
		
		self.lastMerkleUpdate = now
		self.nextMerkleUpdate = now + self.MinimumTxnUpdateWait
		
		if self.needMerkle == 2:
			self.needMerkle = 1
			self.needMerkleSince = now
Example #38
0
    def parse_nlri(cls, data, nlri_type):
        """parse nlri: node, link, prefix
        """
        #      0                   1                   2                   3
        #      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
        #     +-+-+-+-+-+-+-+-+
        #     |  Protocol-ID  |
        #     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        #     |                           Identifier                          |
        #     |                            (64 bits)                          |
        #     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        #     //               Local Node Descriptors (variable)             //
        #     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        #     //               Remote Node Descriptors (variable)            //
        #     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        #     //                  Link Descriptors (variable)                //
        #     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
        #                     Figure 8: The Link NLRI format

        # The Protocol-ID field can contain one of the following values:
        #     +-------------+----------------------------------+
        #     | Protocol-ID | NLRI information source protocol |
        #     +-------------+----------------------------------+
        #     |      1      | IS-IS Level 1                    |
        #     |      2      | IS-IS Level 2                    |
        #     |      3      | OSPFv2                           |
        #     |      4      | Direct                           |
        #     |      5      | Static configuration             |
        #     |      6      | OSPFv3                           |
        #     |      7      | BGP                              |
        #     +-------------+----------------------------------+
        #               Table 2: Protocol Identifiers

        #     +------------+----------------------------------+
        #     | Identifier | Routing Universe                 |
        #     +------------+----------------------------------+
        #     |     0      | Default Layer 3 Routing topology |
        #     +------------+----------------------------------+
        #         Table 3: Well-Known Instance Identifiers

        proto_id = ord(data[0:1])

        identifier = int(binascii.b2a_hex(data[1:9]), 16)

        descriptor_list = []
        descriptors = data[9:]
        while descriptors:
            _type, length = struct.unpack('!HH', descriptors[0:4])
            value = descriptors[4: 4+length]
            descriptors = descriptors[4+length:]
            descriptor = dict()
            if _type == 256:  # local node
                descriptor['type'] = 'local_node'
                descriptor['value'] = cls.parse_node_descriptor(value, proto_id)

            elif _type == 257:  # remote node
                descriptor['type'] = 'remote_node'
                descriptor['value'] = cls.parse_node_descriptor(value, proto_id)
            # elif _type == 258:  # link local/remote identifier
            #     pass
            elif _type == 259:  # ipv4 interface address
                ipv4_addr = str(netaddr.IPAddress(int(binascii.b2a_hex(value), 16)))
                descriptor['type'] = 'link_local_ipv4'
                descriptor['value'] = ipv4_addr
            elif _type == 260:  # ipv4 neighbor address
                ipv4_neighbor_addr = str(netaddr.IPAddress(int(binascii.b2a_hex(value), 16)))
                descriptor['type'] = 'link_remote_ipv4'
                descriptor['value'] = ipv4_neighbor_addr
            # elif _type == 263: # Multi-Topology Identifier
            #     pass
            elif _type == 263:  # Multi-Topology Identifier
                descriptor['type'] = 'mt_id'
                descriptor['value'] = []
                while value:
                    descriptor['value'].append(struct.unpack('!H', value[:2])[0])
                    value = value[2:]
            elif _type == 264:  # OSPF Route Type
                descriptor['type'] = 'prefix_ospf_route_type'
                descriptor['value'] = ord(value[0:1])
            elif _type == 265:   # IP Reachability Information
                descriptor['type'] = 'prefix'
                mask = ord(value[0:1])
                if nlri_type == cls.IPv4_TOPO_PREFIX_NLRI:
                    prefix_value = value[1:] + b'\x00' * (4 - len(value[1:]))
                    ip_str = str(netaddr.IPAddress(int(binascii.b2a_hex(prefix_value), 16)))
                else:
                    ip_str = str(netaddr.IPAddress(int(binascii.b2a_hex(value[1:]), 16)))
                descriptor['value'] = "%s/%s" % (ip_str, mask)
            else:
                descriptor['type'] = _type
                descriptor['value'] = binascii.b2a_hex(value)
            descriptor_list.append(descriptor)
        return proto_id, identifier, descriptor_list
Example #39
0
 def _bToStr(self, val):
     return binascii.b2a_hex(val).decode('utf-8')
Example #40
0
import binascii

# 128 bit CFB
key = ("\x2b\x7e\x15\x16\x28\xae\xd2\xa6" "\xab\xf7\x15\x88\x09\xcf\x4f\x3c")
iv = ("\x00\x01\x02\x03\x04\x05\x06\x07" "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f")
raw_buf = ("\x6b\xc1\xbe\xe2\x2e\x40\x9f\x96"
           "\xe9\x3d\x7e\x11\x73\x93\x17\x2a"
           "\xae\x2d")

iv_length = len(iv)
key_length = len(key)
plain_length = len(raw_buf)
print 'The length of IV is:', iv_length
print 'The length of Key is:', key_length
print 'The length of Plain is:', plain_length
real_plain = binascii.b2a_hex(raw_buf)
print 'The result of plain is:', real_plain
# Encrypt part
aes_obj = AES.new(key, AES.MODE_CFB, iv)
encrypt_buf = aes_obj.encrypt(raw_buf)
real_encrypt = binascii.b2a_hex(encrypt_buf)
print 'The result of encrypt is:', real_encrypt
encrypt_text = real_encrypt.decode('hex')
# Decrypt part
aes_obj = AES.new(key, AES.MODE_CFB, iv)
decrypt_buf = aes_obj.decrypt(encrypt_text)
real_decrypt = binascii.b2a_hex(decrypt_buf)
print 'The result of decrypt is:', real_decrypt

if real_decrypt == real_plain:
    print 'Encrypt and Decrypt test success!'
Example #41
0
        def thg_encode(self, args):
            """modulo referente a encode de estrings"""
            arg_mensage = args.split(" ")
            if arg_mensage[0] == "":
                print("""suporte encode:

    Este módulo fornece funções para codificar dados binários em caracteres ASCII 
    imprimíveis e decodificar essas codificações de volta para dados binários.
    Ele fornece funções de codificação e decodificação para as codificações 
    especificadas em RFC 3548 ,que define os algoritmos Base16, Base32 e Base64,
    e para as codificações Ascii85 e Base85 padrão de fato.

    a2b_uu
    b2a_uu
    a2b_base64
    b2a_base64
    a2b_qp
    b2a_qp
    a2b_hqx
    rledecode_hqx
    rlecode_hqx
    b2a_hqx
    crc_hqx
    crc32
    b2a_hex
    a2b_hex
    hexlify
    unhexlify
    Charcode
    binary
    base62
    basen
    bcd
    ur
    unicode_normalize
    qp_encoding
            encode type[2,16,32,64]  str

            """.format(YELLOW=Fore.YELLOW, BLUE=Fore.BLUE, RED=Fore.RED))

            elif arg_mensage[0] == "64":
                arg_mensage[1] = arg_mensage[1].encode("ascii")
                base64_bytes = base64.b64encode(arg_mensage[1])
                by_to_st(base64_bytes)
            elif arg_mensage[0] == "32":
                arg_mensage[1] = arg_mensage[1].encode("ascii")
                b32encode_bytes = base64.b32encode(arg_mensage[1])
                by_to_st(b32encode_bytes)
            elif arg_mensage[0] == "16":
                arg_mensage[1] = arg_mensage[1].encode("ascii")
                b16encode_bytes = base64.b16encode(arg_mensage[1])
                by_to_st(b16encode_bytes)
            elif arg_mensage[0] == "a85encode":
                arg_mensage[1] = arg_mensage[1].encode("ascii")
                a85encode_bytes = base64.a85encode(arg_mensage[1])
                by_to_st(a85encode_bytes)
            elif arg_mensage[0] == "b85encode":
                arg_mensage[1] = arg_mensage[1].encode("ascii")
                b85encode_bytes = base64.b85encode(arg_mensage[1])
                by_to_st(b85encode_bytes)
            elif arg_mensage[0] == "a2b_uu":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED} Converta uma única linha de dados uuencodificados de volta em binários e retorne os dados binários. As linhas normalmente contêm 45 bytes (binários), exceto a última linha. Os dados da linha podem ser seguidos de espaços em branco."""
                        .format(YELLOW=Fore.YELLOW,
                                BLUE=Fore.BLUE,
                                RED=Fore.RED))
                else:
                    by_to_st((binascii.a2b_uu(arg_mensage[1])))
            elif arg_mensage[0] == "a2b_base64":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED}Converta dados binários em uma linha de caracteres ASCII na codificação base64. O valor de retorno é a linha convertida, incluindo um caractere de nova linha. O comprimento dos dados deve ser de no máximo 57 para aderir ao padrão base64."""
                        .format(YELLOW=Fore.YELLOW,
                                BLUE=Fore.BLUE,
                                RED=Fore.RED))
                else:
                    by_to_st(binascii.a2b_base64(arg_mensage[1]))
            elif arg_mensage[0] == "b2a_base64":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED} Converta dados binários em uma linha de caracteres ASCII na codificação base64. O valor de retorno é a linha convertida, incluindo um caractere de nova linha. O comprimento dos dados deve ser de no máximo 57 para aderir ao padrão base64."""
                        .format(YELLOW=Fore.YELLOW,
                                BLUE=Fore.BLUE,
                                RED=Fore.RED))
                else:
                    by_to_st(binascii.b2a_base64(b"arg_mensage[1]"))
            elif arg_mensage[0] == "a2b_qp":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED}Converta um bloco de dados imprimíveis entre aspas de volta em binários e retorne os dados binários. Mais de uma linha pode ser passada por vez. Se o cabeçalho do argumento opcional estiver presente e verdadeiro, os sublinhados serão decodificados como espaços."""
                        .format(YELLOW=Fore.YELLOW,
                                BLUE=Fore.BLUE,
                                RED=Fore.RED))
                else:
                    by_to_st(binascii.a2b_qp(arg_mensage[1]))
            elif arg_mensage[0] == "b2a_qp":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED}Converta dados binários em uma (s) linha (s) de caracteres ASCII em codificação imprimível entre aspas. O valor de retorno é a (s) linha (s) convertida (s). Se o argumento opcional quotetabs estiver presente e verdadeiro, todas as tabulações e espaços serão codificados. Se o argumento opcional istext estiver presente e verdadeiro, as novas linhas não serão codificadas, mas os espaços em branco finais serão codificados. Se o cabeçalho do argumento opcional estiver presente e verdadeiro, os espaços serão codificados como sublinhados de acordo com RFC1522. Se o cabeçalho do argumento opcional estiver presente e for falso, os caracteres de nova linha também serão codificados; caso contrário, a conversão de alimentação de linha pode corromper o fluxo de dados binários."""
                        .format(YELLOW=Fore.YELLOW,
                                BLUE=Fore.BLUE,
                                RED=Fore.RED))
                else:
                    by_to_st(binascii.a2b_qp(arg_mensage[1].encode()))
            elif arg_mensage[0] == "a2b_hqx":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED}Converta dados ASCII formatados de binhex4 em binários, sem fazer a descompressão RLE. A string deve conter um número completo de bytes binários ou (no caso da última parte dos dados binhex4) ter os bits restantes zero.
    """.format(YELLOW=Fore.YELLOW, BLUE=Fore.BLUE, RED=Fore.RED))
                else:
                    by_to_st(binascii.a2b_hqx(arg_mensage[1]))
            elif arg_mensage[0] == "rledecode_hqx":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED} Execute a descompressão RLE nos dados, de acordo com o padrão binhex4. O algoritmo usa 0x90 após um byte como um indicador de repetição, seguido por uma contagem. Uma contagem de 0 especifica um valor de byte de 0x90 . A rotina retorna os dados descompactados, a menos que os dados de entrada de dados terminem em um indicador de repetição órfão, caso em que a exceção Incompleta é levantada."""
                        .format(YELLOW=Fore.YELLOW,
                                BLUE=Fore.BLUE,
                                RED=Fore.RED))
                else:
                    by_to_st((binascii.rledecode_hqx(arg_mensage[1].encode())))
            elif arg_mensage[0] == "rlecode_hqx":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED} Execute a compactação RLE no estilo binhex4 nos dados e retorne o resultado."""
                        .format(YELLOW=Fore.YELLOW,
                                BLUE=Fore.BLUE,
                                RED=Fore.RED))
                else:
                    by_to_st((binascii.rlecode_hqx(arg_mensage[1].encode())))
            elif arg_mensage[0] == "b2a_hqx":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED} Execute a conversão hexbin4 binário para ASCII e retorne a string resultante. O argumento já deve ser codificado por RLE e ter um comprimento divisível por 3 (exceto possivelmente o último fragmento).
    """.format(YELLOW=Fore.YELLOW, BLUE=Fore.BLUE, RED=Fore.RED))
                else:
                    by_to_st((binascii.b2a_hqx(arg_mensage[1].encode())))
            elif arg_mensage[0] == "crc_hqx":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED} Calcule o valor binhex4 crc dos dados , começando com um crc inicial e retornando o resultado.
    """.format(YELLOW=Fore.YELLOW, BLUE=Fore.BLUE, RED=Fore.RED))
                else:
                    by_to_st((binascii.crc_hqx(arg_mensage[1].encode(),
                                               int(arg_mensage[2]))))
            elif arg_mensage[0] == "crc32":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED} Calcule CRC-32, a soma de verificação de dados de 
                    32 bits, começando com um crc inicial. Isso é consistente com a soma de verificação do arquivo ZIP. 
                    Uma vez que o algoritmo é projetado para uso como um algoritmo de soma de verificação, não é adequado 
                    para uso como um algoritmo de hash geral. 

    {YELLOW}Nota{YELLOW}{RED} Para gerar o mesmo valor numérico em todas as versões e plataformas Python, {RED}{BLUE}use crc32 (dados) & 0xffffffff{BLUE}{RED}. Se você estiver usando apenas a soma de verificação no formato binário compactado, isso não é necessário, pois o valor de retorno é a representação binária correta de 32 bits, independentemente do sinal.
            """.format(YELLOW=Fore.YELLOW, BLUE=Fore.BLUE, RED=Fore.RED))
                else:
                    by_to_st((binascii.crc32(arg_mensage[1].encode())))
            elif arg_mensage[0] == "hexlify":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED} Retorna a representação hexadecimal dos dados 
                    binários . Cada byte de dados é convertido na representação hexadecimal de 2 dígitos correspondente. 
                    A string resultante é, portanto, o dobro do comprimento dos dados . 

            """.format(YELLOW=Fore.YELLOW, BLUE=Fore.BLUE, RED=Fore.RED))
                else:
                    by_to_st((binascii.hexlify(arg_mensage[1].encode(),
                                               arg_mensage[2].encode())))
            elif arg_mensage[0] == "b2a_hex":
                if arg_mensage[1] == "help":
                    print("""{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED} hex
            """.format(YELLOW=Fore.YELLOW, BLUE=Fore.BLUE, RED=Fore.RED))
                else:
                    by_to_st((binascii.b2a_hex(arg_mensage[1].encode(),
                                               int(arg_mensage[2]))))
            elif arg_mensage[0] == "unhexlify":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED} Retorna os dados binários representados pela string hexadecimal hexstr . Esta função é o inverso de b2a_hex () . hexstr deve conter um número par de dígitos hexadecimais (que podem ser maiúsculas ou minúsculas), caso contrário, um TypeError é gerado.

            """.format(YELLOW=Fore.YELLOW, BLUE=Fore.BLUE, RED=Fore.RED))
                else:
                    by_to_st((binascii.unhexlify(arg_mensage[1].encode())))
            elif arg_mensage[0] == "b2a_uu":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}a2b_uu{YELLOW}{BLUE} =>{BLUE}{RED} Converta dados binários em uma linha de caracteres ASCII, o valor de retorno é a linha convertida, incluindo um caractere de nova linha. O comprimento dos dados deve ser de no máximo 45.

            """.format(YELLOW=Fore.YELLOW, BLUE=Fore.BLUE, RED=Fore.RED))
                else:
                    by_to_st((binascii.b2a_uu(arg_mensage[1].encode(),
                                              int(arg_mensage[2]))))
            elif arg_mensage[0] == "charcode":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}charcode{YELLOW}{BLUE} =>{BLUE}{RED}converte string em charcode
            """.format(YELLOW=Fore.YELLOW, BLUE=Fore.BLUE, RED=Fore.RED))
                else:
                    print(ord(arg_mensage[1].encode()))
            elif arg_mensage[0] == "binary":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}binary{YELLOW}{BLUE} =>{BLUE}{RED}converte string em binary
            """.format(YELLOW=Fore.YELLOW, BLUE=Fore.BLUE, RED=Fore.RED))
                else:
                    print(" ".join(
                        format(ord(x), "b") for x in arg_mensage[1]))
            elif arg_mensage[0] == "base62":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}base62{YELLOW}{BLUE} =>{BLUE}{RED}converte string em base62
            """.format(YELLOW=Fore.YELLOW, BLUE=Fore.BLUE, RED=Fore.RED))
                else:
                    print(decode62(arg_mensage[1]))
            elif arg_mensage[0] == "basen":
                if arg_mensage[1] == "help":
                    print(
                        """{YELLOW}basen{YELLOW}{BLUE} =>{BLUE}{RED}converte decimal em basen
            """.format(YELLOW=Fore.YELLOW, BLUE=Fore.BLUE, RED=Fore.RED))
                else:
                    print(
                        numpy.base_repr(int(arg_mensage[1]),
                                        base=int(arg_mensage[2])))
            elif arg_mensage[0] == "url":
                try:
                    if arg_mensage[1] == "help":
                        print(
                            """{YELLOW}url_encode{YELLOW}{BLUE} =>{BLUE}{RED}encode personalidado para url\nencode url_encode safa[] encoding"""
                            .format(YELLOW=Fore.YELLOW,
                                    BLUE=Fore.BLUE,
                                    RED=Fore.RED))
                    else:
                        print(
                            quote(arg_mensage[1],
                                  safe=arg_mensage[2],
                                  encoding=arg_mensage[3]))
                except IndexError:
                    print(
                        "digite a sintaxe correta\nncode url_encode safa[] encoding\n ou use o comando help"
                    )
            elif arg_mensage[0] == "unicode_normalize":
                try:
                    if arg_mensage[1] == "help":
                        print(
                            """{YELLOW}unicode_normalize{YELLOW}{BLUE} =>{BLUE}{RED}Transforme caracteres Unicode em uma das formas de normalização['NFC', 'NFKC', 'NFD','NFKD']\n                   
    {YELLOW}NFD{YELLOW}{BLUE} =>{BLUE}{RED}Normalisation Form Canonical Decomposition
    {YELLOW}NFC{YELLOW}{BLUE} =>{BLUE}{RED}Normalisation Form Canonical Composition
    {YELLOW}NFKD{YELLOW}{BLUE} =>{BLUE}{RED}Normalisation Form Compatibility Decomposition
    {YELLOW}NFKC{YELLOW}{BLUE} =>{BLUE}{RED}Normalisation Form Compatibility Composition    
    encode unicode_normalize str encoding['NFC', 'NFKC', 'NFD','NFKD']\n""".
                            format(YELLOW=Fore.YELLOW,
                                   BLUE=Fore.BLUE,
                                   RED=Fore.RED))
                    else:
                        print(
                            unicodedata.normalize(arg_mensage[1],
                                                  arg_mensage[2]))
                except IndexError:
                    print(
                        "digite a sintaxe correta\nncode url_encode safa[] encoding\n ou use o comando help"
                    )
            elif arg_mensage[0] == "qp_encoding":
                try:
                    if arg_mensage[1] == "help":
                        print(
                            """{YELLOW}qp_encoding{YELLOW}{BLUE} =>{BLUE}{RED}
                        Quoted-Printable, ou QP encoding, 
                        é uma codificação que usa caracteres ASCII imprimíveis (alfanuméricos e o sinal de igual '=') 
                        para transmitir dados de 8 bits em um caminho de dados de 7 bits ou, geralmente, em um meio que não é 8- um pouco limpo. 
                        É definido como uma codificação de transferência de conteúdo MIME para uso em e-mail.
                        QP funciona usando o sinal de igual '=' como um caractere de escape. Ele também limita o comprimento da linha a 76, pois alguns softwares têm limites no comprimento da linha\nencode qp_encoding TXT encode"""
                            .format(YELLOW=Fore.YELLOW,
                                    BLUE=Fore.BLUE,
                                    RED=Fore.RED))
                    else:
                        encoded = quopri.encodestring(arg_mensage[1].encode(
                            arg_mensage[2]))
                        print(encoded.decode())
                except IndexError:
                    print(
                        "digite a sintaxe correta\nencode qp_encoding é utf-16\n ou use o comando help"
                    )
            elif arg_mensage[0] == "idna":
                try:
                    if arg_mensage[1] == "help":
                        print(
                            """{YELLOW}idna{YELLOW}{BLUE} =>{BLUE}{RED}encode personalidado para url\nencode url_encode safa[] encoding"""
                            .format(YELLOW=Fore.YELLOW,
                                    BLUE=Fore.BLUE,
                                    RED=Fore.RED))
                    else:
                        print(
                            idna.encode(arg_mensage[1]).decode(arg_mensage[2]))
                except IndexError:
                    print(
                        "digite a sintaxe correta\nncode idna string encoding\n ou use o comando help"
                    )

            else:
                pass
            try:
                pass

            except IndexError:
                print("verificar a saida")
Example #42
0
 def parse_iso_node_id(cls, data):
     tmp = binascii.b2a_hex(data).decode('utf-8')
     chunks, chunk_size = len(tmp), len(tmp) // 3
     return '.'.join([str(tmp[i:i+chunk_size]) for i in range(0, chunks, chunk_size)])
gb.set_brush_ramps(BOARD_A, BRS_A, RAMP, RAMP, 0)

gb.set_mode(BOARD_A, STEPPER_A, MODE)
gb.freq_stepper(BOARD_A, STEPPER_A, FREQ)
gb.set_mode(BOARD_B, STEPPER_B, MODE)
gb.freq_stepper(BOARD_B, STEPPER_B, FREQ)
gb.set_mode(BOARD_B, STEPPER_C, MODE)
gb.freq_stepper(BOARD_B, STEPPER_C, FREQ)

gb.set_endstop(BOARD_A, BRS_A, 2, 2)
gb.set_endstop(BOARD_A, STEPPER_A, 2, 2)
#gb.set_endstop(BOARD_B, STEPPER_B, 2, 2)
#gb.set_endstop(BOARD_B, STEPPER_C, 2, 2)

while True:
    dlen = binascii.b2a_hex(ser.read()).decode('utf-8')
    if dlen=='08' or  dlen=='05' or  dlen=='04':
        dsep = binascii.b2a_hex(ser.read()).decode('utf-8')
        if dsep=='a1':
            dtyp = binascii.b2a_hex(ser.read()).decode('utf-8')
            if   dtyp=='07':
                for i in range(len(btn)):
                    btn[i] = 0
                for i in range(len(btn)):
                    dbtn = int(binascii.b2a_hex(ser.read()).decode('utf-8'),16)
                    if dbtn==0 or dbtn==1 or dbtn==2 or dbtn==3:
                        btn[dbtn] = 1
                # Stop/Up/Down
                if   btn[0]==0 and btn[1]==0:
                    print('Stop')
                    gb.move_brushed(BOARD_A,BRS_A,STOP)
Example #44
0
 def str_to_hex(str):
     return binascii.b2a_hex(str.encode('ascii')).decode('ascii')
import binascii

#Opcodes
WRITE_REQUEST = '12'
WRITE_RESPONSE = '13'
READ_REQUEST = '0a'
READ_RESPONSE = '0b'

btsnoop = open('/home/anon/nest/btsnoop_hci.pcap', 'rb')
capfile = savefile.load_savefile(btsnoop, verbose=True)

print(capfile)

i = 1
for pkt in capfile.packets:
    raw = binascii.b2a_hex(pkt.raw())
    op = ""
    gattHnd = ""
    payload = ""
    detailStr = ""
    if raw[8:10] == '02' and raw[
            22:
            26] == '0400':  #HCI Packet Type: ACL Data (0x02) / L2CAP Protocol ATT (0x0004 little endian)
        opcode = raw[26:28]
        if opcode == WRITE_REQUEST:
            op = "Write Request"
            gattHnd = bytearray(raw[28:32])
            payload = raw[32:]
            if i == 476: op += "!"  # remove
            detailStr = ": Handle 0x" + str(
                gattHnd
Example #46
0
class Tracker:
    def __init__(self, config, rawserver):
        self.response_size = config['response_size']
        self.dfile = config['dfile']
        self.natcheck = config['nat_check']
        self.max_give = config['max_give']
        self.reannounce_interval = config['reannounce_interval']
        self.save_dfile_interval = config['save_dfile_interval']
        self.show_names = config['show_names']
        self.only_local_override_ip = config['only_local_override_ip']
        favicon = config['favicon']
        self.favicon = None
        if favicon:
            if isfile(favicon):
                h = open(favicon, 'rb')
                self.favicon = h.read()
                h.close()
            else:
                print "**warning** specified favicon file -- %s -- does not exist." % favicon
        self.rawserver = rawserver
        self.becache1 = {}
        self.becache2 = {}
        self.cache1 = {}
        self.cache2 = {}
        self.times = {}
        if exists(self.dfile):
            h = open(self.dfile, 'rb')
            ds = h.read()
            h.close()
            tempstate = bdecode(ds)
        else:
            tempstate = {}
        if tempstate.has_key('peers'):
            self.state = tempstate
        else:
            self.state = {}
            self.state['peers'] = tempstate
        self.downloads = self.state.setdefault('peers', {})
        self.completed = self.state.setdefault('completed', {})
        statefiletemplate(self.state)
        for x, dl in self.downloads.items():
            self.times[x] = {}
            for y, dat in dl.items():
                self.times[x][y] = 0
                if not dat.get('nat',1):
                    ip = dat['ip']
                    gip = dat.get('given ip')
                    if gip and is_valid_ipv4(gip) and (not self.only_local_override_ip or is_local_ip(ip)):
                        ip = gip
                    self.becache1.setdefault(x,{})[y] = Bencached(bencode({'ip': ip, 
                        'port': dat['port'], 'peer id': y}))
                    self.becache2.setdefault(x,{})[y] = compact_peer_info(ip, dat['port'])
        rawserver.add_task(self.save_dfile, self.save_dfile_interval)
        self.prevtime = time()
        self.timeout_downloaders_interval = config['timeout_downloaders_interval']
        rawserver.add_task(self.expire_downloaders, self.timeout_downloaders_interval)
        self.logfile = None
        self.log = None
        if (config['logfile'] != '') and (config['logfile'] != '-'):
            try:
                self.logfile = config['logfile']
                self.log = open(self.logfile,'a')
                sys.stdout = self.log
                print "# Log Started: ", isotime()
            except:
                print "Error trying to redirect stdout to log file:", sys.exc_info()[0]
        self.allow_get = config['allow_get']
        if config['allowed_dir'] != '':
            self.allowed_dir = config['allowed_dir']
            self.parse_allowed_interval = config['parse_allowed_interval']
            self.parse_allowed()
        else:
            self.allowed = None
        if unquote('+') != ' ':
            self.uq_broken = 1
        else:
            self.uq_broken = 0
        self.keep_dead = config['keep_dead']

    def get(self, connection, path, headers):
        try:
            (scheme, netloc, path, pars, query, fragment) = urlparse(path)
            if self.uq_broken == 1:
                path = path.replace('+',' ')
                query = query.replace('+',' ')
            path = unquote(path)[1:]
            params = {}
            for s in query.split('&'):
                if s != '':
                    i = s.index('=')
                    params[unquote(s[:i])] = unquote(s[i+1:])
        except ValueError, e:
            return (400, 'Bad Request', {'Content-Type': 'text/plain'}, 
                    'you sent me garbage - ' + str(e))
        if path == '' or path == 'index.html':
            s = StringIO()
            s.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">\n' \
                '<html><head><title>BitTorrent download info</title>\n')
            if self.favicon != None:
                s.write('<link rel="shortcut icon" href="/favicon.ico" />\n')
            s.write('</head>\n<body>\n' \
                '<h3>BitTorrent download info</h3>\n'\
                '<ul>\n'
                '<li><strong>tracker version:</strong> %s</li>\n' \
                '<li><strong>server time:</strong> %s</li>\n' \
                '</ul>\n' % (version, isotime()))
            names = self.downloads.keys()
            if names:
                names.sort()
                tn = 0
                tc = 0
                td = 0
                tt = 0  # Total transferred
                ts = 0  # Total size
                nf = 0  # Number of files displayed
                uc = {}
                ud = {}
                if self.allowed != None and self.show_names:
                    s.write('<table summary="files" border="1">\n' \
                        '<tr><th>info hash</th><th>torrent name</th><th align="right">size</th><th align="right">complete</th><th align="right">downloading</th><th align="right">downloaded</th><th align="right">transferred</th></tr>\n')
                else:
                    s.write('<table summary="files">\n' \
                        '<tr><th>info hash</th><th align="right">complete</th><th align="right">downloading</th><th align="right">downloaded</th></tr>\n')
                for name in names:
                    l = self.downloads[name]
                    n = self.completed.get(name, 0)
                    tn = tn + n
                    lc = []
                    for i in l.values():
                        if type(i) == DictType:
                            if i['left'] == 0:
                                lc.append(1)
                                uc[i['ip']] = 1
                            else:
                                ud[i['ip']] = 1
                    c = len(lc)
                    tc = tc + c
                    d = len(l) - c
                    td = td + d
                    if self.allowed != None and self.show_names:
                        if self.allowed.has_key(name):
                            nf = nf + 1
                            sz = self.allowed[name]['length']  # size
                            ts = ts + sz
                            szt = sz * n   # Transferred for this torrent
                            tt = tt + szt
                            if self.allow_get == 1:
                                linkname = '<a href="/file?info_hash=' + b2a_hex(name) + '">' + self.allowed[name]['name'] + '</a>'
                            else:
                                linkname = self.allowed[name]['name']
                            s.write('<tr><td><code>%s</code></td><td>%s</td><td align="right">%s</td><td align="right">%i</td><td align="right">%i</td><td align="right">%i</td><td align="right">%s</td></tr>\n' \
                                % (b2a_hex(name), linkname, size_format(sz), c, d, n, size_format(szt)))
                    else:
                        s.write('<tr><td><code>%s</code></td><td align="right"><code>%i</code></td><td align="right"><code>%i</code></td><td align="right"><code>%i</code></td></tr>\n' \
                            % (b2a_hex(name), c, d, n))
                ttn = 0
                for i in self.completed.values():
                    ttn = ttn + i
                if self.allowed != None and self.show_names:
                    s.write('<tr><td align="right" colspan="2">%i files</td><td align="right">%s</td><td align="right">%i/%i</td><td align="right">%i/%i</td><td align="right">%i/%i</td><td align="right">%s</td></tr>\n'
                            % (nf, size_format(ts), len(uc), tc, len(ud), td, tn, ttn, size_format(tt)))
                else:
                    s.write('<tr><td align="right">%i files</td><td align="right">%i/%i</td><td align="right">%i/%i</td><td align="right">%i/%i</td></tr>\n'
                            % (nf, len(uc), tc, len(ud), td, tn, ttn))
                s.write('</table>\n' \
                    '<ul>\n' \
                    '<li><em>info hash:</em> SHA1 hash of the "info" section of the metainfo (*.torrent)</li>\n' \
                    '<li><em>complete:</em> number of connected clients with the complete file (total: unique IPs/total connections)</li>\n' \
                    '<li><em>downloading:</em> number of connected clients still downloading (total: unique IPs/total connections)</li>\n' \
                    '<li><em>downloaded:</em> reported complete downloads (total: current/all)</li>\n' \
                    '<li><em>transferred:</em> torrent size * total downloaded (does not include partial transfers)</li>\n' \
                    '</ul>\n')
            else:
                s.write('<p>not tracking any files yet...</p>\n')
            s.write('</body>\n' \
                '</html>\n')
            return (200, 'OK', {'Content-Type': 'text/html; charset=iso-8859-1'}, s.getvalue())
        elif path == 'scrape':
            fs = {}
            names = []
            if params.has_key('info_hash'):
                if self.downloads.has_key(params['info_hash']):
                    names = [ params['info_hash'] ]
                # else return nothing
            else:
                names = self.downloads.keys()
                names.sort()
            for name in names:
                l = self.downloads[name]
                n = self.completed.get(name, 0)
                c = len([1 for i in l.values() if type(i) == DictType and i['left'] == 0])
                d = len(l) - c
                fs[name] = {'complete': c, 'incomplete': d, 'downloaded': n}
                if (self.allowed is not None) and self.allowed.has_key(name) and self.show_names:
                    fs[name]['name'] = self.allowed[name]['name']
            r = {'files': fs}
            return (200, 'OK', {'Content-Type': 'text/plain'}, bencode(r))
        elif (path == 'file') and (self.allow_get == 1) and params.has_key('info_hash') and self.allowed.has_key(a2b_hex(params['info_hash'])):
            hash = a2b_hex(params['info_hash'])
            fname = self.allowed[hash]['file']
            fpath = self.allowed[hash]['path']
            return (200, 'OK', {'Content-Type': 'application/x-bittorrent', 'Content-Disposition': 'attachment; filename=' + fname}, open(fpath, 'rb').read())
        elif path == 'favicon.ico' and self.favicon != None:
            return (200, 'OK', {'Content-Type' : 'image/x-icon'}, self.favicon)
        if path != 'announce':
            return (404, 'Not Found', {'Content-Type': 'text/plain', 'Pragma': 'no-cache'}, alas)
        try:
            if not params.has_key('info_hash'):
                raise ValueError, 'no info hash'
            if params.has_key('ip') and not is_valid_ipv4(params['ip']):
                raise ValueError('DNS name or invalid IP address given for IP')
            infohash = params['info_hash']
            if self.allowed != None:
                if not self.allowed.has_key(infohash):
                    return (200, 'OK', {'Content-Type': 'text/plain', 'Pragma': 'no-cache'}, bencode({'failure reason':
                    'Requested download is not authorized for use with this tracker.'}))
            ip = connection.get_ip()
            ip_override = 0
            if params.has_key('ip') and is_valid_ipv4(params['ip']) and (
                    not self.only_local_override_ip or is_local_ip(ip)):
                ip_override = 1
            if params.has_key('event') and params['event'] not in ['started', 'completed', 'stopped']:
                raise ValueError, 'invalid event'
            port = long(params.get('port', ''))
            uploaded = long(params.get('uploaded', ''))
            downloaded = long(params.get('downloaded', ''))
            left = long(params.get('left', ''))
            myid = params.get('peer_id', '')
            if len(myid) != 20:
                raise ValueError, 'id not of length 20'
            rsize = self.response_size
            if params.has_key('numwant'):
                rsize = min(long(params['numwant']), self.max_give)
        except ValueError, e:
            return (400, 'Bad Request', {'Content-Type': 'text/plain'}, 
                'you sent me garbage - ' + str(e))
for each in chunkname:

    pos = 0

    while (text.find(each, pos + 1) != -1):

        pos = text.find(each, pos + 1)

        if (pos != -1):

            print "%s:0x%x" % (each, pos)

        if (each == 'IHDR'):

            print " Length:0x%s" % (binascii.b2a_hex(text[pos - 4:pos]))

            print " Chunk:0x%s" % (binascii.b2a_hex(text[pos:pos + 4]))

            print " Width:0x%s" % (binascii.b2a_hex(text[pos + 4:pos + 8]))

            print " Height:0x%s" % (binascii.b2a_hex(text[pos + 8:pos + 12]))

            print " BitDepth:0x%s" % (binascii.b2a_hex(
                text[pos + 12:pos + 13]))

            print " ColorType:0x%s" % (binascii.b2a_hex(
                text[pos + 13:pos + 14]))

            print " ComdivssionMethod:0x%s" % (binascii.b2a_hex(
                text[pos + 14:pos + 15]))
Example #48
0
def _new_id():
    """Generate a new random text id with urandom"""
    return b2a_hex(os.urandom(16)).decode('ascii')
Example #49
0
def proxy_wire(server_name, server_port, listen_host, listen_port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((listen_host, listen_port))
    sock.listen(1)
    client_sock, addr = sock.accept()
    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_sock.connect((server_name, server_port))

    # http://dev.mysql.com/doc/internals/en/connection-phase-packets.html

    # initial packet
    server_data = recv_mysql_packet(server_sock)
    client_sock.send(server_data)
    print('S->C initial packets', binascii.b2a_hex(server_data).decode('ascii'))
    r = print_response_type(server_data[4])
    print('   [' + to_ascii(server_data) + ']')

    # initial response (authentication)
    client_data = recv_mysql_packet(client_sock)
    server_sock.send(client_data)
    print('C->S initial response', binascii.b2a_hex(client_data).decode('ascii'))
    print_command_type(client_data[4])
    print('   [' + to_ascii(client_data) + ']')

    # auth result
    server_data = recv_mysql_packet(server_sock)
    client_sock.send(server_data)
    print('S->C auth result', binascii.b2a_hex(server_data).decode('ascii'))
    r = print_response_type(server_data[4])
    print('   [' + to_ascii(server_data) + ']')

    # http://dev.mysql.com/doc/internals/en/packet-OK_Packet.html
    # payload first byte eq 0.
    if server_data[4:6] == b'\x01\x03':
        print("fast auth")
        server_data = recv_mysql_packet(server_sock)
        client_sock.send(server_data)
        print('S->C auth result', binascii.b2a_hex(server_data).decode('ascii'))
    if server_data[4:6] == b'\x01\x04':
        print("full auth")
        client_data = recv_mysql_packet(client_sock)
        server_sock.send(client_data)
        print('C->S', binascii.b2a_hex(client_data).decode('ascii'))
        server_data = recv_mysql_packet(server_sock)
        client_sock.send(server_data)
        print('S->C', binascii.b2a_hex(server_data).decode('ascii'))
        client_data = recv_mysql_packet(client_sock)
        server_sock.send(client_data)
        print('C->S', binascii.b2a_hex(client_data).decode('ascii'))
        server_data = recv_mysql_packet(server_sock)
        client_sock.send(server_data)
        print('S->C auth result', binascii.b2a_hex(server_data).decode('ascii'))
    else:
        assert server_data[4] == 0

    while True:
        client_data = recv_mysql_packet(client_sock)
        server_sock.send(client_data)
        print('C->S', binascii.b2a_hex(client_data).decode('ascii'))
        print_command_type(client_data[4])
        print('   [' + to_ascii(client_data) + ']')
        if client_data[4] == 0x01:      # COM_QUIT
            break

        assert client_data[4] == 0x03   # COM_QUERY

        server_data = recv_mysql_packet(server_sock)
        client_sock.send(server_data)
        print('S->C', binascii.b2a_hex(server_data).decode('ascii'))
        r = print_response_type(server_data[4])
        print('   [' + to_ascii(server_data) + ']')

        if r:
            continue

        print('[Column definition]')
        while True:
            server_data = recv_mysql_packet(server_sock)
            client_sock.send(server_data)
            print('S->C', binascii.b2a_hex(server_data).decode('ascii'))
            r = print_response_type(server_data[4])
            print('   [' + to_ascii(server_data) + ']')
            if r:
                break

        print('[Result Rows]')
        while True:
            server_data = recv_mysql_packet(server_sock)
            client_sock.send(server_data)
            print('S->C', binascii.b2a_hex(server_data).decode('ascii'))
            r = print_response_type(server_data[4])
            print('   [' + to_ascii(server_data) + ']')
            if r:
                break
Example #50
0
 def kdf_vec(inp):
     k = kdf_rfc5869(inp, T_KEY, M_EXPAND, 100)
     print(repr(inp), "\n\""+ binascii.b2a_hex(k)+ "\"")
Example #51
0
def encrypt_RC2_CBC(str, key):
    str = align(str)
    iv = Random.new().read(ARC2.block_size)
    cipher1 = ARC2.new(key, ARC2.MODE_CBC, iv)
    cipher = iv + cipher1.encrypt(str)
    return b2a_hex(cipher)
Example #52
0
def gen_id():
    """
    Generates and returns a random hex-encoded 256-bit unique ID.
    """
    return binascii.b2a_hex(os.urandom(32)).decode('utf8')
Example #53
0
def encrypt_Blowfish_CBC(str, key):
    str = align(str)
    iv = Random.new().read(Blowfish.block_size)
    cipher1 = Blowfish.new(key, Blowfish.MODE_CBC, iv)
    cipher = iv + cipher1.encrypt(str)
    return b2a_hex(cipher)
 def HEX(n):
     return binascii.b2a_hex(n)
def about_mobs(dic1 = mobs_pass_dict, dic2 = mobs_agress_dict):
    for i in dic1:
        print str(i) + ' -> ' + binascii.b2a_hex(dic1.get(i))
    for i in dic2:
        print str(i) + ' -> ' + binascii.b2a_hex(dic2.get(i))
    return
Example #56
0
def encrypt_CAST_CBC(str, key):
    str = align(str)
    iv = Random.new().read(CAST.block_size)
    cipher1 = CAST.new(key, CAST.MODE_CBC, iv)
    cipher = iv + cipher1.encrypt(str)
    return b2a_hex(cipher)
def MRUFOLDER(reg_nt):
    mru_folder_list = []
    mru_folder_count = 0
    mru_folder_order = []
    check_first_third_ch_list = [
        b'\x19\x00\x1F', b'\x3A\x00\x1F', b'\x14\x00\\', b'\x55\x00\x1F'
    ]
    reg_key = reg_nt.find_key(
        r"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\LastVisitedPidlMRU"
    )
    try:
        if reg_key != None:
            for reg_value in reg_key.values():
                if reg_value.name() == 'MRUListEx':
                    for i in range(0, len(list(reg_key.values())) - 1):
                        mru_folder_order.append(
                            int(
                                binascii.b2a_hex(reg_value.data()[4 * i:4 * i +
                                                                  4][::-1]),
                                16))
            for order in mru_folder_order:
                for reg_value in reg_key.values():
                    if reg_value.name() == str(order):
                        mru_folder_information = MRU_Folder_Information()
                        mru_folder_list.append(mru_folder_information)
                        mru_folder_list[mru_folder_count].source_location = []
                        mru_folder_list[mru_folder_count].source_location.append(
                            'NTUSER-SOFTWARE/Microsoft/Windows/CurrentVersion/Explorer/ComDlg32/LastVisitedPidlMRU'
                        )
                        mru_folder_list[
                            mru_folder_count].program_name = reg_value.data(
                            )[0:reg_value.data().find(b'\x00\x00\x00') +
                              1].decode('utf-16')
                        start_data = reg_value.data().find(b'\x00\x00\x00') + 3
                        file = reg_value.data()
                        saved_file = file[start_data:len(file)]
                        (saved_file, first_component, len_of_file,
                         check_first_third_ch, hasAutoPlay, hasDriveLetterSign,
                         hasNetworkDrive,
                         hasFileName) = MRU_Parser().AssignToType(saved_file)

                        if first_component == len_of_file - 2:
                            result = MRU_Parser().RunType4(saved_file)

                        if check_first_third_ch == b'\x19\x00\x1F':
                            start_point = hasDriveLetterSign
                            if start_point < 0:
                                pass
                            else:
                                result = MRU_Parser().RunType2(
                                    saved_file, start_point)
                        if check_first_third_ch == b'\x14\x00\x1F' or check_first_third_ch == b'\x14\x00\\':
                            if hasDriveLetterSign < 0 and hasNetworkDrive < 0:
                                result = MRU_Parser().RunType1(saved_file)
                            elif hasDriveLetterSign < 0 and hasNetworkDrive > 0:
                                result = MRU_Parser().RunType3(saved_file)
                            elif hasDriveLetterSign > 0 and hasNetworkDrive < 0:
                                start_point = hasDriveLetterSign
                                result = MRU_Parser().RunType2(
                                    saved_file, start_point)
                            else:
                                MRU_Parser().isGUIDFolder(saved_file)

                        if check_first_third_ch == b'\x3A\x00\x1F':
                            if MRU_Parser().isGUIDFolder(saved_file) is True:
                                result = MRU_Parser().RunType1(saved_file)
                            else:
                                try:
                                    result = MRU_Parser().RunType1(saved_file)
                                except:
                                    pass

                        if check_first_third_ch == b'\x55\x00\x1F':
                            start_point = hasDriveLetterSign
                            if start_point < 0:
                                pass
                            else:
                                result = MRU_Parser().RunType2(
                                    saved_file, start_point)

                        if MRU_Parser().hasUniqueFileFormat(
                                saved_file) > 0 and hasFileName < 0:
                            result = MRU_Parser().RunType5(saved_file)

                        mru_folder_list[
                            mru_folder_count].accessed_folder = result
                        if mru_folder_count == 0:
                            mru_folder_list[
                                mru_folder_count].modified_time = reg_key.last_written_timestamp(
                                ).isoformat() + 'Z'
                        mru_folder_list[
                            mru_folder_count].registry_order = mru_folder_count + 1
                        mru_folder_list[
                            mru_folder_count].value = reg_value.name()
                        mru_folder_count = mru_folder_count + 1
                        break

    except:
        print('-----MRU Folder Error')

    return mru_folder_list
Example #58
0
def encrypt_SM4_CBC(str, key):
    str = align(str)
    iv = ''.join(random.sample(string.ascii_letters + string.digits, 8))  #8位
    cipher1 = encrypt_cbc(str, key, iv)
    cipher = bytes(cipher1, "utf-8")
    return b2a_hex(cipher)
Example #59
0
def mock_encrypt_secret(cert, secret):
    # Encode secret w/ binascii.hex() to avoid invalid chars in XML.
    # The actual/real return value of the non-mocked encrypt_secret() is in that form.
    # We still keep the "ENCRYPTED(...)" part here to show that clearly in our test outputs.
    secret = binascii.b2a_hex(secret).upper()
    return "ENCRYPTED({0},{1})".format(cert, secret)
Example #60
0
    def parse(cls, value):

        try:
            afi, safi, nexthop_length = struct.unpack('!HBB', value[0:4])
            nexthop_bin = value[4:4 + nexthop_length]
            nlri_bin = value[5 + nexthop_length:]
        except Exception:
            # error when lenght is wrong
            raise excep.UpdateMessageError(
                sub_error=bgp_cons.ERR_MSG_UPDATE_ATTR_LEN, data=repr(value))

        #  Address Family IPv4
        if afi == afn.AFNUM_INET:
            if safi == safn.SAFNUM_LAB_VPNUNICAST:
                # MPLS VPN
                # parse nexthop
                rd_bin = nexthop_bin[0:8]
                rd_type = struct.unpack('!H', rd_bin[0:2])[0]
                rd_value_bin = rd_bin[2:]
                if rd_type == 0:
                    asn, an = struct.unpack('!HI', rd_value_bin)
                    ipv4 = str(
                        netaddr.IPAddress(
                            int(binascii.b2a_hex(nexthop_bin[8:]), 16)))
                    nexthop = {'rd': '%s:%s' % (asn, an), 'str': ipv4}
                # TODO(xiaoquwl) for other RD type decoding
                else:
                    nexthop = repr(nexthop_bin[8:])
                # parse nlri
                nlri = IPv4MPLSVPN.parse(nlri_bin)
                return dict(afi_safi=(afi, safi), nexthop=nexthop, nlri=nlri)
            elif safi == safn.SAFNUM_FSPEC_RULE:
                # if nlri length is greater than 240 bytes, it is encoded over 2 bytes
                nlri_list = []
                while nlri_bin:
                    length = ord(nlri_bin[0])
                    if length >> 4 == 0xf and len(nlri_bin) > 2:
                        length = struct.unpack('!H', nlri_bin[:2])[0]
                        nlri_tmp = nlri_bin[2:length + 2]
                        nlri_bin = nlri_bin[length + 2:]
                    else:
                        nlri_tmp = nlri_bin[1:length + 1]
                        nlri_bin = nlri_bin[length + 1:]
                    nlri = IPv4FlowSpec.parse(nlri_tmp)
                    if nlri:
                        nlri_list.append(nlri)
                if nexthop_bin:
                    nexthop = str(
                        netaddr.IPAddress(
                            int(binascii.b2a_hex(nexthop_bin), 16)))
                else:
                    nexthop = ''
                return dict(afi_safi=(afi, safi),
                            nexthop=nexthop,
                            nlri=nlri_list)
            else:
                nlri = repr(nlri_bin)

        # #  Address Family IPv6
        elif afi == afn.AFNUM_INET6:
            # IPv6 unicast
            if safi == safn.SAFNUM_UNICAST:
                # decode nexthop
                # RFC 2545
                # The value of the Length of Next Hop Network Address field on a
                # MP_REACH_NLRI attribute shall be set to 16, when only a global
                # address is present, or 32 if a link-local address is also included in
                # the Next Hop field.
                #
                # The link-local address shall be included in the Next Hop field if and
                # only if the BGP speaker shares a common subnet with the entity
                # identified by the global IPv6 address carried in the Network Address
                # of Next Hop field and the peer the route is being advertised to.
                nexthop_addrlen = 16
                has_link_local = False
                nexthop = str(
                    netaddr.IPAddress(
                        int(binascii.b2a_hex(nexthop_bin[:nexthop_addrlen]),
                            16)))
                if len(nexthop_bin) == 2 * nexthop_addrlen:
                    # has link local address
                    has_link_local = True
                    linklocal_nexthop = str(
                        netaddr.IPAddress(
                            int(
                                binascii.b2a_hex(
                                    nexthop_bin[nexthop_addrlen:]), 16)))
                nlri = IPv6Unicast.parse(nlri_bin)
                if has_link_local:
                    return dict(afi_safi=(afi, safi),
                                nexthop=nexthop,
                                linklocal_nexthop=linklocal_nexthop,
                                nlri=nlri)
                else:
                    return dict(afi_safi=(afi, safi),
                                nexthop=nexthop,
                                nlri=nlri)
            elif safi == safn.SAFNUM_LAB_VPNUNICAST:
                # IPv6 MPLS VPN
                # parse nexthop
                rd_bin = nexthop_bin[0:8]
                rd_type = struct.unpack('!H', rd_bin[0:2])[0]
                rd_value_bin = rd_bin[2:]
                if rd_type == 0:
                    asn, an = struct.unpack('!HI', rd_value_bin)
                    ipv6 = str(
                        netaddr.IPAddress(
                            int(binascii.b2a_hex(nexthop_bin[8:]), 16)))
                    nexthop = {'rd': '%s:%s' % (asn, an), 'str': ipv6}
                # TODO(xiaoquwl) for other RD type decoding
                else:
                    nexthop = repr(nexthop_bin[8:])
                # parse nlri
                nlri = IPv6MPLSVPN.parse(nlri_bin)
                return dict(afi_safi=(afi, safi), nexthop=nexthop, nlri=nlri)
            else:
                return dict(afi_safi=(afi, safi),
                            nexthop=nexthop_bin,
                            nlri=nlri_bin)

        # for l2vpn
        elif afi == afn.AFNUM_L2VPN:
            if safi == safn.SAFNUM_EVPN:
                nexthop = str(
                    netaddr.IPAddress(int(binascii.b2a_hex(nexthop_bin), 16)))
                nlri = EVPN.parse(nlri_bin)
                return dict(afi_safi=(afi, safi), nexthop=nexthop, nlri=nlri)
            else:
                nlri = repr(nlri_bin)

        else:
            nlri = repr(nlri_bin)

        return dict(afi_safi=(afi, safi), nexthop=nexthop_bin, nlri=nlri_bin)