Search code examples
pythonpython-2.7for-looppwntools

Increment a Variable With an Unknown Type


Within the pwntools library in Python 2.7, an address is declared as address = p64(0x7fffffff0000). I've been racking my brain trying to figure out how to increment this address, though I keep running into conversion errors during the edition. I started out with the basic stuff, initially:

from pwn import *
address = p64(0x7fffffff0000)    # starting hex value
for i in range(0, 65535):     # how many times you want to increment

    i +=1
    address = p64(0x7fffffff0000 + i)        # increment varhex by 1
    print address

Though the output, rather than incrementing it in a hexadecimal fashion incremented in a unicode fashion like so:

...
_-\xff\xff\xff\x7f\x00\x00
`-\xff\xff\xff\x7f\x00\x00
a-\xff\xff\xff\x7f\x00\x00
...

Does anyone know how to increment this variable to have the output appear as:

...
\x01\x00\xff\xff\xff\x7f\x00\x00
\x02\x00\xff\xff\xff\x7f\x00\x00
...
\x00\x01\xff\xff\xff\x7f\x00\x00
...

Solution

  • p64 is just a trivial converter to str. When a str is printed on Python 2, the repr will display printable ASCII characters in preference to the \x escapes; if you want to prevent this, you need to explicitly write it in the form you prefer. A simple fixer might be:

    from future_builtins import map, zip  # Gets Python 3 generator based version of map/zip
    from itertools import repeat
    import binascii
    
    def bytes_to_x_escapes(s):
        hexstring = binascii.hexlify(s)
        escapecodes = map(''.join, zip(repeat(r'\x'), *[iter(hexstring)]*2))
        return ''.join(escapecodes)
    

    With this fixer, you can change your prints to:

    print bytes_to_x_escapes(address)
    

    and it will display the way you expect.