#!/usr/bin/env python3
import base64
import json
import os
import re
import subprocess
import sys

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
DMP_PATH = os.path.join(SCRIPT_DIR, "..", "public", "suspicious_process.dmp")

if not os.path.exists(DMP_PATH):
    print(f"[!] Dump not found: {DMP_PATH}", file=sys.stderr)
    sys.exit(1)

result = subprocess.run(
    ["strings", DMP_PATH],
    capture_output=True, text=True, timeout=120
)
lines = result.stdout.split("\n")

# Flag 1: C2 URL (mc-update.evil.net/beacon)

flag1_found = False
for line in lines:
    if "mc-update.evil.net/beacon" in line:
        m = re.search(r"(https?://)?mc-update\.evil\.net/beacon", line)
        if m:
            print("Flag 1: vsosh{http://mc-update.evil.net/beacon}")
            flag1_found = True
            break

if not flag1_found:
    print("[!] Flag 1 not found — no 'mc-update.evil.net/beacon' in strings output",
          file=sys.stderr)

# Flag 2: Stolen password from base64-encoded config block

flag2_found = False
for line in lines:
    if "cached_config:" in line:
        # Extract base64 part after the marker
        parts = line.split("cached_config:", 1)
        if len(parts) > 1:
            candidate = parts[1].strip()
            try:
                decoded = base64.b64decode(candidate)
                data = json.loads(decoded)
                password = data.get("stolen_password", "")
                if password:
                    print(f"Flag 2: vsosh{{{password}}}")
                    flag2_found = True
            except Exception:
                pass
        if flag2_found:
            break

if not flag2_found:
    for line in lines:
        stripped = line.strip()
        if len(stripped) > 20 and stripped[-1] in ("=", "A", "Q", "g", "w"):
            try:
                decoded = base64.b64decode(stripped)
                data = json.loads(decoded)
                password = data.get("stolen_password", "")
                if password:
                    print(f"Flag 2: vsosh{{{password}}}")
                    flag2_found = True
                    break
            except Exception:
                continue

if not flag2_found:
    print("[!] Flag 2 not found — could not decode stolen_password from config block",
          file=sys.stderr)
