use std::net::{IpAddr, SocketAddr};
use std::time::Instant;
use crate::detect::exchange::{self, ExchangeError};
use crate::fingerprint::Tunnel;
use crate::model::port::Protocol;
use super::budget::Budget;
use super::capability::{CapError, Capabilities, ScanInstant};
pub struct LiveCapabilities {
addr: SocketAddr,
protocol: Protocol,
tunnel: Option<Tunnel>,
bytes_left: u64,
deadline: Instant,
connections_left: u32,
clock: Instant,
}
impl LiveCapabilities {
pub fn new(
addr: SocketAddr,
protocol: Protocol,
tunnel: Option<Tunnel>,
budget: &Budget,
) -> Self {
Self {
addr,
protocol,
tunnel,
bytes_left: budget.max_bytes,
deadline: Instant::now() + budget.deadline,
connections_left: budget.max_connections,
clock: Instant::now(),
}
}
}
impl Capabilities for LiveCapabilities {
fn speak(&mut self, bytes: &[u8]) -> Result<Vec<u8>, CapError> {
if self.connections_left == 0 {
return Err(CapError::ConnectionBudgetExhausted);
}
if exchange::remaining(self.deadline).is_none() {
return Err(CapError::TimedOut);
}
let sent = bytes.len() as u64;
if sent > self.bytes_left {
return Err(CapError::ByteBudgetExhausted);
}
self.bytes_left -= sent;
self.connections_left -= 1;
let reply = match self.protocol {
Protocol::Tcp => exchange::tcp(
self.addr,
self.tunnel,
bytes,
self.deadline,
self.bytes_left,
)
.map_err(CapError::from),
Protocol::Udp => exchange::udp(self.addr, bytes, self.deadline, self.bytes_left)
.map_err(CapError::from),
Protocol::Sctp => Err(CapError::Denied(
"a detection cannot speak to an SCTP port: the engine scans SCTP without a client \
stack to hold an association open"
.to_string(),
)),
}?
.bytes;
self.bytes_left -= reply.len() as u64;
Ok(reply)
}
fn resolve(&mut self, _name: &str) -> Result<Vec<IpAddr>, CapError> {
Err(CapError::Denied(
"name resolution is not served to a socket-scoped detection".to_string(),
))
}
fn now(&mut self) -> ScanInstant {
ScanInstant::from_millis(
u64::try_from(self.clock.elapsed().as_millis()).unwrap_or(u64::MAX),
)
}
}
impl From<ExchangeError> for CapError {
fn from(error: ExchangeError) -> Self {
match error {
ExchangeError::TimedOut => CapError::TimedOut,
ExchangeError::ConnectionRefused => CapError::ConnectionRefused,
ExchangeError::Reset => CapError::Reset,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::detect::compute::{Budget, ComputeRuntime, Grant, ModuleBody, RhaiRuntime};
use crate::fingerprint::PortContext;
use crate::model::finding::{DetectionClass, DetectionId, Severity, Version};
use std::io::{Read, Write};
use std::net::TcpListener;
use std::thread;
use std::time::Duration;
fn budget() -> Budget {
Budget {
fuel: 1_000_000,
deadline: Duration::from_secs(2),
max_memory: 65_536,
max_bytes: 8_192,
max_connections: 4,
}
}
#[test]
fn a_module_speaks_to_a_live_socket_through_the_seam() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
thread::spawn(move || {
if let Ok((mut sock, _)) = listener.accept() {
let mut probe = [0u8; 64];
let _ = sock.read(&mut probe);
let _ = sock.write_all(b"# Server\r\nredis_version:7.2.4\r\n");
}
});
let source = r#"
fn analyze(ctx, responses) {
let reply = speak(blob(6, 0x41));
if reply.len() > 0 {
[ #{ severity: "high", summary: "the live port answered" } ]
} else {
[]
}
}
"#;
let runtime = RhaiRuntime::new();
let module = runtime
.load(&ModuleBody::Rhai(source.to_string()))
.expect("the module compiles");
let grant = Grant {
detection: DetectionId::new("live-test", Version::new(1, 0, 0), "hash").unwrap(),
class: DetectionClass::ActiveBenign,
budget: budget(),
speak: true,
resolve: false,
};
let mut instance = runtime.instantiate(&module, &grant).expect("instantiates");
let mut caps = LiveCapabilities::new(addr, Protocol::Tcp, None, &budget());
let ctx = PortContext {
port: addr.port(),
protocol: Protocol::Tcp,
addr: Some(addr),
tunnel: None,
speaks_http: false,
detection: crate::config::ServiceDetection::default(),
};
let findings = runtime
.run(&mut instance, &ctx, &[], &mut caps)
.expect("a clean run against the live port");
assert_eq!(findings.len(), 1, "the module read the live reply");
assert_eq!(findings[0].severity(), Severity::High);
}
#[test]
fn the_byte_budget_caps_a_reply_from_the_live_socket() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
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 caps = LiveCapabilities::new(
addr,
Protocol::Tcp,
None,
&Budget {
max_bytes: 20,
..budget()
},
);
let reply = caps.speak(b"ABCDEF").expect("a reply within budget");
assert!(
reply.len() <= 14,
"the reply was not capped: {}",
reply.len()
);
}
#[test]
fn an_exhausted_connection_budget_refuses_before_dialing() {
let addr: SocketAddr = "192.0.2.1:9".parse().unwrap();
let mut caps = LiveCapabilities::new(
addr,
Protocol::Tcp,
None,
&Budget {
max_connections: 1,
deadline: Duration::from_millis(50),
..budget()
},
);
let _ = caps.speak(b"x");
assert_eq!(
caps.speak(b"y"),
Err(CapError::ConnectionBudgetExhausted),
"a second connection was allowed past the budget"
);
}
}