Python hexdump.hexdump() Examples

The following are 30 code examples of hexdump.hexdump(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module hexdump , or try the search function .
Example #1
Source File: wasm-disassembler.py    From WebAssembly with Apache License 2.0 6 votes vote down vote up
def disassemble_block(raw, idx, *args, **kwargs):
    stream = raw[:]

    print("[+] sub_%04x {" % idx)

    if kwargs.get("show_as_hexdump", False) == True:
        hexdump.hexdump(stream)

    else:
        idx = 0
        while idx < len(stream):
            insn = WasmInstruction(stream[idx:])
            print("{:08x}  {:16s}  {}".format(idx, insn.hexdump, str(insn), ))
            idx += insn.length
    print("}")

    del stream
    return 
Example #2
Source File: sdb_dump_patch.py    From python-sdb with Apache License 2.0 6 votes vote down vote up
def dump_patch(bits, arch=ARCH_32):
    ps = GreedyVArray(sdb.PATCHBITS)
    ps.vsParse(bits.value.value)

    for i, _ in ps:
        p = ps[int(i)]

        print("  opcode: %s" % str(p["opcode"]))
        print("  module name: %s" % p.module_name)
        print("  rva: 0x%08x" % p.rva)
        print("  unk: 0x%08x" % p.unknown)

        print("  payload:")
        print(hexdump.hexdump(str(p.pattern), result="return"))

        print("  disassembly:")
        for l in disassemble(str(p.pattern), p.rva, arch=arch):
            print("    " + l)
        print("") 
Example #3
Source File: templateinterface.py    From polymorph with GNU General Public License v2.0 6 votes vote down vote up
def _dump(self, command):
        """Dumps the packet/template bytes in different formats."""
        if len(command) == 1:
            hexdump.hexdump(self._t.raw)
            print("")
            return
        # Parsing the arguments
        cp = CommandParser(TemplateInterface._dump_opts())
        args = cp.parse(command)
        if not args:
            Interface._argument_error()
            return
        if args["-hex"]:
            hexdump.hexdump(self._t.raw)
            print("")
        elif args["-b"]:
            print(str(self._t.raw), "\n")
        elif args["-hexstr"]:
            print(hexdump.dump(self._t.raw), "\n")
        elif args["-h"]:
            Interface.print_help(TemplateInterface._dump_help()) 
Example #4
Source File: omni_sniffer.py    From zktraffic with Apache License 2.0 6 votes vote down vote up
def handle_packet(self, packet):
    try:
      message = self.message_from_packet(packet)
      sniffer = self._find_sniffer_for_packet(packet)
      sniffer.handle_message(message)
      self.handle_message(message)
    except (BadPacket, struct.error) as ex:
      if self._dump_bad_packet:
        print("got: %s" % str(ex))
        hexdump.hexdump(packet.load)
        traceback.print_exc()
        sys.stdout.flush()
    except Exception as ex:
      print("got: %s" % str(ex))
      hexdump.hexdump(packet.load)
      traceback.print_exc()
      sys.stdout.flush() 
Example #5
Source File: mbr.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def mbr_parsing(self, image):
        file_mbr = self.save_mbr(image)
        self.extract_hexa(hexdump.hexdump(open(file_mbr, 'rb').read(512), "return"))
        try:
            cap1 = self.mbrHexa.decode("hex")
            self.mbrStruct = self.mbr.parse(cap1)
            return self.mbrStruct
        except Exception as inst:
            self.logger.error("Error MBR Parsing") 
Example #6
Source File: vbr.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def vbrDisassembly(self):
        l = Decode(0x000, self.vbr, Decode16Bits)
        assemblyCode = ""
        for (offset, size, instruction, hexdump) in l:
            assemblyCode = assemblyCode + "%.8x: %-32s %s" % (offset, hexdump, instruction) + "\n"
        with open(os.path.join(self.dest,"vbr_AssemblyCode.txt"), "w") as f:
            f.write(assemblyCode) 
Example #7
Source File: mbr.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def boot_loader_disassembly(self):
        l = Decode(0x000, self.mbrStruct.bootloaderCode, Decode16Bits)
        assembly_code = ""
        for (offset, size, instruction, hexdump) in l:
            assembly_code = assembly_code + "%.8x: %-32s %s" % (offset, hexdump, instruction) + "\n"
        h_file = open(self.path + os.path.sep + "bootLoaderAssemblyCode.txt", "w")
        h_file.write(assembly_code)
        h_file.close() 
Example #8
Source File: environment_settings.py    From Fastir_Collector with GNU General Public License v3.0 5 votes vote down vote up
def save_boot_sector(self, image):
        try:
            file_image = open(image, "rb")
            file_boot = open(self.path + os.path.sep + "boot sector", "w")
            file_boot.write(hexdump.hexdump(file_image.read(512), "return"))
            file_image.close()
            file_boot.close()
        except Exception as inst:
            self.logger.error("Extracting mbr failed")
        return file_boot.name 
Example #9
Source File: memrepl.py    From memrepl with MIT License 5 votes vote down vote up
def format_string(data, format):
    if format == "hex":
        return hexdump.hexdump(data, result="return")

    elif format == "u8":
        format = "B"

    elif format == "u16":
        format = "H"

    elif format == "u32":
        format = "I"

    elif format == "u64":
        format = "Q"

    out = []
    unpacked_data = struct.unpack(format, data)
    for d, f in zip(unpacked_data, format):
        size = struct.calcsize(f)
        if isinstance(d, int) or isinstance(d, long):
            if size == 1:
                out.append("0x%.2x" % d)
            elif size == 2:
                out.append("0x%.4x" % d)
            elif size == 4:
                out.append("0x%.8x" % d)
            elif size == 8:
                out.append("0x%.16x" % d)

        else:
            out.append(str(d))

    return " ".join(out) 
Example #10
Source File: image4.py    From grandmaster with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def dumpiBootHeader(decryptedFilePath):
	try:
		with open(str(decryptedFilePath), 'rb') as decryptedFile:
			decryptedFile.seek(0x200)
			decryptedFileData = decryptedFile.read(0x90)
			hexdump.hexdump(decryptedFileData)
	except OSError as e:
		LOGGING.PRINT("couldn't open file for hexump!") 
Example #11
Source File: explore_btree.py    From python-idb with Apache License 2.0 5 votes vote down vote up
def do_cat(self, line):
        """
        display the contents of an entry.

        example::

            > ls
            leaf: true
            entry    key
            -------  -----------------------------------------
            0x0      b'$ MAX LINK'
            0x1      b'$ MAX NODE'
            0x2      b'$ NET DESC'
            0x3      nodeid: 0 tag: S index: 0x3e8
            0x4      nodeid: 0 tag: S index: 0x3e9
            ...
            ----  ------------------------------------------------------------------------------------------
            > cat 3
            00000000: 3B 20 46 69 6C 65 20 4E  61 6D 65 20 20 20 3A 20  ; File Name   :
            00000010: 5A 3A 5C 68 6F 6D 65 5C  75 73 65 72 5C 44 6F 63  Z:\\home\\user\\Doc
            00000020: 75 6D 65 6E 74 73 5C 63  6F 64 65 5C 70 79 74 68  uments\\code\\pyth
            00000030: 6F 6E 2D 69 64 62 5C 74  65 73 74 73 5C 64 61 74  on-idb\\tests\dat
            00000040: 61 5C 73 6D 61 6C 6C 5C  73 6D 61 6C 6C 2E 62 69  a\\small\\small.bi
            00000050: 6E 00
        """
        if " " in line:
            part = line.partition(" ")[0]
        else:
            part = line
        target = int(part, 0x10)

        entry = self.current_page.get_entry(target)
        hexdump.hexdump(entry.value) 
Example #12
Source File: tweetentro.py    From tweetentropy with GNU General Public License v3.0 5 votes vote down vote up
def on_status(self, status):
        global BUF

        BUF += status.text.encode('utf-8')
        if len(BUF) > BUF_MIN_SIZE:
            hexdump.hexdump(BUF)
            add_entropy(BUF)
            BUF = "" 
Example #13
Source File: args.py    From Seth with MIT License 5 votes vote down vote up
def hexdump(x): print(hexlify(x).decode()) 
Example #14
Source File: QuincyScan.py    From quincy with GNU General Public License v3.0 5 votes vote down vote up
def __hexdump_vad_start(self, pid, vadStart):
        for process in self.processes:
            if process.Id == pid:
                data = process.read(vadStart, QuincyConfig.HEXDUMP_BYTES)
                hexdump.hexdump(data)
                return 
Example #15
Source File: nc_connection.py    From voltha with Apache License 2.0 5 votes vote down vote up
def dataReceived(self, data):
        log.debug('data-received', len=len(data),
                  received=hexdump(data, result='return'))
        assert len(data)
        self.rx.put(data) 
Example #16
Source File: nc_connection.py    From voltha with Apache License 2.0 5 votes vote down vote up
def send_msg(self, msg, new_framing):
        assert self.connected
        # Apparently ssh has a bug that requires minimum of 64 bytes?
        # This may not be sufficient to fix this.
        if new_framing:
            msg = "#{}\n{}\n##\n".format(len(msg), msg)
        else:
            msg += C.DELIMITER
        for chunk in self.chunkit(msg, self.max_chunk - 64):
            log.info('sending', chunk=chunk,
                     framing="1.1" if new_framing else "1.0")
            # out = hexdump(chunk, result='return')
            self.transport.write('{}\n'.format(chunk)) 
Example #17
Source File: of_connection.py    From voltha with Apache License 2.0 5 votes vote down vote up
def dataReceived(self, data):
        log.debug('data-received', len=len(data),
                  received=hexdump(data, result='return'))

        assert len(data)  # connection close shall be handled by the protocol
        buf = self.read_buffer
        if buf:
            buf += data
        else:
            buf = data

        offset = 0
        while offset < len(buf):
            if offset + 8 > len(buf):
                break  # not enough data for the OpenFlow header

            # parse the header to get type
            _version, _type, _len, _xid = \
                loxi.of14.message.parse_header(buf[offset:])

            ofp = loxi.protocol(_version)

            if (offset + _len) > len(buf):
                break  # not enough data to cover whole message

            rawmsg = buf[offset : offset + _len]
            offset += _len

            msg = ofp.message.parse_message(rawmsg)
            if not msg:
                log.warn('could-not-parse',
                         data=hexdump(rawmsg, result='return'))
            log.debug('received-msg', module=type(msg).__module__,
                  name=type(msg).__name__, xid=msg.xid, len=len(buf))
            self.rx.put(msg)

        if offset == len(buf):
            self.read_buffer = None
        else:
            self.read_buffer = buf[offset:]
            log.debug('remaining', len=len(self.read_buffer)) 
Example #18
Source File: of_connection.py    From voltha with Apache License 2.0 5 votes vote down vote up
def send(self, msg):
        """
        Send a message
        :param msg: An OpenFlow protocol message
        :return: None
        """
        assert self.connected

        if msg.xid is None:
            msg.xid = self._gen_xid()
        buf = msg.pack()
        log.debug('sending', module=type(msg).__module__,
                  name=type(msg).__name__, xid=msg.xid, len=len(buf))
        self.transport.write(buf)
        log.debug('data-sent', sent=hexdump(buf, result='return')) 
Example #19
Source File: wasm-disassembler.py    From WebAssembly with Apache License 2.0 5 votes vote down vote up
def hexdump(self):
        return " ".join(["{:02x}".format(_) for _ in self.raw]) 
Example #20
Source File: dataformat.py    From chepy with GNU General Public License v3.0 5 votes vote down vote up
def from_hexdump(self):
        """Convert hexdump back to str
        
        Returns:
            Chepy: The Chepy object. 
        """
        self.state = hexdump.restore(self._convert_to_str())
        return self 
Example #21
Source File: hp_imc_dbman_conf_BackHoseIp_stack_overflow_73_E0605P06.py    From poc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_cmd(s, cmd, data):
  req = mk_msg(cmd, data)
  print "Command %d request:" % (cmd)
  print hexdump.hexdump(req)
    
  s.send(req)
  res = s.recv(1024)
  print "Command %d response:" % (cmd)
  print hexdump.hexdump(res) 
Example #22
Source File: hp_imc_dbman_conf_cmd_injection_73_E0605P06.py    From poc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_cmd(cmd, data, host, port, timeout=5):
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.settimeout(timeout)
  s.connect((host, port))

  req = mk_msg(cmd, data)
  print "Command %d request:" % (cmd)
  print hexdump.hexdump(req)
    
  s.send(req)
  res = s.recv(1024)
  s.close()
  print "Command %d response:" % (cmd)
  print hexdump.hexdump(res) 
Example #23
Source File: hp_imc_dbman_conf_cmd_injection_73_e0703.py    From poc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_cmd(cmd, data, host, port, timeout=5):
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.settimeout(timeout)
  s.connect((host, port))

  req = mk_msg(cmd, data)
  print "Command %d request:" % (cmd)
  print hexdump.hexdump(req)
    
  s.send(req)
  res = s.recv(1024)
  s.close()
  print "Command %d response:" % (cmd)
  print hexdump.hexdump(res) 
Example #24
Source File: hp_imc_dbman_conf_BackHoseIp_stack_overflow_after_restart_73_e0703.py    From poc with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_cmd(s, cmd, data):
  req = mk_msg(cmd, data)
  print "Command %d request:" % (cmd)
  print hexdump.hexdump(req)
    
  s.send(req)
  res = s.recv(1024)
  print "Command %d response:" % (cmd)
  print hexdump.hexdump(res) 
Example #25
Source File: slippstream.py    From libmelee with GNU Lesser General Public License v3.0 5 votes vote down vote up
def read_message(self):
        """ Read an entire message from the registered socket.

        Returns None on failure, Dict of data from ubjson on success.
        """
        while True:
            try:
                # The first 4 bytes are the message's length
                #   read this first
                while len(self.buf) < 4:
                    self.buf += self.server.recv(4 - len(self.buf))
                    if len(self.buf) == 0:
                        return None
                message_len = unpack(">L", self.buf[0:4])[0]

                # Now read in message_len amount of data
                while len(self.buf) < (message_len + 4):
                    self.buf += self.server.recv((message_len + 4) - len(self.buf))

                try:
                    # Exclude the the message length in the header
                    msg = ubjson.loadb(self.buf[4:])
                    # Clear out the old buffer
                    del self.buf
                    self.buf = bytearray()
                    return msg

                except DecoderException as exception:
                    print("ERROR: Decode failure in Slippstream")
                    print(exception)
                    print(hexdump(self.buf[4:]))
                    self.buf.clear()
                    return None

            except socket.error as exception:
                if exception.args[0] == errno.EWOULDBLOCK:
                    continue
                print("ERROR with socket:", exception)
                return None 
Example #26
Source File: dataformat.py    From chepy with GNU General Public License v3.0 5 votes vote down vote up
def str_from_hexdump(self):
        """Extract a string from a hexdump
        
        Returns:
            Chepy: The Chepy object.
        """
        # TODO make new line aware \n \r\n \0a etc
        self.state = "".join(re.findall(r"\|(.+)\|", self._convert_to_str()))
        return self 
Example #27
Source File: dataformat.py    From chepy with GNU General Public License v3.0 5 votes vote down vote up
def to_hexdump(self):
        """Convert the state to hexdump
        
        Returns:
            Chepy: The Chepy object. 
        """
        self.state = hexdump.hexdump(self._convert_to_bytes(), result="return")
        return self 
Example #28
Source File: emu.py    From emu with GNU General Public License v2.0 5 votes vote down vote up
def dumpData(self, addr, size):
        data = str(self.readData(addr, size))
        try:
            hexdump.hexdump(data)
        except:
            for i in range(0, size, 4):
                if i % 16 == 0: print("")
                print(binascii.hexlify(data[i:i+4]), end=' ') 
Example #29
Source File: sniffer.py    From zktraffic with Apache License 2.0 5 votes vote down vote up
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() 
Example #30
Source File: sniffer.py    From zktraffic with Apache License 2.0 5 votes vote down vote up
def handle_packet(self, packet):
    try:
      message = self.message_from_packet(packet)
      if message:
        self.handle_message(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()