pub mod envelope;
pub mod limits;
pub use crate::config::envelope::DetectionEnvelope;
use std::collections::BTreeSet;
use std::fmt;
use std::net::IpAddr;
use std::num::{NonZeroU8, NonZeroU32};
use std::str::FromStr;
use std::time::Duration;
use crate::evasion::EvasionProfile;
use crate::model::exclusion::Exclusions;
use crate::model::technique::{SctpScanTechnique, TcpScanTechnique};
use crate::transport::probe::SendMode;
fn parse_level<T: Copy>(
written: &str,
all: &[T],
name: fn(T) -> &'static str,
from_level: fn(u8) -> Option<T>,
) -> Option<T> {
let written = written.trim();
if let Ok(level) = written.parse::<u8>() {
return from_level(level);
}
all.iter()
.copied()
.find(|level| name(*level).eq_ignore_ascii_case(written))
}
fn expected_levels<T: Copy>(
all: &[T],
name: fn(T) -> &'static str,
f: &mut fmt::Formatter<'_>,
) -> fmt::Result {
let names: Vec<&str> = all.iter().copied().map(name).collect();
let highest = all.len().saturating_sub(1);
write!(
f,
"expected one of: {} (or 0 to {highest})",
names.join(", ")
)
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ScanEffort {
Single,
Fast,
#[default]
Balanced,
Thorough,
}
impl ScanEffort {
pub const ALL: [ScanEffort; 4] = [
ScanEffort::Single,
ScanEffort::Fast,
ScanEffort::Balanced,
ScanEffort::Thorough,
];
pub const fn name(self) -> &'static str {
match self {
ScanEffort::Single => "single",
ScanEffort::Fast => "fast",
ScanEffort::Balanced => "balanced",
ScanEffort::Thorough => "thorough",
}
}
pub const fn level(self) -> u8 {
match self {
ScanEffort::Single => 0,
ScanEffort::Fast => 1,
ScanEffort::Balanced => 2,
ScanEffort::Thorough => 3,
}
}
pub const fn from_level(level: u8) -> Option<Self> {
match level {
0 => Some(ScanEffort::Single),
1 => Some(ScanEffort::Fast),
2 => Some(ScanEffort::Balanced),
3 => Some(ScanEffort::Thorough),
_ => None,
}
}
}
impl std::fmt::Display for ScanEffort {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownScanEffort {
pub input: String,
}
impl fmt::Display for UnknownScanEffort {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "unknown scan effort '{}', ", self.input)?;
expected_levels(&ScanEffort::ALL, ScanEffort::name, f)
}
}
impl std::error::Error for UnknownScanEffort {}
impl std::str::FromStr for ScanEffort {
type Err = UnknownScanEffort;
fn from_str(s: &str) -> Result<Self, Self::Err> {
parse_level(s, &Self::ALL, Self::name, Self::from_level).ok_or_else(|| UnknownScanEffort {
input: s.to_string(),
})
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum OsDetection {
Off,
#[default]
Passive,
Active,
Aggressive,
}
impl OsDetection {
pub const ALL: [OsDetection; 4] = [
OsDetection::Off,
OsDetection::Passive,
OsDetection::Active,
OsDetection::Aggressive,
];
pub const fn name(self) -> &'static str {
match self {
OsDetection::Off => "off",
OsDetection::Passive => "passive",
OsDetection::Active => "active",
OsDetection::Aggressive => "aggressive",
}
}
pub const fn level(self) -> u8 {
match self {
OsDetection::Off => 0,
OsDetection::Passive => 1,
OsDetection::Active => 2,
OsDetection::Aggressive => 3,
}
}
pub const fn from_level(level: u8) -> Option<Self> {
match level {
0 => Some(OsDetection::Off),
1 => Some(OsDetection::Passive),
2 => Some(OsDetection::Active),
3 => Some(OsDetection::Aggressive),
_ => None,
}
}
pub const fn is_enabled(self) -> bool {
!matches!(self, OsDetection::Off)
}
pub const fn is_active(self) -> bool {
matches!(self, OsDetection::Active | OsDetection::Aggressive)
}
}
impl fmt::Display for OsDetection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownOsDetection {
pub input: String,
}
impl fmt::Display for UnknownOsDetection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "unknown OS detection level '{}', ", self.input)?;
expected_levels(&OsDetection::ALL, OsDetection::name, f)
}
}
impl std::error::Error for UnknownOsDetection {}
impl FromStr for OsDetection {
type Err = UnknownOsDetection;
fn from_str(s: &str) -> Result<Self, Self::Err> {
parse_level(s, &Self::ALL, Self::name, Self::from_level).ok_or_else(|| UnknownOsDetection {
input: s.to_string(),
})
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ServiceDetection {
Off,
Banner,
#[default]
Probe,
Thorough,
}
impl ServiceDetection {
pub const ALL: [ServiceDetection; 4] = [
ServiceDetection::Off,
ServiceDetection::Banner,
ServiceDetection::Probe,
ServiceDetection::Thorough,
];
pub const fn name(self) -> &'static str {
match self {
ServiceDetection::Off => "off",
ServiceDetection::Banner => "banner",
ServiceDetection::Probe => "probe",
ServiceDetection::Thorough => "thorough",
}
}
pub const fn level(self) -> u8 {
match self {
ServiceDetection::Off => 0,
ServiceDetection::Banner => 1,
ServiceDetection::Probe => 2,
ServiceDetection::Thorough => 3,
}
}
pub const fn from_level(level: u8) -> Option<Self> {
match level {
0 => Some(ServiceDetection::Off),
1 => Some(ServiceDetection::Banner),
2 => Some(ServiceDetection::Probe),
3 => Some(ServiceDetection::Thorough),
_ => None,
}
}
pub const fn connects(self) -> bool {
!matches!(self, ServiceDetection::Off)
}
pub const fn sends(self) -> bool {
matches!(self, ServiceDetection::Probe | ServiceDetection::Thorough)
}
pub const fn probe_intensity(self) -> u8 {
match self {
ServiceDetection::Off | ServiceDetection::Banner => 0,
ServiceDetection::Probe => 1,
ServiceDetection::Thorough => 9,
}
}
}
impl fmt::Display for ServiceDetection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownServiceDetection {
pub input: String,
}
impl fmt::Display for UnknownServiceDetection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "unknown service detection level '{}', ", self.input)?;
expected_levels(&ServiceDetection::ALL, ServiceDetection::name, f)
}
}
impl std::error::Error for UnknownServiceDetection {}
impl FromStr for ServiceDetection {
type Err = UnknownServiceDetection;
fn from_str(input: &str) -> Result<Self, Self::Err> {
parse_level(input, &Self::ALL, Self::name, Self::from_level).ok_or_else(|| {
UnknownServiceDetection {
input: input.to_string(),
}
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct TimeoutScale(f64);
impl TimeoutScale {
pub fn new(factor: f64) -> Option<Self> {
(factor.is_finite() && factor > 0.0).then_some(Self(factor))
}
pub const fn get(self) -> f64 {
self.0
}
}
impl fmt::Display for TimeoutScale {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RetryConfig {
pub effort: ScanEffort,
pub max_attempts: Option<NonZeroU8>,
pub timeout_scale: Option<TimeoutScale>,
pub dampen_silent_hosts: bool,
}
impl Default for RetryConfig {
fn default() -> Self {
Self {
effort: ScanEffort::default(),
max_attempts: None,
timeout_scale: None,
dampen_silent_hosts: true,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub struct ProbeTuning {
pub send_mode: SendMode,
pub retry: RetryConfig,
pub max_probe_rate: Option<NonZeroU32>,
pub min_probe_rate: Option<NonZeroU32>,
pub tcp_technique: TcpScanTechnique,
pub sctp_technique: SctpScanTechnique,
pub os_detection: OsDetection,
pub service_detection: ServiceDetection,
pub evasion: EvasionProfile,
pub icmp_evidence: bool,
pub send_source: Vec<IpAddr>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IdleScan {
pub zombie: IpAddr,
pub zombie_port: Option<u16>,
}
impl IdleScan {
pub const fn new(zombie: IpAddr) -> Self {
Self {
zombie,
zombie_port: None,
}
}
#[must_use]
pub const fn with_port(mut self, port: u16) -> Self {
self.zombie_port = Some(port);
self
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct ZondConfig {
pub no_dns: bool,
pub segment_sweep: bool,
pub assume_up: bool,
pub traceroute: bool,
pub characterise: bool,
pub ip_protocols: BTreeSet<u8>,
pub tls_enumeration: bool,
pub idle_scan: Option<IdleScan>,
pub exclusions: Exclusions,
pub redact: bool,
pub send_mode: SendMode,
pub max_probe_rate: Option<NonZeroU32>,
pub min_probe_rate: Option<NonZeroU32>,
pub host_probe_interval: Option<Duration>,
pub host_timeout: Option<Duration>,
pub scan_timeout: Option<Duration>,
pub tcp_technique: TcpScanTechnique,
pub sctp_technique: SctpScanTechnique,
pub retry: RetryConfig,
pub os_detection: OsDetection,
pub service_detection: ServiceDetection,
pub detection: DetectionEnvelope,
pub evasion: EvasionProfile,
pub icmp_evidence: bool,
pub send_source: Vec<IpAddr>,
}
impl Default for ZondConfig {
fn default() -> Self {
Self {
icmp_evidence: true,
send_source: Vec::new(),
no_dns: Default::default(),
segment_sweep: Default::default(),
assume_up: Default::default(),
traceroute: Default::default(),
characterise: Default::default(),
ip_protocols: Default::default(),
tls_enumeration: Default::default(),
idle_scan: Default::default(),
exclusions: Default::default(),
redact: Default::default(),
send_mode: Default::default(),
max_probe_rate: Default::default(),
min_probe_rate: Default::default(),
host_probe_interval: Default::default(),
host_timeout: Default::default(),
scan_timeout: Default::default(),
tcp_technique: Default::default(),
sctp_technique: Default::default(),
retry: Default::default(),
os_detection: Default::default(),
service_detection: Default::default(),
detection: Default::default(),
evasion: Default::default(),
}
}
}
impl ZondConfig {
pub fn probe_tuning(&self) -> ProbeTuning {
let Self {
send_mode,
retry,
max_probe_rate,
min_probe_rate,
tcp_technique,
sctp_technique,
os_detection,
service_detection,
evasion,
icmp_evidence,
send_source,
no_dns: _,
segment_sweep: _,
assume_up: _,
traceroute: _,
characterise: _,
ip_protocols: _,
tls_enumeration: _,
idle_scan: _,
exclusions: _,
redact: _,
detection: _,
host_timeout: _,
scan_timeout: _,
host_probe_interval: _,
} = self;
ProbeTuning {
send_mode: *send_mode,
retry: *retry,
max_probe_rate: *max_probe_rate,
min_probe_rate: *min_probe_rate,
tcp_technique: *tcp_technique,
sctp_technique: *sctp_technique,
os_detection: *os_detection,
service_detection: *service_detection,
evasion: evasion.clone(),
icmp_evidence: *icmp_evidence,
send_source: send_source.clone(),
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn icmp_evidence_reaches_the_probe_tuning_and_is_on_unless_declined() {
let mut cfg = ZondConfig::default();
assert!(
cfg.probe_tuning().icmp_evidence,
"an error is a verdict a scan that was outrun cannot reach any other way"
);
cfg.icmp_evidence = false;
assert!(
!cfg.probe_tuning().icmp_evidence,
"and a caller may decline it"
);
}
use super::*;
use std::num::NonZeroU8;
#[test]
fn every_scale_agrees_with_its_own_numbering() {
fn check<T: Copy + std::fmt::Debug + PartialEq>(
all: &[T],
name: fn(T) -> &'static str,
level: fn(T) -> u8,
from_level: fn(u8) -> Option<T>,
) {
for (index, value) in all.iter().copied().enumerate() {
assert_eq!(usize::from(level(value)), index, "{value:?}");
assert_eq!(from_level(level(value)), Some(value), "{value:?}");
assert!(!name(value).is_empty());
}
let past_the_end = all.len() as u8;
assert_eq!(
from_level(past_the_end),
None,
"a level this engine does not offer is refused, not rounded down"
);
}
check(
&ScanEffort::ALL,
ScanEffort::name,
ScanEffort::level,
ScanEffort::from_level,
);
check(
&OsDetection::ALL,
OsDetection::name,
OsDetection::level,
OsDetection::from_level,
);
check(
&ServiceDetection::ALL,
ServiceDetection::name,
ServiceDetection::level,
ServiceDetection::from_level,
);
}
#[test]
fn every_scale_parses_the_same_by_name_and_by_number() {
for effort in ScanEffort::ALL {
assert_eq!(effort.name().parse(), Ok(effort));
assert_eq!(effort.name().to_uppercase().parse(), Ok(effort));
assert_eq!(format!(" {} ", effort.level()).parse(), Ok(effort));
}
assert!("4".parse::<ScanEffort>().is_err());
assert!("maximum".parse::<ScanEffort>().is_err());
for detection in OsDetection::ALL {
assert_eq!(detection.name().parse(), Ok(detection));
assert_eq!(detection.level().to_string().parse(), Ok(detection));
}
for detection in ServiceDetection::ALL {
assert_eq!(detection.name().parse(), Ok(detection));
assert_eq!(detection.level().to_string().parse(), Ok(detection));
}
}
#[test]
fn a_parse_error_names_every_level_that_would_have_worked() {
let effort = "maximum".parse::<ScanEffort>().unwrap_err().to_string();
for level in ScanEffort::ALL {
assert!(effort.contains(level.name()), "{effort} omits {level}");
}
assert!(effort.contains("0 to 3"), "{effort}");
let os = "9".parse::<OsDetection>().unwrap_err().to_string();
for level in OsDetection::ALL {
assert!(os.contains(level.name()), "{os} omits {level}");
}
let service = "exhaustive"
.parse::<ServiceDetection>()
.unwrap_err()
.to_string();
for level in ServiceDetection::ALL {
assert!(service.contains(level.name()), "{service} omits {level}");
}
assert!(service.contains("0 to 3"), "{service}");
}
#[test]
fn a_retry_override_can_only_hold_a_value_a_scan_could_honour() {
for factor in [0.0, -1.0, -0.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
assert_eq!(TimeoutScale::new(factor), None, "scale {factor}");
}
assert_eq!(TimeoutScale::new(2.5).map(TimeoutScale::get), Some(2.5));
assert!(TimeoutScale::new(f64::MIN_POSITIVE).is_some());
}
#[test]
fn the_retry_overrides_are_unset_by_default() {
let retry = RetryConfig::default();
assert_eq!(retry.max_attempts, None);
assert_eq!(retry.timeout_scale, None);
assert_eq!(retry.effort, ScanEffort::Balanced);
assert!(retry.dampen_silent_hosts);
}
#[test]
fn every_probe_level_knob_reaches_the_strategies() {
let cfg = ZondConfig {
send_mode: SendMode::Ethernet,
retry: RetryConfig {
effort: ScanEffort::Thorough,
max_attempts: NonZeroU8::new(7),
timeout_scale: TimeoutScale::new(3.5),
dampen_silent_hosts: false,
},
max_probe_rate: NonZeroU32::new(1234),
min_probe_rate: NonZeroU32::new(567),
tcp_technique: TcpScanTechnique::Xmas,
sctp_technique: SctpScanTechnique::CookieEcho,
os_detection: OsDetection::Aggressive,
service_detection: ServiceDetection::Banner,
evasion: EvasionProfile::default(),
..Default::default()
};
let tuning = cfg.probe_tuning();
assert_eq!(tuning.send_mode, cfg.send_mode);
assert_eq!(tuning.retry, cfg.retry);
assert_eq!(tuning.max_probe_rate, cfg.max_probe_rate);
assert_eq!(tuning.min_probe_rate, cfg.min_probe_rate);
assert_eq!(tuning.tcp_technique, cfg.tcp_technique);
assert_eq!(tuning.sctp_technique, cfg.sctp_technique);
assert_eq!(tuning.os_detection, cfg.os_detection);
assert_eq!(tuning.service_detection, cfg.service_detection);
assert_eq!(tuning.evasion, cfg.evasion);
}
#[test]
fn each_service_detection_level_says_what_it_puts_on_the_wire() {
assert!(!ServiceDetection::Off.connects());
assert!(!ServiceDetection::Off.sends());
assert!(ServiceDetection::Banner.connects());
assert!(
!ServiceDetection::Banner.sends(),
"listening is the whole of what this level does"
);
assert!(ServiceDetection::Probe.connects());
assert!(ServiceDetection::Probe.sends());
assert!(
ServiceDetection::default().sends(),
"the default asks, because asking is both the informative answer and \
the fast one"
);
}
#[test]
fn os_detection_sends_nothing_below_the_active_level() {
assert!(!OsDetection::Off.is_active());
assert!(!OsDetection::Passive.is_active());
assert!(OsDetection::Active.is_active());
assert!(OsDetection::Aggressive.is_active());
assert!(!OsDetection::default().is_active(), "the default is silent");
assert!(OsDetection::default().is_enabled(), "and it is still on");
}
}