mirror of
https://github.com/CyberSecurityUP/NeuroSploit.git
synced 2026-12-06 02:53:57 +01:00
feat(pivot): health-aware route selection + auto-reroute
- select_route: longest-prefix subnet match, alive-only, SOCKS preferred at equal prefix - find_pivot_for picks the most specific pivot subnet (/24 over /16) - ensure_tunnel reuses the best alive route (port-proxy requires an exact forward) - health_check_all probes each tunnel's local SOCKS/forward port and marks dead tunnels so the next chain round rebuilds instead of failing through a stale proxy - route_for(target_ip, port) returns the per-host proxy/env; pipeline sweeps tunnel health at the start of each chain round
This commit is contained in:
1 parent
3a1612effd
commit
bb9fcbbb14
2 files changed
+187
-21
No files matched your search
@@ -3349,6 +3349,15 @@ async fn attack_chain(pool: &ModelPool, cfg: &RunConfig, recon: &str,
|
||||
// --- Pivot: for each seed, check if its target subnet needs a tunnel ---
|
||||
let mut pivot_ctx = String::new();
|
||||
if pivot_enabled {
|
||||
// Health-sweep existing tunnels up-front so a dead proxy is skipped
|
||||
// (and re-routed) instead of silently failing every tool through it.
|
||||
let health = pivot_mgr.health_check_all().await;
|
||||
let dead = health.iter().filter(|h| !h.alive).count();
|
||||
if dead > 0 {
|
||||
let _ = tx
|
||||
.send(format!("🔀 pivot: {dead} tunnel(s) unhealthy — re-routing"))
|
||||
.await;
|
||||
}
|
||||
let mut target_ips: Vec<String> = Vec::new();
|
||||
for (seed, _) in &seeds {
|
||||
for ip in extract_ips(&seed.endpoint) {
|
||||
|
||||
@@ -144,6 +144,50 @@ impl ActiveTunnel {
|
||||
}
|
||||
}
|
||||
|
||||
/// Health snapshot for one tunnel.
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct TunnelHealth {
|
||||
pub id: String,
|
||||
pub local_port: u16,
|
||||
pub proxy: Option<String>,
|
||||
pub alive: bool,
|
||||
}
|
||||
|
||||
fn subnet_prefix_len(subnet: &str) -> u32 {
|
||||
if let Some((_, bits)) = subnet.split_once('/') {
|
||||
return bits.parse::<u32>().ok().filter(|&b| b <= 32).unwrap_or(0);
|
||||
}
|
||||
match subnet.matches('.').count() {
|
||||
2 => 24,
|
||||
1 => 16,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pick the best route for `target_ip`: alive tunnels only, longest-prefix
|
||||
/// subnet match wins (a /24 beats a /16), SOCKS preferred over port-proxy at
|
||||
/// equal prefix. Pure so it is unit-tested; [`PivotManager::route_for`] applies
|
||||
/// it to the live tunnel set.
|
||||
pub fn select_route<'a>(tunnels: &'a [ActiveTunnel], target_ip: &str) -> Option<&'a ActiveTunnel> {
|
||||
tunnels
|
||||
.iter()
|
||||
.filter(|t| t.alive)
|
||||
.filter_map(|t| {
|
||||
let mut score = t
|
||||
.target_subnets
|
||||
.iter()
|
||||
.filter(|s| ip_in_subnet(target_ip, s))
|
||||
.map(|s| subnet_prefix_len(s))
|
||||
.max();
|
||||
if t.port_forwards.iter().any(|(h, _, _)| h == target_ip) {
|
||||
score = Some(score.unwrap_or(0).max(32));
|
||||
}
|
||||
score.map(|s| (s, t))
|
||||
})
|
||||
.max_by_key(|(s, t)| (*s, u32::from(t.local_port > 0)))
|
||||
.map(|(_, t)| t)
|
||||
}
|
||||
|
||||
/// Manages pivot tunnels for a multi-hop engagement.
|
||||
#[derive(Clone)]
|
||||
pub struct PivotManager {
|
||||
@@ -207,17 +251,22 @@ impl PivotManager {
|
||||
true
|
||||
}
|
||||
|
||||
/// Find the best pivot host that can reach the target subnet.
|
||||
/// Find the best pivot host that can reach the target subnet (longest
|
||||
/// prefix match, so a /24 host is preferred over a broader /16 one).
|
||||
pub async fn find_pivot_for(&self, target_ip: &str) -> Option<PivotHost> {
|
||||
let state = self.inner.read().await;
|
||||
let mut best: Option<(u32, &PivotHost)> = None;
|
||||
for pivot in &state.pivots {
|
||||
for subnet in &pivot.reachable_subnets {
|
||||
if ip_in_subnet(target_ip, subnet) {
|
||||
return Some(pivot.clone());
|
||||
let len = subnet_prefix_len(subnet);
|
||||
if best.as_ref().map(|(b, _)| len > *b).unwrap_or(true) {
|
||||
best = Some((len, pivot));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
best.map(|(_, p)| p.clone())
|
||||
}
|
||||
|
||||
/// Get or create a tunnel to reach the target IP. Returns the tunnel and
|
||||
@@ -228,26 +277,27 @@ impl PivotManager {
|
||||
target_port: u16,
|
||||
tx: &tokio::sync::mpsc::Sender<String>,
|
||||
) -> Result<(ActiveTunnel, Vec<(String, String)>), String> {
|
||||
// Check if we already have a tunnel covering this target.
|
||||
// Reuse the best alive tunnel that actually carries this target
|
||||
// (longest-prefix subnet match; a port-proxy needs an exact forward).
|
||||
{
|
||||
let state = self.inner.read().await;
|
||||
for tunnel in state.tunnels.values() {
|
||||
if tunnel.alive {
|
||||
for subnet in &tunnel.target_subnets {
|
||||
if ip_in_subnet(target_ip, subnet) {
|
||||
return Ok((tunnel.clone(), tunnel.env_vars()));
|
||||
}
|
||||
}
|
||||
for (host, port, local) in &tunnel.port_forwards {
|
||||
if host == target_ip && *port == target_port {
|
||||
let env = vec![
|
||||
("PIVOT_HOST".into(), format!("127.0.0.1")),
|
||||
("PIVOT_PORT".into(), local.to_string()),
|
||||
("PIVOT_ORIGINAL".into(), format!("{}:{}", target_ip, target_port)),
|
||||
];
|
||||
return Ok((tunnel.clone(), env));
|
||||
}
|
||||
}
|
||||
let tunnels: Vec<ActiveTunnel> =
|
||||
state.tunnels.values().filter(|t| t.alive).cloned().collect();
|
||||
if let Some(t) = select_route(&tunnels, target_ip) {
|
||||
if t.local_port > 0 {
|
||||
return Ok((t.clone(), t.env_vars()));
|
||||
}
|
||||
if let Some((_, _, local)) = t
|
||||
.port_forwards
|
||||
.iter()
|
||||
.find(|(h, p, _)| h == target_ip && *p == target_port)
|
||||
{
|
||||
let env = vec![
|
||||
("PIVOT_HOST".into(), "127.0.0.1".to_string()),
|
||||
("PIVOT_PORT".into(), local.to_string()),
|
||||
("PIVOT_ORIGINAL".into(), format!("{target_ip}:{target_port}")),
|
||||
];
|
||||
return Ok((t.clone(), env));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -681,6 +731,77 @@ impl PivotManager {
|
||||
})
|
||||
}
|
||||
|
||||
/// Probe every tunnel's local endpoint and update `alive`. Dead tunnels are
|
||||
/// then skipped by [`select_route`] / [`ensure_tunnel`], which rebuilds a
|
||||
/// fresh tunnel on the next request — auto-route without a stale proxy.
|
||||
pub async fn health_check_all(&self) -> Vec<TunnelHealth> {
|
||||
let snapshot: Vec<(String, u16, Option<String>, Vec<u16>)> = {
|
||||
let st = self.inner.read().await;
|
||||
st.tunnels
|
||||
.values()
|
||||
.map(|t| {
|
||||
(
|
||||
t.id.clone(),
|
||||
t.local_port,
|
||||
t.proxy_url(),
|
||||
t.port_forwards.iter().map(|(_, _, l)| *l).collect(),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let mut results = Vec::new();
|
||||
for (id, local_port, proxy, fwds) in snapshot {
|
||||
let port = if local_port > 0 { Some(local_port) } else { fwds.first().copied() };
|
||||
let alive = match port {
|
||||
Some(p) => tcp_reachable("127.0.0.1", p, 1500).await,
|
||||
None => true,
|
||||
};
|
||||
results.push(TunnelHealth {
|
||||
id: id.clone(),
|
||||
local_port,
|
||||
proxy,
|
||||
alive,
|
||||
});
|
||||
}
|
||||
{
|
||||
let mut st = self.inner.write().await;
|
||||
for r in &results {
|
||||
if let Some(t) = st.tunnels.get_mut(&r.id) {
|
||||
t.alive = r.alive;
|
||||
}
|
||||
}
|
||||
}
|
||||
results
|
||||
}
|
||||
|
||||
/// The proxy/env a tool must use to reach `target_ip:target_port`, using the
|
||||
/// best alive route (longest-prefix, health-aware). This is the per-host
|
||||
/// routing primitive.
|
||||
pub async fn route_for(
|
||||
&self,
|
||||
target_ip: &str,
|
||||
target_port: u16,
|
||||
) -> Option<(ActiveTunnel, Vec<(String, String)>)> {
|
||||
let tunnels: Vec<ActiveTunnel> = {
|
||||
let st = self.inner.read().await;
|
||||
st.tunnels.values().cloned().collect()
|
||||
};
|
||||
let t = select_route(&tunnels, target_ip)?.clone();
|
||||
if t.local_port > 0 {
|
||||
return Some((t.clone(), t.env_vars()));
|
||||
}
|
||||
let (_, _, local) = t
|
||||
.port_forwards
|
||||
.iter()
|
||||
.find(|(h, p, _)| h == target_ip && *p == target_port)?;
|
||||
let env = vec![
|
||||
("PIVOT_HOST".into(), "127.0.0.1".to_string()),
|
||||
("PIVOT_PORT".into(), local.to_string()),
|
||||
("PIVOT_ORIGINAL".into(), format!("{target_ip}:{target_port}")),
|
||||
];
|
||||
Some((t.clone(), env))
|
||||
}
|
||||
|
||||
/// Tear down all active tunnels.
|
||||
pub async fn disconnect_all(&self) {
|
||||
let mut state = self.inner.write().await;
|
||||
@@ -1175,4 +1296,40 @@ mod tests {
|
||||
assert!(is_private_ip("192.168.1.1"));
|
||||
assert!(!is_private_ip("8.8.8.8"));
|
||||
}
|
||||
|
||||
fn tunnel(id: &str, port: u16, subnets: &[&str], alive: bool) -> ActiveTunnel {
|
||||
ActiveTunnel {
|
||||
id: id.into(),
|
||||
pivot_host: "10.0.0.9".into(),
|
||||
method: TunnelMethod::Chisel,
|
||||
local_port: port,
|
||||
target_subnets: subnets.iter().map(|s| s.to_string()).collect(),
|
||||
port_forwards: vec![],
|
||||
local_pid: None,
|
||||
alive,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subnet_prefix_length() {
|
||||
assert_eq!(subnet_prefix_len("10.0.1.0/24"), 24);
|
||||
assert_eq!(subnet_prefix_len("10.0.0.0/16"), 16);
|
||||
assert_eq!(subnet_prefix_len("10.0.1"), 24);
|
||||
assert_eq!(subnet_prefix_len("10.0"), 16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn route_selection_prefers_longest_prefix_then_health() {
|
||||
let t16 = tunnel("t16", 10801, &["10.0.0.0/16"], true);
|
||||
let t24 = tunnel("t24", 10802, &["10.0.1.0/24"], true);
|
||||
let all = vec![t16.clone(), t24.clone()];
|
||||
// A /24 route beats a /16 route for an address inside both.
|
||||
assert_eq!(select_route(&all, "10.0.1.5").unwrap().id, "t24");
|
||||
// Out of every subnet → no route.
|
||||
assert!(select_route(&all, "10.9.9.9").is_none());
|
||||
// Dead tunnel is skipped, falling back to the broader healthy route.
|
||||
let dead24 = ActiveTunnel { alive: false, ..t24 };
|
||||
let all2 = vec![t16, dead24];
|
||||
assert_eq!(select_route(&all2, "10.0.1.5").unwrap().id, "t16");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user