Files
NeuroSploit/neurosploit-rs/app/src/keycli.rs
T
CyberSecurityUP 54e8b13035 feat: pluggable LLM providers, kernel/binary recon, iterative tool-calling, mobile/binary pipeline
Model integration:
- neurosploit key add/list/remove/detect: identify a provider from its key,
  list real callable models, save it — CLI, REPL and web console share one
  detector/keystore.
- custom_providers.rs: register any OpenAI-compatible endpoint under its own
  name (mycorp:<model>) with no source change or rebuild; several can coexist.
- Added deepseek-v4-1-flash-1017, Venice AI, vLLM and LM Studio providers.
- Fixed --sandbox/--stealth/--neo4j/--engagement being silently dropped by
  mobile/container/host/network/ad/cloud/greybox/tui/aitest (only `run` wired
  them before).

Recon depth:
- codeindex.rs: whole-repo indexing for whitebox review (functions, routes,
  call graph, sources/sinks/sanitizers) with cross-file attack-flow tracing,
  replacing the old first-200-files slice. Multi-pass per-agent context within
  a budget, plus a variant/circumvention-review doctrine for every SAST agent.
- kernel_recon.rs: deterministic Linux kernel facts over an authorized SSH
  session (version, modules, SUID surface, sysctls) for the LLM to reason from.
- winbin_harvest.rs: pulls third-party Windows driver/service binaries off an
  authorized host over SMB and runs them through the same deep binary pass.
- re_tools.rs: embedded read-only radare2/Ghidra/IDA/Frida helper scripts and
  headless drivers, shared by the mobile/binary and Windows-harvest pipelines.
- 38 new mobile/iOS/Android/native-binary research agents (agents_md/mobile/
  was empty before — `neurosploit mobile` ran zero agents).
- artifact.rs: resolve a local path or URL, classify by magic bytes, hash.
- profile.rs: network vs AD vs cloud:<provider> vs web agent-set restriction;
  `run` now defaults to web-only agents (--all-agents lifts it).

Agentic capability / opsec:
- agentic_tools.rs: a real iterative tool-calling loop (call a tool, read its
  actual output, decide the next one) replacing the one-shot batch picker;
  wired into the existing recon tool round.
- noise_governor.rs: the per-host rate/jitter governor existed but was never
  called anywhere — wired it into the new tool-calling loop under --stealth.
- credtest.rs: credentials surfaced by the attack-chain loop are now actually
  tested (SSH/SMB/WinRM/HTTP-basic) between rounds instead of left for the
  model to maybe act on; a verified one becomes a confirmed-foothold fact for
  the next round.
- teamboard.rs: exploit agents in the same wave see each other's leads
  (credentials, endpoints) as they land, with IDs so a finding can cite the
  lead it was chained from (chains_from is now actually parsed and recorded).
- poc_gate.rs: lints PoC scripts for known false-positive patterns (success
  printed in an error handler, unconditional success, self-injection, a script
  that reimplements the bug instead of exercising the target) and lowers
  confidence instead of trusting the script blindly.
- taint.rs: detects and strips "poison the AI agent" decoy comments (the
  SpikeStrip pattern — a random hex key followed by a fabricated CVE/route)
  regardless of payload wording, by their structural fingerprint.
- recon_compact.rs: semantic compaction of recon JSON (halves the largest
  array, keeps every key) instead of a hard character truncation that silently
  dropped the tail of the reply.

751 tests passing; release build clean.
2026-11-28 14:18:53 -03:00

208 lines
8.3 KiB
Rust

//! `neurosploit key …` — paste an LLM API key, the provider is identified for
//! you, and you only choose the model. Thin CLI over `harness::provider_detect`
//! and `harness::keystore`, so the CLI, the REPL and the web console share one
//! detector and one keys file.
use clap::Subcommand;
use harness::keystore;
use harness::provider_detect::{self, DetectOutcome, Detected};
use std::io::{BufRead, IsTerminal, Write};
use std::path::Path;
#[derive(Subcommand)]
pub enum KeyCmd {
/// Add a key: identify the provider, list the models it can call, save it.
/// The key is read from the argument, or from stdin when omitted (a key on
/// the command line lands in shell history).
Add {
key: Option<String>,
/// Skip detection and verify against this provider only.
#[arg(long)]
provider: Option<String>,
/// Any OpenAI-compatible endpoint (vLLM, Ollama, a gateway): its base URL.
#[arg(long)]
base_url: Option<String>,
/// Name this endpoint so it gets its own `<name>:<model>` slot (with
/// --base-url). Lets several custom endpoints coexist; omit to use the
/// single shared `litellm` slot.
#[arg(long)]
name: Option<String>,
/// Allow sending a key that does not name its issuer to every public provider.
#[arg(long)]
probe_all: bool,
/// Model to use (skips the prompt); must be one the key can call.
#[arg(long)]
model: Option<String>,
},
/// Show the saved keys (masked) and where they are stored.
List,
/// Remove a saved key.
Remove { provider: String },
/// Detect only: read a key from stdin, print JSON, save nothing. Used by the web console.
Detect {
#[arg(long)]
provider: Option<String>,
#[arg(long)]
base_url: Option<String>,
#[arg(long)]
name: Option<String>,
#[arg(long)]
probe_all: bool,
},
}
fn read_key_from_stdin() -> anyhow::Result<String> {
let stdin = std::io::stdin();
if stdin.is_terminal() {
eprint!(" paste your API key (it is not stored in shell history; the terminal will echo it): ");
std::io::stderr().flush().ok();
}
let mut line = String::new();
stdin.lock().read_line(&mut line)?;
let k = line.trim().to_string();
if k.is_empty() {
anyhow::bail!("no key given");
}
Ok(k)
}
fn ask(prompt: &str) -> Option<String> {
if !std::io::stdin().is_terminal() {
return None;
}
eprint!("{prompt}");
std::io::stderr().flush().ok();
let mut s = String::new();
std::io::stdin().lock().read_line(&mut s).ok()?;
Some(s.trim().to_string())
}
async fn run_detect(key: &str, provider: &Option<String>, base_url: &Option<String>, name: &Option<String>, probe_all: bool) -> DetectOutcome {
if let Some(url) = base_url {
provider_detect::detect_custom(key, url, name.as_deref()).await
} else if let Some(p) = provider {
provider_detect::detect_named(key, p).await
} else {
provider_detect::detect(key, probe_all).await
}
}
fn pick_provider(o: &DetectOutcome) -> anyhow::Result<&Detected> {
if o.detected.len() == 1 {
return Ok(&o.detected[0]);
}
eprintln!(" more than one provider accepted this key:");
for (i, d) in o.detected.iter().enumerate() {
eprintln!(" {}. {} ({}) — {} model(s)", i + 1, d.label, d.provider, d.models.len());
}
match ask(" which one? [number]: ").and_then(|s| s.parse::<usize>().ok()).filter(|n| (1..=o.detected.len()).contains(n)) {
Some(n) => Ok(&o.detected[n - 1]),
None => anyhow::bail!("ambiguous — rerun with --provider <name>"),
}
}
fn pick_model(d: &Detected, wanted: &Option<String>) -> anyhow::Result<Option<String>> {
if let Some(m) = wanted {
if !d.models.is_empty() && !d.models.contains(m) {
anyhow::bail!("'{m}' is not among the {} model(s) this key can call", d.models.len());
}
return Ok(Some(m.clone()));
}
if d.models.is_empty() {
return Ok(None);
}
let default = d.recommended.clone().unwrap_or_else(|| d.models[0].clone());
eprintln!(" {} model(s) available on this key:", d.models.len());
for (i, m) in d.models.iter().take(40).enumerate() {
let star = if *m == default { " ← recommended" } else { "" };
eprintln!(" {:>2}. {m}{star}", i + 1);
}
if d.models.len() > 40 {
eprintln!(" … and {} more (pass --model <id> for any of them)", d.models.len() - 40);
}
let chosen = match ask(&format!(" model [number or id, Enter = {default}]: ")) {
None => return Ok(Some(default)),
Some(s) if s.is_empty() => default,
Some(s) => match s.parse::<usize>() {
Ok(n) if (1..=d.models.len().min(40)).contains(&n) => d.models[n - 1].clone(),
_ => s,
},
};
Ok(Some(chosen))
}
pub async fn handle(base: &Path, cmd: KeyCmd) -> anyhow::Result<()> {
match cmd {
KeyCmd::Add { key, provider, base_url, name, probe_all, model } => {
let key = match key {
Some(k) => k.trim().to_string(),
None => read_key_from_stdin()?,
};
let mut o = run_detect(&key, &provider, &base_url, &name, probe_all).await;
// An ambiguous key: say where it would go, and only go there on consent.
if o.detected.is_empty() && !o.candidates.is_empty() {
eprintln!(" this key does not name its provider. It would be sent to: {}", o.candidates.join(", "));
let yes = ask(" try them all? [y/N]: ").map(|s| s.eq_ignore_ascii_case("y")).unwrap_or(false);
if yes {
o = run_detect(&key, &provider, &base_url, &name, true).await;
} else {
anyhow::bail!("not sent anywhere. Name the provider: neurosploit key add --provider <name>, or use --base-url for a custom endpoint");
}
}
if o.detected.is_empty() {
anyhow::bail!("{}", if o.note.is_empty() { "no provider accepted the key".to_string() } else { o.note.clone() });
}
let d = pick_provider(&o)?;
eprintln!(" ✓ {} ({})", d.label, d.provider);
let chosen = pick_model(d, &model)?;
keystore::save_key(base, &d.provider, &key)?;
if d.provider == "litellm" {
keystore::save_base_url(base, "litellm", &d.base_url)?;
}
eprintln!(" saved to {} ({})", keystore::keys_path(base).display(), keystore::mask(&key));
match chosen {
Some(m) => {
println!("{}:{m}", d.provider);
eprintln!(" use it: neurosploit run <url> --model {}:{m}", d.provider);
}
None => eprintln!(" the provider did not list models; pass --model {}:<model-id>", d.provider),
}
}
KeyCmd::List => {
let keys = keystore::load(base);
println!(" keys file: {}", keystore::keys_path(base).display());
if keys.is_empty() {
println!(" (none saved — neurosploit key add <key>)");
}
let custom = harness::custom_providers::list(base);
for (prov, k) in keys {
let url = custom.get(&prov).map(|u| format!(" ({u})")).unwrap_or_default();
println!(" {prov:<12} {}{url}", keystore::mask(&k));
}
}
KeyCmd::Remove { provider } => {
let mut keys = keystore::load(base);
let had_key = keys.remove(&provider).is_some();
if had_key {
let body = serde_json::to_string_pretty(&keys)?;
std::fs::write(keystore::keys_path(base), body)?;
}
let had_custom = harness::custom_providers::remove(base, &provider).unwrap_or(false);
if had_key || had_custom {
println!(" removed {provider}");
} else {
println!(" no saved key for {provider}");
}
}
KeyCmd::Detect { provider, base_url, name, probe_all } => {
let key = read_key_from_stdin()?;
let o = run_detect(&key, &provider, &base_url, &name, probe_all).await;
println!("{}", serde_json::to_string(&o)?);
}
}
Ok(())
}