#!/usr/bin/env python3
import os
import re
import sys
from scapy.all import rdpcap, TCP, Raw

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PCAP_PATH = os.path.join(SCRIPT_DIR, "..", "public", "pinecraft_shop.pcap")

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

packets = rdpcap(PCAP_PATH)

flag1_found = False
flag2_found = False

for pkt in packets:
    if TCP in pkt and Raw in pkt:
        payload = bytes(pkt[Raw]).decode("utf-8", errors="ignore")

        if not flag1_found and "POST /login" in payload:
            m = re.search(r"username=([^&\s\r\n]+)", payload)
            if m:
                username = m.group(1)
                print(f"Flag 1: vsosh{{{username}}}")
                flag1_found = True

        if not flag2_found and "POST /admin/upload" in payload:
            m = re.search(r'filename="([^"]+)"', payload)
            if m:
                filename = m.group(1)
                print(f"Flag 2: vsosh{{{filename}}}")
                flag2_found = True

    if flag1_found and flag2_found:
        break

if not flag1_found:
    print("[!] Flag 1 not found — could not locate POST /login with username", file=sys.stderr)
if not flag2_found:
    print("[!] Flag 2 not found — could not locate POST /admin/upload with filename", file=sys.stderr)
