{% extends "base.html" %}
{% block title %}Hack Hijack — AUTARCH{% endblock %}
{% block content %}
<div class="page-header">
    <h1>Hack Hijack</h1>
    <p class="text-muted">Scan for existing compromises and take over backdoors</p>
</div>

<div class="tabs">
    <button class="tab active" onclick="switchTab('scan')">Scan Target</button>
    <button class="tab" onclick="switchTab('results')">Results</button>
    <button class="tab" onclick="switchTab('sessions')">Sessions <span id="session-count" class="badge" style="display:none">0</span></button>
    <button class="tab" onclick="switchTab('history')">History</button>
</div>

<!-- Scan Tab -->
<div id="tab-scan" class="tab-content active">
    <div style="display:grid;grid-template-columns:360px 1fr;gap:1.5rem;align-items:start">
        <!-- Config panel -->
        <div class="card">
            <h3>Target Scan</h3>
            <div class="form-group">
                <label>Target IP Address</label>
                <input type="text" id="hh-target" class="form-control" placeholder="192.168.1.100">
            </div>
            <div class="form-group">
                <label>Scan Type</label>
                <select id="hh-scan-type" class="form-control" onchange="toggleCustomPorts()">
                    <option value="quick">Quick — Backdoor signature ports only (~30 ports)</option>
                    <option value="full">Full — All suspicious ports (~70 ports)</option>
                    <option value="nmap">Nmap Deep — Service version + OS detection (requires nmap)</option>
                    <option value="custom">Custom — Specify ports</option>
                </select>
            </div>
            <div class="form-group" id="custom-ports-group" style="display:none">
                <label>Custom Ports (comma-separated)</label>
                <input type="text" id="hh-custom-ports" class="form-control" placeholder="22,80,443,445,4444,8080">
            </div>
            <div style="display:flex;gap:0.5rem">
                <button id="hh-scan-btn" class="btn btn-primary" onclick="startScan()" style="flex:1">Scan for Compromises</button>
                <button id="hh-cancel-btn" class="btn" style="display:none;background:var(--danger);color:#fff" onclick="cancelScan()">Cancel</button>
            </div>

            <!-- Progress bar -->
            <div id="hh-progress-wrap" style="display:none;margin-top:1rem">
                <div style="display:flex;justify-content:space-between;font-size:0.8rem;margin-bottom:4px">
                    <span id="hh-prog-label">Scanning…</span>
                    <span id="hh-prog-pct">0%</span>
                </div>
                <div style="background:var(--border);border-radius:4px;height:6px;overflow:hidden">
                    <div id="hh-prog-bar" style="height:100%;background:var(--accent);transition:width 0.3s;width:0"></div>
                </div>
            </div>
        </div>

        <!-- Live output -->
        <div class="card" style="display:flex;flex-direction:column">
            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:0.5rem">
                <h3 style="margin:0">Live Output</h3>
                <button class="btn btn-sm" onclick="clearOutput()">Clear</button>
            </div>
            <pre id="hh-output" style="background:#0d0d14;color:#c9d1d9;font-family:monospace;font-size:0.78rem;
                padding:12px;border-radius:var(--radius);height:340px;overflow-y:auto;
                white-space:pre-wrap;word-break:break-all;margin:0;border:1px solid var(--border)">Ready. Enter target and click Scan.</pre>

            <!-- Live found ports mini-table -->
            <div id="hh-live-ports" style="margin-top:0.75rem;display:none">
                <h4 style="font-size:0.8rem;color:var(--text-secondary);margin-bottom:6px">Live Discovered Ports</h4>
                <table class="data-table" style="font-size:0.78rem">
                    <thead><tr><th>Port</th><th>Service</th><th>Banner</th></tr></thead>
                    <tbody id="hh-live-ports-body"></tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="card" style="margin-top:1.5rem">
        <h3>What This Scans For</h3>
        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:1rem;font-size:0.85rem">
            <div><strong style="color:var(--danger)">EternalBlue</strong><br>DoublePulsar SMB implant, MS17-010 vulnerability</div>
            <div><strong style="color:#f59e0b">RAT / C2</strong><br>Meterpreter, Cobalt Strike, njRAT, DarkComet, Quasar, AsyncRAT, Gh0st, Poison Ivy</div>
            <div><strong style="color:#6366f1">Shell Backdoors</strong><br>Netcat listeners, bind shells, telnet backdoors, rogue SSH</div>
            <div><strong style="color:#22c55e">Web Shells</strong><br>PHP/ASP/JSP shells on HTTP services</div>
            <div><strong style="color:#8b5cf6">Proxies</strong><br>SOCKS, HTTP proxies, tunnels used as pivot points</div>
            <div><strong style="color:#06b6d4">Miners</strong><br>Cryptocurrency mining stratum connections</div>
        </div>
    </div>
</div>

<!-- Results Tab -->
<div id="tab-results" class="tab-content" style="display:none">
    <div id="hh-no-results" class="card" style="text-align:center;color:var(--text-muted)">
        No scan results yet. Run a scan from the Scan tab.
    </div>
    <div id="hh-results" style="display:none">
        <div class="card">
            <div style="display:flex;justify-content:space-between;align-items:center">
                <h3>Scan: <span id="res-target" style="color:var(--accent)"></span></h3>
                <span id="res-time" style="font-size:0.8rem;color:var(--text-muted)"></span>
            </div>
            <div style="display:flex;gap:2rem;margin:1rem 0;font-size:0.85rem">
                <div><strong id="res-ports-count">0</strong> open ports</div>
                <div><strong id="res-backdoors-count" style="color:var(--danger)">0</strong> backdoor indicators</div>
                <div>Duration: <strong id="res-duration">0</strong>s</div>
                <div id="res-os" style="display:none">OS: <strong id="res-os-text"></strong></div>
            </div>
        </div>

        <!-- Backdoors -->
        <div id="hh-backdoors-section" class="card" style="margin-top:1rem;display:none">
            <h3 style="color:var(--danger)">Backdoor Indicators</h3>
            <table class="data-table" style="margin-top:0.5rem">
                <thead><tr>
                    <th>Confidence</th><th>Signature</th><th>Port</th>
                    <th>Category</th><th>Details</th><th>Action</th>
                </tr></thead>
                <tbody id="hh-backdoors-body"></tbody>
            </table>
        </div>

        <!-- SMB Info -->
        <div id="hh-smb-section" class="card" style="margin-top:1rem;display:none">
            <h3>SMB / EternalBlue</h3>
            <div id="hh-smb-info" style="font-size:0.85rem"></div>
        </div>

        <!-- Open Ports -->
        <div class="card" style="margin-top:1rem">
            <h3>Open Ports</h3>
            <table class="data-table" style="margin-top:0.5rem">
                <thead><tr>
                    <th>Port</th><th>Protocol</th><th>Service</th><th>Banner</th>
                </tr></thead>
                <tbody id="hh-ports-body"></tbody>
            </table>
        </div>
    </div>
</div>

<!-- Sessions Tab -->
<div id="tab-sessions" class="tab-content" style="display:none">
    <div id="hh-no-sessions" class="card" style="text-align:center;color:var(--text-muted)">
        No active sessions. Take over a detected backdoor to start a session.
    </div>
    <div id="hh-sessions-list"></div>

    <!-- Shell terminal -->
    <div id="hh-shell" class="card" style="margin-top:1rem;display:none">
        <div style="display:flex;justify-content:space-between;align-items:center">
            <h3>Shell: <span id="shell-target" style="color:var(--accent)"></span></h3>
            <button class="btn btn-sm" style="background:var(--danger);color:#fff" onclick="closeCurrentSession()">Disconnect</button>
        </div>
        <div id="shell-output" style="background:#0a0a0a;color:#0f0;font-family:monospace;font-size:0.8rem;
            padding:1rem;border-radius:var(--radius);height:400px;overflow-y:auto;white-space:pre-wrap;margin:0.5rem 0"></div>
        <div style="display:flex;gap:0.5rem;margin-top:0.5rem">
            <input type="text" id="shell-input" class="form-control" placeholder="Enter command..."
                   onkeypress="if(event.key==='Enter')shellExec()" style="font-family:monospace">
            <button class="btn btn-primary" onclick="shellExec()">Run</button>
        </div>
    </div>
</div>

<!-- History Tab -->
<div id="tab-history" class="tab-content" style="display:none">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem">
        <h3>Scan History</h3>
        <button class="btn btn-sm" style="background:var(--danger);color:#fff" onclick="clearHistory()">Clear All</button>
    </div>
    <div id="hh-history-list"></div>
</div>

<style>
.badge{display:inline-block;background:var(--danger);color:#fff;border-radius:10px;padding:0 6px;font-size:0.7rem;margin-left:4px;vertical-align:top}
.conf-high{color:var(--danger);font-weight:700}
.conf-medium{color:#f59e0b;font-weight:600}
.conf-low{color:var(--text-muted)}
.cat-eternalblue{color:var(--danger)}
.cat-rat{color:#f59e0b}
.cat-shell{color:#6366f1}
.cat-webshell{color:#22c55e}
.cat-proxy{color:#8b5cf6}
.cat-miner{color:#06b6d4}
.cat-generic{color:var(--text-secondary)}
/* output line colors */
#hh-output .ln-status{color:#7dd3fc}
#hh-output .ln-open{color:#4ade80;font-weight:700}
#hh-output .ln-warn{color:#fbbf24}
#hh-output .ln-error{color:#f87171}
#hh-output .ln-done{color:#a78bfa;font-weight:700}
#hh-output .ln-prog{color:#6b7280}
</style>

<script>
let currentScanResult = null;
let currentSessionId = null;
let activeStream = null;
let currentJobId = null;

function switchTab(name){
    document.querySelectorAll('.tab').forEach((t,i)=>t.classList.toggle('active',
        ['scan','results','sessions','history'][i]===name));
    document.querySelectorAll('.tab-content').forEach(c=>c.style.display='none');
    document.getElementById('tab-'+name).style.display='block';
    if(name==='sessions') loadSessions();
    if(name==='history') loadHistory();
}

function toggleCustomPorts(){
    document.getElementById('custom-ports-group').style.display=
        document.getElementById('hh-scan-type').value==='custom'?'':'none';
}

function appendOutput(text, cls){
    const out = document.getElementById('hh-output');
    const line = document.createElement('span');
    if(cls) line.className = cls;
    line.textContent = text + '\n';
    out.appendChild(line);
    out.scrollTop = out.scrollHeight;
}

function clearOutput(){
    document.getElementById('hh-output').textContent = '';
}

function startScan(){
    const target = document.getElementById('hh-target').value.trim();
    if(!target){ alert('Enter a target IP'); return; }
    const scanType = document.getElementById('hh-scan-type').value;
    let customPorts = [];
    if(scanType === 'custom'){
        customPorts = document.getElementById('hh-custom-ports').value
            .split(',').map(p=>parseInt(p.trim())).filter(p=>p>0&&p<65536);
        if(!customPorts.length){ alert('Enter valid ports'); return; }
    }

    // Reset UI
    clearOutput();
    document.getElementById('hh-live-ports').style.display = 'none';
    document.getElementById('hh-live-ports-body').innerHTML = '';
    document.getElementById('hh-scan-btn').disabled = true;
    document.getElementById('hh-cancel-btn').style.display = '';
    document.getElementById('hh-progress-wrap').style.display = '';
    document.getElementById('hh-prog-bar').style.width = '0';
    document.getElementById('hh-prog-pct').textContent = '0%';
    document.getElementById('hh-prog-label').textContent = 'Starting…';
    appendOutput(`[*] Starting ${scanType} scan on ${target}…`, 'ln-status');

    fetch('/hack-hijack/scan', {method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({target, scan_type: scanType, custom_ports: customPorts})})
    .then(r=>r.json()).then(d=>{
        if(!d.ok){ scanDone(false, d.error); return; }
        currentJobId = d.job_id;
        openStream(d.job_id);
    }).catch(e=>scanDone(false, e.message));
}

function openStream(jobId){
    if(activeStream){ activeStream.close(); activeStream = null; }
    const es = new EventSource('/hack-hijack/scan/' + jobId + '/stream');
    activeStream = es;

    es.onmessage = function(e){
        try{ handleEvent(JSON.parse(e.data)); } catch(ex){}
    };
    es.onerror = function(){
        es.close(); activeStream = null;
        appendOutput('[!] Stream connection lost', 'ln-error');
        scanDone(false, 'Stream disconnected');
    };
}

function handleEvent(ev){
    switch(ev.type){
        case 'progress': {
            const pct = ev.pct || 0;
            document.getElementById('hh-prog-bar').style.width = pct + '%';
            document.getElementById('hh-prog-pct').textContent = pct + '%';
            if(ev.msg) document.getElementById('hh-prog-label').textContent = ev.msg;
            if(ev.msg) appendOutput('[~] ' + ev.msg, 'ln-prog');
            break;
        }
        case 'status':
            appendOutput('[*] ' + ev.msg, 'ln-status');
            document.getElementById('hh-prog-label').textContent = ev.msg;
            break;
        case 'port_found': {
            const svc = ev.service ? ` (${ev.service})` : '';
            const banner = ev.banner ? `  "${ev.banner.slice(0,60)}"` : '';
            appendOutput(`[+] OPEN  ${ev.port}/tcp${svc}${banner}`, 'ln-open');
            addLivePort(ev.port, ev.service, ev.banner);
            break;
        }
        case 'error':
            appendOutput('[!] ' + ev.msg, 'ln-error');
            break;
        case 'done':
            if(activeStream){ activeStream.close(); activeStream = null; }
            document.getElementById('hh-prog-bar').style.width = '100%';
            document.getElementById('hh-prog-pct').textContent = '100%';
            if(ev.ok){
                appendOutput('[✓] Scan complete — fetching results…', 'ln-done');
                fetchResult(currentJobId);
            } else {
                appendOutput('[!] Scan failed', 'ln-error');
                scanDone(false, 'Scan failed');
            }
            break;
    }
}

function addLivePort(port, service, banner){
    const tbody = document.getElementById('hh-live-ports-body');
    document.getElementById('hh-live-ports').style.display = '';
    const tr = document.createElement('tr');
    tr.innerHTML = `<td>${port}</td><td>${esc(service||'—')}</td>
        <td style="font-family:monospace;font-size:0.72rem;max-width:300px;overflow:hidden;text-overflow:ellipsis">${esc((banner||'').slice(0,80))}</td>`;
    tbody.appendChild(tr);
}

function fetchResult(jobId){
    fetch('/hack-hijack/scan/' + jobId)
    .then(r=>r.json()).then(d=>{
        if(!d.done){ setTimeout(()=>fetchResult(jobId), 500); return; }
        if(!d.ok){ scanDone(false, d.error); return; }
        currentScanResult = d.result;
        appendOutput(`[✓] Done — ${d.result.open_ports.length} ports, ${d.result.backdoors.length} backdoor indicators`, 'ln-done');
        scanDone(true);
        renderResults(d.result);
        switchTab('results');
    }).catch(e=>scanDone(false, e.message));
}

function scanDone(ok, errMsg){
    document.getElementById('hh-scan-btn').disabled = false;
    document.getElementById('hh-cancel-btn').style.display = 'none';
    document.getElementById('hh-progress-wrap').style.display = 'none';
    if(!ok && errMsg) appendOutput('[!] Error: ' + errMsg, 'ln-error');
    currentJobId = null;
}

function cancelScan(){
    if(activeStream){ activeStream.close(); activeStream = null; }
    appendOutput('[x] Scan cancelled by user', 'ln-warn');
    scanDone(false);
}

function renderResults(r){
    document.getElementById('hh-no-results').style.display='none';
    document.getElementById('hh-results').style.display='';
    document.getElementById('res-target').textContent=r.target;
    document.getElementById('res-time').textContent=(r.scan_time||'').replace('T',' ').slice(0,19)+' UTC';
    document.getElementById('res-ports-count').textContent=(r.open_ports||[]).length;
    document.getElementById('res-backdoors-count').textContent=(r.backdoors||[]).length;
    document.getElementById('res-duration').textContent=r.duration;
    if(r.os_guess){
        document.getElementById('res-os').style.display='';
        document.getElementById('res-os-text').textContent=r.os_guess;
    }

    // Ports table
    const pb=document.getElementById('hh-ports-body');
    pb.innerHTML='';
    (r.open_ports||[]).forEach(p=>{
        const tr=document.createElement('tr');
        tr.innerHTML=`<td>${p.port}</td><td>${p.protocol}</td><td>${p.service||'—'}</td>
            <td style="font-family:monospace;font-size:0.75rem;max-width:400px;overflow:hidden;text-overflow:ellipsis">${esc(p.banner||'')}</td>`;
        pb.appendChild(tr);
    });

    // Backdoors
    const bs=document.getElementById('hh-backdoors-section');
    const bb=document.getElementById('hh-backdoors-body');
    if((r.backdoors||[]).length){
        bs.style.display='';
        bb.innerHTML='';
        r.backdoors.forEach((b,i)=>{
            const tr=document.createElement('tr');
            tr.innerHTML=`<td class="conf-${b.confidence}">${b.confidence.toUpperCase()}</td>
                <td>${esc(b.signature)}</td><td>${b.port}</td>
                <td><span class="cat-${b.category}">${b.category}</span></td>
                <td style="font-size:0.8rem">${esc(b.details)}</td>
                <td><button class="btn btn-sm btn-primary" onclick="tryTakeover(${i})">Takeover</button></td>`;
            bb.appendChild(tr);
        });
    } else {
        bs.style.display='none';
    }

    // SMB
    const ss=document.getElementById('hh-smb-section');
    if(r.smb_info&&(r.smb_info.vulnerable||r.smb_info.os)){
        ss.style.display='';
        let html='';
        if(r.smb_info.vulnerable) html+='<p style="color:var(--danger);font-weight:700">MS17-010 (EternalBlue) VULNERABLE</p>';
        if(r.smb_info.os) html+=`<p>OS: ${esc(r.smb_info.os)}</p>`;
        if(r.smb_info.signing) html+=`<p>SMB Signing: ${esc(r.smb_info.signing)}</p>`;
        document.getElementById('hh-smb-info').innerHTML=html;
    } else {
        ss.style.display='none';
    }
}

function tryTakeover(idx){
    if(!currentScanResult) return;
    const bd=currentScanResult.backdoors[idx];
    const host=currentScanResult.target;
    fetch('/hack-hijack/takeover',{method:'POST',headers:{'Content-Type':'application/json'},
        body:JSON.stringify({host,backdoor:{port:bd.port,takeover_method:bd.takeover_method}})})
    .then(r=>r.json()).then(d=>{
        if(d.session_id){
            currentSessionId=d.session_id;
            switchTab('sessions');
            openShell(d.session_id,host+':'+bd.port,d.initial_output||d.message||'');
        } else {
            alert(d.message||d.error||'Takeover result received');
            if(d.msf_command){
                navigator.clipboard.writeText(d.msf_command).then(()=>{
                    alert('MSF command copied to clipboard');
                }).catch(()=>{});
            }
        }
    }).catch(e=>alert('Error: '+e.message));
}

function loadSessions(){
    fetch('/hack-hijack/sessions').then(r=>r.json()).then(d=>{
        const list=document.getElementById('hh-sessions-list');
        const badge=document.getElementById('session-count');
        const sessions=d.sessions||[];
        if(!sessions.length){
            document.getElementById('hh-no-sessions').style.display='';
            list.innerHTML='';
            badge.style.display='none';
            return;
        }
        document.getElementById('hh-no-sessions').style.display='none';
        badge.style.display='';badge.textContent=sessions.length;
        list.innerHTML=sessions.map(s=>`<div class="card" style="margin-bottom:0.5rem;cursor:pointer"
            onclick="openShell('${esc(s.session_id)}','${esc(s.host)}:${s.port}','')">
            <div style="display:flex;justify-content:space-between;align-items:center">
                <div><strong>${esc(s.type)}</strong> &rarr; ${esc(s.host)}:${s.port}</div>
                <div style="font-size:0.75rem;color:var(--text-muted)">${(s.connected_at||'').slice(0,19)}</div>
            </div></div>`).join('');
    });
}

function openShell(sessionId,label,initial){
    currentSessionId=sessionId;
    document.getElementById('hh-shell').style.display='';
    document.getElementById('shell-target').textContent=label;
    const out=document.getElementById('shell-output');
    out.textContent=initial||'Connected. Type commands below.\n';
    document.getElementById('shell-input').focus();
}

function shellExec(){
    if(!currentSessionId) return;
    const input=document.getElementById('shell-input');
    const cmd=input.value.trim();
    if(!cmd) return;
    input.value='';
    const out=document.getElementById('shell-output');
    out.textContent+='$ '+cmd+'\n';
    fetch('/hack-hijack/sessions/'+currentSessionId+'/exec',{
        method:'POST',headers:{'Content-Type':'application/json'},
        body:JSON.stringify({command:cmd})})
    .then(r=>r.json()).then(d=>{
        if(d.ok) out.textContent+=(d.output||'')+'\n';
        else out.textContent+='[error] '+(d.error||'failed')+'\n';
        out.scrollTop=out.scrollHeight;
    }).catch(e=>{out.textContent+='[error] '+e.message+'\n'});
}

function closeCurrentSession(){
    if(!currentSessionId) return;
    fetch('/hack-hijack/sessions/'+currentSessionId,{method:'DELETE'})
    .then(r=>r.json()).then(()=>{
        document.getElementById('hh-shell').style.display='none';
        currentSessionId=null;
        loadSessions();
    });
}

function loadHistory(){
    fetch('/hack-hijack/history').then(r=>r.json()).then(d=>{
        const list=document.getElementById('hh-history-list');
        const scans=d.scans||[];
        if(!scans.length){list.innerHTML='<div class="card" style="text-align:center;color:var(--text-muted)">No scan history</div>';return}
        list.innerHTML=scans.map(s=>{
            const highCount=(s.backdoors||[]).filter(b=>b.confidence==='high').length;
            const medCount=(s.backdoors||[]).filter(b=>b.confidence==='medium').length;
            return `<div class="card" style="margin-bottom:0.5rem;cursor:pointer" onclick='loadHistoryScan(${JSON.stringify(s).replace(/'/g,"&#39;")})'>
                <div style="display:flex;justify-content:space-between;align-items:center">
                    <div><strong>${esc(s.target)}</strong>
                        — ${(s.open_ports||[]).length} ports,
                        ${(s.backdoors||[]).length} indicators
                        ${highCount?'<span class="conf-high">('+highCount+' HIGH)</span>':''}
                        ${medCount?'<span class="conf-medium">('+medCount+' MED)</span>':''}
                    </div>
                    <div style="font-size:0.75rem;color:var(--text-muted)">${(s.scan_time||'').slice(0,19)} — ${s.duration}s</div>
                </div></div>`;
        }).join('');
    });
}

function loadHistoryScan(scan){
    currentScanResult=scan;
    renderResults(scan);
    switchTab('results');
}

function clearHistory(){
    if(!confirm('Clear all scan history?')) return;
    fetch('/hack-hijack/history',{method:'DELETE'}).then(r=>r.json()).then(()=>loadHistory());
}

function esc(s){return s?String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'):''}
</script>
{% endblock %}
