use std::net::IpAddr;
use std::num::NonZeroU32;
use std::time::Duration;
use crate::evasion::SegmentShaping;
use crate::logging::error;
use crate::model::technique::TcpScanTechnique;
use crate::protocols as protocol;
use crate::scanner::pacing::deadline::AdaptiveDeadlineConfig;
use crate::scanner::pacing::retry::{RetryPolicy, SilentHostPolicy};
use crate::scanner::pacing::timer::ScanBudget;
use crate::scanner::payload;
use crate::transport::probe::{Emission, ProbeSender, SendError};
use crate::{info, success};
pub(super) const DEADLINE_CONFIG: AdaptiveDeadlineConfig = AdaptiveDeadlineConfig::new(
ScanBudget::new(
Duration::from_millis(2_000),
Duration::from_millis(1),
Duration::from_secs(60),
),
ScanBudget::new(
Duration::from_millis(300),
Duration::from_micros(500),
Duration::from_secs(10),
),
Duration::from_millis(400),
Duration::from_secs(3),
4.0,
20,
);
pub(super) const RETRY_POLICY: RetryPolicy = RetryPolicy::new(
3,
Duration::from_millis(200),
Duration::from_millis(25),
Duration::from_secs(2),
2.0,
0.2,
Some(SilentHostPolicy::new(32, 2)),
);
pub(super) const MIN_SEND_TICK: Duration = Duration::from_millis(1);
pub(super) fn rate_within(
ceiling: Option<NonZeroU32>,
floor: Option<NonZeroU32>,
default: NonZeroU32,
) -> NonZeroU32 {
let rate = ceiling.unwrap_or(default);
let lifted = match floor {
Some(floor) => rate.max(floor),
None => rate,
};
match ceiling {
Some(ceiling) => lifted.min(ceiling),
None => lifted,
}
}
pub(super) fn pacing_for(rate_per_sec: NonZeroU32) -> (Duration, usize) {
let rate = f64::from(rate_per_sec.get());
let batch = (rate * MIN_SEND_TICK.as_secs_f64()).round().max(1.0);
(Duration::from_secs_f64(batch / rate), batch as usize)
}
pub(super) type SeqNum = u32;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SynToken {
pub seq: SeqNum,
pub src_port: u16,
}
#[derive(Debug, Clone, Copy)]
pub(super) struct EvasionParts<'a> {
pub emission: Emission,
pub shaping: SegmentShaping,
pub decoys: &'a [IpAddr],
}
pub(super) fn emit_among_decoys(
sender: &dyn ProbeSender,
dst: IpAddr,
zone: Option<u32>,
emission: Emission,
real_src: IpAddr,
real_packet: &[u8],
decoy_packets: &[(IpAddr, Vec<u8>)],
) -> Result<(), SendError> {
if decoy_packets.is_empty() {
return sender.send(real_packet, real_src, dst, zone, emission);
}
use rand::seq::SliceRandom;
let mut probes: Vec<(IpAddr, &[u8], bool)> = Vec::with_capacity(1 + decoy_packets.len());
probes.push((real_src, real_packet, true));
for (src, packet) in decoy_packets {
probes.push((*src, packet.as_slice(), false));
}
probes.shuffle(&mut rand::rng());
let mut real_result = None;
for (src, packet, is_real) in &probes {
let result = sender.send(packet, *src, dst, zone, emission);
if *is_real {
real_result = Some(result);
}
}
real_result.expect("the real probe is always among those sent")
}
#[allow(clippy::too_many_arguments)]
pub(super) fn send_init(
sender: &dyn ProbeSender,
src_addr: IpAddr,
dst_addr: IpAddr,
dst_zone: Option<u32>,
dst_port: u16,
src_port: u16,
decoys: &[IpAddr],
emission: Emission,
faults: &mut SendFaults,
) -> Option<u32> {
let tag: u32 = rand::random_range(1..=u32::MAX);
let packet = protocol::sctp::build_init_probe(src_port, dst_port, tag);
let decoy_packets: Vec<(IpAddr, Vec<u8>)> = decoys
.iter()
.filter(|decoy| decoy.is_ipv4() == dst_addr.is_ipv4())
.map(|&decoy| {
let packet = protocol::sctp::build_init_probe(
rand::random_range(50_000..u16::MAX),
dst_port,
rand::random_range(1..=u32::MAX),
);
(decoy, packet)
})
.collect();
match emit_among_decoys(
sender,
dst_addr,
dst_zone,
emission,
src_addr,
&packet,
&decoy_packets,
) {
Ok(()) => {
success!(verbosity = 2, "sent SCTP init to {dst_addr}:{dst_port}");
Some(tag)
}
Err(e) => {
faults.record(dst_addr, &e);
None
}
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn send_syn(
sender: &dyn ProbeSender,
src_addr: IpAddr,
dst_addr: IpAddr,
dst_zone: Option<u32>,
dst_port: u16,
src_port_override: Option<u16>,
evasion: EvasionParts<'_>,
faults: &mut SendFaults,
) -> Option<SynToken> {
let EvasionParts {
emission,
shaping,
decoys,
} = evasion;
let src_port: u16 = src_port_override.unwrap_or_else(|| rand::random_range(50_000..u16::MAX));
let seq_num: u32 = rand::random_range(0..=u32::MAX);
let packet = match protocol::tcp::build_probe_shaped(
TcpScanTechnique::Syn,
src_addr,
dst_addr,
src_port,
dst_port,
seq_num,
shaping.padding,
shaping.bad_tcp_checksum,
) {
Ok(pkt) => pkt,
Err(e) => {
error!(
verbosity = 2,
"failed to create SYN packet for {dst_addr}:{dst_port}: {e}"
);
return None;
}
};
let decoy_packets: Vec<(IpAddr, Vec<u8>)> = decoys
.iter()
.filter(|decoy| decoy.is_ipv4() == dst_addr.is_ipv4())
.filter_map(|&decoy| {
protocol::tcp::build_probe_shaped(
TcpScanTechnique::Syn,
decoy,
dst_addr,
rand::random_range(50_000..u16::MAX),
dst_port,
rand::random_range(0..=u32::MAX),
shaping.padding,
shaping.bad_tcp_checksum,
)
.ok()
.map(|packet| (decoy, packet))
})
.collect();
match emit_among_decoys(
sender,
dst_addr,
dst_zone,
emission,
src_addr,
&packet,
&decoy_packets,
) {
Ok(_) => {
success!(verbosity = 2, "sent SYN probe to {dst_addr}:{dst_port}");
Some(SynToken {
seq: seq_num,
src_port,
})
}
Err(e) => {
if e.is_unroutable() {
if faults.unroutable.is_none() {
info!(verbosity = 1, "no route to {dst_addr}: {e:#}");
}
} else if faults.broken.is_none() {
error!(
verbosity = 2,
"failed to send SYN probe to {dst_addr}:{dst_port}: {e:#}"
);
}
faults.record(dst_addr, &e);
None
}
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn send_udp(
sender: &dyn ProbeSender,
src_port: u16,
src_addr: IpAddr,
dst_addr: IpAddr,
dst_zone: Option<u32>,
dst_port: u16,
evasion: EvasionParts<'_>,
reason: &mut Option<String>,
) -> Option<()> {
let EvasionParts {
emission,
shaping,
decoys,
} = evasion;
let payload = payload::for_port(dst_port).to_vec();
let packet = match crate::protocols::udp::build_packet_shaped(
src_addr,
dst_addr,
src_port,
dst_port,
payload,
shaping.padding,
) {
Ok(pkt) => pkt,
Err(e) => {
error!(
verbosity = 2,
"failed to create UDP packet for {dst_addr}:{dst_port}: {e}"
);
return None;
}
};
let decoy_packets: Vec<(IpAddr, Vec<u8>)> = decoys
.iter()
.filter(|decoy| decoy.is_ipv4() == dst_addr.is_ipv4())
.filter_map(|&decoy| {
crate::protocols::udp::build_packet_shaped(
decoy,
dst_addr,
rand::random_range(50_000..u16::MAX),
dst_port,
payload::for_port(dst_port).to_vec(),
shaping.padding,
)
.ok()
.map(|packet| (decoy, packet))
})
.collect();
match emit_among_decoys(
sender,
dst_addr,
dst_zone,
emission,
src_addr,
&packet,
&decoy_packets,
) {
Ok(_) => {
success!(verbosity = 2, "sent UDP probe to {dst_addr}:{dst_port}");
Some(())
}
Err(e) => {
if reason.is_none() {
error!(
verbosity = 2,
"failed to send UDP probe to {dst_addr}:{dst_port}: {e:#}"
);
*reason = Some(format!("{e:#}"));
}
None
}
}
}
#[derive(Debug, Default)]
pub(super) struct SendFaults {
pub(super) broken: Option<String>,
pub(super) unroutable: Option<(IpAddr, String)>,
pub(super) unroutable_count: u64,
pub(super) addresses: std::collections::BTreeSet<IpAddr>,
}
impl SendFaults {
fn record(&mut self, target: IpAddr, error: &SendError) {
if error.is_unroutable() {
self.unroutable_count += 1;
self.addresses.insert(target);
self.unroutable
.get_or_insert_with(|| (target, error.to_string()));
} else {
self.broken.get_or_insert_with(|| error.to_string());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::scanner::strategy::routed::PROBE_RATE_PER_SEC;
use std::net::Ipv4Addr;
struct RefusesOneSource(IpAddr);
impl ProbeSender for RefusesOneSource {
fn send(
&self,
_segment: &[u8],
src: IpAddr,
_dst: IpAddr,
_zone: Option<u32>,
_emission: Emission,
) -> Result<(), SendError> {
if src == self.0 {
Err(SendError::Unsupported("refused for the test"))
} else {
Ok(())
}
}
}
#[test]
fn emit_among_decoys_sends_every_probe_and_reports_the_real_ones_outcome() {
use crate::transport::probe::MockSender;
let real = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));
let dst = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 9));
let real_packet = vec![0xAAu8, 0xBB];
let decoys = vec![
(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2)), vec![1u8, 1]),
(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 3)), vec![2u8, 2]),
];
let mock = MockSender::default();
assert!(
emit_among_decoys(
&mock,
dst,
None,
Emission::routed(),
real,
&real_packet,
&decoys
)
.is_ok()
);
let sent = mock.sent.lock().unwrap();
assert_eq!(sent.len(), 3, "the real probe and both decoys are all sent");
assert_eq!(sent.iter().filter(|(_, src, _)| *src == real).count(), 1);
drop(sent);
let mock = MockSender::default();
emit_among_decoys(
&mock,
dst,
None,
Emission::routed(),
real,
&real_packet,
&[],
)
.unwrap();
assert_eq!(mock.sent.lock().unwrap().len(), 1);
let refusing_the_real = RefusesOneSource(real);
assert!(
emit_among_decoys(
&refusing_the_real,
dst,
None,
Emission::routed(),
real,
&real_packet,
&decoys
)
.is_err()
);
let refusing_a_decoy = RefusesOneSource(decoys[0].0);
assert!(
emit_among_decoys(
&refusing_a_decoy,
dst,
None,
Emission::routed(),
real,
&real_packet,
&decoys
)
.is_ok()
);
}
#[test]
fn a_missing_route_is_counted_apart_from_a_broken_send_path() {
let unreachable = |address: &str| {
SendError::from_io(std::io::Error::new(
std::io::ErrorKind::HostUnreachable,
format!("failed to send to {address}: No route to host"),
))
};
let mut faults = SendFaults::default();
let first: IpAddr = "2001:db8::1".parse().expect("literal");
let second: IpAddr = "2001:db8::2".parse().expect("literal");
faults.record(first, &unreachable("2001:db8::1"));
faults.record(second, &unreachable("2001:db8::2"));
assert_eq!(faults.unroutable_count, 2);
assert_eq!(
faults.unroutable.as_ref().map(|(address, _)| *address),
Some(first),
"the first address is kept, not the last"
);
assert!(
faults.broken.is_none(),
"no route to somewhere is not a scan that could not run"
);
faults.record(
first,
&SendError::from_io(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"Operation not permitted",
)),
);
assert!(faults.broken.is_some(), "and this one is");
assert_eq!(faults.unroutable_count, 2, "which is a separate tally");
}
fn effective_rate(rate_per_sec: u32) -> f64 {
let (tick, batch) = pacing_for(NonZeroU32::new(rate_per_sec).expect("a non-zero rate"));
batch as f64 / tick.as_secs_f64()
}
#[test]
fn a_fast_rate_is_expressed_as_a_batch_on_the_shortest_tick() {
assert_eq!(
pacing_for(NonZeroU32::new(2_000).unwrap()),
(MIN_SEND_TICK, 2)
);
assert_eq!(
pacing_for(NonZeroU32::new(100_000).unwrap()),
(MIN_SEND_TICK, 100)
);
}
#[test]
fn a_slow_rate_lengthens_the_tick_rather_than_doubling_the_rate() {
assert_eq!(
pacing_for(NonZeroU32::new(500).unwrap()),
(Duration::from_millis(2), 1)
);
assert_eq!(
pacing_for(NonZeroU32::new(100).unwrap()),
(Duration::from_millis(10), 1)
);
}
#[test]
fn every_rate_is_paced_at_the_rate_it_asked_for() {
for rate in [1, 100, 500, 999, 1_000, 1_500, 2_000, 4_000, 16_000] {
let effective = effective_rate(rate);
let error = (effective - f64::from(rate)).abs() / f64::from(rate);
assert!(
error < 0.01,
"{rate}/s is paced at {effective}/s, off by {:.0}%",
error * 100.0
);
}
}
#[test]
fn an_unset_rate_falls_back_to_the_default_and_a_set_one_is_obeyed() {
assert_eq!(
rate_within(None, None, PROBE_RATE_PER_SEC),
PROBE_RATE_PER_SEC
);
assert_eq!(
rate_within(NonZeroU32::new(500), None, PROBE_RATE_PER_SEC).get(),
500,
"a rate the caller meant is the rate they get"
);
}
#[test]
fn a_floor_raises_the_default_but_never_a_ceiling() {
let default = PROBE_RATE_PER_SEC;
assert_eq!(
rate_within(None, NonZeroU32::new(default.get() * 2), default).get(),
default.get() * 2,
"with no ceiling set, a floor above the engine's own rate is the rate"
);
assert_eq!(
rate_within(None, NonZeroU32::new(1), default),
default,
"a floor below the engine's own rate changes nothing"
);
assert_eq!(
rate_within(NonZeroU32::new(50), NonZeroU32::new(5_000), default).get(),
50,
"the ceiling wins: a safety limit is not traded away for a throughput wish"
);
assert_eq!(
rate_within(NonZeroU32::new(5_000), NonZeroU32::new(50), default).get(),
5_000,
"a ceiling already above the floor is left where it is"
);
}
}