So I am currently doing a beginner CTF challengeon pwnable.tw, the "start" challenge specifically. After reversing the challenge binary I found out there was a buffer overflow exploit, and one thing I would have to do to get an ideal starting point would be to leak the stack address by pointing it back to a specific address (0x08048087), so i crafted a payload, that would then overwrite the return address with the address I was aiming for. However, I'm having trouble converting the byte data into a string format to be fed to the vulnerable program.
Below is my python code:
from pwn import *
shellcode = b'A' * 20
shellcode += pack(0x08048087, 32)
print(shellcode)
I use the pwn library to simplify packing the address, and then I print it and then pipe it into the vulnerable binary as stdin. However, what will happen when I print this, is that rather than printing the string equivalent of the associated hex values of that address, it will instead print this:
b'AAAAAAAAAAAAAAAAAAAA\x87\x80\x04\x08'
Just a string literal version of the hex values themselves. However, this will of course not be interpreted by the program in the way i intend it to be. So I try to decode it into utf-8 or an ASCII string, or even use str to convert it no matter which way I choose I get the following error:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x87 in position 20: invalid start byte
It would seem it can't decode the 0x87, which makes sense, in this case there does not seem to be an equivalent for it to decode to. But then my question becomes how can I deliver my shell code, specifically the hexadecimal address part, to the program in a way that the program will interpret that portion of the overflowed buffer as the address that i intend it to, rather than it being incorrectly mapped since my script gave me a stringified version of the hex values themselves?
printrequires a string. Importsysand usesys.stdout.write.process(ELF running on your PC) orremote(remote connection) to connect to the process, then you can use the functionssendandrecv(and derivatives)sys.stdout.buffer.writewas the answer, which gives me the forced terminal output I need. As for the prior issue, again output redirect happens at the shell level after the data has been written to stdout, no idea why python has an issue with it, so that eludes me still. Thanks for the help!sys.stdoutis aTextIOWrapperthat accepts strings. The underlying binary (buffered) stream is in itsbufferproperty, so itssys.stdout.buffer.writeto write bytes. But escapes onbytesobjects should work regardless of how they are used. But consider using theprocessclass ofpwntools, it s simpler.