use std::net::SocketAddr;
use std::time::{Duration, Instant};
use crate::detect::compute::Budget;
use crate::detect::exchange;
use crate::fingerprint::Tunnel;
use crate::model::port::Protocol;
use crate::transport::dial::Egress;
use super::{Probe, ProbeRefusal};
pub struct SocketProbe {
addr: SocketAddr,
protocol: Protocol,
tunnel: Option<Tunnel>,
egress: Egress,
bytes_left: u64,
deadline: Instant,
connections_left: u32,
last_refusal: Option<ProbeRefusal>,
last_complete: bool,
exchanges_left: Option<u32>,
}
const DATAGRAM_WAIT_FLOOR: Duration = Duration::from_millis(500);
impl SocketProbe {
pub fn new(
addr: SocketAddr,
protocol: Protocol,
tunnel: Option<Tunnel>,
budget: &Budget,
) -> Self {
Self {
addr,
protocol,
tunnel,
egress: Egress::KERNEL,
bytes_left: budget.max_bytes,
deadline: Instant::now() + budget.deadline,
connections_left: budget.max_connections,
last_refusal: None,
last_complete: false,
exchanges_left: None,
}
}
pub(crate) fn via(mut self, egress: Egress) -> Self {
self.egress = egress;
self
}
fn datagram_wait(&self, left: Duration) -> DatagramWait {
let Some(planned) = self.exchanges_left else {
return DatagramWait {
until: self.deadline,
full_share: false,
};
};
let share = (left / planned.max(1)).max(DATAGRAM_WAIT_FLOOR);
DatagramWait {
until: (Instant::now() + share).min(self.deadline),
full_share: share <= left,
}
}
}
struct DatagramWait {
until: Instant,
full_share: bool,
}
impl Probe for SocketProbe {
fn speak(&mut self, bytes: &[u8]) -> Option<Vec<u8>> {
self.last_refusal = None;
self.last_complete = false;
if self.connections_left == 0 {
self.last_refusal = Some(ProbeRefusal::Connections);
return None;
}
let Some(left) = exchange::remaining(self.deadline) else {
self.last_refusal = Some(ProbeRefusal::Deadline);
return None;
};
let sent = bytes.len() as u64;
if sent > self.bytes_left {
self.last_refusal = Some(ProbeRefusal::Bytes);
return None;
}
self.bytes_left -= sent;
self.connections_left -= 1;
let datagram = self.datagram_wait(left);
self.exchanges_left = self.exchanges_left.map(|planned| planned.saturating_sub(1));
let reply = match self.protocol {
Protocol::Tcp => exchange::tcp(
self.addr,
self.egress,
self.tunnel,
bytes,
self.deadline,
self.bytes_left,
),
Protocol::Udp => exchange::udp(
self.addr,
self.egress,
bytes,
datagram.until,
self.bytes_left,
),
Protocol::Sctp => return None,
};
if matches!(reply, Err(exchange::ExchangeError::Starved)) {
self.last_refusal = Some(ProbeRefusal::Descriptors);
return None;
}
let reply = reply.ok().filter(|reply| !reply.bytes.is_empty());
let Some(reply) = reply else {
let heard_out = self.protocol == Protocol::Udp && datagram.full_share;
if exchange::remaining(self.deadline).is_none() && !heard_out {
self.last_refusal = Some(ProbeRefusal::Deadline);
}
return None;
};
self.bytes_left -= reply.bytes.len() as u64;
self.last_complete = reply.complete;
Some(reply.bytes)
}
fn last_refusal(&self) -> Option<ProbeRefusal> {
self.last_refusal
}
fn reply_complete(&self) -> bool {
self.last_complete
}
fn plan(&mut self, exchanges: u32) {
self.exchanges_left = Some(exchanges);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
fn budget(max_bytes: u64, millis: u64, max_connections: u32) -> Budget {
Budget::new(0, Duration::from_millis(millis))
.with_max_bytes(max_bytes)
.with_max_connections(max_connections)
}
#[cfg(unix)]
#[test]
fn an_exchange_with_no_socket_to_give_is_refused_rather_than_read_as_silence() {
use crate::system::descriptors::testing::{exhaust, in_a_process_of_its_own};
if !in_a_process_of_its_own(
module_path!(),
"an_exchange_with_no_socket_to_give_is_refused_rather_than_read_as_silence",
) {
return;
}
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("a loopback listener");
let addr = listener.local_addr().expect("its address");
let held = exhaust(64);
let mut probe = SocketProbe::new(addr, Protocol::Tcp, None, &budget(4_096, 300, 8));
let reply = probe.speak(b"GET / HTTP/1.1\r\n\r\n");
drop(held);
assert_eq!(reply, None, "a reply with no socket to carry it");
assert_eq!(
probe.last_refusal(),
Some(ProbeRefusal::Descriptors),
"the process's shortfall was not told apart from the port's silence"
);
}
#[test]
fn a_reply_is_capped_at_the_flows_byte_budget() {
use std::io::{Read as _, Write as _};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
std::thread::spawn(move || {
if let Ok((mut sock, _)) = listener.accept() {
let _ = sock.read(&mut [0u8; 64]);
let _ = sock.write_all(&vec![b'A'; 4096]);
}
});
let mut probe = SocketProbe::new(addr, Protocol::Tcp, None, &budget(20, 5_000, 8));
let reply = probe.speak(b"x").expect("a reply within budget");
assert!(
reply.len() <= 19,
"reply was not capped, got {}",
reply.len()
);
}
#[test]
fn a_flow_cannot_open_more_connections_than_its_budget() {
use std::io::Write as _;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
std::thread::spawn(move || {
if let Ok((mut sock, _)) = listener.accept() {
let _ = sock.write_all(b"ok");
}
});
let mut probe = SocketProbe::new(addr, Protocol::Tcp, None, &budget(4096, 5_000, 1));
assert!(
probe.speak(b"a").is_some(),
"the one permitted exchange failed"
);
assert!(
probe.speak(b"b").is_none(),
"a second connection was opened past the budget"
);
assert_eq!(probe.last_refusal(), Some(ProbeRefusal::Connections));
}
#[test]
fn an_expired_time_budget_refuses_the_exchange() {
let addr: SocketAddr = "192.0.2.1:9".parse().unwrap();
let mut probe = SocketProbe::new(addr, Protocol::Tcp, None, &budget(4096, 0, 8));
assert!(probe.speak(b"anything").is_none());
assert_eq!(probe.last_refusal(), Some(ProbeRefusal::Deadline));
}
#[test]
fn a_send_past_the_byte_budget_is_refused_and_names_the_budget() {
let addr: SocketAddr = "192.0.2.1:9".parse().unwrap();
let mut probe = SocketProbe::new(addr, Protocol::Tcp, None, &budget(4, 5_000, 8));
assert!(probe.speak(b"far too long").is_none());
assert_eq!(probe.last_refusal(), Some(ProbeRefusal::Bytes));
}
#[test]
fn a_reply_that_says_how_long_it_is_ends_there_rather_than_when_the_server_hangs_up() {
use std::io::{Read as _, Write as _};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
std::thread::spawn(move || {
for sock in listener.incoming().take(3) {
let Ok(mut sock) = sock else { return };
std::thread::spawn(move || {
let _ = sock.read(&mut [0u8; 512]);
let _ = sock
.write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 9\r\n\r\nnot found");
let _ = sock.read(&mut [0u8; 1]);
});
}
});
let budget_ms = 1_500;
let mut probe = SocketProbe::new(addr, Protocol::Tcp, None, &budget(4096, budget_ms, 3));
let started = Instant::now();
for path in ["/a", "/b", "/c"] {
let request = format!("GET {path} HTTP/1.1\r\nConnection: close\r\n\r\n");
let reply = probe.speak(request.as_bytes());
assert!(
reply
.as_deref()
.is_some_and(|reply| reply.ends_with(b"not found")),
"{path} went unanswered: {reply:?}, refused on {:?}",
probe.last_refusal()
);
assert!(
probe.reply_complete(),
"{path}'s reply was whole but not taken as such"
);
}
assert!(
started.elapsed() < Duration::from_millis(budget_ms / 2),
"three exchanges with an idle server took {:?}",
started.elapsed()
);
}
#[test]
fn a_reply_the_service_holds_the_connection_open_after_ends_once_the_port_goes_quiet() {
use std::io::{Read as _, Write as _};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
std::thread::spawn(move || {
for sock in listener.incoming().take(2) {
let Ok(mut sock) = sock else { return };
std::thread::spawn(move || {
let _ = sock.read(&mut [0u8; 512]);
let _ = sock.write_all(b"+PONG\r\n");
let _ = sock.read(&mut [0u8; 1]);
});
}
});
let mut probe = SocketProbe::new(addr, Protocol::Tcp, None, &budget(4096, 3_000, 2));
for command in ["PING\r\n", "PING\r\n"] {
let reply = probe.speak(command.as_bytes());
assert_eq!(
reply.as_deref(),
Some(&b"+PONG\r\n"[..]),
"a question went unanswered, refused on {:?}",
probe.last_refusal()
);
}
assert!(
!probe.reply_complete(),
"a reply ended by the port going quiet was taken as whole"
);
}
#[test]
fn a_udp_flow_tries_every_guess_when_the_first_goes_unanswered() {
use crate::detect::flow::{FlowSeed, run, schema::FlowDetection};
let agent = std::net::UdpSocket::bind("127.0.0.1:0").unwrap();
let addr = agent.local_addr().unwrap();
std::thread::spawn(move || {
let mut buffer = [0u8; 512];
while let Ok((read, from)) = agent.recv_from(&mut buffer) {
if &buffer[..read] == b"second" {
let _ = agent.send_to(b"accepted", from);
}
}
});
let flow: FlowDetection = toml::from_str(
r#"
[detection]
id = "guesses"
version = "1.0.0"
title = "Guesses"
[detection.when]
protocol = "udp"
[detection.capabilities]
class = "active-benign"
max_millis = 1500
[[step]]
for_each = { var = "guess", in = ["first", "second", "third"] }
on_no_match = "continue"
send = "{guess}"
expect = "accepted"
[[step.finding]]
when = "matched"
severity = "high"
summary = "the agent accepted {guess}"
"#,
)
.expect("a valid flow");
let mut probe = SocketProbe::new(addr, Protocol::Udp, None, &budget(4096, 1_500, 8));
let findings = run(
&flow,
"0",
&FlowSeed::new("127.0.0.1", addr.port()),
&mut probe,
);
let summaries: Vec<&str> = findings.iter().map(|finding| finding.title()).collect();
assert_eq!(
summaries,
vec!["the agent accepted second"],
"the accepted guess was never tried; last refusal {:?}",
probe.last_refusal()
);
assert_eq!(probe.last_refusal(), None);
}
#[test]
fn an_exchange_that_drew_nothing_is_not_reported_whole() {
use std::io::{Read as _, Write as _};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
if let Ok((mut sock, _)) = listener.accept() {
let _ = sock.read(&mut [0u8; 16]);
let _ = sock.write_all(b"ok");
}
});
let mut probe = SocketProbe::new(addr, Protocol::Tcp, None, &budget(4096, 5_000, 8));
assert!(probe.speak(b"a").is_some());
assert!(
probe.reply_complete(),
"a reply read to the close was not whole"
);
server.join().unwrap();
assert!(probe.speak(b"b").is_none(), "a closed port answered");
assert!(
!probe.reply_complete(),
"the unanswered exchange was described by the one before it"
);
}
#[test]
fn an_exchange_its_time_budget_ran_out_on_is_refused_rather_than_unanswered() {
use std::io::Read as _;
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
std::thread::spawn(move || {
if let Ok((mut sock, _)) = listener.accept() {
let _ = sock.read(&mut [0u8; 512]);
let _ = sock.read(&mut [0u8; 1]);
}
});
let mut probe = SocketProbe::new(addr, Protocol::Tcp, None, &budget(4096, 300, 8));
assert!(probe.speak(b"GET / HTTP/1.1\r\n\r\n").is_none());
assert_eq!(probe.last_refusal(), Some(ProbeRefusal::Deadline));
}
#[test]
fn a_port_that_refuses_the_connection_is_unanswered_rather_than_refused() {
let addr = std::net::TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap();
let mut probe = SocketProbe::new(addr, Protocol::Tcp, None, &budget(4096, 5_000, 8));
assert!(probe.speak(b"anything").is_none());
assert_eq!(probe.last_refusal(), None);
}
#[test]
fn an_sctp_port_is_unanswered_rather_than_refused() {
let addr: SocketAddr = "192.0.2.1:9".parse().unwrap();
let mut probe = SocketProbe::new(addr, Protocol::Sctp, None, &budget(4096, 5_000, 8));
assert!(probe.speak(b"anything").is_none());
assert_eq!(probe.last_refusal(), None);
}
}