示例#1
0
    def test_with_ascii_file_only(self):
        print("************ ASCII IN ****************")
        with open(TEST_ASCII_IPM_FILENAME, "rb") as ascii_file:
            ascii_data = ascii_file.read()
            hexdump.hexdump(ascii_data)

        args = self.parser.parse_args(["convert", "-s", "ascii", TEST_ASCII_IPM_FILENAME])
        _main(args)

        # Convert file with DE55 in it
        args = self.parser.parse_args(["convert", "-s", "ascii", "build/test/test_ascii_de55_ipm.in"])
        _main(args)

        print("************ EBCDIC IN ****************")
        with open(TEST_ASCII_IPM_FILENAME + ".out", "rb") as ebcdic_file:
            ebcdic_data = ebcdic_file.read()
            hexdump.hexdump(ebcdic_data)

        args = self.parser.parse_args(["convert", TEST_ASCII_IPM_FILENAME + ".out"])
        _main(args)

        with open(TEST_ASCII_IPM_FILENAME + ".out.out", "rb") as ascii2_file:
            ascii2_data = ascii2_file.read()

        self.assertEqual(ascii2_data, ascii_data)
示例#2
0
文件: ctf.py 项目: notclu/ctf
def send(sock, data, dump=True):
    sock.sendall(data)
    print("\nSent len=%d (0x%X)\n>>>>>>>>>>>>>>>>\n" % (len(data), len(data)))
    if dump:
        hexdump.hexdump(data)
    else:
        print data
示例#3
0
 def parse(self, r):
     from hexdump import hexdump
     hexdump(str(r.data))
     try:
         self.ocsp_response = parse_ocsp_response(str(r.data))
     except Exception as error:
         log.error('Error parsing OCSP response: {0}'.format(error))
示例#4
0
文件: parsers.py 项目: rpcope1/PyDNS
def parse_dns_message(raw_data):
    transaction_id, flags, question_count, answer_rr_count, authority_rr_count, additional_rr_count = \
        struct.unpack("!HHHHHH", raw_data[:12])
    print
    hexdump.hexdump(raw_data)
    header = DNSHeader(transaction_id, flags, question_count, answer_rr_count, authority_rr_count, additional_rr_count)
    print header
    current_index = 12
    questions = [None]*question_count
    answer_rrs = [None]*answer_rr_count
    authority_rrs = [None]*authority_rr_count
    additional_rrs = [None]*additional_rr_count
    print "Questions"
    for i in xrange(question_count):
        question, current_index = parse_dns_question(raw_data, current_index)
        questions[i] = question
    print "Answers"
    for i in xrange(answer_rr_count):
        answer, current_index = parse_dns_rr(raw_data, current_index)
        answer_rrs[i] = answer
    print "Authorities"
    for i in xrange(authority_rr_count):
        authority, current_index = parse_dns_rr(raw_data, current_index)
        authority_rrs[i] = authority
    print "Additional"
    for i in xrange(additional_rr_count):
        additional_rr, current_index = parse_dns_rr(raw_data, current_index)
        additional_rrs[i] = additional_rr
    message = DNSMessage(header, questions, answer_rrs, authority_rrs, additional_rrs)
    return message
示例#5
0
def decrypt(bytes, From="Client"):
    cleartext = b""
    if is_fast_path(bytes):
        is_encrypted = (bytes[0] >> 7 == 1)
        has_opt_length = (bytes[1] >= 0x80)
        offset = 2
        if has_opt_length:
            offset += 1
        if is_encrypted:
            offset += 8
            cleartext = rc4_decrypt(bytes[offset:], From=From)
    else: # slow path
        offset = 13
        if len(bytes) <= 15: return bytes
        if bytes[offset] >= 0x80: offset += 1
        offset += 1
        security_flags = struct.unpack('<H', bytes[offset:offset+2])[0]
        is_encrypted = (security_flags & 0x0008)
        if is_encrypted:
            offset += 12
            cleartext = rc4_decrypt(bytes[offset:], From=From)

    if not cleartext == b"":
        if args.debug:
            print("Cleartext: ")
            hexdump(cleartext)
        return bytes[:offset] + cleartext
    else:
        return bytes
示例#6
0
 def OnOpen(self, event):
     openFileDialog = wx.FileDialog(self, "Open .exe file", "", "", "All files (*.*)|*.*", wx.FD_OPEN)
     if openFileDialog.ShowModal() == wx.ID_OK:
         filename = openFileDialog.GetPath()
         self.progress()
         pef = pefile.PE(filename)
         l1 = open('<filepath of your choice to store the log file .txt extension>','w')
         sys.stdout = l1
         print pef
         l2 = open('<filepath of your choice to store the log file .txt extension>','w')
         sys.stdout = l2
         hexdump(open(filename,'rb'))
         l = open(filename,'rb')
         b = l.read()
         l3 = open('<filepath of your choice to store the log file .txt extension>','w') #hash_value
         l3.write(hashlib.md5(b).hexdigest())
         hash = hashlib.md5(b).hexdigest()
         #get registered with Virustotal api and get an API key
         params = {'apikey': '<apikey>'}
         files = {'file': (filename, open(filename, 'r+'))}
         response_up = requests.post('http://www.virustotal.com/vtapi/v2/file/scan', files=files, params=params)
         params = {'apikey': '<apikey>','resource': hash}
         response_down = requests.get('https://www.virustotal.com/vtapi/v2/file/report', params=params)
         json_response = response_down.json()
         l4 = open('<filepath of your choice to store the log file .txt extension>','w')
         sys.stdout = l4
         print json_response
         if 'True' in open('<filepath of your choice to store the log file .txt extension>','r').read():
             print "\n\nTHE FILE IS A PACKER MALWARE"
         else:
             print "\n\nThis file needs to be analysed"
示例#7
0
文件: ctf.py 项目: notclu/ctf
def recv(sock, recv_len=1024, dump=True):
    data = sock.recv(recv_len)
    print("\nReceived len=%d (0x%X)\n<<<<<<<<<<<<<<<\n" % (len(data), len(data)))
    if dump:
        hexdump.hexdump(data)
    else:
        print(data)
    return data
def hexOutput(hex_location_blob):
    print "Hexdump Output:"
    print "----------------------------------------------------------------------------"
    print hexdump.hexdump(hex_location_blob)
    print "----------------------------------------------------------------------------"
    print "Hex Output: "
    print "[" + binascii.hexlify(hex_location_blob) + "]"
    print "----------------------------------------------------------------------------"
示例#9
0
 def _zmq_worker(self):
     while True:
         metadata_str, eth_bytes = self.zs.recv_multipart()
         metadata = json.loads(metadata_str)
         print("===== Packet: %s =====" % metadata)
         print("Ethernet Frame (%d bytes)" % len(eth_bytes))
         hexdump.hexdump(eth_bytes)
         self._accept(metadata)
示例#10
0
 def handle_packet(self, packet):
   try:
     message = self.message_from_packet(packet)
     self.handle_message(message)
   except (BadPacket, DeserializationError, struct.error) as ex:
     if self.config.dump_bad_packet:
       print("got: %s" % str(ex))
       hexdump.hexdump(packet.load)
       sys.stdout.flush()
示例#11
0
 def save(self):
   # WRITE 4: 09 53 00 5C
   # READ 4: 09 00 00 09 
   packet = struct.pack('BB', 9, 0x53)
   self.send(packet)
   ret = self.recv(2)
   if ret != "\x09\x00":
     print "Didn't get ack?"
     hexdump(ret)
示例#12
0
    def hex(self, path=None):
        """Display the contents of a zNode as an hexadecimal dump."""
        self.connect()
        path, stat = self._check_path(path)
        if not stat.data_length:
            return

        data, _ = self._zk.get(path)
        hexdump.hexdump(data)
示例#13
0
 def test_block(self):
     linebreakdata = []
     for x in range(0, 73):
         linebreakdata.append(b("1234567890"))
     output = mciutil.block(linebreakdata)
     hexdump.hexdump(output)
     input = mciutil.unblock(output)
     print(len(input))
     print(input)
def decrypt_lines(body, OrderID):
    print "encrypted:"
    hexdump.hexdump(body)

    key="\xcd\xc5\x7e\xad\x28\x5f\x6d\xe1\xce\x8f\xcc\x29\xb1\x21\x88\x8e"
    
    IV=struct.pack("iiBBBBBBBB", OrderID, -OrderID, 0x79, 0xc1, 0x69, 0xb, 0x67, 0xc1, 0x4, 0x7d)
    buf=frobenoid.AES_CFB_decryption(key, IV, body)
    print "plain:"
    hexdump.hexdump(buf)
示例#15
0
文件: ctf_socket.py 项目: notclu/ctf
    def send(self, data, dump=True):
        self.sock.sendall(data)

        print("\nSent len=%d (0x%X)\n>>>>>>>>>>>>>>>>\n" % (len(data), len(data)))

        dump = dump if dump else self.dump
        if dump:
            hexdump.hexdump(data)
        else:
            print data
示例#16
0
 def handle_packet(self, packet):
   try:
     message = self._message_from_packet(packet)
     if not self.config.excluded(message.opcode):
       for h in self._handlers_for(message):
         h(message)
   except (BadPacket, DeserializationError, struct.error) as ex:
     if self.config.dump_bad_packet:
       print("got: %s" % str(ex))
       hexdump.hexdump(packet.load)
       sys.stdout.flush()
示例#17
0
 def recv(self, len):
   # len is the data, not including the checksum
   packet = self.s.read(len + 2)
   cksum = self.cksum(packet[:-2])
   if cksum != struct.unpack('>H', packet[-2:])[0]:
     print hex(cksum), hex(struct.unpack('>H', packet[-2:])[0])
     print "cksum missmatch?!?"
     hexdump(packet)
     print hex(cksum)
     return None
   return packet[:-2]
示例#18
0
文件: ctf_socket.py 项目: notclu/ctf
    def recv(self, recv_len=1024, dump=None):
        data = self.sock.recv(recv_len)
        print("\nReceived len=%d (0x%X)\n<<<<<<<<<<<<<<<\n" % (len(data), len(data)))

        dump = dump if dump else self.dump
        if dump:
            hexdump.hexdump(data)
        else:
            print(data)

        return data
示例#19
0
def main(serial_port, key_rev, write):
    """Megadump dumps and writes Megatouch iButton keys"""
    with SerialConnection(serial_port) as bp:
        # Set up some variables
        ibutton = b''
        key_file = (key_rev+'.pickle')

        if write:
            # Write data to iButton
            click.secho('\nWriting key from {}.\n'.format(key_file), fg='blue')
            k = pickle.load(open(key_file, "rb"))
            pprint(k)
            #
            # TODO: Insert code to write keys here.
            #

        else:
            # Dump the iButton key contents
            try:
                k = eval(key_rev)
            except NameError:
                k = UNKNOWN

            click.secho('\nDumping contents of key.\n', fg='blue')
            # Send commands reset (CC), read scratch (69), start addr,
            # inverted start addr. Then rec 64 bytes. 
            k['scratch'] = cmd_data(bp, b'\xCC\x69\xC0\x3F', 64)
            click.echo('Scratchpad:')
            hexdump.hexdump(k.get('scratch'))
            click.echo()

            for idx, n in enumerate([0,64,128]):
                # Calculate memory ID to send to iButton
                mem_id = struct.pack("B", (n+16))
                mem_id_oc = struct.pack("B", (n+16) ^ 0xFF)

                # Send commands reset (CC), read subkey (69), key+start addr,
                # key+start addr inverted. Rec. 8 byte key ID in response.
                k['k_id'].append(cmd_data(bp, b'\xCC\x66'+mem_id+mem_id_oc, 8))
                click.echo('Subkey {} id 0x{} ({}):'.format(idx, k['k_id'][idx].hex(), k['k_id'][idx]))
                # Send password then rec. 48 bytes from secure memory
                k['mem'].append(cmd_data(bp, k["password"][idx], 48, rst=False))
                hexdump.hexdump(k['mem'][idx])
                click.echo()

            # write key information to file
            if os.path.isfile(key_file):
                click.confirm('Dump file already exists, overwrite it?', abort=True)
            f = open(key_file, 'wb')
            pickle.dump(k, f)
            f.close()
            click.echo('Wrote key to {}/{}'.format(os.getcwd(), key_file))

    print()
示例#20
0
def readurl(url, header=1, content=1, showurl=0, hexcontent=0):
    furl = urllib.urlopen(url)
    if showurl:
        print "URL retrieved:", furl.geturl()
    if header:
        print furl.info()
    if hexcontent:
        import hexdump
        hexdump.hexdump(furl)
    elif content:
        print furl.read()
示例#21
0
def dump_data(data, From=None, Modified=False):
    if args.debug:
        modified = ""
        if Modified:
            modified = " (modified)"
        if From == "Server":
            print("From server:"+modified)
        elif From == "Client":
            print("From client:"+modified)

        hexdump(data)
示例#22
0
 def list_files(self):
   s = self.s
   s.write("~!F")
   data = ''
   while True:
     c = s.read(1)
     if ord(c) == 0x1a:
       break
     data += c
   hexdump.hexdump(data)
   data = data.split(chr(0x0d))
   print data
示例#23
0
def _flip_element_encoding(bit_config, message_data, source_format):
    """
    Converts a field in an iso8583 style message from ascii to ebcdic

    :param bit_config: dict of field iso8583 bits mapping
    :param message_data: the message containing the field
    :param source_format: encoding of source -- ebcdic or ascii
    :returns: converted string
    :returns: pointer to next field in message

    """

    flipped_element = b("")

    field_length = bit_config['field_length']
    print("processing field {0}".format(bit_config["field_name"]))

    length_size = _get_field_length(bit_config)

    if length_size > 0:
        field_length_string = message_data[:length_size]
        print("field_length_string {0}, {1}".format(length_size, field_length_string))
        if source_format == 'ebcdic':
            field_length_string = _convert_text_eb2asc(field_length_string)
            field_length = int(field_length_string)
        else:
            field_length = int(field_length_string)
            field_length_string = _convert_text_asc2eb(field_length_string)

        flipped_element += field_length_string

    field_data = message_data[length_size:length_size+field_length]

    field_processor = _set_parameter(bit_config,
                                     'field_processor')
    # flip except for ICC field
    if field_processor != 'ICC':
        if source_format == 'ebcdic':
            converted_data = _convert_text_eb2asc(field_data)
        else:
            converted_data = _convert_text_asc2eb(field_data)
        if len(field_data) != len(converted_data):
            raise Exception(
                "Conversion returned different lengths\n{0}\n{1}".format(
                    hexdump.hexdump(field_data, result="return"),
                    hexdump.hexdump(converted_data, result='return')
                )
            )
        flipped_element += converted_data
    else:  # Add ICC data as is
        flipped_element += field_data

    return flipped_element, field_length + length_size
示例#24
0
  def handle_packet(self, packet):
    sampling = self.config.sampling
    if sampling < 1.0 and random() > sampling:
      return

    try:
      message = self.message_from_packet(packet)
      self.handle_message(message)
    except (BadPacket, StringTooLong, DeserializationError, struct.error) as ex:
      if self.config.dump_bad_packet:
        print("got: %s" % str(ex))
        hexdump.hexdump(packet.load)
        sys.stdout.flush()
示例#25
0
def ParseFinderPlist(MRUFile):
    plistfile = open(MRUFile, "rb")
    plist = ccl_bplist.load(plistfile)

    print "[MRUs are listed from Newest to Oldest (ie: Item 0 - Item 9)]"
    for n,item in enumerate(plist["FXRecentFolders"]):
        print "    [Item Number: " + str(n) + "] '" + item["name"] + "'"
        
        if args.blob == True:
            print "----------------------------------------------------------------------------"
            print "Hexdump of Bookmark BLOB: "
            print hexdump.hexdump(item["file-bookmark"])
            print "----------------------------------------------------------------------------"
示例#26
0
def b64decode_hexdump(value, default=""):
    if isinstance(value, unicode):
        return hexdump.hexdump(
            value.decode('base64'),
            result='return'
        )
    elif isinstance(value, str):
        return hexdump.hexdump(
            unicode(value).decode('base64'),
            result='return'
        )
    else:
        return default
示例#27
0
  def upload_file(self, file):
    filename = os.path.basename(file).upper()
    fh = open(file, "rb")
    data = fh.read()
    comm =  "DOWNLOAD \"%s\",%d," % (filename, len(data))
    print comm
    data = comm + data
    print len(data)
    hexdump.hexdump(data)
    self.s.write(comm + data)
#  s.flush()
    print "wait: ", self.s.inWaiting()
#  hexdump.hexdump(s.read())
    self.status()
示例#28
0
    def hexdump(self):
        """Prints structure's data in hex format.

        >>> 00000000: 46 49 4C 45 30 00 03 00  EA 22 20 00 00 00 00 00  \
        FILE0...." .....
        >>> 00000010: 01 00 01 00 38 00 01 00  A0 01 00 00 00 04 00 00  \
        ....8...........
        >>> 00000020: 00 00 00 00 00 00 00 00  06 00 00 00 00 00 00 00  \
        ................

        See More:
            https://bitbucket.org/techtonik/hexdump/
        """
        hexdump.hexdump(self._data)
示例#29
0
 def handle_packet(self, packet):
   try:
     message = self._message_from_packet(packet)
     for h in self._handlers:
       h(message)
   except (BadPacket, struct.error) as ex:
     if self._dump_bad_packet:
       print("got: %s" % str(ex))
       hexdump.hexdump(packet.load)
       sys.stdout.flush()
   except Exception as ex:
     print("got: %s" % str(ex))
     hexdump.hexdump(packet.load)
     sys.stdout.flush()
def encrypt(data):
    # nounce + countr - 16 bytes 
    # key / user id   - 16 bytes 
    # data            - n bytes 
    nonce = data[:8]
    count = data[8:16]
    key = data[16:32]
    l = int(100)
    try:
        l = int(data[32])
    except:
        pass
    print "l: " + str(l)

    enc = ""
    c = Counter.new(64, initial_value=0, prefix=nonce)
    e = AES.new(key, AES.MODE_ECB)
    n_blocks = int(math.ceil(l*8/128.0))
    for n in xrange(n_blocks):
        enc = enc + e.encrypt(str(c()))

    print "Nonce: "
    hexdump.hexdump(nonce)
    print "Count: "
    hexdump.hexdump(count)
    print "Key: "
    hexdump.hexdump(key)
    print "Enc: "
    hexdump.hexdump(enc)

    return enc
示例#31
0
 if sock in republish_socks:
     republish_socks[sock].send(msg)
 if args.map and evt.which() == 'liveLocation':
     print('send loc')
     socketio.emit(
         'location', {
             'lat': evt.liveLocation.lat,
             'lon': evt.liveLocation.lon,
             'alt': evt.liveLocation.alt,
         })
 if not args.no_print:
     if args.pipe:
         sys.stdout.write(msg)
         sys.stdout.flush()
     elif args.raw:
         hexdump(msg)
     elif args.json:
         print(json.loads(msg))
     elif args.dump_json:
         print(json.dumps(evt.to_dict()))
     elif values:
         print("logMonotime = {}".format(evt.logMonoTime))
         for value in values:
             if hasattr(evt, value[0]):
                 item = evt
                 for key in value:
                     item = getattr(item, key)
                 print("{} = {}".format(".".join(value), item))
         print("")
     else:
         print(evt)
示例#32
0
文件: tv.py 项目: anjeloarnav/THM
import sys, hexdump, binascii
from Crypto.Cipher import AES


class AESCipher:
    def __init__(self, key):
        self.key = key

    def decrypt(self, iv, data):
        self.cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self.cipher.decrypt(data)


key = binascii.unhexlify("0602000000a400005253413100040000")
iv = binascii.unhexlify("0100010067244F436E6762F25EA8D704")
hex_str_cipher = "871C158E545657D6D714B34730465D85E4A5F96D3E6CCF47AE7310A3FC41AA4A18ADFE594917DD1847A810EFF8C13356"  #Query

ciphertext = binascii.unhexlify(hex_str_cipher)
raw_un = AESCipher(key).decrypt(iv, ciphertext)
print(hexdump.hexdump(raw_un))
password = raw_un.decode('utf-16')
print(password)
示例#33
0
    host = "f.%s.%s.%s" % (encfile, offset, domain)
    ips = socket.gethostbyname_ex(host)[2]
    ips.sort(key=lambda x: int(x.split(".")[0]) & 0x0f)
    datalen = 0
    for i in ips:
        b = i.split(".")
        thislen = (int(b[0]) >> 4)
        for n in xrange(thislen):
            data.append(chr(int(b[1:][n])))
        datalen += thislen

    return (datalen, "".join(data))


stat = 1
filelen = 0
if args.out == "-":
    f = sys.stdout
else:
    f = open(args.out, "w")
while stat:
    (stat, dat) = dns_get_file_data(args.domain, args.file, filelen)
    if dohexdump and (args.hex != 0):
        hexdump.hexdump(dat)
        print ""
    else:
        print "%d bytes." % stat
    filelen += stat
    f.write(dat)
f.close()
示例#34
0
 def __init__(self, binary_data):
     with io.StringIO() as buf, redirect_stdout(buf):
         generator = hexdump.hexdump(binary_data, 'generator')
         for line in generator:
             print('| ' + line)
         self.hex_string = buf.getvalue()
示例#35
0
datasize = struct.unpack('>L' , data[44:48])[0]  

totalsize = hdrsize + datasize

sha1data = bytearray(totalsize)
sha1data[:] = data[:totalsize]


for x in range(0,256):
    sha1data[52+x] = 0

decrypted = enc.encrypt(binascii.unhexlify((hcrypt)),None)[0]


print 'decrypted : '
hexdump.hexdump(decrypted)



for x in range(0,len(decrypted)) : 
    if  decrypted[x] == b'\x00' :
          p = x +1
          break


hmac = binascii.hexlify( decrypted[p:len(decrypted)])
#print hmac 
digest = hashlib.sha1(sha1data).hexdigest()
#print digest

#if hmac == digest : 
示例#36
0
    parser = argparse.ArgumentParser(description='Sniff a communcation socket')
    parser.add_argument('--raw', action='store_true')
    parser.add_argument('--json', action='store_true')
    parser.add_argument('--addr', default='127.0.0.1')
    parser.add_argument("socket", type=str, nargs='*', help="socket name")
    args = parser.parse_args()

    for m in args.socket if len(args.socket) > 0 else service_list:
        if m in service_list:
            messaging.sub_sock(context,
                               service_list[m].port,
                               poller,
                               addr=args.addr)
        elif m.isdigit():
            messaging.sub_sock(context, int(m), poller, addr=args.addr)
        else:
            print("service not found")
            exit(-1)

    while 1:
        polld = poller.poll(timeout=1000)
        for sock, mode in polld:
            if mode != zmq.POLLIN:
                continue
            if args.raw:
                hexdump(sock.recv())
            elif args.json:
                print(json.loads(sock.recv()))
            else:
                print messaging.recv_one(sock)
示例#37
0
#!/usr/bin/python

import serial
import time
import sys
import hexdump

ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=0)

while True:
    # ser.write("hello")
    s = ser.read(32)
    hexdump.hexdump(s)
    #for i in range(0,len(s)):
    #  c = s[i]
    #  print "%#04x" % ord(c)
    time.sleep(0.5)
示例#38
0
def hex_dump(mu, address, size):
    data = mu.mem_read(address, size)
    return hexdump.hexdump(data)
示例#39
0
def dump(title, data):
    if debug and data:
        print('[-- %s --]' % (title))
        hexdump.hexdump(data)
示例#40
0
#!/usr/bin/env python
import sys, hexdump, array

def xor_strings(s,t):
    # https://en.wikipedia.org/wiki/XOR_cipher#Example_implementation
    """xor two strings together"""
    return "".join(chr(ord(a)^ord(b)) for a,b in zip(s,t))

key=array.array('B', [144, 160, 33, 80, 79, 143, 251, 255, 133, 131, 207, 86, 65, 18, 122, 249, 49]).tostring()

def chunks(l, n):
    n = max(1, n)
    return [l[i:i + n] for i in range(0, len(l), n)]

def read_file(fname):
    file=open(fname, mode='rb')
    content=file.read()
    file.close()
    return content

content=read_file(sys.argv[1])
tmp=chunks(content, 17)
for t in tmp:
    hexdump.hexdump(t)
    print xor_strings (t, key)

示例#41
0
            supported <<= 1
        pid += 0x20
        if pid not in ret:
            break
    return ret


if __name__ == "__main__":
    panda = Panda()
    panda.set_safety_mode(Panda.SAFETY_ELM327)
    panda.can_clear(0)

    # 09 02 = Get VIN
    isotp_send(panda, "\x09\x02", 0x7e0)
    ret = isotp_recv(panda, 0x7e8)
    hexdump(ret)
    print "VIN: %s" % ret[2:]

    # 03 = get DTCS
    isotp_send(panda, "\x03", 0x7e0)
    dtcs = isotp_recv(panda, 0x7e8)
    print "DTCs:", dtcs[2:].encode("hex")

    supported_pids = get_supported_pids()
    print "Supported PIDs:", supported_pids

    while 1:
        speed = struct.unpack(">B", get_current_data_for_pid(13)[2:])[0]  # kph
        rpm = struct.unpack(">H",
                            get_current_data_for_pid(12)[2:])[0] / 4.0  # revs
        throttle = struct.unpack(
示例#42
0
                    type=float,
                    help='Time to sleep between repetitions in seconds')
parser.add_argument(
    'f',
    type=str,
    help=
    'File containing the conversation until the format string vulnerability vector'
)
args = parser.parse_args()

print args.n

sys.exit(1)

context.log_level = 'error'
if len(sys.argv) != 3:
    print 'Usage: ./prog <number of repetitions> <number of words to print> <time to sleep between repetitions in seconds>'
    sys.exit(2)

H, P = 'localhost', 6666
pre = ''
with open(args.f, 'r') as f:
    pre = f.read()

#H,P='pwnbox',1337
for i in range(args.n):
    r = remote(H, P)
    dump = get64(r, pre, args.w)
    hexdump.hexdump(dump.decode('hex'))
    time.sleep(args.t)
示例#43
0
    # Decrypt, parse and print data file(s)
    if file_rcdata:
        dfiles = {}
        logger.info("[+] Processing data files")
        data_files = decrypt(file_rcdata, script_key)
        if data_files[0:4] == "PK\x03\x04":
            logger.info("[+] Data files are compressed")
            dfiles = unzip(data_files)
        else:
            dfiles = get_files(data_files)

        for name, content in dfiles.items():
            h = get_sha(content)
            print("\nData file: {0} [{1}]".format(name, h))
            hexdump(content[:128])
            if dump_files:
                write_file(args.dump, name, content)

    # Decrypt, parse and print library file(s)
    if library_rcdata:
        lfiles = {}
        logger.info("[+] Processing library files")
        library_files = decrypt(library_rcdata, script_key)
        if library_files[0:4] == "PK\x03\x04":
            logger.info("[+] Library files are compressed")
            lfiles = unzip(library_files)
        else:
            lfiles = get_files(library_files)

        for name, content in lfiles.items():
示例#44
0
    def handleData(self, event):
        """
        This is called every time we receive a data frame
        """

        # inform our h2connection that we have received N bytes and the space
        # should be handed back to the remote side at an opportune time
        self.h2conn.acknowledge_received_data(len(event.data), event.stream_id)

        data = event.data
        stream_id = event.stream_id

        if not self.accept_phase:  # "wait" phase
            if stream_id == 1:
                # this is the RESPONSE_TYPE=1 message. Maybe we should validate
                # this, but I don't think we need to do so right now, so we're just
                # gonna ignore it
                xpc_wrapper, data = XpcWrapper.from_bytes(data)
                if xpc_wrapper == None:
                    return
                xpc_stream = XPCByteStream(data)
                xpc_obj = XPC_Root(xpc_stream)
                response = xpc_obj.value.value.get("RESPONSE_TYPE", None)
                if response == None:
                    return
                print("Received XPC object on stream %d:" % stream_id)
                print(xpc_wrapper)
                print(xpc_obj)
                # we need to get the number of bytes to be transferred and the filename
                self.file_tx_size = xpc_obj.value.value[
                    "FILE_TX"].transfer_size
                self.sysdiagnose_filename = xpc_obj.value.value[
                    "FILE_NAME"].value
                self.response_received = True
            elif stream_id == 2:
                # we need to open stream 2 and then send an empty reply with the
                # correct msg_id so the data transfer can start
                xpc_wrapper, data = XpcWrapper.from_bytes(data)
                if xpc_wrapper == None:
                    return
                if not xpc_wrapper.flags == 0x100001:
                    return
                print("Received XPC object on stream %d:" % stream_id)
                print(xpc_wrapper)
                msg_id = xpc_wrapper.msg_id
                print("Opening stream %d for file transfer, msg_id=%d" %
                      (stream_id, msg_id))
                self.openStreamForFileTX(stream_id, msg_id)
                self.file_stream_open = True
            else:  # we don't care about any messages on any other stream
                return

            if self.response_received and self.file_stream_open:
                print("moving to accept phase")
                self.accept_phase = True

        else:  # "accept" phase
            # we should only be getting messages on stream 2 until we get an
            # empty frame
            if stream_id != 2:
                return
            if len(data) > 0:
                print("New data frame on stream %d:" % stream_id)
                hexdump.hexdump(data[:32])
                self.bytes_received += len(data)
                print("%d bytes of %d" %
                      (self.bytes_received, self.file_tx_size))
                if DUMP_FILE:
                    self.sysdiagnose_bytes.append(data)
            else:
                self.h2conn.end_stream(stream_id)
                self.h2conn.send_data(1, b"")
                if DUMP_FILE:
                    # write out sysdiagnose file
                    with open(self.sysdiagnose_filename, "wb") as f:
                        for b in self.sysdiagnose_bytes:
                            f.write(b)
                self.endConnection()
示例#45
0
                (SUB_VEC3 1 0 0)
            )
        )
        (IF_EQ v 199
            (
                (ADD_VEC3 1 0 0)
            )
        )
        (SHOW_HSV)
    )
    """

    vm_parser = LEDEffectVMParser()
    led_programs = {
        "init": vm_parser.parse_asm(init_prog),
        "main": vm_parser.parse_asm(main_prog),
    }
    vm = LEDEffectVM(led_programs, num_pixels=64)

    for prog in led_programs:
        print(prog, led_programs[prog])
        byte_code_as_bytes = bytes([])
        for word in led_programs[prog]:
            byte_code_as_bytes += bytes([word & 0xff, word >> 8 & 0xff])
        hexdump.hexdump(byte_code_as_bytes)

    vm.execute_program('init')
    for i in range(300):
        vm.execute_program('main')
    print(vm.pixels)
 def _connect(self, mu, fd, addr, addr_len):
     print(hexdump.hexdump(mu.mem_read(addr, addr_len)))
     return -1
示例#47
0
def initCuckoo(sampleFile):
    global proc
    if not os.path.isfile(misc_config.PATH_IFCONFIG):
        misc_config.PATH_IFCONFIG = '/sbin/ifconfig'

    try:
        net = subprocess.check_output([misc_config.PATH_IFCONFIG])
        if not "vboxnet0" in net:
            subprocess.call([
                "vboxmanage", "hostonlyif", "ipconfig", settings.VBOX_DEV,
                "--ip", settings.VBOX_IP, "--netmask", settings.VBOX_NETM
            ])

    except:
        print "Error during check for running VMs"
        if misc_config.ENABLE_SENTRY_LOGGING:
            client.captureException()

    print 'Starting CUCKOO SERVER'
    try:
        proc = subprocess.Popen(['python2', settings.CUCKOO_SERVER],
                                stdout=subprocess.PIPE,
                                stdin=subprocess.PIPE,
                                stderr=subprocess.STDOUT)
    except:
        print "Error starting cuckoo server"
        if misc_config.ENABLE_SENTRY_LOGGING:
            client.captureException()

    print 'Starting CUCKOO SUBMIT'
    try:
        #print sampleFile
        proc2 = subprocess.Popen(
            ["python2", settings.CUCKOO_SUBMIT, sampleFile],
            stdout=subprocess.PIPE,
            stdin=subprocess.PIPE,
            stderr=subprocess.PIPE)
        results = proc2.communicate()
    except:
        print "Error in sample submission"
        if misc_config.ENABLE_SENTRY_LOGGING:
            client.captureException()

    regex_cuckooID = r'added as task with ID (\d+)'
    try:
        results = re.findall(regex_cuckooID, results[0])
    except:
        print "Error finding task ID"
        if misc_config.ENABLE_SENTRY_LOGGING:
            client.captureException()

    if len(results) < 1:
        if misc_config.ENABLE_SENTRY_LOGGING:
            client.captureMessage(
                'ERROR: Could not submit sample to cuckoo-droid!')
        print 'ERROR: Could not submit sample to cuckoo-droid!'
        return None

    if len(results) > 1:
        if misc_config.ENABLE_SENTRY_LOGGING:
            client.captureMessage(
                'ERROR: Somehow, cuckoo-droid returned two TASK IDs. Please revise this output: '
            )
        print 'ERROR: Somehow, cuckoo-droid returned two TASK IDs. Please revise this output: '
        from hexdump import hexdump
        for idx, result in enumerate(results):
            print 'RESULT ID {}'.format(idx)
            hexdump(result)
        return None

    cuckooID = results[0]
    return cuckooID
示例#48
0
if __name__ == "__main__":
    layout = None
    rf = None

    with open("test_layout.yaml") as file_name:
        layout = yaml.safe_load(file_name.read())
    with open("test_rf_config.yaml") as file_name:
        rf = yaml.safe_load(file_name.read())

    settings = SettingsGenerator(layout_data=layout, rf_settings=rf)

    target_layout_id = 0x30

    print("settings:")
    try:
        hexdump.hexdump(bytes(settings.gen_settings_section(target_layout_id)))
    except ParseError as e:
        print(e)
        # print(e.with_traceback())
        exit(1)

    print("layout:")
    try:
        hexdump.hexdump(bytes(settings.gen_layout_section(target_layout_id)))
    except ParseError as e:
        print(e)
        exit(1)

    print()
    print()
    settings = RFSettings.from_rand()
示例#49
0
文件: ekc_data.py 项目: mo10/keyplus
    def size(self):
        return self.current_size

    def to_bytes(self):
        total_size = self.size()
        if total_size > 0xFFFF:
            raise ValueError(
                "EKC data section too large: {} bytes".format(total_size))

        result = bytearray(0)

        # first byte is the total size of the data
        result += struct.pack('<H', total_size)

        # after append all the children
        for (i, child) in enumerate(self.children):
            result += child.to_bytes()

        return result

    pack = to_bytes


if __name__ == '__main__':
    ekc_data = EKCDataTable()
    ekc_data.add_child(EKCData([1, 2, 3]))
    sticky_ent = EKCHoldKey(keycodes.KC_ENTER, keycodes.KC_STICKY_LSHIFT)
    ekc_data.add_child(sticky_ent)

    hexdump(ekc_data.to_bytes())
示例#50
0
def beauty_print(data):
    hexdump.hexdump(data)
示例#51
0
# mod to make the header okay
# MH_CIGAM_64 is good
from macholib import MachO
a = MachO.MachO("model.hwx")

# load commands
for c in a.headers[0].commands:
  print(c[0])
  if c[0].cmd == 25:
    print(c[1])
    for section in c[2]:
      print(section.segname.strip(b'\0'), section.sectname.strip(b'\0'), hex(section.addr), hex(section.size), "@", hex(c[1].fileoff))
      #print(dir(section))
      if c[1].filesize > 0:
        hexdump(section.section_data)

# this parser is wrong (fixed with 64-bit one)
from macholib import SymbolTable
sym = SymbolTable.SymbolTable(a) 

syms = {}
for l in sym.nlists:
  print(l)
  if l[0].n_value != 0:
    syms[l[1]] = l[0].n_value

for k,v in syms.items():
  print(k, hex(v))

示例#52
0
 def from_bytes(cls, raw_bytes: bytes):
     source_port, target_port, size = struct.unpack("!HHH", raw_bytes[:6])
     data = hexdump.hexdump(raw_bytes[8:], "return")
     raw = raw_bytes
     return cls(source_port, target_port, size, data, raw)
示例#53
0
#!/usr/bin/env python3
from panda import Panda
from hexdump import hexdump

DEBUG = False

if __name__ == "__main__":
    p = Panda()

    len = p._handle.controlRead(Panda.REQUEST_IN, 0x06, 3 << 8 | 238, 0, 1)
    print('Microsoft OS String Descriptor')
    dat = p._handle.controlRead(Panda.REQUEST_IN, 0x06, 3 << 8 | 238, 0,
                                len[0])
    if DEBUG: print('LEN: {}'.format(hex(len[0])))
    hexdump("".join(map(chr, dat)))

    ms_vendor_code = dat[16]
    if DEBUG: print('MS_VENDOR_CODE: {}'.format(hex(len[0])))

    print('\nMicrosoft Compatible ID Feature Descriptor')
    len = p._handle.controlRead(Panda.REQUEST_IN, ms_vendor_code, 0, 4, 1)
    if DEBUG: print('LEN: {}'.format(hex(len[0])))
    dat = p._handle.controlRead(Panda.REQUEST_IN, ms_vendor_code, 0, 4, len[0])
    hexdump("".join(map(chr, dat)))

    print('\nMicrosoft Extended Properties Feature Descriptor')
    len = p._handle.controlRead(Panda.REQUEST_IN, ms_vendor_code, 0, 5, 1)
    if DEBUG: print('LEN: {}'.format(hex(len[0])))
    dat = p._handle.controlRead(Panda.REQUEST_IN, ms_vendor_code, 0, 5, len[0])
    hexdump("".join(map(chr, dat)))
示例#54
0
from struct import pack
from hexdump import hexdump


def make_chunk(id, data):
    if len(id) != 4:
        raise "id wrong length"
    if len(data) % 2 == 1:
        pstr = ">4sI" + str(len(data)) + "sc"
        return pack(pstr, id, len(data), data, "\x00")
    else:
        pstr = ">4sI" + str(len(data)) + "s"
        return pack(pstr, id, len(data), data)


def make_sub_chunk(id, data):
    if len(id) != 4:
        raise "id wrong length"
    if len(data) > 65535:
        raise "subchunk too long"
    pstr = ">4sH" + str(len(data)) + "s"
    return pack(pstr, id, len(data), data)


if __name__ == "__main__":
    hexdump(make_chunk("FISH", "\xee"))
    hexdump(make_chunk("FISH", "\xee\xbb"))
    hexdump(make_chunk("FISH", "\xee\xbb\xaa"))
    hexdump(make_chunk("FISH", "\x00\xff\x00lkshdflkhfdglsjhfdg\x00"))
    hexdump(make_sub_chunk("FISH", "\x00\xff\x00lkshdflkhfdglsjhfdg\x00"))
示例#55
0
    def on_message(self, message, data):
        if 'payload' not in message:
            print(message)
            return

        what = message['payload']
        parts = what.split(':::')
        if len(parts) < 2:
            print(what)
            return

        cmd = parts[0]
        if cmd == 'backtrace':
            if self.app.get_session_ui(
            ) is not None and self.app.get_backtrace_panel() is not None:
                try:
                    self.app.get_backtrace_panel().set_backtrace(
                        json.loads(parts[1]))
                except:
                    pass
        elif cmd == 'enumerate_java_classes_start':
            if self.app.get_java_classes_panel() is not None:
                self.app.get_java_classes_panel().on_enumeration_start()
        elif cmd == 'enumerate_java_classes_match':
            if self.app.get_java_classes_panel() is not None:
                self.app.get_java_classes_panel().on_enumeration_match(
                    parts[1])
        elif cmd == 'enumerate_java_classes_complete':
            self.app_window.get_menu().on_java_classes_enumeration_complete()
            if self.app.get_java_classes_panel() is not None:
                self.app.get_java_classes_panel().on_enumeration_complete()
        elif cmd == 'enumerate_java_methods_complete':
            Dwarf.bus.emit(parts[1], json.loads(parts[2]))
        elif cmd == 'ftrace':
            if self.app.get_ftrace_panel() is not None:
                self.app.get_ftrace_panel().append_data(parts[1])
        elif cmd == 'log':
            self.app.get_log_panel().log(parts[1])
        elif cmd == 'hook_java_callback':
            h = Hook(Hook.HOOK_JAVA)
            h.set_ptr(1)
            h.set_input(parts[1])
            if self.java_pending_args:
                h.set_condition(self.java_pending_args['condition'])
                h.set_logic(self.java_pending_args['logic'])
                self.java_pending_args = None
            self.java_hooks[h.get_input()] = h
            self.app.get_hooks_panel().hook_java_callback(h)
        elif cmd == 'hook_native_callback':
            h = Hook(Hook.HOOK_NATIVE)
            h.set_ptr(int(parts[1], 16))
            h.set_input(self.temporary_input)
            self.temporary_input = ''
            if self.native_pending_args:
                h.set_condition(self.native_pending_args['condition'])
                h.set_logic(self.native_pending_args['logic'])
                self.native_pending_args = None
            self.hooks[h.get_ptr()] = h
            self.app.get_hooks_panel().hook_native_callback(h)
        elif cmd == 'hook_onload_callback':
            h = Hook(Hook.HOOK_ONLOAD)
            h.set_ptr(0)
            h.set_input(parts[1])

            self.on_loads[parts[1]] = h
            if self.app.session_ui is not None and self.app.get_hooks_panel(
            ) is not None:
                self.app.get_hooks_panel().hook_onload_callback(h)
        elif cmd == 'memory_scan_match':
            Dwarf.bus.emit(parts[1], parts[2], json.loads(parts[3]))
        elif cmd == 'memory_scan_complete':
            self.app_window.get_menu().on_bytes_search_complete()
            Dwarf.bus.emit(parts[1] + ' complete', 0, 0)
        elif cmd == 'onload_callback':
            self.loading_library = parts[1]
            self.app.get_log_panel().log('hook onload %s @thread := %s' %
                                         (parts[1], parts[3]))
            self.app.get_hooks_panel().hit_onload(parts[1], parts[2])
        elif cmd == 'set_context':
            data = json.loads(parts[1])
            self.app.get_contexts().append(data)

            if 'context' in data:
                sym = ''
                if 'pc' in data['context']:
                    name = data['ptr']
                    if 'moduleName' in data['symbol']:
                        sym = '(%s - %s)' % (data['symbol']['moduleName'],
                                             data['symbol']['name'])
                else:
                    name = data['ptr']
                self.app.get_contexts_panel().add_context(
                    data, library_onload=self.loading_library)
                # check if data['reason'] is 0 (REASON_HOOK)
                if self.loading_library is None and data['reason'] == 0:
                    self.log('hook %s %s @thread := %d' %
                             (name, sym, data['tid']))
                if len(self.app.get_contexts()
                       ) > 1 and self.app.get_registers_panel().have_context():
                    return
                self.app.get_session_ui().request_session_ui_focus()
            else:
                self.app.set_arch(data['arch'])
                if self.app.get_arch() == 'arm':
                    self.app.pointer_size = 4
                else:
                    self.app.pointer_size = 8
                self.pid = data['pid']
                self.java_available = data['java']
                self.app.get_log_panel().log('injected into := ' +
                                             str(self.pid))
                self.app_window.on_context_info()

            self.app.apply_context(data)
            if self.loading_library is not None:
                self.loading_library = None
        elif cmd == 'set_data':
            key = parts[1]
            if data:
                self.app.get_data_panel().append_data(
                    key, hexdump(data, result='return'))
            else:
                self.app.get_data_panel().append_data(key, str(parts[2]))
        elif cmd == 'tracer':
            panel = self.app.get_trace_panel()
            if panel is not None:
                # safely checked later
                panel.start()

                trace_events_parts = parts[1].split(',')
                while len(trace_events_parts) > 0:
                    t = TraceEvent(trace_events_parts.pop(0),
                                   trace_events_parts.pop(0),
                                   trace_events_parts.pop(0),
                                   trace_events_parts.pop(0))
                    panel.event_queue.append(t)
        elif cmd == 'update_modules':
            self.app.apply_context({
                'tid': parts[1],
                'modules': json.loads(parts[2])
            })
        elif cmd == 'update_ranges':
            self.app.apply_context({
                'tid': parts[1],
                'ranges': json.loads(parts[2])
            })
        elif cmd == 'watcher':
            exception = json.loads(parts[1])
            self.log('watcher hit op %s address %s @thread := %s' %
                     (exception['memory']['operation'],
                      exception['memory']['address'], parts[2]))
        elif cmd == 'watcher_added':
            if self.app.get_watchers_panel() is not None:
                self.app.get_watchers_panel().add_watcher_callback(parts[1])
        elif cmd == 'watcher_removed':
            if self.app.get_watchers_panel() is not None:
                self.app.get_watchers_panel().remove_watcher_callback(parts[1])
        else:
            print(what)
def main_ampdu():
    # "Requests" Python library: http://docs.python-requests.org/en/master/user/advanced/
    #session = requests.Session()
    count = 1
    ip_count = 0

    printd(clr(Color.BLUE, "Building container..."), Level.INFO)
    """ Build container """
    container = ''
    for i in range(0, 2):
        count = (count + 1) % 1024
        ip_count = (ip_count % 255) + 1

        # Ping from attacker --> victim
        # You need to change the MAC addresses and IPs to match the remote AP
        ampdu_pkt = AMPDUPacket('ff:ff:ff:ff:ff:ff', '64:D1:A3:3D:26:5B',
                                '64:D1:A3:3D:26:5B', 0x02)

        printd(clr(Color.YELLOW, "Radiotap (rt):"), Level.INFO)
        #sys.stdout.flush()
        #hexdump.hexdump(str(ampdu_pkt.rt))  #this was valid for python2
        #hexdump.hexdump(bytes(ampdu_pkt.rt))

        #for character in str(ampdu_pkt.rt):
        # this prints "\x 00 \x 00 \x 12 \x 00 \x 2e \x 08 \x 00 \x 00 \x 00 \x 6c \x 6c \x 09 \x c0 \x 00 \x c0 \x 01 \x 00 \x 00 "
        #print "\\x",character.encode('hex'),   #does not work in python3
        #sys.stdout.flush()
        print("", Level.INFO)  #print a linefeed

        printd(clr(Color.YELLOW, "dot11hdr:"), Level.INFO)
        #sys.stdout.flush()
        #hexdump.hexdump(str(ampdu_pkt.dot11hdr))
        sys.stdout.flush()

        # add an MSDU to the AMPDU
        ampdu_pkt.add_msdu(
            ping_packet(count, "10.0.0.1", "192.168.0." + str(ip_count)))
        printd(clr(Color.YELLOW, "AMPDU with the MSDU added:"), Level.INFO)
        #sys.stdout.flush()
        #hexdump.hexdump(str(ampdu_pkt))
        sys.stdout.flush()

        ampdu_pkt.add_padding(8)
        printd(
            clr(Color.YELLOW,
                "AMPDU with MSDU and 8 padding delimiters added:"), Level.INFO)
        #sys.stdout.flush()
        #hexdump.hexdump(str(ampdu_pkt))
        sys.stdout.flush()

        container += str(ampdu_pkt)

        # Beacon from attacker --> victim
        #ampdu_pkt = ssid_packet()
        #container += str(ampdu_pkt)

        # Ping from victim --> access point
        #ampdu_pkt = AMPDUPacket('4C:5E:0C:9E:82:19', 'f8:1a:67:1b:14:00', '4C:5E:0C:9E:82:19')
        #ampdu_pkt.add_msdu(ping_packet(count, "192.168.88.254", "10.0.0." + str(ip_count)))
        #ampdu_pkt.add_padding(8)
        #container += str(ampdu_pkt)
    """ end package """
    printd(clr(Color.BLUE, "Final A-MPDU built:"), Level.INFO)
    sys.stdout.flush()

    #hexdump.hexdump('\x00'*16)
    #hexdump.hexdump("Hello world")
    hexdump.hexdump(container)
    sys.stdout.flush()

    #for character in container:
    # this prints "\x 80 \x 04 \x bb \x 4e \x 88 \x 02 \x 00 \x 00 \x ff \x ff \x ff \x ff \x ff \x ff \x 64 "
    #print "\\x",character.encode('hex'),   #does not work in python3
    #print character, character.encode('hex'),
    print("", Level.INFO)  #print a linefeed

    # send the packet a number of times
    for i in range(0, 10):
        # send the packet
        ampdu_pkt.send()  #the interface has to be in monitor mode
        printd("packet sent", Level.INFO)
        time.sleep(0.1)
    """
encrypt_data_length = encrypt_data[0:4]

encrypt_data_length = int.from_bytes(encrypt_data_length,
                                     byteorder='big',
                                     signed=False)

encrypt_data_l = encrypt_data[4:len(encrypt_data)]

data1 = encrypt_data_l[0:encrypt_data_length - 16]
signature = encrypt_data_l[encrypt_data_length - 16:encrypt_data_length]
iv_bytes = bytes("abcdefghijklmnop", 'utf-8')

dec = decrypt(data1, iv_bytes, signature, SHARED_KEY, HMAC_KEY)

counter = dec[0:4]
counter = int.from_bytes(counter, byteorder='big', signed=False)
print("counter:{}".format(counter))

dec_length = dec[4:8]
dec_length = int.from_bytes(dec_length, byteorder='big', signed=False)
print("任务返回长度:{}".format(dec_length))

de_data = dec[8:len(dec)]
Task_type = de_data[0:4]
Task_type = int.from_bytes(Task_type, byteorder='big', signed=False)
print("任务输出类型:{}".format(Task_type))

print(de_data[4:dec_length].decode('utf-8'))

print(hexdump.hexdump(dec))
示例#58
0
#rdstr[0x114:0x118] = b'\x66\x66\x66\x66' # <--- proof of landing

o = open('connect', 'rb')
data = o.read()
o.close

print len(data)

for x in range(0, len(data)):
    rdstr[0x110 + x] = data[x]

#rdstr[0x114:len(data)] = data

#hexdump.hexdump(data)
#print '---------------------------------------------------------------------'
hexdump.hexdump(str(rdstr))

UDP_IP = "239.255.255.250"
UDP_PORT = 1900
MESSAGE =   "M-SEARCH * HTTP/1.1\r\n"\
            "Host:239.255.255.250:1900\r\n"\
            "ST:\"uuid:schemas:device:" + rdstr + ":end\"\r\n"\
            "Man:\"ssdp:discover\"\r\n"\
            "MX:2\r\n\r\n"

print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP

sock.setsockopt(socket.SOL_SOCKET, 25, 'eth1')
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
示例#59
0
def get_animation_info(filename):
    animation_list = []

    with open(filename, "rb") as infile:
        _, sheets, animations, sprites, sprite_info_offset, animations_offset = struct.unpack(
            "<HHHHII", infile.read(0x10))

        for i in range(animations):
            infile.seek(animations_offset + (i * 0x04))
            offset = struct.unpack("<I", infile.read(0x04))[0]

            infile.seek(offset)

            cur_anim_frames = []

            print("File", i)

            while True:
                block_data = infile.read(0x24)
                infile.seek(-0x24, 1)

                print()
                print("Data")
                import hexdump
                hexdump.hexdump(block_data)

                anim_type, anim_id, anim_format, opacity, start_frame, end_frame, frame_offset = struct.unpack(
                    "<HHHHHHI", infile.read(0x10))
                sprite_x, sprite_y, position_info_offset = struct.unpack(
                    "<HHI", infile.read(0x08))
                zoom_info_offset, fade_info_offset, rotation_info_offset = struct.unpack(
                    "<III", infile.read(0x0c))

                positions = transforms.read_position_block(
                    infile, position_info_offset, start_frame, end_frame)
                zooms = transforms.read_zoom_block(infile, zoom_info_offset,
                                                   start_frame, end_frame)
                fades = transforms.read_fade_block(infile, fade_info_offset,
                                                   start_frame, end_frame)
                rotations = transforms.read_rotation_block(
                    infile, rotation_info_offset, start_frame, end_frame)

                cur_anim_frames.append({
                    'anim_type':
                    anim_type,
                    'anim_id':
                    anim_id,
                    'anim_format':
                    anim_format,
                    'position':
                    positions,
                    'zooms':
                    zooms,
                    'fades':
                    fades,
                    'rotations':
                    rotations,
                    'opacity':
                    opacity / 100 if opacity <= 100 else 1.0,
                    'x':
                    sprite_x,
                    'y':
                    sprite_y,
                    'start_frame':
                    start_frame,
                    'end_frame':
                    end_frame,
                    'frame_offset':
                    frame_offset,
                })

                if anim_id == 0xffff:
                    break

            # Fix end frame since overflow frames are also a thing apparently
            # Find metadata frame
            max_end_frame = 0
            metadata_frame = None
            for idx, frame in enumerate(cur_anim_frames):
                if frame['end_frame'] > max_end_frame:
                    max_end_frame = frame['end_frame']

                if frame['anim_type'] == 0xffff:
                    metadata_frame = idx

            if metadata_frame is None:
                print("Couldn't find metadata frame")
                exit(1)

            cur_anim_frames[idx]['end_frame'] = max_end_frame

            animation_list.append({
                'anim_id': i,
                'frames': cur_anim_frames[::-1],
            })

    return animation_list
示例#60
0
def dump_response(data, description):
    print(f'-------------- {description} ----------------')
    hexdump(data)