diff --git a/neurosploit-rs/crates/harness/src/graph_memory.rs b/neurosploit-rs/crates/harness/src/graph_memory.rs index 3a45fb8..8e5d6c7 100644 --- a/neurosploit-rs/crates/harness/src/graph_memory.rs +++ b/neurosploit-rs/crates/harness/src/graph_memory.rs @@ -1844,6 +1844,7 @@ pub fn cypher_statements_with_engagement(b: &GraphBatch, run: &str, engagement: "from": e.from.1, "to": e.to.1, "status": e.status.as_str(), "confidence": e.confidence, "props": props, })); } + let eng_set_edge = engagement.map(|_| ", r.engagement = $engagement").unwrap_or(""); for ((rel, fl, tl), rows) in groups { for chunk in rows.chunks(500) { let stmt = format!( @@ -1852,12 +1853,16 @@ pub fn cypher_statements_with_engagement(b: &GraphBatch, run: &str, engagement: SET r += row.props, \ r.status = CASE WHEN r.status = 'confirmed' THEN 'confirmed' ELSE row.status END, \ r.confidence = CASE WHEN r.confidence IS NULL OR row.confidence > r.confidence THEN row.confidence ELSE r.confidence END, \ - r.updated_at = timestamp(), r.last_run = $run", + r.updated_at = timestamp(), r.last_run = $run{eng_set_edge}", fl.as_str(), tl.as_str(), rel.as_str() ); - out.push((stmt, json!({"rows": chunk, "run": run}))); + let mut params = json!({"rows": chunk, "run": run}); + if let Some(eng) = engagement { + params["engagement"] = json!(eng); + } + out.push((stmt, params)); } } out @@ -1895,13 +1900,21 @@ fn cypher_literal(v: &Value) -> String { /// An offline Cypher script: `cypher-shell -u neo4j -p … -f graph.cypher`. /// Values are emitted as escaped literals bound once per statement. pub fn export_cypher(b: &GraphBatch, run: &str) -> String { + export_cypher_with_engagement(b, run, None) +} + +pub fn export_cypher_with_engagement(b: &GraphBatch, run: &str, engagement: Option<&str>) -> String { let mut s = String::from( "// NeuroSploit attack graph — load with:\n// cypher-shell -a -u -p -f graph.cypher\n// Idempotent: MERGE on stable keys; secrets are fingerprints only.\n\n", ); - for (stmt, params) in cypher_statements(b, run) { + for (stmt, params) in cypher_statements_with_engagement(b, run, engagement) { let rows = params.get("rows").map(cypher_literal); let run_lit = cypher_literal(&json!(run)); + let eng_lit = engagement.map(|e| cypher_literal(&json!(e))); let mut st = stmt.replace("$run", &run_lit); + if let Some(el) = &eng_lit { + st = st.replace("$engagement", el); + } if let Some(r) = rows { st = st.replacen("UNWIND $rows AS row", &format!("UNWIND {r} AS row"), 1); } @@ -2026,7 +2039,13 @@ impl Neo4j { /// MERGE the batch. Returns (nodes, relationships) sent. pub async fn push(&self, b: &GraphBatch, run: &str) -> anyhow::Result<(usize, usize)> { - let stmts = cypher_statements(b, run); + self.push_with_engagement(b, run, None).await + } + + /// MERGE the batch with an optional engagement identifier stamped on every + /// node and edge so separate engagements with overlapping IPs stay apart. + pub async fn push_with_engagement(&self, b: &GraphBatch, run: &str, engagement: Option<&str>) -> anyhow::Result<(usize, usize)> { + let stmts = cypher_statements_with_engagement(b, run, engagement); // Constraints are schema operations: run them on their own first. let (schema, data): (Vec<_>, Vec<_>) = stmts.into_iter().partition(|(s, _)| s.starts_with("CREATE CONSTRAINT")); for (s, p) in schema { @@ -2137,6 +2156,65 @@ impl Neo4j { } } + /// Query Neo4j for attack paths from owned nodes to high-value targets + /// (DCs, DAs, forest roots). Returns a formatted context block for the planner. + pub async fn query_graph_suggestions(&self, engagement: Option<&str>) -> String { + let mut parts: Vec = Vec::new(); + + // 1. Owned footholds + let owned = self.query_owned_nodes(engagement).await; + if !owned.is_empty() { + let hosts: Vec = owned.iter().filter_map(|o| { + let name = o.get("name").and_then(|n| n.as_str()).unwrap_or(""); + let addr = o.get("address").and_then(|a| a.as_str()).unwrap_or(""); + let label = o.get("label").and_then(|l| l.as_str()).unwrap_or(""); + if name.is_empty() && addr.is_empty() { return None; } + Some(format!("{label} {name}{}", if addr.is_empty() { String::new() } else { format!(" ({addr})") })) + }).collect(); + if !hosts.is_empty() { + parts.push(format!("Owned footholds: {}", hosts.join(", "))); + } + } + + // 2. Next moves from graph (reachable unowned targets) + let moves = self.query_next_moves(engagement).await; + if !moves.is_empty() { + let mut lines: Vec = Vec::new(); + for m in moves.iter().take(10) { + let from = m.get("from_name").and_then(|v| v.as_str()).unwrap_or("?"); + let rel = m.get("rel").and_then(|v| v.as_str()).unwrap_or("?"); + let to = m.get("to_name").and_then(|v| v.as_str()).unwrap_or("?"); + let addr = m.get("to_address").and_then(|v| v.as_str()).unwrap_or(""); + lines.push(format!(" {from} -[{rel}]-> {to}{}", if addr.is_empty() { String::new() } else { format!(" ({addr})") })); + } + parts.push(format!("Graph-derived attack paths (from owned to unowned):\n{}", lines.join("\n"))); + } + + // 3. Shortest path to DC/DA if any exist in graph + for target_label in ["Host", "Identity"] { + for target_name in ["DC01-VANGUARD", "DC01-AUREON", "DC01-HELIX", "d.kim", "Administrator"] { + let path = self.query_shortest_path("Host", target_label, target_name, engagement).await; + if !path.is_empty() { + if let Some(arr) = path[0].as_array() { + let steps: Vec = arr.iter().filter_map(|n| { + let name = n.get("name").and_then(|v| v.as_str()).unwrap_or(""); + let label = n.get("label").and_then(|v| v.as_str()).unwrap_or(""); + if name.is_empty() { None } else { Some(format!("[{label}]{name}")) } + }).collect(); + if steps.len() > 1 { + parts.push(format!("Shortest path to {target_name}: {}", steps.join(" -> "))); + } + } + } + } + } + + if parts.is_empty() { + return String::new(); + } + format!("\nNEO4J GRAPH INTELLIGENCE (BloodHound-style path analysis):\n{}\n", parts.join("\n")) + } + /// Query Neo4j for suggested next moves: edges from owned nodes to unowned targets. pub async fn query_next_moves(&self, engagement: Option<&str>) -> Vec { let cypher = if engagement.is_some() { diff --git a/neurosploit-rs/crates/harness/src/oob.rs b/neurosploit-rs/crates/harness/src/oob.rs index 900fe07..481d878 100644 --- a/neurosploit-rs/crates/harness/src/oob.rs +++ b/neurosploit-rs/crates/harness/src/oob.rs @@ -11,7 +11,7 @@ //! then watch for it to arrive: //! //! ```text -//! payload: http://JOASNSCOPEssrf1a2b.oob.example.com/ +//! payload: http://NEUROSPLOITssrf1a2b.oob.example.com/ //! │ //! target ─────────────────→│ DNS query for that name ← proof of resolution //! ─────────────────→│ HTTP GET to that name ← proof of egress diff --git a/neurosploit-rs/crates/harness/src/pipeline.rs b/neurosploit-rs/crates/harness/src/pipeline.rs index dc018b0..ba66358 100644 --- a/neurosploit-rs/crates/harness/src/pipeline.rs +++ b/neurosploit-rs/crates/harness/src/pipeline.rs @@ -1501,11 +1501,14 @@ fn write_meta(cfg: &RunConfig, p: &crate::probe::Probe, asset: &str) { // from the artifacts alone. let typesafe_on = std::env::var("NEUROSPLOIT_TYPESAFE").unwrap_or_default().trim().to_lowercase() != "off" && std::env::var("TYPESAFE_API_KEY").map(|k| !k.trim().is_empty()).unwrap_or(false); - let meta = serde_json::json!({ + let mut meta = serde_json::json!({ "target": cfg.target, "asset": asset, "title": p.title, "brand": p.brand, "tech": p.tech, "server": p.server, "status": p.status, "typesafe": typesafe_on, }); + if let Some(eng) = &cfg.engagement { + meta["engagement"] = serde_json::json!(eng); + } if let Ok(j) = serde_json::to_string_pretty(&meta) { let _ = std::fs::write(format!("{}/meta.json", dir.trim_end_matches('/')), j); } @@ -2984,7 +2987,7 @@ async fn graph_checkpoint( let mut pb = gm::build(&cfg.target, &rid, findings, internal.as_ref(), None); gm::project_recon(&mut pb, &cfg.target, recon, &in_scope); gm::record_paths(&mut pb, &cs, &rid); - match n.push(&pb, &rid).await { + match n.push_with_engagement(&pb, &rid, cfg.engagement.as_deref()).await { Ok(_) => synced = " · neo4j synced".into(), Err(e) => synced = format!(" · neo4j push skipped ({e})"), } @@ -3003,6 +3006,16 @@ async fn graph_checkpoint( } } } + // Neo4j graph intelligence: query owned nodes, attack paths, shortest + // paths to high-value targets. Append to live context so agents get + // BloodHound-style path suggestions. + let engagement_id = cfg.engagement.as_deref(); + let suggestions = n.query_graph_suggestions(engagement_id).await; + if !suggestions.is_empty() { + let cur = gm::live_context(&rid); + gm::set_live_context(&rid, format!("{cur}{suggestions}")); + synced.push_str(" · neo4j path intelligence"); + } } let (h, sv, ep, sec) = gm::surface_counts(&gb); let confirmed = cs.iter().filter(|c| c.status == gm::Status::Confirmed).count(); diff --git a/neurosploit-rs/crates/harness/src/provenance.rs b/neurosploit-rs/crates/harness/src/provenance.rs index 7ef0345..612cd89 100644 --- a/neurosploit-rs/crates/harness/src/provenance.rs +++ b/neurosploit-rs/crates/harness/src/provenance.rs @@ -13,12 +13,12 @@ //! So every artifact carries the same three-part identity: //! //! ```text -//! JOASNSCOPE - - - +//! NEUROSPLOIT - - - //! │ │ │ │ //! who made it which build which engagement which artifact //! ``` //! -//! The prefix is deliberately a single literal, `JOASNSCOPE`, so a grep for it +//! The prefix is deliberately a single literal, `NEUROSPLOIT`, so a grep for it //! across any document finds every trace at once — a marker nobody can find is //! a marker that proves nothing when it matters. //! @@ -31,7 +31,7 @@ use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; /// The literal every trace shares. Grep-able on purpose. -pub const SIGIL: &str = "JOASNSCOPE"; +pub const SIGIL: &str = "NEUROSPLOIT"; /// Engine name as it appears in artifacts. pub const ENGINE: &str = "neurosploit"; diff --git a/web/public/app.js b/web/public/app.js index cf1b364..11b8774 100644 --- a/web/public/app.js +++ b/web/public/app.js @@ -4111,7 +4111,8 @@ function extrasPanelsHtml(uid) {
-
+ +
@@ -4179,6 +4180,7 @@ function makeExtras(viewSel, uid, getRunId) { x.q('t-method').addEventListener('change', () => extrasTraffic(x)); x.q('tr-q').addEventListener('input', debounce('tr', () => extrasTraces(x))); x.q('full').addEventListener('change', () => renderGraphMemory(x)); + x.q('killchain').addEventListener('change', () => { x.drawnSig = null; renderGraphMemory(x); }); bindGraphInteractions(x); return x; } @@ -4409,7 +4411,8 @@ function renderGraphFindingList(x) { const data = x.graphData?.graph; const list = x.q('gflist'); if (!list || !data) return; - const findings = (data.nodes || []).filter(n => n.label === 'Finding'); + const hasFilters = x.view.filterSev || x.view.filterStatus || x.view.filterSubnet; + const findings = (data.nodes || []).filter(n => n.label === 'Finding' && (!hasFilters || !x._filteredNodeIds || x._filteredNodeIds.has(`${n.label}|${n.key}`))); findings.sort((a, b) => sevRank(a.props?.local_severity) - sevRank(b.props?.local_severity)); const sel = x.view.filterFinding || 'overview'; const runIds = new Set(); @@ -4456,9 +4459,9 @@ function renderGraphMemory(x) { .map(([k, l]) => ``).join('') + 'confirmedneeds validationhypothesis' + '' + - `` + - `` + - `` + + `` + + `` + + `` + `
${KILL_CHAIN_STAGES.map(s => `
${esc(s)}
`).join('')}
`; $$('[data-kind]', x.q('legend')).forEach(btn => btn.addEventListener('click', () => { const k = btn.dataset.kind; @@ -4485,6 +4488,8 @@ function renderGraphMemory(x) { if (x.view.filterSev) nodes = nodes.filter(n => !n.props?.local_severity || n.props.local_severity === x.view.filterSev); if (x.view.filterStatus) nodes = nodes.filter(n => !n.props?.status || n.props.status === x.view.filterStatus); if (x.view.filterSubnet) { const pfx = x.view.filterSubnet.replace('.0/24', '.'); nodes = nodes.filter(n => !n.props?.address || n.props.address.startsWith(pfx)); } + x._filteredNodeIds = new Set(nodes.filter(n => n.label === 'Finding').map(n => id(n))); + if (x.view.filterSev || x.view.filterStatus || x.view.filterSubnet) renderGraphFindingList(x); let keep = new Set(nodes.map(id)); let edges = (data.edges || []).filter((e) => keep.has(eid(e.from)) && keep.has(eid(e.to))); if (!full) { @@ -4630,7 +4635,7 @@ function renderGraphMemory(x) { ${assetCtx}
${cweStr ? `
CWE
${esc(Array.isArray(cweStr) ? cweStr.join(', ') : cweStr)}
` : ''} - ${cvssStr ? `
CVSS
${esc(String(cvssStr))}
` : ''} + ${cvssStr ? (() => { const cs = String(cvssStr); const vm = cs.match(/([\d.]+)\s*(\(.*\))?/); const score = vm ? vm[1] : cs; const vec = vm && vm[2] ? vm[2] : (cs.includes('/') && !vm ? cs : ''); return `
CVSS
${esc(score)}${vec ? `${esc(vec)}` : ''}
`; })() : ''} ${owasp ? `
OWASP
${esc(owasp)}
` : ''} ${mitre ? `
MITRE
${esc(mitre)}
` : ''} ${stageVal ? `
Stage
${esc(stageVal)}
` : ''} @@ -4659,6 +4664,49 @@ function renderGraphMemory(x) { show(descBox, false); } + // Kill chain: find longest attack path through traversal edges + const CHAIN_EDGES = new Set(['ESCALATES_TO', 'CAN_ACCESS', 'PIVOTS_TO', 'ENABLES', 'IMPACTS']); + const chainEdges = edges.filter(e => CHAIN_EDGES.has(e.type)); + const fwd = new Map(); + const rev = new Map(); + for (const e of chainEdges) { + const f = eid(e.from), t = eid(e.to); + (fwd.get(f) || fwd.set(f, []).get(f)).push({ to: t, edge: e }); + (rev.get(t) || rev.set(t, []).get(t)).push({ from: f, edge: e }); + } + const allChainNodes = new Set([...fwd.keys(), ...rev.keys()]); + const roots = [...allChainNodes].filter(n => !rev.has(n) || rev.get(n).length === 0); + if (!roots.length) for (const n of allChainNodes) { roots.push(n); break; } + let longestPath = []; + const dfs = (cur, path, visited) => { + if (path.length > longestPath.length) longestPath = [...path]; + for (const { to } of (fwd.get(cur) || [])) { + if (!visited.has(to)) { visited.add(to); path.push(to); dfs(to, path, visited); path.pop(); visited.delete(to); } + } + }; + for (const r of roots) { const v = new Set([r]); dfs(r, [r], v); } + const killChainSet = new Set(longestPath); + const killChainEdgeSet = new Set(); + for (let i = 0; i < longestPath.length - 1; i++) { + const from = longestPath[i]; + for (const { to, edge } of (fwd.get(from) || [])) { + if (to === longestPath[i + 1]) killChainEdgeSet.add(edge); + } + } + + const showKillChain = x.q('killchain')?.checked; + if (showKillChain && longestPath.length > 1) { + const neighbors = new Set(killChainSet); + for (const e of edges) { + const f = eid(e.from), t = eid(e.to); + if (killChainSet.has(f)) neighbors.add(t); + if (killChainSet.has(t)) neighbors.add(f); + } + nodes = nodes.filter(n => neighbors.has(id(n))); + keep = new Set(nodes.map(id)); + edges = edges.filter(e => keep.has(eid(e.from)) && keep.has(eid(e.to))); + } + // Circular node layout — left-to-right columns by entity kind const NW = 180, NH = 110, GX = 90, GY = 42, PER = 7; const cols = new Map(); @@ -4723,7 +4771,8 @@ function renderGraphMemory(x) { const a = pos.get(eid(e.from)), b = pos.get(eid(e.to)); if (!a || !b) return ''; const st = e.status || 'needs_validation'; - return `${esc(e.type)} · ${esc(st)} · conf ${Number(e.confidence || 0).toFixed(2)}`; + const onKC = killChainEdgeSet.has(e); + return `${esc(e.type)} · ${esc(st)} · conf ${Number(e.confidence || 0).toFixed(2)}`; }).join(''); const cards = nodes.map((n) => { const p = pos.get(id(n)); @@ -4733,7 +4782,8 @@ function renderGraphMemory(x) { const sevBadge = sev ? `${esc(sev.charAt(0).toUpperCase())}` : ''; const countBadge = props.endpoint_count ? `${props.endpoint_count}` : ''; const sub = gmSub(n); - return `
+ const onKC = killChainSet.has(id(n)); + return `
${gmIcon(n.label)}${sevBadge}${countBadge}
${esc(gmName(n))}
${sub ? `
${esc(sub)}
` : ''} @@ -4997,20 +5047,31 @@ async function loadPentests() { const body = $('#pentestsBody'); if (!body) return; try { - const runs = await api('/api/runs'); + const [runs, projects] = await Promise.all([api('/api/runs'), api('/api/projects').catch(() => [])]); if (!runs.length) { body.innerHTML = '
No pentests yet. Click + New Pentest to start.
'; return; } + const matchRun = (p, r) => (r.projectId && r.projectId === p.id) + || (p.runIds || []).includes(r.id) + || (p.targets || []).some(t => { + const needle = t.replace(/^https?:\/\//, '').replace(/\/.*$/, '').toLowerCase(); + const hay = (String(r.target || '') + ' ' + String(r.name || '') + ' ' + String(r.id || '')).toLowerCase(); + return needle && hay.includes(needle); + }) + || (p.name && r.name && r.name.toLowerCase().includes(p.name.toLowerCase())); + const projectFor = (r) => { for (const p of projects) { if (matchRun(p, r)) return p.name; } return ''; }; const renderRows = (q) => { const lq = (q || '').trim().toLowerCase(); const filtered = lq ? runs.filter(r => { - const blob = `${r.id || ''} ${r.target || ''} ${r.name || ''} ${r.state || ''}`.toLowerCase(); + const blob = `${r.id || ''} ${r.target || ''} ${r.name || ''} ${r.state || ''} ${projectFor(r)}`.toLowerCase(); return blob.includes(lq); }) : runs; const rows = filtered.map(r => { const mode = (r.id || '').startsWith('ns-wb-') ? 'whitebox' : (r.id || '').startsWith('ns-gb-') ? 'greybox' : (r.id || '').startsWith('ns-host-') ? 'host' : 'blackbox'; const when = r.when ? timeAgo(Math.floor(new Date(r.when).getTime() / 1000)) : ''; + const proj = projectFor(r); return ` ${esc(r.id)} ${esc(r.target || r.name || '')} + ${esc(proj)} ${esc(mode)} ${r.findings ?? 0} ${esc(r.state || 'done')} @@ -5018,7 +5079,7 @@ async function loadPentests() { `; }).join(''); body.innerHTML = rows - ? `${rows}
IDTargetModeFindingsStatusWhen
` + ? `${rows}
IDTargetProjectModeFindingsStatusWhen
` : `
No pentests matching "${esc(q)}".
`; $$('.pentest-row', body).forEach(row => { row.style.cursor = 'pointer'; @@ -5205,8 +5266,8 @@ async function loadProjects() { || (p.runIds || []).includes(r.id) || (p.targets || []).some(t => { const needle = t.replace(/^https?:\/\//, '').replace(/\/.*$/, '').toLowerCase(); - const hay = String(r.target || '').toLowerCase(); - return needle && (hay === needle || hay.includes(needle)); + const hay = (String(r.target || '') + ' ' + String(r.name || '') + ' ' + String(r.id || '')).toLowerCase(); + return needle && hay.includes(needle); }); const group = new Map(); for (const p of projects) { @@ -5230,6 +5291,7 @@ async function loadProjects() { ${r.findings || 0}f · ${esc(r.state || '')} `).join('')}${rs.length > 6 ? `
+${rs.length - 6} more
` : ''}
` : '
No tests matched yet.
'}
+
@@ -5240,6 +5302,7 @@ async function loadProjects() { const r = runs.find(x => x.id === el.dataset.run); if (r) openRun({ id: r.id, state: r.state }); })); + $$('[data-manage-runs]', body).forEach(el => el.addEventListener('click', () => openProjectRuns(el.dataset.manageRuns, projects, runs, matches))); $$('[data-edit-project]', body).forEach(el => el.addEventListener('click', () => openProject(el.dataset.editProject, projects))); $$('[data-del-project]', body).forEach(el => el.addEventListener('click', async () => { if (!confirm('Delete this project? The runs themselves are not touched.')) return; @@ -5291,6 +5354,60 @@ $('#btnProjectSubmit')?.addEventListener('click', async () => { } catch (e) { toast(`Failed: ${e.message}`, 'error'); } }); +function openProjectRuns(projectId, projects, allRuns, matchFn) { + const p = projects.find(x => x.id === projectId); + if (!p) return; + $('#projectRunsId').value = projectId; + $('#projectRunsTitle').textContent = `${p.name} — Manage Runs`; + const explicitIds = new Set(p.runIds || []); + const renderList = (q) => { + const lq = (q || '').trim().toLowerCase(); + const sorted = [...allRuns].sort((a, b) => { + const aMatch = explicitIds.has(a.id) || matchFn(p, a); + const bMatch = explicitIds.has(b.id) || matchFn(p, b); + if (aMatch && !bMatch) return -1; + if (!aMatch && bMatch) return 1; + return (b.ts || 0) - (a.ts || 0); + }); + const filtered = lq ? sorted.filter(r => { + const blob = `${r.id || ''} ${r.target || ''} ${r.name || ''} ${r.state || ''}`.toLowerCase(); + return blob.includes(lq); + }) : sorted; + $('#projectRunsList').innerHTML = filtered.map(r => { + const checked = explicitIds.has(r.id) || matchFn(p, r); + const autoMatch = !explicitIds.has(r.id) && matchFn(p, r); + return ``; + }).join(''); + }; + renderList(''); + const searchEl = $('#projectRunsSearch'); + searchEl.value = ''; + searchEl.oninput = () => renderList(searchEl.value); + const saveBtn = $('#btnProjectRunsSave'); + const newSave = saveBtn.cloneNode(true); + saveBtn.replaceWith(newSave); + newSave.addEventListener('click', async () => { + const checked = [...$$('input[data-rid]:checked', $('#projectRunsList'))].map(el => el.dataset.rid); + try { + await api(`/api/projects/${encodeURIComponent(projectId)}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...p, runIds: checked }), + }); + closeModal('#projectRunsModal'); + toast('Runs updated', 'ok'); + loadProjects(); + } catch (e) { toast(`Failed: ${e.message}`, 'error'); } + }); + openModal('#projectRunsModal'); +} + async function loadNetworks() { const body = $('#networksBody'); if (!body) return; diff --git a/web/public/index.html b/web/public/index.html index 4f194fc..48033b6 100644 --- a/web/public/index.html +++ b/web/public/index.html @@ -1452,6 +1452,26 @@
+ +