示例#1
0
文件: rop.py 项目: cxh852456/pwntools
    def chain(self):
        """Build the ROP chain

        Returns:
            str containing raw ROP bytes
        """
        return packing.flat(self.build())
示例#2
0
    def chain(self):
        """Build the ROP chain

        Returns:
            str containing raw ROP bytes
        """
        return packing.flat(self.build(), word_size=8 * self.align)
示例#3
0
    def chain(self):
        """Build the ROP chain

        Returns:
            str containing raw ROP bytes
        """
        return packing.flat(self.build())
示例#4
0
    def chain(self, base=None) -> bytes:
        '''Build the ROP chain (and use a `base` if given)

        Returns:
            str containing raw ROP bytes
        '''
        return flat(self.build(base=base))
示例#5
0
def emulate_plt_instructions(elf, got, address, data, targets):
    """Emulates instructions in ``data``

    Arguments:
        elf(ELF): ELF that we are emulating
        got(int): Address of the GOT, as expected in e.g. EBX
        address(int): Address of ``data`` for emulation
        data(str): Array of bytes to emulate
        targets(list): List of target addresses

    Returns:
        :class:`dict`: Map of ``{address: target}`` for each address which
            reaches one of the selected targets.
    """
    rv = {}

    # Unicorn doesn't support big-endian for everything yet.
    if elf.endian == 'big' and elf.arch == 'mips':
        data = packing.unpack_many(data, bits=32, endian='little')
        data = packing.flat(data, bits=32, endian='big')

    # Brute force addresses, assume that PLT entry points are at 4-byte aligned
    # Do not emulate more than a handful of instructions.
    for i, pc in enumerate(range(address, address + len(data), 4)):
        if log.isEnabledFor(logging.DEBUG):
            log.debug('%s %#x', fiddling.enhex(data[i * 4:(i + 1) * 4]), pc)
            log.debug(elf.disasm(pc, 4))
        target = emulate_plt_instructions_inner(elf, got, pc, data[i * 4:],
                                                targets)

        if target in targets:
            log.debug("%#x -> %#x", pc, target)
            rv[pc] = target

    return rv
示例#6
0
文件: plt.py 项目: cxh852456/pwntools
def emulate_plt_instructions(elf, got, address, data, targets):
    """Emulates instructions in ``data``

    Arguments:
        elf(ELF): ELF that we are emulating
        got(int): Address of the GOT, as expected in e.g. EBX
        address(int): Address of ``data`` for emulation
        data(str): Array of bytes to emulate
        targets(list): List of target addresses

    Returns:
        :class:`dict`: Map of ``{address: target}`` for each address which
            reaches one of the selected targets.
    """
    rv = {}

    # Unicorn doesn't support big-endian for everything yet.
    if elf.endian == 'big' and elf.arch == 'mips':
        data = packing.unpack_many(data, bits=32, endian='little')
        data = packing.flat(data, bits=32, endian='big')

    # Brute force addresses, assume that PLT entry points are at 4-byte aligned
    # Do not emulate more than a handful of instructions.
    for i, pc in enumerate(range(address, address + len(data), 4)):
        if log.isEnabledFor(logging.DEBUG):
            log.debug('%s %#x', fiddling.enhex(data[i*4:(i+1) * 4]), pc)
            log.debug(elf.disasm(pc, 4))
        target = emulate_plt_instructions_inner(elf, got, pc, data[i*4:], targets)

        if target in targets:
            log.debug("%#x -> %#x", pc, target)
            rv[pc] = target

    return rv
示例#7
0
def hexdump(s,
            width=16,
            skip=True,
            hexii=False,
            begin=0,
            style=None,
            highlight=None,
            cyclic=False):
    """hexdump(s, width = 16, skip = True, hexii = False, begin = 0,
               style = None, highlight = None, cyclic = False) -> str generator

    Return a hexdump-dump of a string.

    Arguments:
        s(str): The data to hexdump.
        width(int): The number of characters per line
        skip(bool): Set to True, if repeated lines should be replaced by a "*"
        hexii(bool): Set to True, if a hexii-dump should be returned instead of a hexdump.
        begin(int):  Offset of the first byte to print in the left column
        style(dict): Color scheme to use.
        highlight(iterable): Byte values to highlight.
        cyclic(bool): Attempt to skip consecutive, unmodified cyclic lines

    Returns:
        A hexdump-dump in the form of a string.
"""
    s = packing.flat(s)
    return '\n'.join(
        hexdump_iter(StringIO.StringIO(s), width, skip, hexii, begin, style,
                     highlight, cyclic))
示例#8
0
def xor(*args, **kwargs):
    """xor(*args, cut = 'max') -> str

    Flattens its arguments using :func:`pwnlib.util.packing.flat` and
    then xors them together. If the end of a string is reached, it wraps
    around in the string.

    Arguments:
       args: The arguments to be xor'ed together.
       cut: How long a string should be returned.
            Can be either 'min'/'max'/'left'/'right' or a number.

    Returns:
       The string of the arguments xor'ed together.

    Example:
       >>> xor(b'lol', b'hello', 42)
       b'. ***'
    """

    cut = kwargs.pop('cut', 'max')

    if kwargs != {}:
        raise TypeError("xor() got an unexpected keyword argument '%s'" %
                        kwargs.pop()[0])

    if len(args) == 0:
        raise ValueError("Must have something to xor")

    strs = [
        packing.flat(s, word_size=8, sign=False, endianness='little')
        for s in args
    ]
    strs = [bytearray(s) for s in strs if s]

    if strs == []:
        return b''

    if isinstance(cut, six.integer_types):
        cut = cut
    elif cut == 'left':
        cut = len(strs[0])
    elif cut == 'right':
        cut = len(strs[-1])
    elif cut == 'min':
        cut = min(len(s) for s in strs)
    elif cut == 'max':
        cut = max(len(s) for s in strs)
    else:
        raise ValueError("Not a valid argument for 'cut'")

    def get(n):
        rv = 0
        for s in strs:
            rv ^= s[n % len(s)]
        return packing._p8lu(rv)

    return b''.join(map(get, range(cut)))
示例#9
0
    def finishStackDump(self):
        dump = flat(self.memdumps)
        log.warn("Stack dump @0x%08x written to %s!" %
                 (self.memdump_addr, self.stack_dump_filename))
        f = open(self.stack_dump_filename, "wb")
        f.write(dump)
        f.close()

        # Shut down:
        self.stack_dump_has_happend = True
示例#10
0
def xor(*args, **kwargs):
    """xor(*args, cut = 'max') -> str

    Flattens its arguments using :func:`pwnlib.util.packing.flat` and
    then xors them together. If the end of a string is reached, it wraps
    around in the string.

    Arguments:
       args: The arguments to be xor'ed together.
       cut: How long a string should be returned.
            Can be either 'min'/'max'/'left'/'right' or a number.

    Returns:
       The string of the arguments xor'ed together.

    Example:
       >>> xor('lol', 'hello', 42)
       '. ***'
    """

    cut = kwargs.pop('cut', 'max')

    if kwargs != {}:
        raise TypeError("xor() got an unexpected keyword argument '%s'" %
                        kwargs.pop()[0])

    if len(args) == 0:
        raise ValueError("Must have something to xor")

    strs = [
        packing.flat(s, word_size=8, sign=False, endianness='little')
        for s in args
    ]
    strs = [[ord(c) for c in s] for s in strs if s != '']

    if strs == []:
        return ''

    if isinstance(cut, (int, long)):
        cut = cut
    elif cut == 'left':
        cut = len(strs[0])
    elif cut == 'right':
        cut = len(strs[-1])
    elif cut == 'min':
        cut = min(len(s) for s in strs)
    elif cut == 'max':
        cut = max(len(s) for s in strs)
    else:
        raise ValueError("Not a valid argument for 'cut'")

    def get(n):
        return chr(reduce(lambda x, y: x ^ y, [s[n % len(s)] for s in strs]))

    return ''.join(get(n) for n in range(cut))
示例#11
0
    def __call__(self, *args):
        self._called = True
        old_children = self._children
        self._children = concat_all(args)

        for n, c in enumerate(self._children):
            if not isinstance(c, (Align, Location, Buf)):
                self._children[n] = flat(c)

        if self._children != old_children:
            self._changed = True
        return self
示例#12
0
    def chain(self, base=None):
        """Build the ROP chain
        
        Arguments:
            base(int):
                The base address to build the rop-chain from. Defaults to
                :attr:`base`.

        Returns:
            str containing raw ROP bytes
        """
        return packing.flat(self.build(base=base))
示例#13
0
def xor(*args, **kwargs):
    """xor(*args, cut = 'max') -> str

    Flattens its arguments using :func:`pwnlib.util.packing.flat` and
    then xors them together. If the end of a string is reached, it wraps
    around in the string.

    Arguments:
       args: The arguments to be xor'ed together.
       cut: How long a string should be returned.
            Can be either 'min'/'max'/'left'/'right' or a number.

    Returns:
       The string of the arguments xor'ed together.

    Example:
       >>> xor('lol', 'hello', 42)
       '. ***'
    """

    cut = kwargs.pop('cut', 'max')

    if kwargs != {}:
        raise TypeError("xor() got an unexpected keyword argument '%s'" % kwargs.pop()[0])

    if len(args) == 0:
        raise ValueError("Must have something to xor")

    strs = [packing.flat(s, word_size = 8, sign = False, endianness = 'little') for s in args]
    strs = [[ord(c) for c in s] for s in strs if s != '']

    if strs == []:
        return ''

    if isinstance(cut, (int, long)):
        cut = cut
    elif cut == 'left':
        cut = len(strs[0])
    elif cut == 'right':
        cut = len(strs[-1])
    elif cut == 'min':
        cut = min(len(s) for s in strs)
    elif cut == 'max':
        cut = max(len(s) for s in strs)
    else:
        raise ValueError("Not a valid argument for 'cut'")

    def get(n):
        return chr(reduce(lambda x, y: x ^ y, [s[n % len(s)] for s in strs]))

    return ''.join(get(n) for n in range(cut))
示例#14
0
    def finishStackDump(self):
        """
        Write the stack dump to a file once it is finished.
        """
        dump = flat(
            self.memdumps)  # flatten, as we have one entry per address chunk
        log.warn("Stack dump @0x%08x written to %s!" %
                 (self.memdump_addr, self.stack_dump_filename))
        f = open(self.stack_dump_filename, "wb")
        f.write(dump)
        f.close()

        # Shut down:
        self.stack_dump_has_happend = True
示例#15
0
def _slot_len(x):
    if isinstance(x, six.integer_types + (Unresolved, Padding, Gadget)):
        return context.bytes
    else:
        return len(packing.flat(x))
示例#16
0
def render_body(context, string, append_null=True, **pageargs):
    __M_caller = context.caller_stack._push_frame()
    try:
        __M_locals = __M_dict_builtin(pageargs=pageargs,
                                      string=string,
                                      append_null=append_null)
        ord = context.get('ord', UNDEFINED)
        isinstance = context.get('isinstance', UNDEFINED)
        str = context.get('str', UNDEFINED)
        __M_writer = context.writer()

        from pwnlib.util import lists, packing, fiddling
        from pwnlib.shellcraft import pretty, okay

        __M_locals_builtin_stored = __M_locals_builtin()
        __M_locals.update(
            __M_dict_builtin([
                (__M_key, __M_locals_builtin_stored[__M_key]) for __M_key in
                ['packing', 'fiddling', 'okay', 'pretty', 'lists']
                if __M_key in __M_locals_builtin_stored
            ]))
        __M_writer(u'\n')
        __M_writer(u'\n')
        __M_writer(u'\n')

        original = string
        string = packing.flat(string)

        if append_null:
            string += '\x00'
            if isinstance(original, str):
                original += '\x00'

        if not string:
            return

        if ord(string[-1]) >= 128:
            extend = '\xff'
        else:
            extend = '\x00'

        __M_locals_builtin_stored = __M_locals_builtin()
        __M_locals.update(
            __M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key])
                              for __M_key in ['original', 'extend', 'string']
                              if __M_key in __M_locals_builtin_stored]))
        __M_writer(u'    /* push ')
        __M_writer(unicode(pretty(original, False)))
        __M_writer(u' */\n')
        for word in lists.group(4, string, 'fill', extend)[::-1]:

            sign = packing.u32(word, endian='little', sign='signed')

            __M_locals_builtin_stored = __M_locals_builtin()
            __M_locals.update(
                __M_dict_builtin([(__M_key, __M_locals_builtin_stored[__M_key])
                                  for __M_key in ['sign']
                                  if __M_key in __M_locals_builtin_stored]))
            if sign in [0, 0xa]:
                __M_writer(u'    push ')
                __M_writer(unicode(pretty(sign + 1)))
                __M_writer(u'\n    dec byte ptr [esp]\n')
            elif -0x80 <= sign <= 0x7f and okay(word[0]):
                __M_writer(u'    push ')
                __M_writer(unicode(pretty(sign)))
                __M_writer(u'\n')
            elif okay(word):
                __M_writer(u'    push ')
                __M_writer(unicode(pretty(sign)))
                __M_writer(u'\n')
            else:

                a, b = fiddling.xor_pair(word, avoid='\x00\n')
                a = packing.u32(a, endian='little', sign='unsigned')
                b = packing.u32(b, endian='little', sign='unsigned')

                __M_locals_builtin_stored = __M_locals_builtin()
                __M_locals.update(
                    __M_dict_builtin([
                        (__M_key, __M_locals_builtin_stored[__M_key])
                        for __M_key in ['a', 'b']
                        if __M_key in __M_locals_builtin_stored
                    ]))
                __M_writer(u'    push ')
                __M_writer(unicode(pretty(a)))
                __M_writer(u'\n    xor dword ptr [esp], ')
                __M_writer(unicode(pretty(b)))
                __M_writer(u'\n')
        return ''
    finally:
        context.caller_stack._pop_frame()
示例#17
0
文件: elf.py 项目: tavakyan/pwntools
    def flat(self, address, *a, **kw):
        """Writes a full array of values to the specified address.

        See: :func:`.packing.flat`
        """
        return self.write(address, packing.flat(*a,**kw))
示例#18
0
文件: test.py 项目: br0ns/pyfix
def rop2(end=0):
    rop2 = flat(pop_rdi, end, puts)
    end = base + len(rop2)
    rop2 += "/bin/sh\x00"
示例#19
0
def hexdump(s,
            width=16,
            skip=True,
            hexii=False,
            begin=0,
            style=None,
            highlight=None,
            cyclic=False,
            groupsize=4,
            total=True):
    r"""hexdump(s, width = 16, skip = True, hexii = False, begin = 0, style = None,
                highlight = None, cyclic = False, groupsize=4, total = True) -> str

    Return a hexdump-dump of a string.

    Arguments:
        s(bytes): The data to hexdump.
        width(int): The number of characters per line
        groupsize(int): The number of characters per group
        skip(bool): Set to True, if repeated lines should be replaced by a "*"
        hexii(bool): Set to True, if a hexii-dump should be returned instead of a hexdump.
        begin(int):  Offset of the first byte to print in the left column
        style(dict): Color scheme to use.
        highlight(iterable): Byte values to highlight.
        cyclic(bool): Attempt to skip consecutive, unmodified cyclic lines
        total(bool): Set to True, if total bytes should be printed

    Returns:
        A hexdump-dump in the form of a string.

    Examples:

        >>> print(hexdump(b"abc"))
        00000000  61 62 63                                            │abc│
        00000003

        >>> print(hexdump(b'A'*32))
        00000000  41 41 41 41  41 41 41 41  41 41 41 41  41 41 41 41  │AAAA│AAAA│AAAA│AAAA│
        *
        00000020

        >>> print(hexdump(b'A'*32, width=8))
        00000000  41 41 41 41  41 41 41 41  │AAAA│AAAA│
        *
        00000020

        >>> print(hexdump(cyclic(32), width=8, begin=0xdead0000, hexii=True))
        dead0000  .a  .a  .a  .a   .b  .a  .a  .a  │
        dead0008  .c  .a  .a  .a   .d  .a  .a  .a  │
        dead0010  .e  .a  .a  .a   .f  .a  .a  .a  │
        dead0018  .g  .a  .a  .a   .h  .a  .a  .a  │
        dead0020

        >>> print(hexdump(bytearray(range(256))))
        00000000  00 01 02 03  04 05 06 07  08 09 0a 0b  0c 0d 0e 0f  │····│····│····│····│
        00000010  10 11 12 13  14 15 16 17  18 19 1a 1b  1c 1d 1e 1f  │····│····│····│····│
        00000020  20 21 22 23  24 25 26 27  28 29 2a 2b  2c 2d 2e 2f  │ !"#│$%&'│()*+│,-./│
        00000030  30 31 32 33  34 35 36 37  38 39 3a 3b  3c 3d 3e 3f  │0123│4567│89:;│<=>?│
        00000040  40 41 42 43  44 45 46 47  48 49 4a 4b  4c 4d 4e 4f  │@ABC│DEFG│HIJK│LMNO│
        00000050  50 51 52 53  54 55 56 57  58 59 5a 5b  5c 5d 5e 5f  │PQRS│TUVW│XYZ[│\]^_│
        00000060  60 61 62 63  64 65 66 67  68 69 6a 6b  6c 6d 6e 6f  │`abc│defg│hijk│lmno│
        00000070  70 71 72 73  74 75 76 77  78 79 7a 7b  7c 7d 7e 7f  │pqrs│tuvw│xyz{│|}~·│
        00000080  80 81 82 83  84 85 86 87  88 89 8a 8b  8c 8d 8e 8f  │····│····│····│····│
        00000090  90 91 92 93  94 95 96 97  98 99 9a 9b  9c 9d 9e 9f  │····│····│····│····│
        000000a0  a0 a1 a2 a3  a4 a5 a6 a7  a8 a9 aa ab  ac ad ae af  │····│····│····│····│
        000000b0  b0 b1 b2 b3  b4 b5 b6 b7  b8 b9 ba bb  bc bd be bf  │····│····│····│····│
        000000c0  c0 c1 c2 c3  c4 c5 c6 c7  c8 c9 ca cb  cc cd ce cf  │····│····│····│····│
        000000d0  d0 d1 d2 d3  d4 d5 d6 d7  d8 d9 da db  dc dd de df  │····│····│····│····│
        000000e0  e0 e1 e2 e3  e4 e5 e6 e7  e8 e9 ea eb  ec ed ee ef  │····│····│····│····│
        000000f0  f0 f1 f2 f3  f4 f5 f6 f7  f8 f9 fa fb  fc fd fe ff  │····│····│····│····│
        00000100

        >>> print(hexdump(bytearray(range(256)), hexii=True))
        00000000      01  02  03   04  05  06  07   08  09  0a  0b   0c  0d  0e  0f  │
        00000010  10  11  12  13   14  15  16  17   18  19  1a  1b   1c  1d  1e  1f  │
        00000020  20  .!  ."  .#   .$  .%  .&  .'   .(  .)  .*  .+   .,  .-  ..  ./  │
        00000030  .0  .1  .2  .3   .4  .5  .6  .7   .8  .9  .:  .;   .<  .=  .>  .?  │
        00000040  .@  .A  .B  .C   .D  .E  .F  .G   .H  .I  .J  .K   .L  .M  .N  .O  │
        00000050  .P  .Q  .R  .S   .T  .U  .V  .W   .X  .Y  .Z  .[   .\  .]  .^  ._  │
        00000060  .`  .a  .b  .c   .d  .e  .f  .g   .h  .i  .j  .k   .l  .m  .n  .o  │
        00000070  .p  .q  .r  .s   .t  .u  .v  .w   .x  .y  .z  .{   .|  .}  .~  7f  │
        00000080  80  81  82  83   84  85  86  87   88  89  8a  8b   8c  8d  8e  8f  │
        00000090  90  91  92  93   94  95  96  97   98  99  9a  9b   9c  9d  9e  9f  │
        000000a0  a0  a1  a2  a3   a4  a5  a6  a7   a8  a9  aa  ab   ac  ad  ae  af  │
        000000b0  b0  b1  b2  b3   b4  b5  b6  b7   b8  b9  ba  bb   bc  bd  be  bf  │
        000000c0  c0  c1  c2  c3   c4  c5  c6  c7   c8  c9  ca  cb   cc  cd  ce  cf  │
        000000d0  d0  d1  d2  d3   d4  d5  d6  d7   d8  d9  da  db   dc  dd  de  df  │
        000000e0  e0  e1  e2  e3   e4  e5  e6  e7   e8  e9  ea  eb   ec  ed  ee  ef  │
        000000f0  f0  f1  f2  f3   f4  f5  f6  f7   f8  f9  fa  fb   fc  fd  fe  ##  │
        00000100

        >>> print(hexdump(b'X' * 64))
        00000000  58 58 58 58  58 58 58 58  58 58 58 58  58 58 58 58  │XXXX│XXXX│XXXX│XXXX│
        *
        00000040

        >>> print(hexdump(b'X' * 64, skip=False))
        00000000  58 58 58 58  58 58 58 58  58 58 58 58  58 58 58 58  │XXXX│XXXX│XXXX│XXXX│
        00000010  58 58 58 58  58 58 58 58  58 58 58 58  58 58 58 58  │XXXX│XXXX│XXXX│XXXX│
        00000020  58 58 58 58  58 58 58 58  58 58 58 58  58 58 58 58  │XXXX│XXXX│XXXX│XXXX│
        00000030  58 58 58 58  58 58 58 58  58 58 58 58  58 58 58 58  │XXXX│XXXX│XXXX│XXXX│
        00000040

        >>> print(hexdump(fit({0x10: b'X'*0x20, 0x50-1: b'\xff'*20}, length=0xc0) + b'\x00'*32))
        00000000  61 61 61 61  62 61 61 61  63 61 61 61  64 61 61 61  │aaaa│baaa│caaa│daaa│
        00000010  58 58 58 58  58 58 58 58  58 58 58 58  58 58 58 58  │XXXX│XXXX│XXXX│XXXX│
        *
        00000030  6d 61 61 61  6e 61 61 61  6f 61 61 61  70 61 61 61  │maaa│naaa│oaaa│paaa│
        00000040  71 61 61 61  72 61 61 61  73 61 61 61  74 61 61 ff  │qaaa│raaa│saaa│taa·│
        00000050  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  │····│····│····│····│
        00000060  ff ff ff 61  7a 61 61 62  62 61 61 62  63 61 61 62  │···a│zaab│baab│caab│
        00000070  64 61 61 62  65 61 61 62  66 61 61 62  67 61 61 62  │daab│eaab│faab│gaab│
        00000080  68 61 61 62  69 61 61 62  6a 61 61 62  6b 61 61 62  │haab│iaab│jaab│kaab│
        00000090  6c 61 61 62  6d 61 61 62  6e 61 61 62  6f 61 61 62  │laab│maab│naab│oaab│
        000000a0  70 61 61 62  71 61 61 62  72 61 61 62  73 61 61 62  │paab│qaab│raab│saab│
        000000b0  74 61 61 62  75 61 61 62  76 61 61 62  77 61 61 62  │taab│uaab│vaab│waab│
        000000c0  00 00 00 00  00 00 00 00  00 00 00 00  00 00 00 00  │····│····│····│····│
        *
        000000e0

        >>> print(hexdump(fit({0x10: b'X'*0x20, 0x50-1: b'\xff'*20}, length=0xc0) + b'\x00'*32, cyclic=1))
        00000000  61 61 61 61  62 61 61 61  63 61 61 61  64 61 61 61  │aaaa│baaa│caaa│daaa│
        00000010  58 58 58 58  58 58 58 58  58 58 58 58  58 58 58 58  │XXXX│XXXX│XXXX│XXXX│
        *
        00000030  6d 61 61 61  6e 61 61 61  6f 61 61 61  70 61 61 61  │maaa│naaa│oaaa│paaa│
        00000040  71 61 61 61  72 61 61 61  73 61 61 61  74 61 61 ff  │qaaa│raaa│saaa│taa·│
        00000050  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  │····│····│····│····│
        00000060  ff ff ff 61  7a 61 61 62  62 61 61 62  63 61 61 62  │···a│zaab│baab│caab│
        00000070  64 61 61 62  65 61 61 62  66 61 61 62  67 61 61 62  │daab│eaab│faab│gaab│
        *
        000000c0  00 00 00 00  00 00 00 00  00 00 00 00  00 00 00 00  │····│····│····│····│
        *
        000000e0

        >>> print(hexdump(fit({0x10: b'X'*0x20, 0x50-1: b'\xff'*20}, length=0xc0) + b'\x00'*32, cyclic=1, hexii=1))
        00000000  .a  .a  .a  .a   .b  .a  .a  .a   .c  .a  .a  .a   .d  .a  .a  .a  │
        00000010  .X  .X  .X  .X   .X  .X  .X  .X   .X  .X  .X  .X   .X  .X  .X  .X  │
        *
        00000030  .m  .a  .a  .a   .n  .a  .a  .a   .o  .a  .a  .a   .p  .a  .a  .a  │
        00000040  .q  .a  .a  .a   .r  .a  .a  .a   .s  .a  .a  .a   .t  .a  .a  ##  │
        00000050  ##  ##  ##  ##   ##  ##  ##  ##   ##  ##  ##  ##   ##  ##  ##  ##  │
        00000060  ##  ##  ##  .a   .z  .a  .a  .b   .b  .a  .a  .b   .c  .a  .a  .b  │
        00000070  .d  .a  .a  .b   .e  .a  .a  .b   .f  .a  .a  .b   .g  .a  .a  .b  │
        *
        000000c0                                                                     │
        *
        000000e0

        >>> print(hexdump(b'A'*16, width=9))
        00000000  41 41 41 41  41 41 41 41  41  │AAAA│AAAA│A│
        00000009  41 41 41 41  41 41 41         │AAAA│AAA│
        00000010
        >>> print(hexdump(b'A'*16, width=10))
        00000000  41 41 41 41  41 41 41 41  41 41  │AAAA│AAAA│AA│
        0000000a  41 41 41 41  41 41               │AAAA│AA│
        00000010
        >>> print(hexdump(b'A'*16, width=11))
        00000000  41 41 41 41  41 41 41 41  41 41 41  │AAAA│AAAA│AAA│
        0000000b  41 41 41 41  41                     │AAAA│A│
        00000010
        >>> print(hexdump(b'A'*16, width=12))
        00000000  41 41 41 41  41 41 41 41  41 41 41 41  │AAAA│AAAA│AAAA│
        0000000c  41 41 41 41                            │AAAA│
        00000010
        >>> print(hexdump(b'A'*16, width=13))
        00000000  41 41 41 41  41 41 41 41  41 41 41 41  41  │AAAA│AAAA│AAAA│A│
        0000000d  41 41 41                                   │AAA│
        00000010
        >>> print(hexdump(b'A'*16, width=14))
        00000000  41 41 41 41  41 41 41 41  41 41 41 41  41 41  │AAAA│AAAA│AAAA│AA│
        0000000e  41 41                                         │AA│
        00000010
        >>> print(hexdump(b'A'*16, width=15))
        00000000  41 41 41 41  41 41 41 41  41 41 41 41  41 41 41  │AAAA│AAAA│AAAA│AAA│
        0000000f  41                                               │A│
        00000010

        >>> print(hexdump(b'A'*24, width=16, groupsize=8))
        00000000  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  │AAAAAAAA│AAAAAAAA│
        00000010  41 41 41 41 41 41 41 41                           │AAAAAAAA│
        00000018
        >>> print(hexdump(b'A'*24, width=16, groupsize=-1))
        00000000  41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41  │AAAAAAAAAAAAAAAA│
        00000010  41 41 41 41 41 41 41 41                          │AAAAAAAA│
        00000018

        >>> print(hexdump(b'A'*24, width=16, total=False))
        00000000  41 41 41 41  41 41 41 41  41 41 41 41  41 41 41 41  │AAAA│AAAA│AAAA│AAAA│
        00000010  41 41 41 41  41 41 41 41                            │AAAA│AAAA│
        >>> print(hexdump(b'A'*24, width=16, groupsize=8, total=False))
        00000000  41 41 41 41 41 41 41 41  41 41 41 41 41 41 41 41  │AAAAAAAA│AAAAAAAA│
        00000010  41 41 41 41 41 41 41 41                           │AAAAAAAA│
    """
    s = packing.flat(s, stacklevel=1)
    return '\n'.join(
        hexdump_iter(BytesIO(s), width, skip, hexii, begin, style, highlight,
                     cyclic, groupsize, total))
示例#20
0
 def __bytes__(self):
     return packing.flat(self.resolve())
示例#21
0
def hexdump(s, width=16, skip=True, hexii=False, begin=0,
            style=None, highlight=None, cyclic=False):
    r"""hexdump(s, width = 16, skip = True, hexii = False, begin = 0,
               style = None, highlight = None, cyclic = False) -> str generator

    Return a hexdump-dump of a string.

    Arguments:
        s(str): The data to hexdump.
        width(int): The number of characters per line
        skip(bool): Set to True, if repeated lines should be replaced by a "*"
        hexii(bool): Set to True, if a hexii-dump should be returned instead of a hexdump.
        begin(int):  Offset of the first byte to print in the left column
        style(dict): Color scheme to use.
        highlight(iterable): Byte values to highlight.
        cyclic(bool): Attempt to skip consecutive, unmodified cyclic lines

    Returns:
        A hexdump-dump in the form of a string.

    Examples:

        >>> print hexdump("abc")
        00000000  61 62 63                                            │abc│
        00000003

        >>> print hexdump('A'*32)
        00000000  41 41 41 41  41 41 41 41  41 41 41 41  41 41 41 41  │AAAA│AAAA│AAAA│AAAA│
        *
        00000020

        >>> print hexdump('A'*32, width=8)
        00000000  41 41 41 41  41 41 41 41   │AAAA│AAAA│
        *
        00000020

        >>> print hexdump(cyclic(32), width=8, begin=0xdead0000, hexii=True)
        dead0000  .a  .a  .a  .a   .b  .a  .a  .a  │
        dead0008  .c  .a  .a  .a   .d  .a  .a  .a  │
        dead0010  .e  .a  .a  .a   .f  .a  .a  .a  │
        dead0018  .g  .a  .a  .a   .h  .a  .a  .a  │
        dead0020

        >>> print hexdump(list(map(chr, range(256))))
        00000000  00 01 02 03  04 05 06 07  08 09 0a 0b  0c 0d 0e 0f  │····│····│····│····│
        00000010  10 11 12 13  14 15 16 17  18 19 1a 1b  1c 1d 1e 1f  │····│····│····│····│
        00000020  20 21 22 23  24 25 26 27  28 29 2a 2b  2c 2d 2e 2f  │ !"#│$%&'│()*+│,-./│
        00000030  30 31 32 33  34 35 36 37  38 39 3a 3b  3c 3d 3e 3f  │0123│4567│89:;│<=>?│
        00000040  40 41 42 43  44 45 46 47  48 49 4a 4b  4c 4d 4e 4f  │@ABC│DEFG│HIJK│LMNO│
        00000050  50 51 52 53  54 55 56 57  58 59 5a 5b  5c 5d 5e 5f  │PQRS│TUVW│XYZ[│\]^_│
        00000060  60 61 62 63  64 65 66 67  68 69 6a 6b  6c 6d 6e 6f  │`abc│defg│hijk│lmno│
        00000070  70 71 72 73  74 75 76 77  78 79 7a 7b  7c 7d 7e 7f  │pqrs│tuvw│xyz{│|}~·│
        00000080  80 81 82 83  84 85 86 87  88 89 8a 8b  8c 8d 8e 8f  │····│····│····│····│
        00000090  90 91 92 93  94 95 96 97  98 99 9a 9b  9c 9d 9e 9f  │····│····│····│····│
        000000a0  a0 a1 a2 a3  a4 a5 a6 a7  a8 a9 aa ab  ac ad ae af  │····│····│····│····│
        000000b0  b0 b1 b2 b3  b4 b5 b6 b7  b8 b9 ba bb  bc bd be bf  │····│····│····│····│
        000000c0  c0 c1 c2 c3  c4 c5 c6 c7  c8 c9 ca cb  cc cd ce cf  │····│····│····│····│
        000000d0  d0 d1 d2 d3  d4 d5 d6 d7  d8 d9 da db  dc dd de df  │····│····│····│····│
        000000e0  e0 e1 e2 e3  e4 e5 e6 e7  e8 e9 ea eb  ec ed ee ef  │····│····│····│····│
        000000f0  f0 f1 f2 f3  f4 f5 f6 f7  f8 f9 fa fb  fc fd fe ff  │····│····│····│····│
        00000100

        >>> print hexdump(list(map(chr, range(256))), hexii=True)
        00000000      01  02  03   04  05  06  07   08  09  0a  0b   0c  0d  0e  0f  │
        00000010  10  11  12  13   14  15  16  17   18  19  1a  1b   1c  1d  1e  1f  │
        00000020  20  .!  ."  .#   .$  .%  .&  .'   .(  .)  .*  .+   .,  .-  ..  ./  │
        00000030  .0  .1  .2  .3   .4  .5  .6  .7   .8  .9  .:  .;   .<  .=  .>  .?  │
        00000040  .@  .A  .B  .C   .D  .E  .F  .G   .H  .I  .J  .K   .L  .M  .N  .O  │
        00000050  .P  .Q  .R  .S   .T  .U  .V  .W   .X  .Y  .Z  .[   .\  .]  .^  ._  │
        00000060  .`  .a  .b  .c   .d  .e  .f  .g   .h  .i  .j  .k   .l  .m  .n  .o  │
        00000070  .p  .q  .r  .s   .t  .u  .v  .w   .x  .y  .z  .{   .|  .}  .~  7f  │
        00000080  80  81  82  83   84  85  86  87   88  89  8a  8b   8c  8d  8e  8f  │
        00000090  90  91  92  93   94  95  96  97   98  99  9a  9b   9c  9d  9e  9f  │
        000000a0  a0  a1  a2  a3   a4  a5  a6  a7   a8  a9  aa  ab   ac  ad  ae  af  │
        000000b0  b0  b1  b2  b3   b4  b5  b6  b7   b8  b9  ba  bb   bc  bd  be  bf  │
        000000c0  c0  c1  c2  c3   c4  c5  c6  c7   c8  c9  ca  cb   cc  cd  ce  cf  │
        000000d0  d0  d1  d2  d3   d4  d5  d6  d7   d8  d9  da  db   dc  dd  de  df  │
        000000e0  e0  e1  e2  e3   e4  e5  e6  e7   e8  e9  ea  eb   ec  ed  ee  ef  │
        000000f0  f0  f1  f2  f3   f4  f5  f6  f7   f8  f9  fa  fb   fc  fd  fe  ##  │
        00000100

        >>> print hexdump('X' * 64)
        00000000  58 58 58 58  58 58 58 58  58 58 58 58  58 58 58 58  │XXXX│XXXX│XXXX│XXXX│
        *
        00000040

        >>> print hexdump('X' * 64, skip=False)
        00000000  58 58 58 58  58 58 58 58  58 58 58 58  58 58 58 58  │XXXX│XXXX│XXXX│XXXX│
        00000010  58 58 58 58  58 58 58 58  58 58 58 58  58 58 58 58  │XXXX│XXXX│XXXX│XXXX│
        00000020  58 58 58 58  58 58 58 58  58 58 58 58  58 58 58 58  │XXXX│XXXX│XXXX│XXXX│
        00000030  58 58 58 58  58 58 58 58  58 58 58 58  58 58 58 58  │XXXX│XXXX│XXXX│XXXX│
        00000040

        >>> print hexdump(fit({0x10: 'X'*0x20, 0x50-1: '\xff'*20}, length=0xc0) + '\x00'*32)
        00000000  61 61 61 61  62 61 61 61  63 61 61 61  64 61 61 61  │aaaa│baaa│caaa│daaa│
        00000010  58 58 58 58  58 58 58 58  58 58 58 58  58 58 58 58  │XXXX│XXXX│XXXX│XXXX│
        *
        00000030  6d 61 61 61  6e 61 61 61  6f 61 61 61  70 61 61 61  │maaa│naaa│oaaa│paaa│
        00000040  71 61 61 61  72 61 61 61  73 61 61 61  74 61 61 ff  │qaaa│raaa│saaa│taa·│
        00000050  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  │····│····│····│····│
        00000060  ff ff ff 61  7a 61 61 62  62 61 61 62  63 61 61 62  │···a│zaab│baab│caab│
        00000070  64 61 61 62  65 61 61 62  66 61 61 62  67 61 61 62  │daab│eaab│faab│gaab│
        00000080  68 61 61 62  69 61 61 62  6a 61 61 62  6b 61 61 62  │haab│iaab│jaab│kaab│
        00000090  6c 61 61 62  6d 61 61 62  6e 61 61 62  6f 61 61 62  │laab│maab│naab│oaab│
        000000a0  70 61 61 62  71 61 61 62  72 61 61 62  73 61 61 62  │paab│qaab│raab│saab│
        000000b0  74 61 61 62  75 61 61 62  76 61 61 62  77 61 61 62  │taab│uaab│vaab│waab│
        000000c0  00 00 00 00  00 00 00 00  00 00 00 00  00 00 00 00  │····│····│····│····│
        *
        000000e0

        >>> print hexdump(fit({0x10: 'X'*0x20, 0x50-1: '\xff'*20}, length=0xc0) + '\x00'*32, cyclic=1)
        00000000  61 61 61 61  62 61 61 61  63 61 61 61  64 61 61 61  │aaaa│baaa│caaa│daaa│
        00000010  58 58 58 58  58 58 58 58  58 58 58 58  58 58 58 58  │XXXX│XXXX│XXXX│XXXX│
        *
        00000030  6d 61 61 61  6e 61 61 61  6f 61 61 61  70 61 61 61  │maaa│naaa│oaaa│paaa│
        00000040  71 61 61 61  72 61 61 61  73 61 61 61  74 61 61 ff  │qaaa│raaa│saaa│taa·│
        00000050  ff ff ff ff  ff ff ff ff  ff ff ff ff  ff ff ff ff  │····│····│····│····│
        00000060  ff ff ff 61  7a 61 61 62  62 61 61 62  63 61 61 62  │···a│zaab│baab│caab│
        00000070  64 61 61 62  65 61 61 62  66 61 61 62  67 61 61 62  │daab│eaab│faab│gaab│
        *
        000000c0  00 00 00 00  00 00 00 00  00 00 00 00  00 00 00 00  │····│····│····│····│
        *
        000000e0

        >>> print hexdump(fit({0x10: 'X'*0x20, 0x50-1: '\xff'*20}, length=0xc0) + '\x00'*32, cyclic=1, hexii=1)
        00000000  .a  .a  .a  .a   .b  .a  .a  .a   .c  .a  .a  .a   .d  .a  .a  .a  │
        00000010  .X  .X  .X  .X   .X  .X  .X  .X   .X  .X  .X  .X   .X  .X  .X  .X  │
        *
        00000030  .m  .a  .a  .a   .n  .a  .a  .a   .o  .a  .a  .a   .p  .a  .a  .a  │
        00000040  .q  .a  .a  .a   .r  .a  .a  .a   .s  .a  .a  .a   .t  .a  .a  ##  │
        00000050  ##  ##  ##  ##   ##  ##  ##  ##   ##  ##  ##  ##   ##  ##  ##  ##  │
        00000060  ##  ##  ##  .a   .z  .a  .a  .b   .b  .a  .a  .b   .c  .a  .a  .b  │
        00000070  .d  .a  .a  .b   .e  .a  .a  .b   .f  .a  .a  .b   .g  .a  .a  .b  │
        *
        000000c0                                                                     │
        *
        000000e0

        >>> print hexdump('A'*16, width=9)
        00000000  41 41 41 41  41 41 41 41  41  │AAAA│AAAA│A│
        00000009  41 41 41 41  41 41 41         │AAAA│AAA│
        00000010
        >>> print hexdump('A'*16, width=10)
        00000000  41 41 41 41  41 41 41 41  41 41  │AAAA│AAAA│AA│
        0000000a  41 41 41 41  41 41               │AAAA│AA│
        00000010
        >>> print hexdump('A'*16, width=11)
        00000000  41 41 41 41  41 41 41 41  41 41 41  │AAAA│AAAA│AAA│
        0000000b  41 41 41 41  41                     │AAAA│A│
        00000010
        >>> print hexdump('A'*16, width=12)
        00000000  41 41 41 41  41 41 41 41  41 41 41 41  │AAAA│AAAA│AAAA│
        0000000c  41 41 41 41                            │AAAA││
        00000010
        >>> print hexdump('A'*16, width=13)
        00000000  41 41 41 41  41 41 41 41  41 41 41 41  41  │AAAA│AAAA│AAAA│A│
        0000000d  41 41 41                                   │AAA│
        00000010
        >>> print hexdump('A'*16, width=14)
        00000000  41 41 41 41  41 41 41 41  41 41 41 41  41 41  │AAAA│AAAA│AAAA│AA│
        0000000e  41 41                                         │AA│
        00000010
        >>> print hexdump('A'*16, width=15)
        00000000  41 41 41 41  41 41 41 41  41 41 41 41  41 41 41  │AAAA│AAAA│AAAA│AAA│
        0000000f  41                                               │A│
        00000010
    """
    s = packing.flat(s)
    return '\n'.join(hexdump_iter(StringIO.StringIO(s),
                                  width,
                                  skip,
                                  hexii,
                                  begin,
                                  style,
                                  highlight,
                                  cyclic))
示例#22
0
 def __str__(self):
     return packing.flat(self.resolve())
示例#23
0
 def flat(self, *a, **kw):
     return self.send(packing.flat(*a, **kw))
示例#24
0
 def __str__(self):
     return packing.flat(self.resolve())