Merge pull request #56 from JoasASantos/feat/neo4j-graph

feat(graph): managed Neo4j, exploration graph sync and chain leads
This commit is contained in:
Joas A Santos authored and GitHub committed 2026-11-15 22:57:36 -03:00
commit cdc4a15e73
10 files changed
+760 -10

No files matched your search

+2
View File
@@ -97,6 +97,8 @@ TYPESAFE_API_KEY=
#NEO4J_USER=neo4j
#NEO4J_PASSWORD=
#NEO4J_DATABASE=neo4j
# Or skip all of the above: `neurosploit neo4j up` runs a local Neo4j in Docker and
# runs use it automatically (connection saved to ~/.neurosploit/neo4j.json, mode 0600).
# Salt for the graph's secret fingerprints (so credential reuse correlates
# without storing any secret). Share one value across a team that shares a Neo4j.
# Defaults to ~/.neurosploit/graph-salt when unset.
+24 -6
View File
@@ -800,15 +800,33 @@ watch the graph evolve (the web console's Attack graph tab reads these).
### Enabling Neo4j (optional)
Point the run at a Neo4j and the graph is MERGEd in at the end, and accumulated paths from earlier
runs are read back:
**Easiest: let NeuroSploit run it.** One command starts a local Neo4j in Docker, generates a
password, saves the connection, and from then on every run uses it automatically:
```bash
# one-time: a local Neo4j in Docker
docker run -d --name neo4j -p7474:7474 -p7687:7687 \
-e NEO4J_AUTH=neo4j/please-change-me neo4j:5
neurosploit neo4j up # create/start (127.0.0.1 only), wait until ready
neurosploit neo4j status # state, URLs, whether runs use it automatically
neurosploit neo4j info # connection details (--show-password to reveal)
neurosploit neo4j sync <run> # push a run's exploration graph, print chain leads
neurosploit neo4j down # stop (data kept); add --purge to delete data + saved connection
```
# credentials ONLY via env — never on the command line, never written to disk
- The connection (including the generated password) is saved to `~/.neurosploit/neo4j.json`
(or `$NEUROSPLOIT_HOME/neo4j.json`) with mode `0600`. The password is handed to Docker through
the environment, never on a command line.
- `neurosploit neo4j up --no-auto` starts it but keeps runs from using it unless you pass `--neo4j`.
- An explicit `--neo4j` or `NEO4J_URI` always wins over the managed instance.
- With Neo4j active, each graph checkpoint also pushes the **exploration graph** (assets, goals,
intents, facts, negatives, findings and their anchors) and reads back **chain leads**: untested
assets sitting next to something already broken. Those leads are injected into agent prompts as
unverified hypotheses.
- The web console backend exposes the same controls: `GET /api/neo4j/status`,
`POST /api/neo4j/up`, `POST /api/neo4j/down`, `POST /api/runs/<id>/neo4j-sync`.
- Prefer compose? `NEO4J_PASSWORD=... docker compose -f docker-compose.neo4j.yml up -d`.
**Bring your own Neo4j.** Point the run at any instance; credentials only via env:
```bash
export NEO4J_USER=neo4j NEO4J_PASSWORD='please-change-me'
neurosploit run https://app.example --neo4j bolt://localhost:7687
```
+31
View File
@@ -0,0 +1,31 @@
# Local Neo4j for NeuroSploit's attack / exploration graph.
#
# NEO4J_PASSWORD='choose-a-password' docker compose -f docker-compose.neo4j.yml up -d
# export NEO4J_URI=bolt://127.0.0.1:7687 NEO4J_USER=neo4j NEO4J_PASSWORD='choose-a-password'
#
# Or skip all of this and let NeuroSploit manage it for you (generated password,
# saved with mode 0600, used automatically by runs):
#
# neurosploit neo4j up
#
# Ports are bound to loopback only. Do not publish them on a shared network.
services:
neo4j:
image: neo4j:5-community
container_name: neurosploit-neo4j
restart: unless-stopped
ports:
- "127.0.0.1:7474:7474" # browser / HTTP transactional API (what NeuroSploit uses)
- "127.0.0.1:7687:7687" # bolt
environment:
NEO4J_AUTH: "neo4j/${NEO4J_PASSWORD:?set NEO4J_PASSWORD}"
volumes:
- neurosploit-neo4j-data:/data
healthcheck:
test: ["CMD-SHELL", "wget -q --spider http://localhost:7474 || exit 1"]
interval: 10s
timeout: 5s
retries: 12
volumes:
neurosploit-neo4j-data:
+99 -1
View File
@@ -254,6 +254,13 @@ enum Cmd {
#[arg(long = "top", default_value_t = 5)]
top: usize,
},
/// Manage the local Neo4j used for the attack/exploration graph: start it in
/// Docker, check it, stop it, sync a run into it. Once `up`, runs use it
/// automatically (no --neo4j flag or NEO4J_* variables needed).
Neo4j {
#[command(subcommand)]
cmd: Neo4jCmd,
},
/// Verify a finished run's audit trail — the hash chain and, with --anchor,
/// the signed anchors that catch truncation and silent rebuilds.
Audit {
@@ -892,6 +899,7 @@ async fn main() -> anyhow::Result<()> {
Cmd::Compliance { run, framework, include_leads } => handle_compliance(&base, &run, &framework, include_leads)?,
Cmd::Poc { run, repeats, apply, only, json } => handle_poc(&base, &run, repeats, apply, only, json).await?,
Cmd::Sandbox { cmd } => handle_sandbox(cmd).await?,
Cmd::Neo4j { cmd } => handle_neo4j(&base, cmd).await?,
Cmd::Capability { cmd } => handle_capability(cmd)?,
Cmd::Provenance { cmd } => handle_provenance(cmd)?,
Cmd::Internal { graph, scaffold, from, expand, mermaid, save } => {
@@ -1629,6 +1637,41 @@ fn apply_authorization(
Ok(())
}
#[derive(Subcommand)]
enum Neo4jCmd {
/// Create/start the Neo4j container (127.0.0.1 only), save the connection,
/// and wait until it answers. Safe to re-run.
Up {
/// Image (default neo4j:5-community).
#[arg(long)]
image: Option<String>,
/// Start it but do not let runs use it automatically.
#[arg(long = "no-auto")]
no_auto: bool,
},
/// Stop and remove the container (data volume kept unless --purge).
Down {
/// Also delete the data volume and the saved connection.
#[arg(long)]
purge: bool,
},
/// Show container and connection state.
Status {
#[arg(long)]
json: bool,
},
/// Push a finished run's graphs into Neo4j and print chain leads.
Sync {
/// Run id (`ns-…`) or a path to the run directory.
run: String,
},
/// Print the saved connection (password hidden unless --show-password).
Info {
#[arg(long = "show-password")]
show_password: bool,
},
}
#[derive(Subcommand)]
enum SandboxCmd {
/// Pull the image and start the container.
@@ -1862,7 +1905,9 @@ async fn handle_graph(base: &std::path::Path, run: &str, internal: Option<&str>,
anyhow::bail!("{} is not a readable internal graph", ipath.display());
}
let mut b = gm::build(&target, &run_id, &findings, ig.as_ref(), None);
let neo = gm::Neo4j::resolve(neo4j).filter(|_| push || neo4j.is_some() || std::env::var("NEO4J_URI").is_ok());
let neo = gm::Neo4j::resolve(neo4j).filter(|_| {
push || neo4j.is_some() || std::env::var("NEO4J_URI").is_ok() || harness::neo4j_managed::auto_connection().is_some()
});
if let Some(n) = &neo {
let mut pushed = b.clone();
let local = gm::chains(&pushed, 8, 50);
@@ -2043,6 +2088,59 @@ async fn handle_poc(base: &std::path::Path, run: &str, repeats: usize, apply: bo
Ok(())
}
async fn handle_neo4j(base: &std::path::Path, cmd: Neo4jCmd) -> anyhow::Result<()> {
use harness::neo4j_managed as nm;
match cmd {
Neo4jCmd::Up { image, no_auto } => {
println!(" starting Neo4j (this can take a minute on first boot)…");
let c = nm::up(image.as_deref(), !no_auto).await.map_err(|e| anyhow::anyhow!(e))?;
println!(" \x1b[1;32m✓\x1b[0m neo4j ready");
println!(" browser : {}", c.http_uri());
println!(" bolt : {}", c.bolt_uri());
println!(" user : {} (password saved to {}, mode 0600)", c.user,
nm::config_path().map(|p| p.display().to_string()).unwrap_or_default());
println!(" runs use it {}", if c.auto { "automatically" } else { "only with --neo4j (auto disabled)" });
}
Neo4jCmd::Down { purge } => {
nm::down(purge).await.map_err(|e| anyhow::anyhow!(e))?;
println!(" neo4j stopped{}", if purge { " and data purged" } else { " (data volume kept)" });
}
Neo4jCmd::Status { json } => {
let s = nm::status().await;
if json {
println!("{}", serde_json::to_string(&s)?);
} else {
println!(" state : {:?}{}", s.state, if s.ready { " (ready)" } else { "" });
if let Some(r) = &s.runtime { println!(" runtime : {r}"); }
if let Some(u) = &s.browser { println!(" browser : {u}"); }
println!(" auto-use: {}", s.auto);
}
}
Neo4jCmd::Info { show_password } => {
let c = nm::load().ok_or_else(|| anyhow::anyhow!("no managed neo4j configured — run `neurosploit neo4j up`"))?;
println!(" http: {}\n bolt: {}\n user: {}\n db : {}\n pass: {}", c.http_uri(), c.bolt_uri(), c.user, c.database,
if show_password { c.password.clone() } else { "(hidden; use --show-password)".into() });
}
Neo4jCmd::Sync { run } => {
let n = harness::graph_memory::Neo4j::resolve(None)
.ok_or_else(|| anyhow::anyhow!("no neo4j configured — run `neurosploit neo4j up` or set NEO4J_URI"))?;
let dir = resolve_run(base, &run)?;
let target = std::fs::read_to_string(dir.join("meta.json")).ok()
.and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
.and_then(|v| v.get("target").and_then(|x| x.as_str()).map(String::from))
.unwrap_or_else(|| run.clone());
let rid = dir.file_name().and_then(|s| s.to_str()).unwrap_or("run").to_string();
let dg = harness::exploration_graph::DualGraph::load(&dir.join("graphs"))
.map_err(|e| anyhow::anyhow!("no exploration graph in {} ({e})", dir.join("graphs").display()))?;
let leads = harness::neo4j_exploration::sync(&n, &dg, &target, &rid).await?;
println!(" neo4j: synced {} asset(s), {} exploration node(s) → {}", dg.assets.nodes.len(), dg.exploration.nodes.len(), n.label());
if leads.is_empty() { println!(" no chain leads yet"); }
for l in &leads { println!(" lead: {l}"); }
}
}
Ok(())
}
async fn handle_sandbox(cmd: SandboxCmd) -> anyhow::Result<()> {
use harness::sandbox::{Sandbox, SandboxConfig};
let mk = |image: Option<String>, mount: Option<String>| -> anyhow::Result<Sandbox> {
@@ -1930,10 +1930,41 @@ pub struct Neo4j {
}
impl Neo4j {
/// From an explicit URI, else `NEO4J_URI`. `None` when neither is set.
/// From an explicit URI, else `NEO4J_URI`, else the managed local instance
/// (`neurosploit neo4j up`) when it is configured for automatic use.
/// `None` when none of those is set.
pub fn resolve(explicit: Option<&str>) -> Option<Neo4j> {
let uri = explicit.map(str::to_string).filter(|s| !s.trim().is_empty()).or_else(|| std::env::var("NEO4J_URI").ok().filter(|s| !s.trim().is_empty()))?;
Some(Neo4j::new(&uri))
let uri = explicit.map(str::to_string).filter(|s| !s.trim().is_empty()).or_else(|| std::env::var("NEO4J_URI").ok().filter(|s| !s.trim().is_empty()));
if let Some(uri) = uri { return Some(Neo4j::new(&uri)); }
let (uri, db, user, pass) = crate::neo4j_managed::auto_connection()?;
Some(Neo4j::with_credentials(&uri, &db, &user, &pass))
}
pub fn with_credentials(uri: &str, db: &str, user: &str, pass: &str) -> Neo4j {
Neo4j {
base: http_base(uri),
db: db.to_string(),
user: user.to_string(),
pass: pass.to_string(),
http: reqwest::Client::builder().timeout(std::time::Duration::from_secs(60)).build().unwrap_or_default(),
}
}
/// Run a batch of (cypher, params) statements in one transaction each chunk.
/// Used by sibling modules (exploration graph sync); returns the raw result.
pub async fn run_statements(&self, stmts: Vec<(String, Value)>) -> anyhow::Result<Vec<Value>> {
let mut out = Vec::new();
for chunk in stmts.chunks(10) {
out.push(self.tx(chunk.iter().map(|(s, p)| json!({"statement": s, "parameters": p})).collect()).await?);
}
Ok(out)
}
/// One read query; rows come back as JSON arrays in column order.
pub async fn query_rows(&self, cypher: &str, params: Value) -> anyhow::Result<Vec<Vec<Value>>> {
let v = self.tx(vec![json!({"statement": cypher, "parameters": params, "resultDataContents": ["row"]})]).await?;
Ok(v.pointer("/results/0/data").and_then(|d| d.as_array()).cloned().unwrap_or_default().into_iter()
.filter_map(|r| r.get("row").and_then(|x| x.as_array()).cloned()).collect())
}
pub fn new(uri: &str) -> Neo4j {
+2
View File
@@ -49,6 +49,8 @@ pub mod redact;
pub mod request_analyzer;
pub mod provenance;
pub mod models;
pub mod neo4j_exploration;
pub mod neo4j_managed;
pub mod netguard;
pub mod noise_governor;
pub mod oob;
@@ -0,0 +1,219 @@
//! Exploration graph in Neo4j — connected history to chain exploitation.
//!
//! `graph_memory` already stores the attack graph (findings, identities,
//! permissions, impact) in Neo4j. This module adds the *exploration* side from
//! [`crate::exploration_graph::DualGraph`]: what exists on the target (assets),
//! what was tried (goals, intents, facts, negatives, hints, findings) and how
//! they connect. Having both in one graph lets a Cypher query answer the
//! question that drives chaining: *"which untested assets sit next to something
//! I already broke?"*
//!
//! Everything that builds Cypher is pure and unit-tested. Labels and
//! relationship types come only from closed enums (never from model output), so
//! there is no Cypher injection surface; all free text travels as parameters.
use crate::exploration_graph::{AnchorDirection, DualGraph};
use serde_json::{json, Value};
use std::collections::BTreeMap;
/// `ParentOf` -> `PARENT_OF`. Input is a Debug-printed enum variant.
fn screaming(name: &str) -> String {
let mut out = String::new();
for (i, c) in name.chars().filter(|c| c.is_ascii_alphanumeric()).enumerate() {
if c.is_ascii_uppercase() && i > 0 { out.push('_'); }
out.push(c.to_ascii_uppercase());
}
out
}
fn asset_key(target: &str, id: &str) -> String { format!("{target}|{id}") }
fn exp_key(target: &str, run: &str, id: &str) -> String { format!("{target}|{run}|{id}") }
/// Cypher to MERGE the whole dual graph. Idempotent: re-running updates in place.
pub fn statements(dg: &DualGraph, target: &str, run: &str) -> Vec<(String, Value)> {
let mut out: Vec<(String, Value)> = Vec::new();
out.push(("CREATE CONSTRAINT ns_exploration_key IF NOT EXISTS FOR (n:Exploration) REQUIRE n.key IS UNIQUE".into(), json!({})));
out.push(("CREATE CONSTRAINT ns_asset_key IF NOT EXISTS FOR (n:AssetNode) REQUIRE n.key IS UNIQUE".into(), json!({})));
// Asset nodes (shared across runs of the same target).
let assets: Vec<Value> = dg.assets.nodes.iter().map(|a| json!({
"key": asset_key(target, &a.id), "kind": format!("{:?}", a.kind), "value": a.value,
"by": a.discovered_by, "explored": a.exploration_count, "findings": a.finding_count,
})).collect();
if !assets.is_empty() {
out.push(("UNWIND $rows AS r MERGE (a:AssetNode {key: r.key}) \
SET a.kind = r.kind, a.value = r.value, a.discovered_by = r.by, \
a.exploration_count = r.explored, a.finding_count = r.findings, a.target = $target".into(),
json!({"rows": assets, "target": target})));
}
// Asset edges, one statement per relationship type (closed enum).
let mut by_rel: BTreeMap<String, Vec<Value>> = BTreeMap::new();
for e in &dg.assets.edges {
by_rel.entry(screaming(&format!("{:?}", e.kind))).or_default()
.push(json!({"from": asset_key(target, &e.from), "to": asset_key(target, &e.to)}));
}
for (rel, rows) in by_rel {
out.push((format!("UNWIND $rows AS r MATCH (a:AssetNode {{key: r.from}}) MATCH (b:AssetNode {{key: r.to}}) MERGE (a)-[:{rel}]->(b)"),
json!({"rows": rows})));
}
// Exploration nodes: one statement per kind so each gets a real label.
let mut by_kind: BTreeMap<String, Vec<Value>> = BTreeMap::new();
for n in &dg.exploration.nodes {
by_kind.entry(format!("{:?}", n.kind)).or_default().push(json!({
"key": exp_key(target, run, &n.id), "content": n.content,
"status": format!("{:?}", n.status), "agent": n.agent, "at": n.created_at,
}));
}
for (kind, rows) in by_kind {
let label: String = kind.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
out.push((format!("UNWIND $rows AS r MERGE (n:Exploration {{key: r.key}}) SET n:{label}, \
n.content = r.content, n.status = r.status, n.agent = r.agent, n.created_at = r.at, \
n.run = $run, n.target = $target"),
json!({"rows": rows, "run": run, "target": target})));
}
// Exploration edges.
let mut ex_rel: BTreeMap<String, Vec<Value>> = BTreeMap::new();
for e in &dg.exploration.edges {
ex_rel.entry(screaming(&format!("{:?}", e.kind))).or_default()
.push(json!({"from": exp_key(target, run, &e.from), "to": exp_key(target, run, &e.to)}));
}
for (rel, rows) in ex_rel {
out.push((format!("UNWIND $rows AS r MATCH (a:Exploration {{key: r.from}}) MATCH (b:Exploration {{key: r.to}}) MERGE (a)-[:{rel}]->(b)"),
json!({"rows": rows})));
}
// Anchors: exploration -> asset.
for (dir, rel) in [(AnchorDirection::Targets, "TARGETS"), (AnchorDirection::Discovered, "DISCOVERED")] {
let rows: Vec<Value> = dg.exploration.anchors.iter().filter(|a| a.direction == dir)
.map(|a| json!({"e": exp_key(target, run, &a.exploration_id), "a": asset_key(target, &a.asset_id)})).collect();
if !rows.is_empty() {
out.push((format!("UNWIND $rows AS r MATCH (e:Exploration {{key: r.e}}) MATCH (a:AssetNode {{key: r.a}}) MERGE (e)-[:{rel}]->(a)"),
json!({"rows": rows})));
}
}
out
}
/// Untested surface: endpoints/parameters/services nothing has targeted yet.
pub const UNTESTED_QUERY: &str = "MATCH (a:AssetNode {target: $target}) \
WHERE a.kind IN ['Endpoint','Parameter','Service','Application'] \
AND NOT EXISTS { MATCH (:Exploration)-[:TARGETS]->(a) } \
RETURN a.kind, a.value ORDER BY a.kind, a.value LIMIT $limit";
/// Chaining candidates: untested assets within two hops of an asset where a
/// finding already landed.
pub const CHAIN_QUERY: &str = "MATCH (f:Finding {target: $target})-[:TARGETS]->(a:AssetNode) \
MATCH (a)-[:PARENT_OF|HOSTED_ON|SERVES_ON|LINKS_TO|USES_AUTH|USES_TECH|RESOLVES_TO|REDIRECTS_TO*1..2]-(b:AssetNode) \
WHERE b <> a AND NOT EXISTS { MATCH (:Exploration)-[:TARGETS]->(b) } \
RETURN a.value, f.content, b.kind, b.value LIMIT $limit";
/// Turn chain-query rows into prompt lines for the planner.
pub fn suggestion_lines(rows: &[Vec<Value>]) -> Vec<String> {
let s = |v: Option<&Value>| v.and_then(|x| x.as_str()).unwrap_or("").to_string();
let mut seen = std::collections::BTreeSet::new();
let mut out = Vec::new();
for r in rows {
let (a, f, kind, b) = (s(r.first()), s(r.get(1)), s(r.get(2)), s(r.get(3)));
if a.is_empty() || b.is_empty() { continue; }
let f: String = f.chars().take(80).collect();
let line = format!("{kind} {b} is adjacent to {a}, where \"{f}\" was found and {b} is still untested");
if seen.insert(line.clone()) { out.push(line); }
}
out
}
/// Prompt block for chain suggestions. Empty when there are none.
pub fn suggestion_block(lines: &[String]) -> String {
if lines.is_empty() { return String::new(); }
let mut s = String::from("GRAPH CHAIN LEADS (from Neo4j; unverified hypotheses, test before relying on them):\n");
for l in lines { s.push_str(&format!(" - {l}\n")); }
s
}
/// Push the dual graph and read back chain leads. Returns the lead lines.
pub async fn sync(n: &crate::graph_memory::Neo4j, dg: &DualGraph, target: &str, run: &str) -> anyhow::Result<Vec<String>> {
let st = statements(dg, target, run);
// Constraints are schema operations and must run before data, on their own.
let (schema, data): (Vec<_>, Vec<_>) = st.into_iter().partition(|(s, _)| s.starts_with("CREATE CONSTRAINT"));
for stmt in schema { n.run_statements(vec![stmt]).await?; }
n.run_statements(data).await?;
let rows = n.query_rows(CHAIN_QUERY, json!({"target": target, "limit": 15})).await?;
Ok(suggestion_lines(&rows))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::exploration_graph::{AssetKind, ExplorationStatus};
fn sample() -> DualGraph {
let mut dg = DualGraph::default();
dg.discover_asset(AssetKind::Endpoint, "/api/users", BTreeMap::new(), "recon", None);
dg.discover_asset(AssetKind::Endpoint, "/api/orders", BTreeMap::new(), "recon", None);
let goal = dg.exploration.add_goal("test authz", "planner");
let a = dg.assets.find(AssetKind::Endpoint, "/api/users").unwrap().id.clone();
let i = dg.target_asset("probe IDOR", &goal, "planner", &a);
dg.exploration.add_negative("id param clean", &i, "w");
dg.exploration.set_status(&i, ExplorationStatus::Completed);
dg.record_finding("IDOR on /api/users", &i, "w", &a);
dg
}
#[test]
fn screaming_case_conversion() {
assert_eq!(screaming("ParentOf"), "PARENT_OF");
assert_eq!(screaming("Spawns"), "SPAWNS");
assert_eq!(screaming("DerivedFrom"), "DERIVED_FROM");
assert!(screaming("X; DROP }) //").chars().all(|c| c.is_ascii_uppercase() || c == '_'), "only [A-Z_] can ever reach cypher");
}
#[test]
fn statements_cover_nodes_edges_anchors_and_constraints() {
let st = statements(&sample(), "app.example.com", "run-1");
let all: String = st.iter().map(|(s, _)| s.as_str()).collect::<Vec<_>>().join("\n");
assert!(all.contains("CREATE CONSTRAINT ns_exploration_key"));
assert!(all.contains("MERGE (a:AssetNode"));
for label in ["Goal", "Intent", "Negative", "Finding"] {
assert!(all.contains(&format!("SET n:{label}")), "missing label {label}");
}
assert!(all.contains("MERGE (a)-[:SPAWNS]->(b)"));
assert!(all.contains("MERGE (a)-[:PROVES]->(b)") && all.contains("MERGE (a)-[:DISPROVES]->(b)"));
assert!(all.contains("MERGE (e)-[:TARGETS]->(a)"));
}
#[test]
fn free_text_is_only_ever_a_parameter() {
let mut dg = DualGraph::default();
let g = dg.exploration.add_goal("x' }) DETACH DELETE n //", "p");
dg.exploration.add_fact("`; MATCH (n) DELETE n", &g, "w");
for (cypher, _) in statements(&dg, "t", "r") {
assert!(!cypher.contains("DETACH DELETE") && !cypher.contains("MATCH (n) DELETE"),
"free text leaked into cypher: {cypher}");
}
}
#[test]
fn keys_are_namespaced_by_target_and_run() {
let st = statements(&sample(), "t.com", "r9");
let json: String = st.iter().map(|(_, p)| p.to_string()).collect();
assert!(json.contains("t.com|r9|exp-0"), "exploration keys are per run");
assert!(json.contains("t.com|asset-"), "asset keys are shared across runs: {json}");
}
#[test]
fn suggestions_dedupe_and_skip_empty() {
let rows = vec![
vec![json!("/api/users"), json!("IDOR on users"), json!("Endpoint"), json!("/api/orders")],
vec![json!("/api/users"), json!("IDOR on users"), json!("Endpoint"), json!("/api/orders")],
vec![json!(""), json!("x"), json!("Endpoint"), json!("/y")],
];
let l = suggestion_lines(&rows);
assert_eq!(l.len(), 1);
assert!(l[0].contains("/api/orders") && l[0].contains("still untested"));
assert!(suggestion_block(&l).contains("unverified hypotheses"));
assert!(suggestion_block(&[]).is_empty());
}
}
@@ -0,0 +1,298 @@
//! Managed Neo4j — bring up a local Neo4j in Docker and let the harness use it.
//!
//! `graph_memory::Neo4j` already speaks to any Neo4j over HTTP. This module is
//! the missing operational half: it can create, start, stop and health-check a
//! local Neo4j container, remembers the connection (including a generated
//! password) in a private file, and lets the harness resolve it automatically so
//! `neurosploit run` consumes it with no flags or exported variables.
//!
//! Security choices:
//! - ports are published on `127.0.0.1` only, never on all interfaces;
//! - the password is generated (random), stored in a `0600` file, and passed to
//! Docker through the process environment (`-e NEO4J_AUTH` with no value), so
//! it never appears in `docker run` arguments or in `ps` output. (The container
//! itself necessarily holds it in its environment, as with any Neo4j image.)
//! - explicit `--neo4j` / `NEO4J_URI` always win over the managed instance.
use crate::sandbox::Runtime;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::time::Duration;
pub const DEFAULT_CONTAINER: &str = "neurosploit-neo4j";
pub const DEFAULT_IMAGE: &str = "neo4j:5-community";
pub const DEFAULT_VOLUME: &str = "neurosploit-neo4j-data";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManagedConfig {
pub container: String,
pub image: String,
pub volume: String,
pub http_port: u16,
pub bolt_port: u16,
pub user: String,
pub password: String,
pub database: String,
/// When true the harness uses this instance without any flag or env var.
pub auto: bool,
}
impl ManagedConfig {
pub fn new_with_password(password: String) -> Self {
Self {
container: DEFAULT_CONTAINER.into(),
image: DEFAULT_IMAGE.into(),
volume: DEFAULT_VOLUME.into(),
http_port: 7474,
bolt_port: 7687,
user: "neo4j".into(),
password,
database: "neo4j".into(),
auto: true,
}
}
pub fn http_uri(&self) -> String { format!("http://127.0.0.1:{}", self.http_port) }
pub fn bolt_uri(&self) -> String { format!("bolt://127.0.0.1:{}", self.bolt_port) }
}
/// `$NEUROSPLOIT_HOME/neo4j.json`, else `~/.neurosploit/neo4j.json`.
pub fn config_path() -> Option<PathBuf> {
let home = std::env::var_os("NEUROSPLOIT_HOME").map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".neurosploit")))
.or_else(|| std::env::var_os("LOCALAPPDATA").map(|l| PathBuf::from(l).join("NeuroSploit")))?;
Some(home.join("neo4j.json"))
}
pub fn load() -> Option<ManagedConfig> {
let t = std::fs::read_to_string(config_path()?).ok()?;
serde_json::from_str(&t).ok()
}
/// Write the config, owner-read/write only on unix.
pub fn save(cfg: &ManagedConfig) -> std::io::Result<()> {
let path = config_path().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::NotFound, "no home directory"))?;
if let Some(dir) = path.parent() { std::fs::create_dir_all(dir)?; }
let json = serde_json::to_string_pretty(cfg).map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
#[cfg(unix)]
{
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&path)?;
f.write_all(json.as_bytes())?;
// An existing file keeps its old mode; tighten it explicitly.
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
Ok(())
}
#[cfg(not(unix))]
{ std::fs::write(&path, json) }
}
/// 24 random url-safe characters. Reads the OS RNG; falls back to hashing
/// time+pid only if that is unavailable (still unguessable enough for a
/// loopback-only dev database, and the fallback is flagged by shorter entropy).
pub fn generate_password() -> String {
use base64::Engine;
let mut buf = [0u8; 18];
let ok = std::fs::File::open("/dev/urandom").and_then(|mut f| { use std::io::Read; f.read_exact(&mut buf) }).is_ok();
if !ok {
use sha2::{Digest, Sha256};
let seed = format!("{:?}-{}-{:p}", std::time::SystemTime::now(), std::process::id(), &buf);
buf.copy_from_slice(&Sha256::digest(seed.as_bytes())[..18]);
}
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(buf)
}
/// Arguments for `docker run`. Pure so it is unit-tested. The password is NOT in
/// here: `-e NEO4J_AUTH` (no value) makes Docker read it from our environment.
pub fn run_args(c: &ManagedConfig) -> Vec<String> {
vec![
"run".into(), "-d".into(),
"--name".into(), c.container.clone(),
"--restart".into(), "unless-stopped".into(),
"-p".into(), format!("127.0.0.1:{}:7474", c.http_port),
"-p".into(), format!("127.0.0.1:{}:7687", c.bolt_port),
"-v".into(), format!("{}:/data", c.volume),
"-e".into(), "NEO4J_AUTH".into(),
c.image.clone(),
]
}
/// The `NEO4J_AUTH` value Docker will read from the environment.
pub fn auth_env(c: &ManagedConfig) -> String { format!("{}/{}", c.user, c.password) }
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum State {
NoRuntime,
NotCreated,
Stopped,
Running,
}
#[derive(Debug, Clone, Serialize)]
pub struct Status {
pub state: State,
pub ready: bool,
pub runtime: Option<String>,
pub http_uri: Option<String>,
pub bolt_uri: Option<String>,
pub browser: Option<String>,
pub auto: bool,
}
async fn docker(rt: Runtime, args: &[String], env: &[(&str, String)]) -> Result<(i32, String, String), String> {
let mut cmd = tokio::process::Command::new(rt.bin());
cmd.args(args).kill_on_drop(true);
for (k, v) in env { cmd.env(k, v); }
let out = tokio::time::timeout(Duration::from_secs(300), cmd.output()).await
.map_err(|_| format!("`{} {}` timed out", rt.bin(), args.first().cloned().unwrap_or_default()))?
.map_err(|e| format!("could not run {}: {e}", rt.bin()))?;
Ok((out.status.code().unwrap_or(-1),
String::from_utf8_lossy(&out.stdout).trim().to_string(),
String::from_utf8_lossy(&out.stderr).trim().to_string()))
}
async fn container_state(rt: Runtime, name: &str) -> State {
let args = ["ps", "-a", "--filter", &format!("name=^/{name}$"), "--format", "{{.State}}"]
.map(String::from);
match docker(rt, &args, &[]).await {
Ok((0, out, _)) if out.is_empty() => State::NotCreated,
Ok((0, out, _)) if out.starts_with("running") => State::Running,
Ok((0, _, _)) => State::Stopped,
_ => State::NoRuntime,
}
}
async fn http_ready(c: &ManagedConfig) -> bool {
let Ok(client) = reqwest::Client::builder().timeout(Duration::from_secs(3)).build() else { return false };
matches!(client.get(c.http_uri()).send().await, Ok(r) if r.status().is_success())
}
pub async fn status() -> Status {
let cfg = load();
let Some(rt) = Runtime::detect() else {
return Status { state: State::NoRuntime, ready: false, runtime: None, http_uri: None, bolt_uri: None,
browser: None, auto: cfg.map_or(false, |c| c.auto) };
};
let Some(c) = cfg else {
return Status { state: State::NotCreated, ready: false, runtime: Some(rt.bin().into()), http_uri: None,
bolt_uri: None, browser: None, auto: false };
};
let state = container_state(rt, &c.container).await;
let ready = state == State::Running && http_ready(&c).await;
Status { state, ready, runtime: Some(rt.bin().into()), http_uri: Some(c.http_uri()), bolt_uri: Some(c.bolt_uri()),
browser: Some(c.http_uri()), auto: c.auto }
}
/// Create (or start) the container, save the config, wait until it answers.
/// Idempotent: running it again on a healthy instance changes nothing.
pub async fn up(image: Option<&str>, auto: bool) -> Result<ManagedConfig, String> {
let rt = Runtime::detect().ok_or("no container runtime found (install docker or podman)")?;
let mut cfg = load().unwrap_or_else(|| ManagedConfig::new_with_password(generate_password()));
if let Some(i) = image.filter(|i| !i.trim().is_empty()) { cfg.image = i.to_string(); }
cfg.auto = auto;
match container_state(rt, &cfg.container).await {
State::NoRuntime => return Err(format!("the {} engine is not reachable — start it (e.g. `open -a Docker`, `colima start`, `systemctl start docker`) and retry", rt.bin())),
State::Running => {}
State::Stopped => {
let (code, _, err) = docker(rt, &["start".into(), cfg.container.clone()], &[]).await?;
if code != 0 { return Err(format!("docker start failed: {err}")); }
}
State::NotCreated => {
// Save first: the generated password must outlive a crash mid-start,
// because the data volume is initialised with it on first boot.
save(&cfg).map_err(|e| format!("could not save neo4j config: {e}"))?;
let (code, _, err) = docker(rt, &run_args(&cfg), &[("NEO4J_AUTH", auth_env(&cfg))]).await?;
if code != 0 { return Err(format!("docker run failed: {err}")); }
}
}
save(&cfg).map_err(|e| format!("could not save neo4j config: {e}"))?;
for _ in 0..60 {
if http_ready(&cfg).await { return Ok(cfg); }
tokio::time::sleep(Duration::from_secs(2)).await;
}
Err("neo4j started but did not answer on its HTTP port within 2 minutes (first boot can be slow; check `docker logs neurosploit-neo4j`)".into())
}
/// Stop (and remove) the container. The data volume is kept unless `purge`.
/// Auto-use is switched off so runs stop trying to reach it.
pub async fn down(purge: bool) -> Result<(), String> {
let rt = Runtime::detect().ok_or("no container runtime found")?;
let mut cfg = load().ok_or("no managed neo4j configured (run `neurosploit neo4j up`)")?;
let _ = docker(rt, &["rm".into(), "-f".into(), cfg.container.clone()], &[]).await?;
if purge {
let _ = docker(rt, &["volume".into(), "rm".into(), "-f".into(), cfg.volume.clone()], &[]).await?;
if let Some(p) = config_path() { let _ = std::fs::remove_file(p); }
} else {
cfg.auto = false;
save(&cfg).map_err(|e| format!("could not save neo4j config: {e}"))?;
}
Ok(())
}
/// Connection details for the harness: (uri, db, user, password) when a managed
/// instance is configured for automatic use.
pub fn auto_connection() -> Option<(String, String, String, String)> {
let c = load().filter(|c| c.auto)?;
Some((c.http_uri(), c.database.clone(), c.user.clone(), c.password.clone()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn password_is_random_and_url_safe() {
let (a, b) = (generate_password(), generate_password());
assert_ne!(a, b);
assert_eq!(a.len(), 24);
assert!(a.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'));
}
#[test]
fn run_args_bind_loopback_and_never_contain_the_password() {
let c = ManagedConfig::new_with_password("S3cretPw".into());
let args = run_args(&c);
let joined = args.join(" ");
assert!(args.contains(&"127.0.0.1:7474:7474".to_string()));
assert!(args.contains(&"127.0.0.1:7687:7687".to_string()));
assert!(!joined.contains("S3cretPw"), "password must not be in argv");
assert!(args.contains(&"NEO4J_AUTH".to_string()), "value is inherited from the environment");
assert_eq!(auth_env(&c), "neo4j/S3cretPw");
assert!(args.contains(&"--restart".to_string()));
assert_eq!(args.last().unwrap(), DEFAULT_IMAGE);
}
#[test]
fn uris_use_configured_ports() {
let mut c = ManagedConfig::new_with_password("x".into());
c.http_port = 17474;
c.bolt_port = 17687;
assert_eq!(c.http_uri(), "http://127.0.0.1:17474");
assert_eq!(c.bolt_uri(), "bolt://127.0.0.1:17687");
}
#[cfg(unix)]
#[test]
fn saved_config_is_private_and_roundtrips() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("ns-neo-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::env::set_var("NEUROSPLOIT_HOME", &dir);
let c = ManagedConfig::new_with_password("pw123".into());
save(&c).unwrap();
let mode = std::fs::metadata(config_path().unwrap()).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
let back = load().unwrap();
assert_eq!(back.password, "pw123");
assert!(auto_connection().is_some());
let mut off = back; off.auto = false; save(&off).unwrap();
assert!(auto_connection().is_none(), "auto=false must disable automatic use");
std::env::remove_var("NEUROSPLOIT_HOME");
let _ = std::fs::remove_dir_all(&dir);
}
}
@@ -2093,6 +2093,21 @@ async fn graph_checkpoint(
Ok(_) => synced = " · neo4j synced".into(),
Err(e) => synced = format!(" · neo4j push skipped ({e})"),
}
// Exploration graph (assets + what was tried): push it and turn
// "untested assets next to a finding" into prompt leads for the agents.
if let Some(d) = cfg.workdir.as_deref() {
if let Ok(dg) = crate::exploration_graph::DualGraph::load(&Path::new(d).join("graphs")) {
match crate::neo4j_exploration::sync(n, &dg, &cfg.target, &rid).await {
Ok(leads) if !leads.is_empty() => {
let cur = gm::live_context(&rid);
gm::set_live_context(&rid, format!("{cur}{}", crate::neo4j_exploration::suggestion_block(&leads)));
synced.push_str(&format!(" · {} chain lead(s)", leads.len()));
}
Ok(_) => {}
Err(e) => synced.push_str(&format!(" · exploration sync skipped ({e})")),
}
}
}
}
let (h, sv, ep, sec) = gm::surface_counts(&gb);
let confirmed = cs.iter().filter(|c| c.status == gm::Status::Confirmed).count();
+36
View File
@@ -2012,6 +2012,42 @@ const server = http.createServer(async (req, res) => {
return;
}
// ---- Neo4j (managed local instance; the CLI does the Docker work) ----
if (p === '/api/neo4j/status' && req.method === 'GET') {
const out = await runCli(['neo4j', 'status', '--json']);
let st = null;
try { st = JSON.parse(lastJsonLine(out.buf)); } catch { /* fall through */ }
if (!st || Array.isArray(st) || typeof st.state !== 'string') return sendJson(res, 502, { error: out.buf.trim() || 'neo4j status failed' });
return sendJson(res, 200, st);
}
if (p === '/api/neo4j/up' && req.method === 'POST') {
const body = await readBody(req).catch(() => ({}));
const args = ['neo4j', 'up'];
if (body.noAuto) args.push('--no-auto');
// Image is passed as an argument vector (no shell), but keep it to a
// plain image reference anyway.
if (typeof body.image === 'string' && /^[a-z0-9][a-z0-9._/:@-]{0,200}$/i.test(body.image)) args.push('--image', body.image);
const out = await runCli(args);
if (out.code !== 0) return sendJson(res, 502, { error: out.buf.trim() || 'neo4j up failed' });
return sendJson(res, 200, { ok: true, output: out.buf.trim() });
}
if (p === '/api/neo4j/down' && req.method === 'POST') {
const body = await readBody(req).catch(() => ({}));
const args = ['neo4j', 'down'];
if (body.purge === true) args.push('--purge');
const out = await runCli(args);
if (out.code !== 0) return sendJson(res, 502, { error: out.buf.trim() || 'neo4j down failed' });
return sendJson(res, 200, { ok: true, output: out.buf.trim() });
}
m = p.match(/^\/api\/runs\/([^/]+)\/neo4j-sync$/);
if (req.method === 'POST' && m) {
const dir = safeRunDir(decodeURIComponent(m[1]));
if (!dir || !fs.existsSync(dir)) return sendJson(res, 404, { error: 'run not found' });
const out = await runCli(['neo4j', 'sync', dir]);
if (out.code !== 0) return sendJson(res, 502, { error: out.buf.trim() || 'neo4j sync failed' });
return sendJson(res, 200, { ok: true, output: out.buf.trim() });
}
// ---- attack graph / traffic / traces (files the CLI wrote) ----
m = p.match(/^\/api\/runs\/([^/]+)\/graph$/);
if (m) {