diff --git a/neurosploit-rs/crates/harness/src/credtest.rs b/neurosploit-rs/crates/harness/src/credtest.rs index 92fe0dd..555fa25 100644 --- a/neurosploit-rs/crates/harness/src/credtest.rs +++ b/neurosploit-rs/crates/harness/src/credtest.rs @@ -54,8 +54,27 @@ pub fn parse_loot(loot: &[String]) -> Vec { for raw in loot { let l = raw.trim(); let lo = l.to_ascii_lowercase(); + // A bare secret with no username — an API key or bearer token lifted + // from a sourcemap, a leaked `.env`, a response header. Tested against + // the target's own API (service "bearer"), never against a password + // field. + let token_prefix = ["token:", "apikey:", "api_key:", "bearer:"].iter().find(|p| lo.starts_with(**p)).map(|p| p.len()); + if let Some(plen) = token_prefix { + let rest = &l[plen..]; + let (val, host) = match rest.rsplit_once('@') { + Some((v, h)) if !sanitize_host(h).is_empty() => (v.trim().to_string(), sanitize_host(h)), + _ => (rest.trim().to_string(), String::new()), + }; + if val.len() >= 8 && val.len() <= 2048 && !val.contains('<') && !val.contains('>') && !val.contains(' ') { + let key = format!("token:{val}@{host}"); + if seen.insert(key) { + out.push(Credential { user: String::new(), secret: val, host, kind: "token".into() }); + } + } + continue; + } // Other loot shapes the chain loop also produces — never credentials. - if ["token:", "host:", "endpoint:", "url:", "access:", "secret-file:", "key:", "note:"].iter().any(|p| lo.starts_with(p)) { + if ["host:", "endpoint:", "url:", "access:", "secret-file:", "key:", "note:"].iter().any(|p| lo.starts_with(p)) { continue; } let l = l.strip_prefix("cred:").or_else(|| l.strip_prefix("credential:")).unwrap_or(l); @@ -156,20 +175,77 @@ fn probe_command(c: &Credential, host: &str, service: &str, timeout_secs: u64) - t = timeout_secs, u = sq(&c.user), sec = sq(&c.secret), h = host ), )), + // A login FORM: no API to ask "was this accepted", so the signal is a + // Set-Cookie (a session got created) with no visible failure text in + // the body, against each common login path in turn. + "http-form" if c.kind == "password" => Some(( + "curl".into(), + format!( + "for p in /login /api/login /signin /Account/Login /auth/login /user/login; do \ + body=$(mktemp); \ + resp=$(curl -s -D - -m {t} -o \"$body\" -X POST \"https://{h}$p\" \ + --data-urlencode {u_field} --data-urlencode {p_field} \ + --data-urlencode {e_field} \ + -w 'HTTPCODE:%{{http_code}} EFFURL:%{{url_effective}}' 2>&1); \ + code=$(echo \"$resp\" | grep -oE 'HTTPCODE:[0-9]+' | cut -d: -f2); \ + eff=$(echo \"$resp\" | grep -oE 'EFFURL:\\S+' | cut -d: -f2-); \ + cookie=$(echo \"$resp\" | grep -ic '^set-cookie:'); \ + errtext=$(grep -ic -E 'invalid|incorrect|denied|failed|error' \"$body\" 2>/dev/null); \ + echo \"PATH=$p CODE=$code EFF=$eff COOKIE=$cookie ERR=$errtext\"; \ + rm -f \"$body\"; \ + done", + t = timeout_secs, h = host, + u_field = sq(&format!("username={}", c.user)), p_field = sq(&format!("password={}", c.secret)), e_field = sq(&format!("email={}", c.user)), + ), + )), + // A bearer token / API key lifted from a sourcemap, `.env`, or a + // response header: tried as both an `Authorization: Bearer` and an + // `X-Api-Key` header against a short list of common authenticated + // endpoints. A 200 where an unauthenticated request would 401/403 is + // the signal; it never guesses at a login form. + "bearer" if c.kind == "token" => Some(( + "curl".into(), + format!( + "for p in /api/me /api/user /api/v1/me /api/account /api/whoami /; do \ + b=$(curl -s -o /dev/null -w '%{{http_code}}' -m {t} -H 'Authorization: Bearer {sec}' \"https://{h}$p\" 2>&1); \ + a=$(curl -s -o /dev/null -w '%{{http_code}}' -m {t} -H 'X-Api-Key: {sec}' \"https://{h}$p\" 2>&1); \ + echo \"PATH=$p BEARER=$b APIKEY=$a\"; \ + done", + t = timeout_secs, h = host, sec = sanitize_header_value(&c.secret), + ), + )), _ => None, } } +/// A token is already shape-validated by `parse_loot`; this only strips +/// anything that would break out of the header value in the shell command. +fn sanitize_header_value(s: &str) -> String { + s.chars().filter(|c| c.is_ascii_graphic() && *c != '\'' && *c != '"').collect() +} + fn success_from_output(service: &str, out: &str) -> bool { let lo = out.to_ascii_lowercase(); match service { "ssh" => lo.contains("ns_auth_ok"), "smb" | "winrm" => lo.contains("[+]") && !lo.contains("[-]"), "http-basic" => out.trim() == "200" || out.trim() == "204", + "http-form" => out.lines().any(|l| { + let cookie = field(l, "COOKIE=").and_then(|v| v.parse::().ok()).unwrap_or(0); + let err = field(l, "ERR=").and_then(|v| v.parse::().ok()).unwrap_or(1); + let code = field(l, "CODE=").unwrap_or_default(); + cookie > 0 && err == 0 && matches!(code.as_str(), "200" | "302" | "303") + }), + "bearer" => out.lines().any(|l| field(l, "BEARER=").as_deref() == Some("200") || field(l, "APIKEY=").as_deref() == Some("200")), _ => false, } } +/// Pull `KEY=value` out of one space-separated report line. +fn field(line: &str, key: &str) -> Option { + line.split_whitespace().find_map(|tok| tok.strip_prefix(key)).map(|v| v.to_string()) +} + /// Run one probe via `runner` (a shell-command executor), honest about whether /// the needed tool exists. `runner` returns `None` when the tool is missing or /// the command failed to even start — NOT when the credential was rejected @@ -195,10 +271,11 @@ where /// Services worth trying for a credential: the one its loot line named, or /// every candidate service when it named none. pub fn services_for(c: &Credential) -> Vec<&'static str> { - if c.kind == "hash" { - return vec!["smb", "winrm"]; + match c.kind.as_str() { + "hash" => vec!["smb", "winrm"], + "token" => vec!["bearer"], + _ => vec!["ssh", "smb", "winrm", "http-basic", "http-form"], } - vec!["ssh", "smb", "winrm", "http-basic"] } /// Loot lines to carry into the NEXT round: a confirmed access fact for every @@ -208,7 +285,13 @@ pub fn verified_loot(results: &[ProbeResult]) -> Vec { results .iter() .filter(|r| r.verified) - .map(|r| format!("access:{}@{} via {} — VERIFIED, authenticate with user={} secret={} and continue from this foothold", r.credential.user, r.host, r.service, r.credential.user, r.credential.secret)) + .map(|r| if r.credential.kind == "token" { + format!("access:{} via {} — VERIFIED, the leaked token/API-key {} is live, authenticate with it and continue from this foothold", + r.host, r.service, r.credential.secret) + } else { + format!("access:{}@{} via {} — VERIFIED, authenticate with user={} secret={} and continue from this foothold", + r.credential.user, r.host, r.service, r.credential.user, r.credential.secret) + }) .collect() } diff --git a/neurosploit-rs/crates/harness/src/lib.rs b/neurosploit-rs/crates/harness/src/lib.rs index 976f41f..3dd9cd6 100644 --- a/neurosploit-rs/crates/harness/src/lib.rs +++ b/neurosploit-rs/crates/harness/src/lib.rs @@ -93,6 +93,8 @@ pub mod custom_providers; pub mod kernel_recon; pub mod winbin_harvest; pub mod agentic_tools; +pub mod privesc; +pub mod svc_probe; pub mod keystore; pub mod threat_actors; pub mod toolbox; diff --git a/neurosploit-rs/crates/harness/src/pipeline.rs b/neurosploit-rs/crates/harness/src/pipeline.rs index fd0a446..198ec3c 100644 --- a/neurosploit-rs/crates/harness/src/pipeline.rs +++ b/neurosploit-rs/crates/harness/src/pipeline.rs @@ -3400,7 +3400,13 @@ async fn attack_chain(pool: &ModelPool, cfg: &RunConfig, recon: &str, { let creds = crate::credtest::parse_loot(&loot); if !creds.is_empty() { - let hosts_hint = crate::credtest::known_hosts(recon, &loot); + let mut hosts_hint = crate::credtest::known_hosts(recon, &loot); + // A credential with no host named in its loot line still has + // one obvious candidate on a web engagement: the engagement's + // own target — `known_hosts` only finds bare IPs, so a domain + // target is otherwise never tried. + let own_host = crate::scope::host_of(&cfg.target); + if !own_host.is_empty() && !hosts_hint.contains(&own_host) { hosts_hint.push(own_host); } let mut results = Vec::new(); for c in &creds { let targets: Vec = if c.host.is_empty() { hosts_hint.clone() } else { vec![c.host.clone()] }; @@ -3424,6 +3430,32 @@ async fn attack_chain(pool: &ModelPool, cfg: &RunConfig, recon: &str, for l in crate::credtest::verified_loot(&results) { if !loot.iter().any(|x| x.eq_ignore_ascii_case(&l)) { loot.push(l); } } + // A verified SSH/WinRM session is a foothold, not an + // endpoint: run the standard privesc enumeration over it now, + // deterministically, instead of leaving "you have a shell" as + // a lead the next round might not act on. + let mut privesc_lines: Vec = Vec::new(); + for r in results.iter().filter(|r| r.verified && (r.service == "ssh" || r.service == "winrm")) { + let secs = 20u64; + let facts = if r.service == "ssh" { + crate::privesc::linux_privesc(&r.credential, &r.host, secs, |cmd| async move { + recon_tool_timed(cfg, "sh", &cmd, secs + 5).await + }).await + } else { + crate::privesc::windows_privesc(&r.credential, &r.host, secs, |cmd| async move { + recon_tool_timed(cfg, "sh", &cmd, secs + 5).await + }).await + }; + if let Some(f) = facts { + if !f.loot.is_empty() { + let _ = tx.send(format!("🔺 privesc on {}: {}", r.host, f.loot.join("; "))).await; + } + privesc_lines.extend(f.loot); + } + } + for l in privesc_lines { + if !loot.iter().any(|x| x.eq_ignore_ascii_case(&l)) { loot.push(l); } + } } } // JEV / System One progress checkpoint (the jev-skill agent-checkpoint @@ -6502,6 +6534,17 @@ pub async fn run_host(cfg: RunConfig, lib: &Library, pool: &ModelPool, tx: Sende Ok((m, t)) => { let _ = tx.send(format!("recon complete via {}", m.label())).await; t } Err(e) => { let _ = tx.send(format!("recon failed ({e})")).await; "{}".to_string() } }; + // Found a port → validate it → pull the version → check for a known + // CVE/exploit, deterministically, before the agents even start — not + // left to whether the model remembers to ask for an nmap scan. Skipped + // for a web target (the web pipeline's own tool-recon already covers + // it) and for `--offline`. + if !cfg.target.starts_with("http://") && !cfg.target.starts_with("https://") { + let host = crate::scope::host_of(&cfg.target); + if !host.is_empty() { + r.push_str(&crate::svc_probe::scan_enrich_and_lookup(&cfg, &host, &tx).await); + } + } // Network/AD profiles with an authorized SSH/Windows credential get a // deterministic pass before the agents run: real kernel facts over SSH, // and any reachable third-party driver/service binary pulled and put diff --git a/neurosploit-rs/crates/harness/src/privesc.rs b/neurosploit-rs/crates/harness/src/privesc.rs new file mode 100644 index 0000000..fc07c40 --- /dev/null +++ b/neurosploit-rs/crates/harness/src/privesc.rs @@ -0,0 +1,182 @@ +//! Deterministic post-foothold privilege-escalation enumeration. +//! +//! `credtest.rs` turns a credential into a confirmed SSH/WinRM session — what +//! happens from there used to be a text lead the next model round might or +//! might not act on, same gap `credtest.rs` closed for the credential itself. +//! This module runs the standard, read-only enumeration a human does first +//! (`sudo -l`, SUID, capabilities, writable cron on Linux; `whoami /priv` and +//! group membership on Windows) over the SAME verified session, and for the +//! one unambiguous case worth auto-confirming — NOPASSWD sudo, or a +//! credential already in `BUILTIN\Administrators` — actually proves it and +//! reports root/SYSTEM with evidence. Everything else (a GTFOBins SUID +//! binary, SeImpersonatePrivilege) becomes a cited, ranked hypothesis for the +//! next round, not a guess the model has to construct from a command's raw +//! text. +//! +//! Nothing here drops a binary or runs a real exploit (PrintSpoofer, a SUID +//! GTFOBins payload): those need an interactive tty or an extra uploaded +//! file, which this harness does not open for the operator. + +use crate::credtest::Credential; + +/// SUID binaries GTFOBins lists as a direct root shell with no extra +/// arguments. Reported as a hypothesis, never run. +const GTFOBINS_SUID: &[&str] = &[ + "nmap", "vim", "vi", "find", "bash", "sh", "python", "python3", "perl", "awk", "man", "less", "more", "env", "nice", "ftp", "tar", "docker", "node", "ruby", +]; + +#[derive(Debug, Clone, Default)] +pub struct PrivescFacts { + /// Short, actionable facts for the next chain round's loot (never raw + /// command output — that goes in `evidence`). + pub loot: Vec, + /// The full enumeration output, for the operator-visible log only. + pub evidence: String, +} + +fn sq(s: &str) -> String { + format!("'{}'", s.replace('\'', "'\\''")) +} + +/// Linux: sudo rights, SUID set, capabilities, writable cron. +pub async fn linux_privesc(c: &Credential, host: &str, timeout_secs: u64, runner: F) -> Option +where + F: Fn(String) -> Fut, + Fut: std::future::Future>, +{ + if c.kind != "password" { + return None; + } + let enum_cmd = format!( + "sshpass -p {sec} ssh -o StrictHostKeyChecking=no -o ConnectTimeout={t} {u}@{h} '\ + echo ---SUDO---; sudo -n -l 2>&1; \ + echo ---SUID---; find / -xdev -perm -4000 -type f 2>/dev/null | head -60; \ + echo ---CAP---; getcap -r / 2>/dev/null | head -30; \ + echo ---CRONW---; find /etc/cron.d /etc/cron.daily /etc/cron.hourly -writable 2>/dev/null; \ + echo ---ID---; id' 2>&1", + sec = sq(&c.secret), t = timeout_secs, u = sq(&c.user), h = sq(host) + ); + let out = runner(enum_cmd).await?; + let nopasswd_all = out.lines().any(|l| { + let lo = l.to_ascii_lowercase(); + lo.contains("nopasswd") && lo.contains("all") && !lo.contains("may not run sudo") && !lo.contains("is not allowed to run sudo") + }); + let suid_hits: Vec<&str> = GTFOBINS_SUID.iter().copied().filter(|b| out.lines().any(|l| l.trim_end().ends_with(&format!("/{b}")))).collect(); + + let mut facts = PrivescFacts { evidence: out.chars().take(4000).collect(), ..Default::default() }; + if !suid_hits.is_empty() { + facts.loot.push(format!( + "privesc:suid-gtfobins@{host} — SUID binar{} present ({}), root shell plausible via GTFOBins but needs an interactive tty this harness does not open — try manually", + if suid_hits.len() == 1 { "y" } else { "ies" }, suid_hits.join(", ") + )); + } + if nopasswd_all { + let confirm_cmd = format!( + "sshpass -p {sec} ssh -o StrictHostKeyChecking=no -o ConnectTimeout={t} {u}@{h} 'sudo -n id' 2>&1", + sec = sq(&c.secret), t = timeout_secs, u = sq(&c.user), h = sq(host) + ); + if let Some(confirm) = runner(confirm_cmd).await { + if confirm.to_ascii_lowercase().contains("uid=0(root)") { + facts.evidence.push_str(&format!("\n---CONFIRM---\n{confirm}")); + facts.loot.push(format!( + "access:root@{host} via sudo-nopasswd — VERIFIED, authenticate as {} and run `sudo ` for a root shell", + c.user + )); + } + } + } + Some(facts) +} + +/// Windows (over a verified WinRM credential): current privileges and local +/// admin membership. SeImpersonate/SeAssignPrimaryToken enabled is reported as +/// a hypothesis (Potato-family: PrintSpoofer/GodPotato/RoguePotato) — that +/// needs dropping and running an extra binary, which is not attempted here. +pub async fn windows_privesc(c: &Credential, host: &str, timeout_secs: u64, runner: F) -> Option +where + F: Fn(String) -> Fut, + Fut: std::future::Future>, +{ + if c.kind != "password" && c.kind != "hash" { + return None; + } + let auth = if c.kind == "hash" { format!("-H {}", sq(&c.secret)) } else { format!("-p {}", sq(&c.secret)) }; + let cmd = format!( + "netexec winrm {h} -u {u} {auth} -x 'whoami /priv & whoami /groups' --timeout {t} 2>&1", + h = sq(host), u = sq(&c.user), t = timeout_secs + ); + let out = runner(cmd).await?; + let is_admin = out.to_ascii_lowercase().contains("builtin\\administrators") || out.contains("S-1-5-32-544"); + let impersonate = out.lines().any(|l| { + let ll = l.to_ascii_lowercase(); + (ll.contains("seimpersonateprivilege") || ll.contains("seassignprimarytokenprivilege")) && ll.contains("enabled") + }); + + let mut facts = PrivescFacts { evidence: out.chars().take(4000).collect(), ..Default::default() }; + if is_admin { + facts.loot.push(format!( + "access:administrator@{host} via local-admin-group — VERIFIED, authenticate as {} for a full admin session", + c.user + )); + } else if impersonate { + facts.loot.push(format!( + "privesc:se-impersonate@{host} — SeImpersonatePrivilege/SeAssignPrimaryTokenPrivilege enabled, NT AUTHORITY\\SYSTEM plausible via a Potato-family technique (PrintSpoofer/GodPotato/RoguePotato) — untested, needs an uploaded binary" + )); + } + Some(facts) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cred(kind: &str) -> Credential { + Credential { user: "svc".into(), secret: "hunter2".into(), host: "10.0.0.5".into(), kind: kind.into() } + } + + #[tokio::test] + async fn nopasswd_all_is_confirmed_by_a_second_call_and_yields_verified_root() { + let c = cred("password"); + let call = std::sync::atomic::AtomicU32::new(0); + let r = linux_privesc(&c, "10.0.0.5", 5, |_cmd| { + let first = call.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0; + async move { + if first { + Some("---SUDO---\n(ALL : ALL) NOPASSWD: ALL\n---SUID---\n/usr/bin/find\n---ID---\nuid=1000(svc)".to_string()) + } else { + Some("uid=0(root) gid=0(root)".to_string()) + } + } + }).await.unwrap(); + assert!(r.loot.iter().any(|l| l.starts_with("access:root@10.0.0.5") && l.contains("VERIFIED"))); + assert!(r.loot.iter().any(|l| l.contains("suid-gtfobins") && l.contains("find"))); + } + + #[tokio::test] + async fn no_sudo_rights_yields_no_root_claim() { + let c = cred("password"); + let r = linux_privesc(&c, "10.0.0.5", 5, |_| async { Some("---SUDO---\nSorry, user svc may not run sudo on host.\n---SUID---\n---ID---\nuid=1000(svc)".to_string()) }).await.unwrap(); + assert!(!r.loot.iter().any(|l| l.contains("VERIFIED"))); + } + + #[tokio::test] + async fn local_admin_group_membership_is_verified_without_a_second_call() { + let c = cred("password"); + let r = windows_privesc(&c, "10.0.0.6", 5, |_| async { Some("GroupName\nBUILTIN\\Administrators\nGroup used for deny only".to_string()) }).await.unwrap(); + assert!(r.loot.iter().any(|l| l.contains("administrator@10.0.0.6") && l.contains("VERIFIED"))); + } + + #[tokio::test] + async fn an_enabled_impersonate_privilege_is_a_hypothesis_not_a_claim() { + let c = cred("password"); + let r = windows_privesc(&c, "10.0.0.6", 5, |_| async { Some("Privilege Name Description State\nSeImpersonatePrivilege Impersonate a client Enabled".to_string()) }).await.unwrap(); + assert!(r.loot.iter().any(|l| l.contains("se-impersonate") && l.contains("untested"))); + assert!(!r.loot.iter().any(|l| l.contains("VERIFIED"))); + } + + #[tokio::test] + async fn a_hash_credential_is_skipped_on_linux() { + let c = cred("hash"); + assert!(linux_privesc(&c, "h", 5, |_| async { Some(String::new()) }).await.is_none()); + } +} diff --git a/neurosploit-rs/crates/harness/src/svc_probe.rs b/neurosploit-rs/crates/harness/src/svc_probe.rs new file mode 100644 index 0000000..581393e --- /dev/null +++ b/neurosploit-rs/crates/harness/src/svc_probe.rs @@ -0,0 +1,181 @@ +//! Deterministic port/service discovery → enrichment → CVE/exploit lookup. +//! +//! An infra/network/AD engagement's recon used to be entirely an LLM reply: +//! whether `nmap` even runs, and against which ports, depended on the model +//! deciding to ask the toolbox for it. This module runs the version scan +//! deterministically, then for every (port, service, version) triple it finds: +//! runs a fixed, read-only enrichment probe for that service (never a +//! password spray, never destructive), and looks the service+version up in +//! the local exploit-db mirror (`searchsploit`) for candidate CVEs/exploits. +//! Both are handed to the agents as FACTS — "port 445 is Samba 4.6.2, here are +//! 3 candidate CVEs" — instead of the model having to recall a CVE number +//! from memory and hope it is current. + +use crate::types::RunConfig; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PortFact { + pub port: u16, + pub proto: String, + pub service: String, + pub version: String, +} + +fn sq(s: &str) -> String { + format!("'{}'", s.replace('\'', "'\\''")) +} + +/// Parse nmap's `-oG -`-free default output: lines shaped +/// `PORT STATE SERVICE VERSION...`, e.g. `445/tcp open netbios-ssn Samba smbd 4.6.2`. +pub fn parse_nmap(out: &str) -> Vec { + let mut facts = Vec::new(); + for line in out.lines() { + let t = line.trim(); + let Some((port_proto, rest)) = t.split_once(char::is_whitespace) else { continue }; + let Some((port_s, proto)) = port_proto.split_once('/') else { continue }; + let Some(port) = port_s.parse::().ok() else { continue }; + if !proto.eq_ignore_ascii_case("tcp") && !proto.eq_ignore_ascii_case("udp") { + continue; + } + let rest = rest.trim(); + if !rest.to_ascii_lowercase().starts_with("open") { + continue; + } + let mut cols = rest.split_whitespace(); + cols.next(); // "open" / "open|filtered" + let service = cols.next().unwrap_or("unknown").to_string(); + let version: String = cols.collect::>().join(" "); + facts.push(PortFact { port, proto: proto.to_ascii_lowercase(), service, version }); + } + facts +} + +/// Run `nmap -sV` against `host` and return the parsed ports plus the raw +/// output (kept so the agent can see anything the parser missed). +pub async fn nmap_version_scan(cfg: &RunConfig, host: &str, timeout_secs: u64) -> (Vec, String) { + let cmd = format!("nmap -sV -Pn -T4 --top-ports 1000 {} 2>&1", sq(host)); + match crate::pipeline::recon_tool_timed(cfg, "nmap", &cmd, timeout_secs).await { + Some(out) => { + let facts = parse_nmap(&out); + (facts, out) + } + None => (Vec::new(), String::new()), + } +} + +/// A fixed, read-only enrichment probe for one service. Anonymous-bind / +/// banner / unauthenticated-info-only — never a credential guess, never +/// destructive. `None` when the service has no enrichment worth running. +fn enrich_command(host: &str, port: u16, service: &str) -> Option { + let s = service.to_ascii_lowercase(); + let h = sq(host); + Some(match s.as_str() { + _ if s.contains("snmp") => format!("onesixtyone {h} public 2>&1; snmpwalk -v2c -c public -t 3 {h} 2>&1 | head -40"), + _ if s.contains("ldap") => format!("ldapsearch -x -H ldap://{host}:{port} -s base 2>&1 | head -40"), + _ if s.contains("microsoft-ds") || s.contains("netbios-ssn") || port == 445 || port == 139 => { + format!("smbclient -L //{host}/ -N 2>&1 | head -30; netexec smb {h} -u '' -p '' 2>&1 | head -10") + } + _ if s.contains("mysql") => format!("mysql -h {h} -u root --connect-timeout=3 -e 'select version();' 2>&1 | head -10"), + _ if s.contains("ms-sql") || port == 1433 => format!("impacket-mssqlclient -port {port} guest@{h} -no-pass 2>&1 | head -15"), + _ if s.contains("postgres") => format!("psql -h {host} -p {port} -U postgres -c 'select version();' -w 2>&1 | head -10"), + _ if s.contains("redis") => format!("redis-cli -h {host} -p {port} --timeout 3 ping 2>&1; redis-cli -h {host} -p {port} --timeout 3 info server 2>&1 | head -20"), + _ if s.contains("mongo") => format!("mongosh --host {host} --port {port} --eval 'db.version()' --quiet 2>&1 | head -10"), + _ if s.contains("nfs") || port == 2049 => format!("showmount -e {host} 2>&1 | head -20"), + _ if s.contains("rpcbind") || port == 111 => format!("rpcinfo -p {host} 2>&1 | head -20"), + _ if s.contains("vnc") => format!("echo -e '\\x03' | nc -w3 {host} {port} 2>&1 | xxd | head -3"), + _ if s.contains("ftp") => format!("curl -s -m 5 'ftp://anonymous:anon@{host}:{port}/' 2>&1 | head -20"), + _ if s.contains("telnet") => format!("( echo; sleep 2 ) | nc -w3 {host} {port} 2>&1 | head -5"), + _ if s.contains("elastic") || port == 9200 => format!("curl -s -m 5 'http://{host}:{port}/_cluster/health?pretty' 2>&1 | head -20"), + _ if s.contains("memcache") || port == 11211 => format!("( printf 'stats\\r\\nquit\\r\\n' | nc -w3 {host} {port} ) 2>&1 | head -20"), + _ if s.contains("docker") || port == 2375 => format!("curl -s -m 5 'http://{host}:{port}/version' 2>&1 | head -10"), + _ if s.contains("winrm") || port == 5985 || port == 5986 => format!("netexec winrm {h} -u '' -p '' 2>&1 | head -10"), + _ if s.contains("kerberos") || port == 88 => format!("nmap -p {port} --script krb5-enum-users --script-args krb5-enum-users.realm='WORKGROUP' {h} 2>&1 | head -20"), + _ => return None, + }) +} + +/// Local exploit-db lookup for `service version`. Never reaches the network — +/// `searchsploit` is a local flat-file mirror, so this is a lookup, not a scan. +async fn searchsploit(cfg: &RunConfig, service: &str, version: &str) -> Option { + let query = format!("{service} {version}").trim().to_string(); + if query.is_empty() || query.eq_ignore_ascii_case("unknown") { + return None; + } + let cmd = format!("searchsploit {} 2>&1 | head -20", sq(&query)); + crate::pipeline::recon_tool_timed(cfg, "searchsploit", &cmd, 30).await + .filter(|o| !o.to_ascii_lowercase().contains("exploits: no results")) +} + +/// Run the version scan, enrich every open port, and look each one up for +/// candidate CVEs/exploits. Returns the combined FACTS block to append to +/// recon (empty if nmap itself produced nothing). +pub async fn scan_enrich_and_lookup(cfg: &RunConfig, host: &str, tx: &tokio::sync::mpsc::Sender) -> String { + let _ = tx.send(format!("🔎 service scan: nmap -sV against {host}")).await; + let (facts, raw) = nmap_version_scan(cfg, host, 180).await; + if facts.is_empty() { + return if raw.is_empty() { String::new() } else { format!("\n\nSERVICE SCAN (nmap -sV {host}):\n{}\n", raw.chars().take(3000).collect::()) }; + } + let _ = tx.send(format!("🔎 service scan: {} open port(s) with a version banner — enriching + CVE lookup", facts.len())).await; + let mut block = format!("\n\nSERVICE SCAN + CVE LOOKUP for {host} (deterministic — found a port, validated the version, checked for known exploits; CONFIRM before reporting):\n"); + for f in &facts { + block.push_str(&format!("\n--- {}/{} {} {}\n", f.port, f.proto, f.service, f.version)); + if let Some(cmd) = enrich_command(host, f.port, &f.service) { + if let Some(out) = crate::pipeline::recon_tool_timed(cfg, "sh", &cmd, 20).await { + let clipped: String = out.chars().take(1500).collect(); + if !clipped.trim().is_empty() { + block.push_str(&format!("enrichment:\n{}\n", clipped.trim_end())); + } + } + } + if let Some(hits) = searchsploit(cfg, &f.service, &f.version).await { + block.push_str(&format!("searchsploit candidates (VERIFY each applies — a version-string match is not proof):\n{}\n", hits.chars().take(1500).collect::())); + } + } + block +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_standard_nmap_service_lines() { + let out = "\ +Starting Nmap\n\ +PORT STATE SERVICE VERSION\n\ +22/tcp open ssh OpenSSH 8.2p1 Ubuntu\n\ +445/tcp open netbios-ssn Samba smbd 4.6.2\n\ +53/udp open domain dnsmasq 2.80\n\ +8080/tcp closed http\n"; + let facts = parse_nmap(out); + assert_eq!(facts.len(), 3); + assert_eq!(facts[0], PortFact { port: 22, proto: "tcp".into(), service: "ssh".into(), version: "OpenSSH 8.2p1 Ubuntu".into() }); + assert_eq!(facts[1].service, "netbios-ssn"); + assert_eq!(facts[1].version, "Samba smbd 4.6.2"); + assert_eq!(facts[2].proto, "udp"); + assert!(!facts.iter().any(|f| f.port == 8080), "closed ports must not be reported as open"); + } + + #[test] + fn a_closed_or_filtered_port_is_never_reported() { + let out = "111/tcp filtered rpcbind\n80/tcp open|filtered http\n"; + // "open|filtered" starts with "open" and is a real nmap state when a + // firewall drops probes silently — it is kept, "filtered" alone is not. + let facts = parse_nmap(out); + assert_eq!(facts.len(), 1); + assert_eq!(facts[0].port, 80); + } + + #[test] + fn snmp_and_smb_each_get_a_read_only_enrichment_command() { + let snmp = enrich_command("10.0.0.5", 161, "snmp").unwrap(); + assert!(snmp.contains("onesixtyone") && snmp.contains("public")); + let smb = enrich_command("10.0.0.5", 445, "netbios-ssn").unwrap(); + assert!(smb.contains("smbclient")); + } + + #[test] + fn an_unmapped_service_has_no_enrichment() { + assert!(enrich_command("h", 54321, "totally-custom-proto").is_none()); + } +} diff --git a/web/public/app.js b/web/public/app.js index e976e1a..5728f47 100644 --- a/web/public/app.js +++ b/web/public/app.js @@ -8,7 +8,10 @@ const MODE_LABELS = { run: { target: 'Target URL', help: 'The application to test.', showRepo: false, placeholder: 'https://target.example.com' }, whitebox: { target: 'Source repo / path', help: "A GitHub URL, owner/repo shorthand, or a local path — cloned automatically if it's remote.", showRepo: false, placeholder: 'owner/repo' }, greybox: { target: 'Target URL', help: 'The running application to exploit, alongside the source repo below.', showRepo: true, placeholder: 'https://target.example.com' }, - host: { target: 'Target host / IP', help: 'Runs Linux / Windows / Active Directory agents.', showRepo: false, placeholder: '10.0.0.10' }, + host: { target: 'Target host / IP', help: 'Generic Linux/Windows host — no network/AD profile filtering.', showRepo: false, placeholder: '10.0.0.10' }, + network: { target: 'Target host / IP', help: 'Internal network agents only — this profile assumes no Active Directory on the network.', showRepo: false, placeholder: '10.0.0.10' }, + ad: { target: 'Domain host / DC', help: 'Active Directory-specific agents (and Windows/Linux domain members).', showRepo: false, placeholder: 'dc01.corp.local' }, + mobile: { target: 'Artifact', help: 'Upload the APK, IPA, or native binary below — it is analysed only inside this engagement.', showRepo: false, placeholder: '', showUpload: true }, aitest: { target: 'AI endpoint URL', help: 'A live AI agent, LLM chat, or MCP endpoint (OWASP LLM Top 10).', showRepo: false, placeholder: 'https://target.example.com/chat' }, cloud: { target: 'Cloud account / project', help: 'Test a connected cloud environment — select from configured AWS, GCP, or Azure integrations.', showRepo: false, placeholder: 'aws / gcp / azure', showCloudPicker: true }, }; @@ -31,6 +34,8 @@ const state = { credsPath: '', collectionPath: '', collectionData: '', + artifactPath: '', + artifactMeta: null, // Engagement authorization: the grant, plus settings that may only narrow it. authz: { capability: '', inScope: '', environment: 'production', policyProfile: 'web', transport: '', oobDomain: '', oobHttp: '', oobDns: '', sms: '' }, keys: [], @@ -230,7 +235,13 @@ function validateStep(n) { fieldError('#errName', 'Name the engagement — this is how it is labelled in the sidebar and run history.'); firstBad = firstBad || '#fieldName'; } - if (!$('#fieldTarget').value.trim()) { + if (state.mode === 'mobile') { + if (!state.artifactPath) { + fieldError('#errUpload', 'Upload an artifact first.'); + show($('#errUpload'), true); + firstBad = firstBad || '#fieldUploadFile'; + } + } else if (!$('#fieldTarget').value.trim()) { fieldError('#errTarget', `${MODE_LABELS[state.mode].target} is required.`); firstBad = firstBad || '#fieldTarget'; } @@ -268,12 +279,42 @@ function selectMode(mode) { $('#fieldTarget').placeholder = cfg.placeholder; show($('#fieldRepoGroup'), cfg.showRepo); show($('#fieldCloudGroup'), !!cfg.showCloudPicker); + show($('#fieldUploadGroup'), !!cfg.showUpload); + show($('#fieldTargetGroup'), !cfg.showUpload); if (cfg.showCloudPicker) populateCloudPicker(); updateWizardSummary(); } $$('.mode-tile').forEach((tile) => tile.addEventListener('click', () => selectMode(tile.dataset.mode))); $('#fieldTarget').addEventListener('input', updateWizardSummary); +// --------------------------------------------------------------------------- +// artifact upload (mobile / binary mode) +// --------------------------------------------------------------------------- + +$('#fieldUploadFile')?.addEventListener('change', async (e) => { + const file = e.target.files?.[0]; + const status = $('#uploadStatus'); + const err = $('#errUpload'); + show(err, false); + if (!file) return; + state.artifactPath = ''; + state.artifactMeta = null; + status.textContent = `Uploading ${file.name}…`; + try { + const res = await fetch(`/api/upload?name=${encodeURIComponent(file.name)}`, { method: 'POST', body: file }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'upload failed'); + state.artifactPath = data.path; + state.artifactMeta = data; + status.textContent = `${data.name} — ${data.kind}, ${(data.size / 1024 / 1024).toFixed(2)} MB, sha256 ${data.sha256.slice(0, 16)}…${data.warning ? ` — ⚠ ${data.warning}` : ''}`; + } catch (ex) { + status.textContent = ''; + err.textContent = ex.message; + show(err, true); + } + updateWizardSummary(); +}); + async function populateCloudPicker() { const sel = $('#fieldCloudProvider'); if (!sel) return; @@ -851,6 +892,8 @@ async function startExploitation() { collectionPath: state.collectionPath || undefined, collectionData: state.collectionData || undefined, cloudProvider: mode === 'cloud' ? ($('#fieldCloudProvider')?.value || target) : undefined, + artifactPath: mode === 'mobile' ? state.artifactPath : undefined, + platform: mode === 'mobile' ? ($('#fieldPlatform')?.value || undefined) : undefined, capability: state.authz.capability || undefined, inScope: state.authz.inScope.split(/[,;\s]+/).filter(Boolean), environment: state.authz.environment, diff --git a/web/public/index.html b/web/public/index.html index 3ae1980..b3b3236 100644 --- a/web/public/index.html +++ b/web/public/index.html @@ -550,7 +550,10 @@ - + + + + @@ -574,6 +577,18 @@
Pick a connected cloud integration from the Integrations page. Configure credentials there first.
+ diff --git a/web/server.js b/web/server.js index 0cd1bfa..49d46eb 100644 --- a/web/server.js +++ b/web/server.js @@ -21,6 +21,8 @@ const os = require('node:os'); const path = require('node:path'); const { spawn, execFileSync } = require('node:child_process'); const crypto = require('node:crypto'); +const { Transform } = require('node:stream'); +const { pipeline: streamPipeline } = require('node:stream/promises'); const { EventEmitter } = require('node:events'); const { StringDecoder } = require('node:string_decoder'); @@ -274,23 +276,38 @@ const PROVIDERS = [ ]; const apiKeys = new Map(); // provider key -> secret +// Keys in the file for providers this console does not list (the CLI knows +// more of them). Kept verbatim so saving one key never drops another. +const extraKeys = new Map(); +const baseUrls = new Map(); // provider key -> custom OpenAI-compatible base URL const KEYS_FILE = path.join(CONFIG_DIR, 'keys.json'); +const BASE_URLS_FILE = path.join(CONFIG_DIR, 'base_urls.json'); async function loadKeys() { try { const raw = await fsp.readFile(KEYS_FILE, 'utf8'); const obj = JSON.parse(raw); for (const [k, v] of Object.entries(obj)) { - if (v && PROVIDERS.some(p => p.key === k)) apiKeys.set(k, v); + if (!v) continue; + if (PROVIDERS.some(p => p.key === k)) apiKeys.set(k, v); + else extraKeys.set(k, v); } } catch { /* first run or corrupted — start empty */ } + try { + const obj = JSON.parse(await fsp.readFile(BASE_URLS_FILE, 'utf8')); + for (const [k, v] of Object.entries(obj)) if (v) baseUrls.set(k, String(v)); + } catch { /* none saved */ } } async function persistKeys() { await ensureConfigDir(); const obj = {}; + for (const [k, v] of extraKeys) obj[k] = v; for (const [k, v] of apiKeys) obj[k] = v; await fsp.writeFile(KEYS_FILE, JSON.stringify(obj, null, 2), { mode: 0o600 }); + const urls = {}; + for (const [k, v] of baseUrls) urls[k] = v; + await fsp.writeFile(BASE_URLS_FILE, JSON.stringify(urls, null, 2), { mode: 0o600 }); } // A cheap authenticated endpoint per provider, to confirm a key works. GET a @@ -339,6 +356,9 @@ function envOverrides() { const p = PROVIDERS.find((x) => x.key === key); if (p && secret) env[p.envKey] = secret; } + // Custom OpenAI-compatible endpoint (generic `litellm` provider) and local servers. + const urlEnv = { litellm: 'LITELLM_BASE_URL', ollama: 'OLLAMA_BASE_URL', llamacpp: 'LLAMACPP_BASE_URL' }; + for (const [prov, url] of baseUrls) if (urlEnv[prov] && url) env[urlEnv[prov]] = url; // TypeSafe agent pruning is too aggressive — disable by default. // Re-enable per-run via the UI's typesafe toggle. if (!env.NEUROSPLOIT_TYPESAFE) env.NEUROSPLOIT_TYPESAFE = 'off'; @@ -1413,14 +1433,32 @@ function ingestLine(job, rawLine) { } } +const CLOUD_PROVIDERS = ['aws', 'azure', 'gcp']; +function normCloudProvider(v) { + const s = String(v || 'aws').trim().toLowerCase(); + const alias = { google: 'gcp', 'google-cloud': 'gcp', gcloud: 'gcp', entra: 'azure', amazon: 'aws' }; + const c = alias[s] || s; + if (!CLOUD_PROVIDERS.includes(c)) { + throw Object.assign(new Error(`unsupported cloud provider '${v}' — use aws, azure or gcp`), { status: 400 }); + } + return c; +} +// Modes whose CLI subcommand takes the same flag set as `host` (session-scoped +// engagements: they reject several run-only flags). +const HOST_LIKE_MODES = ['host', 'network', 'ad', 'cloud', 'aitest', 'internal']; + function buildArgs(body) { - const rawMode = body.mode || 'run'; - const mode = rawMode === 'cloud' ? 'host' : rawMode; + const mode = body.mode || 'run'; const args = [mode]; - if (rawMode === 'cloud') { - args.push(body.target || 'localhost'); - args.push('--cloud', body.target || 'aws'); - } else if (mode === 'run' || mode === 'host' || mode === 'aitest') { + if (mode === 'cloud') { + args.push(normCloudProvider(body.cloudProvider || body.target)); + for (const [flag, key] of [['--label', 'cloudLabel'], ['--aws-profile', 'cloudProfile'], ['--region', 'cloudRegion'], + ['--subscription-id', 'cloudSubscription'], ['--tenant', 'cloudTenant'], ['--project', 'cloudProject']]) { + if (body[key]) args.push(flag, String(body[key])); + } + } else if (mode === 'mobile') { + args.push(body.artifactPath); + } else if (mode === 'run' || mode === 'host' || mode === 'network' || mode === 'ad' || mode === 'aitest') { args.push(body.target); } else if (mode === 'whitebox' || mode === 'skills') { args.push(body.repo || body.target); @@ -1428,9 +1466,22 @@ function buildArgs(body) { args.push(body.repo); args.push('--url', body.target); } - // host/aitest/internal are session-style engagements and reject several - // run-only flags; gate those so a console-launched host run doesn't crash. - const runOnly = !['host', 'aitest', 'internal'].includes(mode); + // Mobile/binary analysis takes a small flag set of its own. + if (mode === 'mobile') { + if (body.platform) args.push('--platform', String(body.platform)); + for (const m of body.models || []) args.push('--model', m); + if (body.votes) args.push('--vote-n', String(body.votes)); + if (body.maxAgents) args.push('--max-agents', String(body.maxAgents)); + if (body.offline) args.push('--offline'); + if (body.subscription) args.push('--subscription'); + if (body.focus) args.push('--focus', body.focus); + args.push('--agent-tools', '--verbose'); + return args; + } + // host/network/ad/cloud/aitest/internal are session-style engagements and + // reject several run-only flags; gate those so a console-launched run + // doesn't crash. + const runOnly = !HOST_LIKE_MODES.includes(mode); for (const m of body.models || []) args.push('--model', m); if (body.votes) args.push('--vote-n', String(body.votes)); if (body.chainDepth !== undefined) args.push('--chain-depth', String(body.chainDepth)); @@ -1441,6 +1492,7 @@ function buildArgs(body) { if (body.research && (mode === 'whitebox' || mode === 'greybox')) args.push('--research'); if (body.offline) args.push('--offline'); if (body.subscription) args.push('--subscription'); + if (mode === 'run' && body.allAgents) args.push('--all-agents'); if (runOnly && body.mcp) args.push('--mcp'); if (body.creds) args.push('--creds', body.creds); if (body.collectionPath) args.push('--collection', body.collectionPath); @@ -1469,7 +1521,7 @@ function buildArgs(body) { // can only narrow within it, and the environment scales every risk score. // host/aitest/internal expose these as --session-* (set before the first // command of an interactive/one-shot session); run/cloud use the plain flags. - const sessionScoped = ['host', 'aitest', 'internal'].includes(mode); + const sessionScoped = HOST_LIKE_MODES.includes(mode); for (const entry of body.inScope || []) args.push(sessionScoped ? '--session-in-scope' : '--in-scope', entry); if (body.scopePath && !sessionScoped) args.push('--scope-file', body.scopePath); if (body.capability) args.push('--capability-token', body.capability); @@ -1497,13 +1549,20 @@ async function startJob(body) { const credsPath = await materializeCreds(body, id); const scopePath = await materializeScope(body, id); const collectionPath = await materializeCollection(body, id); - const args = buildArgs({ ...body, creds: credsPath, scopePath, collectionPath }); - const job = new Job(id, BIN, args, body.repo || body.target || '', body.name || ''); + // Mobile/binary: only a file this console received is analysed, never an + // arbitrary path on the server. + const artifactPath = body.mode === 'mobile' ? await resolveUploadedArtifact(body.artifactPath) : undefined; + const cloudProv = body.mode === 'cloud' ? normCloudProvider(body.cloudProvider || body.target) : body.cloudProvider; + const args = buildArgs({ ...body, creds: credsPath, scopePath, collectionPath, artifactPath, cloudProvider: cloudProv }); + const jobTarget = body.mode === 'mobile' ? path.basename(artifactPath) + : body.mode === 'cloud' ? `cloud:${cloudProv}` + : (body.repo || body.target || ''); + const job = new Job(id, BIN, args, jobTarget, body.name || ''); job.pinnedAgents = body.agents || []; job.projectId = body.projectId || null; jobs.set(id, job); - const cloudEnv = body.cloudProvider ? await cloudEnvOverrides(body.cloudProvider) : {}; + const cloudEnv = cloudProv ? await cloudEnvOverrides(cloudProv) : {}; const child = spawn(BIN, args, { cwd: ROOT, env: { ...process.env, ...envOverrides(), ...cloudEnv } }); job.child = child; let buf = ''; @@ -1597,6 +1656,7 @@ function sanitizeLaunch(body) { typesafe: body.typesafe, quick: !!body.quick, research: !!body.research, + allAgents: !!body.allAgents, maxAgents: body.maxAgents || undefined, c2: !!body.c2, c2Authorization: body.c2Authorization || undefined, @@ -1671,7 +1731,7 @@ async function startJobViaRepl(body) { // The REPL session inherits the engagement's authorization from argv, so the // ceiling is set before the first command is scripted into it. - const child = spawn(BIN, auth, { cwd: ROOT, env: { ...process.env, ...envOverrides() } }); + const child = spawn(BIN, auth, { cwd: ROOT, env: { ...process.env, ...envOverrides(), ...(body.allAgents ? { NEUROSPLOIT_ALL_AGENTS: '1' } : {}) } }); job.child = child; let buf = ''; const onData = (chunk) => { @@ -1716,7 +1776,7 @@ function relaunchJobViaRepl(job) { job.phase = 'resuming'; job.push({ type: 'log', line: '[web] resuming — recovering the on-disk checkpoint and continuing…' }); - const child = spawn(BIN, auth, { cwd: ROOT, env: { ...process.env, ...envOverrides(), NEUROSPLOIT_AUTO_RESUME: '1' } }); + const child = spawn(BIN, auth, { cwd: ROOT, env: { ...process.env, ...envOverrides(), ...(launch.allAgents ? { NEUROSPLOIT_ALL_AGENTS: '1' } : {}), NEUROSPLOIT_AUTO_RESUME: '1' } }); job.child = child; let buf = ''; const onData = (chunk) => { @@ -1869,6 +1929,133 @@ function sendJson(res, code, obj) { res.end(body); } +// --------------------------------------------------------------------------- +// Artifact uploads (APK/IPA/binaries) for mobile/binary analysis +// --------------------------------------------------------------------------- + +const UPLOADS_DIR = path.join(ROOT, 'uploads'); +const UPLOAD_KINDS = { + apk: 'Android APK', aab: 'Android App Bundle', xapk: 'Android XAPK', apks: 'Android APK set', ipa: 'iOS IPA', + jar: 'Java archive', war: 'Java web archive', dex: 'Dalvik executable', so: 'Shared object (ELF)', + elf: 'ELF binary', exe: 'Windows executable (PE)', dll: 'Windows library (PE)', bin: 'Raw binary', + zip: 'ZIP archive', macho: 'Mach-O binary', dylib: 'macOS library (Mach-O)', +}; +const ZIP_LIKE = new Set(['apk', 'aab', 'xapk', 'apks', 'ipa', 'jar', 'war', 'zip']); + +function safeUploadName(raw) { + let n = String(raw || '').split(/[\\/]/).pop(); + n = n.replace(/[\u0000-\u001f\u007f]/g, '').replace(/\.{2,}/g, '.').replace(/[^\w.\-+@ ()]/g, '_').trim().replace(/^\.+/, ''); + if (n.length > 120) { + const ext = path.extname(n); + n = n.slice(0, 120 - ext.length) + ext; + } + return n; +} + +function uploadMagicWarning(ext, head) { + const hex = head.toString('hex'); + const ok = ZIP_LIKE.has(ext) ? hex.startsWith('504b0304') || hex.startsWith('504b0506') + : ext === 'dex' ? head.toString('latin1').startsWith('dex\n') + : (ext === 'so' || ext === 'elf') ? hex.startsWith('7f454c46') + : (ext === 'exe' || ext === 'dll') ? hex.startsWith('4d5a') + : (ext === 'macho' || ext === 'dylib') ? ['feedface', 'feedfacf', 'cefaedfe', 'cffaedfe', 'cafebabe'].some((m) => hex.startsWith(m)) + : true; + return ok ? undefined : `the content does not look like a ${UPLOAD_KINDS[ext]} — analysing it anyway`; +} + +/// A browser always sends Origin on a cross-site POST; refuse when it names another host. +function sameOrigin(req) { + const origin = req.headers.origin; + if (!origin) return true; // curl / CLI clients send none + try { return new URL(origin).host === req.headers.host; } catch { return false; } +} + +async function handleUpload(req, res, u) { + if (!sameOrigin(req)) return sendJson(res, 403, { error: 'cross-origin upload refused' }); + const name = safeUploadName(u.searchParams.get('name')); + const ext = path.extname(name).slice(1).toLowerCase(); + if (!name || !UPLOAD_KINDS[ext]) { + return sendJson(res, 400, { error: `unsupported file type — allowed: ${Object.keys(UPLOAD_KINDS).map((e) => '.' + e).join(' ')}` }); + } + const capMb = Number(process.env.NEUROSPLOIT_MAX_UPLOAD_MB) || 1024; + const cap = capMb * 1024 * 1024; + const tooLarge = () => { + res.once('finish', () => req.destroy()); + sendJson(res, 413, { error: `file exceeds the ${capMb} MB upload limit (NEUROSPLOIT_MAX_UPLOAD_MB)` }); + }; + if (Number(req.headers['content-length'] || 0) > cap) return tooLarge(); + + const id = crypto.randomBytes(8).toString('hex'); + const dir = path.join(UPLOADS_DIR, id); + const file = path.join(dir, name); + await fsp.mkdir(dir, { recursive: true, mode: 0o700 }); + const hash = crypto.createHash('sha256'); + let size = 0; + const meter = new Transform({ + transform(chunk, _enc, cb) { + size += chunk.length; + if (size > cap) return cb(Object.assign(new Error('too large'), { code: 'E2BIG' })); + hash.update(chunk); + cb(null, chunk); + }, + }); + try { + await streamPipeline(req, meter, fs.createWriteStream(file, { flags: 'wx', mode: 0o600 })); + } catch (e) { + await fsp.rm(dir, { recursive: true, force: true }).catch(() => {}); + if (e.code === 'E2BIG') return tooLarge(); + return sendJson(res, 400, { error: 'upload interrupted' }); + } + if (size === 0) { + await fsp.rm(dir, { recursive: true, force: true }).catch(() => {}); + return sendJson(res, 400, { error: 'empty file' }); + } + const fh = await fsp.open(file, 'r'); + const head = Buffer.alloc(8); + await fh.read(head, 0, 8, 0).catch(() => {}); + await fh.close(); + const warning = uploadMagicWarning(ext, head); + return sendJson(res, 200, { path: file, name, size, sha256: hash.digest('hex'), kind: UPLOAD_KINDS[ext], ext, ...(warning ? { warning } : {}) }); +} + +/// Mobile/binary runs analyse only a file this console received. +async function resolveUploadedArtifact(p) { + const bad = (m) => Object.assign(new Error(m), { status: 400 }); + if (!p || typeof p !== 'string') throw bad('upload the artifact first — no file path was given'); + let real; let root; + try { + real = await fsp.realpath(path.resolve(p)); + root = await fsp.realpath(UPLOADS_DIR); + } catch { throw bad('artifact not found in the uploads directory'); } + if (!real.startsWith(root + path.sep)) throw bad('the artifact must be a file uploaded through the console'); + const st = await fsp.stat(real); + if (!st.isFile()) throw bad('the artifact path is not a file'); + return real; +} + +/// Run `neurosploit key detect` with the key on STDIN — never in argv or logs. +function detectKeyViaCli({ key, provider, baseUrl, probeAll }) { + return new Promise((resolve, reject) => { + const args = ['key', 'detect']; + if (provider) args.push('--provider', provider); + if (baseUrl) args.push('--base-url', baseUrl); + if (probeAll) args.push('--probe-all'); + const child = spawn(BIN, args, { cwd: ROOT, env: { ...process.env } }); + let out = ''; + const timer = setTimeout(() => { child.kill('SIGKILL'); reject(new Error('key detection timed out')); }, 45000); + child.stdout.on('data', (c) => { if (out.length < 2_000_000) out += c; }); + child.stderr.on('data', () => {}); // discarded: never surfaced, never logged + child.on('error', (e) => { clearTimeout(timer); reject(e); }); + child.on('close', () => { + clearTimeout(timer); + const line = out.trim().split('\n').filter(Boolean).pop() || ''; + try { resolve(JSON.parse(line)); } catch { reject(new Error('the neurosploit binary returned no detection result')); } + }); + child.stdin.on('error', () => {}); + child.stdin.end(key + '\n'); + }); +} + function readBody(req) { return new Promise((resolve, reject) => { let data = ''; @@ -2664,7 +2851,7 @@ const server = http.createServer(async (req, res) => { return sendJson(res, 200, PROVIDERS.map(({ key, label, kind, models }) => ({ key, label, kind, models }))); } if (req.method === 'GET' && p === '/api/keys') { - return sendJson(res, 200, PROVIDERS.map((pr) => ({ provider: pr.key, set: apiKeys.has(pr.key) && !!apiKeys.get(pr.key) }))); + return sendJson(res, 200, PROVIDERS.map((pr) => ({ provider: pr.key, set: apiKeys.has(pr.key) && !!apiKeys.get(pr.key), ...(baseUrls.has(pr.key) ? { baseUrl: baseUrls.get(pr.key) } : {}) }))); } if (req.method === 'POST' && p === '/api/keys') { const body = await readBody(req); @@ -2673,11 +2860,36 @@ const server = http.createServer(async (req, res) => { } if (body.key) apiKeys.set(body.provider, body.key); else apiKeys.delete(body.provider); + if (body.baseUrl !== undefined) { + const url = String(body.baseUrl || '').trim().replace(/\/+$/, ''); + if (!url) baseUrls.delete(body.provider); + else if (!/^https?:\/\//i.test(url)) return sendJson(res, 400, { error: 'baseUrl must start with http:// or https://' }); + else baseUrls.set(body.provider, url); + } await persistKeys(); let verify = { ok: null, message: 'saved' }; if (body.key && body.verify !== false) verify = await verifyKey(body.provider, body.key); return sendJson(res, 200, { ok: true, verify }); } + if (req.method === 'POST' && p === '/api/upload') { + return handleUpload(req, res, u); + } + if (req.method === 'POST' && p === '/api/keys/detect') { + if (!sameOrigin(req)) return sendJson(res, 403, { error: 'cross-origin request refused' }); + if (!BIN) return sendJson(res, 500, { error: 'neurosploit binary not found — run `cargo build --release` in neurosploit-rs/' }); + const body = await readBody(req); + const key = String(body.key || '').trim(); + if (!key || /[\r\n]/.test(key)) return sendJson(res, 400, { error: 'paste a single API key' }); + const provider = body.provider ? String(body.provider).trim() : ''; + if (provider && !/^[a-z0-9_]{1,32}$/.test(provider)) return sendJson(res, 400, { error: 'invalid provider' }); + const baseUrl = body.baseUrl ? String(body.baseUrl).trim() : ''; + if (baseUrl && !/^https?:\/\/\S+$/i.test(baseUrl)) return sendJson(res, 400, { error: 'baseUrl must start with http:// or https://' }); + try { + return sendJson(res, 200, await detectKeyViaCli({ key, provider, baseUrl, probeAll: body.probeAll === true })); + } catch (e) { + return sendJson(res, 502, { error: e.message }); + } + } if (req.method === 'POST' && p === '/api/keys/verify') { const body = await readBody(req); const key = body.key || apiKeys.get(body.provider); @@ -2860,7 +3072,7 @@ const server = http.createServer(async (req, res) => { sendJson(res, 404, { error: 'not found' }); } catch (err) { - sendJson(res, 500, { error: err.message }); + sendJson(res, err.status || 500, { error: err.message }); } });