pub mod paths;
use std::collections::BTreeMap;
use std::fmt;
use std::io::BufRead;
use std::num::{NonZeroU8, NonZeroU32};
use std::path::{Path, PathBuf};
use std::time::Duration;
use serde::Deserialize;
use crate::config::ZondConfig;
use crate::config::{ScanEffort, TimeoutScale};
use crate::model::exclusion::Exclusions;
use crate::model::ip::set::IpSet;
use crate::model::port::PortSet;
use crate::model::technique::{SctpScanTechnique, TcpScanTechnique};
use crate::transport::probe::SendMode;
pub const FILE_NAME: &str = "engine.toml";
pub const MAX_DOCUMENT_BYTES: u64 = 1024 * 1024;
pub const TEMPLATE: &str = include_str!("../../assets/settings/engine.toml");
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum SettingsError {
#[error("{path}: {source}")]
Io {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("settings are malformed: {0}")]
Malformed(String),
#[error("{path}: settings longer than the {limit} byte limit")]
TooLarge {
path: PathBuf,
limit: u64,
},
#[error("no profile named '{wanted}'; this document defines: {}",
if .available.is_empty() { "none".to_string() } else { .available.join(", ") })]
UnknownProfile {
wanted: String,
available: Vec<String>,
},
#[error("no settings directory could be located for this user")]
NoPath,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Provisioned {
Existed,
Created,
}
impl Provisioned {
pub fn created(self) -> bool {
matches!(self, Provisioned::Created)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SettingsWarning {
pub key: String,
pub suggestion: Option<&'static str>,
}
impl fmt::Display for SettingsWarning {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.suggestion {
Some(suggestion) => {
write!(
f,
"unknown setting '{}'; did you mean '{suggestion}'?",
self.key
)
}
None => write!(f, "unknown setting '{}'", self.key),
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct Loaded {
pub document: SettingsDocument,
pub warnings: Vec<SettingsWarning>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SettingsDocument {
#[serde(default)]
pub defaults: Settings,
#[serde(default)]
pub profiles: BTreeMap<String, Settings>,
}
impl SettingsDocument {
pub fn resolve(&self, profile: Option<&str>) -> Result<Settings, SettingsError> {
let mut settings = self.defaults.clone();
if let Some(wanted) = profile {
let Some(overrides) = self.profiles.get(wanted) else {
return Err(SettingsError::UnknownProfile {
wanted: wanted.to_string(),
available: self.profiles.keys().cloned().collect(),
});
};
settings.overlay(overrides);
}
Ok(settings)
}
pub fn profile_names(&self) -> impl Iterator<Item = &str> {
self.profiles.keys().map(String::as_str)
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
#[serde(default)]
pub struct Settings {
pub no_dns: Option<bool>,
pub redact: Option<bool>,
#[serde(deserialize_with = "de_send_mode")]
pub send_mode: Option<SendMode>,
#[serde(deserialize_with = "de_probe_rate")]
pub max_probe_rate: Option<NonZeroU32>,
#[serde(deserialize_with = "de_min_probe_rate")]
pub min_probe_rate: Option<NonZeroU32>,
#[serde(deserialize_with = "de_millis")]
pub host_probe_interval: Option<Duration>,
#[serde(deserialize_with = "de_timeout")]
pub host_timeout: Option<Duration>,
#[serde(deserialize_with = "de_timeout")]
pub scan_timeout: Option<Duration>,
#[serde(deserialize_with = "de_technique")]
pub tcp_technique: Option<TcpScanTechnique>,
#[serde(deserialize_with = "de_sctp_technique")]
pub sctp_technique: Option<SctpScanTechnique>,
#[serde(deserialize_with = "de_effort")]
pub effort: Option<ScanEffort>,
#[serde(deserialize_with = "de_max_attempts")]
pub max_attempts: Option<NonZeroU8>,
#[serde(deserialize_with = "de_timeout_scale")]
pub timeout_scale: Option<TimeoutScale>,
pub dampen_silent_hosts: Option<bool>,
pub tls_enumeration: Option<bool>,
pub default_ports: Option<String>,
#[serde(deserialize_with = "de_exclusions")]
pub exclude: Exclusions,
}
impl Settings {
pub fn new() -> Self {
Self::default()
}
pub fn overlay(&mut self, other: &Settings) {
macro_rules! take {
($($field:ident),+ $(,)?) => {
$(if other.$field.is_some() {
self.$field = other.$field.clone();
})+
};
}
take!(
no_dns,
redact,
send_mode,
max_probe_rate,
min_probe_rate,
host_probe_interval,
host_timeout,
scan_timeout,
tcp_technique,
sctp_technique,
effort,
max_attempts,
timeout_scale,
dampen_silent_hosts,
tls_enumeration,
default_ports,
);
self.exclude.extend(&other.exclude);
}
pub fn ports(&self) -> Option<Result<PortSet, SettingsError>> {
self.default_ports.as_deref().map(|spec| {
PortSet::try_from(spec).map_err(|error| {
SettingsError::Malformed(format!("default_ports = '{spec}': {error}"))
})
})
}
pub fn apply_to(&self, config: &mut ZondConfig) {
if let Some(value) = self.no_dns {
config.no_dns = value;
}
if let Some(value) = self.redact {
config.redact = value;
}
if let Some(value) = self.send_mode {
config.send_mode = value;
}
if self.max_probe_rate.is_some() {
config.max_probe_rate = self.max_probe_rate;
}
if self.min_probe_rate.is_some() {
config.min_probe_rate = self.min_probe_rate;
}
if self.host_probe_interval.is_some() {
config.host_probe_interval = self.host_probe_interval;
}
if self.host_timeout.is_some() {
config.host_timeout = self.host_timeout;
}
if self.scan_timeout.is_some() {
config.scan_timeout = self.scan_timeout;
}
if let Some(value) = self.tcp_technique {
config.tcp_technique = value;
}
if let Some(value) = self.sctp_technique {
config.sctp_technique = value;
}
if let Some(value) = self.effort {
config.retry.effort = value;
}
if self.max_attempts.is_some() {
config.retry.max_attempts = self.max_attempts;
}
if self.timeout_scale.is_some() {
config.retry.timeout_scale = self.timeout_scale;
}
if let Some(value) = self.dampen_silent_hosts {
config.retry.dampen_silent_hosts = value;
}
if let Some(value) = self.tls_enumeration {
config.tls_enumeration = value;
}
config.exclusions.extend(&self.exclude);
}
}
const KNOWN_KEYS: [&str; 17] = [
"exclude",
"no_dns",
"redact",
"send_mode",
"max_probe_rate",
"min_probe_rate",
"host_probe_interval",
"host_timeout",
"scan_timeout",
"tcp_technique",
"sctp_technique",
"effort",
"max_attempts",
"timeout_scale",
"dampen_silent_hosts",
"tls_enumeration",
"default_ports",
];
pub fn read(input: &mut dyn BufRead) -> Result<Loaded, SettingsError> {
read_bounded(input, &PathBuf::from("<reader>"))
}
fn read_bounded(input: &mut dyn BufRead, path: &Path) -> Result<Loaded, SettingsError> {
use std::io::Read as _;
let mut text = String::new();
let read = std::io::Read::take(input, MAX_DOCUMENT_BYTES.saturating_add(1))
.read_to_string(&mut text)
.map_err(|source| SettingsError::Io {
path: path.to_path_buf(),
source,
})?;
if read as u64 > MAX_DOCUMENT_BYTES {
return Err(SettingsError::TooLarge {
path: path.to_path_buf(),
limit: MAX_DOCUMENT_BYTES,
});
}
parse(&text)
}
pub fn load(path: &Path) -> Result<Loaded, SettingsError> {
let file = std::fs::File::open(path).map_err(|source| SettingsError::Io {
path: path.to_path_buf(),
source,
})?;
read_bounded(&mut std::io::BufReader::new(file), path)
}
pub fn parse(text: &str) -> Result<Loaded, SettingsError> {
let raw: toml::Table = text
.parse()
.map_err(|error: toml::de::Error| SettingsError::Malformed(error.to_string()))?;
let document: SettingsDocument = toml::from_str(text)
.map_err(|error: toml::de::Error| SettingsError::Malformed(error.to_string()))?;
let mut warnings = Vec::new();
collect_warnings(&raw, &mut warnings);
Ok(Loaded { document, warnings })
}
fn collect_warnings(raw: &toml::Table, warnings: &mut Vec<SettingsWarning>) {
for (table, value) in raw {
match table.as_str() {
"defaults" => warn_unknown_keys("defaults", value, warnings),
"profiles" => {
let Some(profiles) = value.as_table() else {
continue;
};
for (name, settings) in profiles {
warn_unknown_keys(&format!("profiles.{name}"), settings, warnings);
}
}
other => warnings.push(SettingsWarning {
key: other.to_string(),
suggestion: nearest("defaults", other).or_else(|| nearest("profiles", other)),
}),
}
}
}
fn warn_unknown_keys(table: &str, value: &toml::Value, warnings: &mut Vec<SettingsWarning>) {
let Some(settings) = value.as_table() else {
return;
};
for key in settings.keys() {
if KNOWN_KEYS.contains(&key.as_str()) {
continue;
}
warnings.push(SettingsWarning {
key: format!("{table}.{key}"),
suggestion: KNOWN_KEYS
.iter()
.copied()
.map(|known| (edit_distance(key, known), known))
.filter(|(distance, _)| *distance <= 2)
.min_by_key(|(distance, _)| *distance)
.map(|(_, known)| known),
});
}
}
fn nearest(candidate: &'static str, written: &str) -> Option<&'static str> {
(edit_distance(written, candidate) <= 2).then_some(candidate)
}
fn edit_distance(a: &str, b: &str) -> usize {
let a: Vec<char> = a.chars().collect();
let b: Vec<char> = b.chars().collect();
let mut previous: Vec<usize> = (0..=b.len()).collect();
let mut current = vec![0usize; b.len() + 1];
for (i, left) in a.iter().enumerate() {
current[0] = i + 1;
for (j, right) in b.iter().enumerate() {
let substitution = previous[j] + usize::from(left != right);
current[j + 1] = substitution.min(previous[j + 1] + 1).min(current[j] + 1);
}
std::mem::swap(&mut previous, &mut current);
}
previous[b.len()]
}
pub fn provision(path: &Path) -> Result<Provisioned, SettingsError> {
if let Some(parent) = path.parent() {
create_directory(parent)?;
}
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
match options.open(path) {
Ok(mut file) => {
use std::io::Write;
file.write_all(TEMPLATE.as_bytes())
.map_err(|source| SettingsError::Io {
path: path.to_path_buf(),
source,
})?;
Ok(Provisioned::Created)
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => Ok(Provisioned::Existed),
Err(source) => Err(SettingsError::Io {
path: path.to_path_buf(),
source,
}),
}
}
fn create_directory(path: &Path) -> Result<(), SettingsError> {
let mut builder = std::fs::DirBuilder::new();
builder.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt;
builder.mode(0o700);
}
builder.create(path).map_err(|source| SettingsError::Io {
path: path.to_path_buf(),
source,
})
}
pub fn provision_user() -> Result<(PathBuf, Provisioned), SettingsError> {
let path = paths::user().ok_or(SettingsError::NoPath)?;
let outcome = provision(&path)?;
Ok((path, outcome))
}
pub fn resolve(profile: Option<&str>) -> Result<(Settings, Vec<SettingsWarning>), SettingsError> {
let mut settings = Settings::new();
let mut warnings = Vec::new();
let mut found_profile = profile.is_none();
let mut available: Vec<String> = Vec::new();
for path in paths::layered() {
if !path.exists() {
continue;
}
let loaded = load(&path)?;
warnings.extend(loaded.warnings);
settings.overlay(&loaded.document.defaults);
for name in loaded.document.profile_names() {
if !available.iter().any(|known| known == name) {
available.push(name.to_string());
}
}
if let Some(wanted) = profile
&& let Some(overrides) = loaded.document.profiles.get(wanted)
{
settings.overlay(overrides);
found_profile = true;
}
}
if !found_profile {
available.sort();
return Err(SettingsError::UnknownProfile {
wanted: profile.unwrap_or_default().to_string(),
available,
});
}
Ok((settings, warnings))
}
pub(super) fn de_named<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
D: serde::Deserializer<'de>,
T: std::str::FromStr,
T::Err: fmt::Display,
{
let Some(text) = Option::<String>::deserialize(deserializer)? else {
return Ok(None);
};
text.parse().map(Some).map_err(serde::de::Error::custom)
}
fn de_send_mode<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<SendMode>, D::Error> {
de_named(d)
}
fn de_technique<'de, D: serde::Deserializer<'de>>(
d: D,
) -> Result<Option<TcpScanTechnique>, D::Error> {
de_named(d)
}
fn de_sctp_technique<'de, D: serde::Deserializer<'de>>(
d: D,
) -> Result<Option<SctpScanTechnique>, D::Error> {
de_named(d)
}
fn de_effort<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<ScanEffort>, D::Error> {
de_named(d)
}
fn de_probe_rate<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<NonZeroU32>, D::Error> {
let Some(rate) = Option::<u32>::deserialize(d)? else {
return Ok(None);
};
NonZeroU32::new(rate).map(Some).ok_or_else(|| {
serde::de::Error::custom(
"max_probe_rate = 0: a ceiling of zero probes per second is not a slower scan \
but no scan. Remove the key to leave each scanner its own pacing.",
)
})
}
fn de_min_probe_rate<'de, D: serde::Deserializer<'de>>(
d: D,
) -> Result<Option<NonZeroU32>, D::Error> {
let Some(rate) = Option::<u32>::deserialize(d)? else {
return Ok(None);
};
NonZeroU32::new(rate).map(Some).ok_or_else(|| {
serde::de::Error::custom(
"min_probe_rate = 0: a floor of zero probes per second is the absence of a floor. \
Remove the key to let each scanner settle where it will.",
)
})
}
fn de_timeout<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
let Some(seconds) = Option::<u64>::deserialize(d)? else {
return Ok(None);
};
if seconds == 0 {
return Err(serde::de::Error::custom(
"a timeout of 0 seconds expires before the first probe, which is a scan \
that asks nothing. Remove the key to leave the scan unbounded.",
));
}
Ok(Some(Duration::from_secs(seconds)))
}
fn de_millis<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<Duration>, D::Error> {
let Some(millis) = Option::<u64>::deserialize(d)? else {
return Ok(None);
};
if millis == 0 {
return Err(serde::de::Error::custom(
"host_probe_interval = 0: a gap of no time is the absence of a gap. \
Remove the key to let each pass send as fast as its own pacing allows.",
));
}
Ok(Some(Duration::from_millis(millis)))
}
fn de_max_attempts<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<NonZeroU8>, D::Error> {
let Some(attempts) = Option::<u8>::deserialize(d)? else {
return Ok(None);
};
NonZeroU8::new(attempts).map(Some).ok_or_else(|| {
serde::de::Error::custom(
"max_attempts = 0: a probe that is never sent is not a scan setting. \
Write 1 for a single attempt with no retransmission.",
)
})
}
fn de_timeout_scale<'de, D: serde::Deserializer<'de>>(
d: D,
) -> Result<Option<TimeoutScale>, D::Error> {
let Some(scale) = Option::<f64>::deserialize(d)? else {
return Ok(None);
};
TimeoutScale::new(scale).map(Some).ok_or_else(|| {
serde::de::Error::custom(format!(
"timeout_scale = {scale}: a scale multiplies how long the scan waits, \
so it has to be a positive, finite number."
))
})
}
fn de_exclusions<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Exclusions, D::Error> {
let written = Vec::<String>::deserialize(d)?;
let mut ips = IpSet::new();
for expression in &written {
let parsed: IpSet = expression.parse().map_err(|error| {
serde::de::Error::custom(format!(
"exclude = '{expression}': {error}. A settings file takes addresses, \
ranges and CIDR blocks; names and keywords such as 'lan' mean something \
different on every machine that reads the file and are not accepted here."
))
})?;
for range in parsed.v4() {
ips.push_v4_range(*range);
}
for range in parsed.v6() {
ips.push_v6_range(*range);
}
}
Ok(Exclusions::new(ips))
}
#[cfg(test)]
mod tests {
use super::*;
fn document(text: &str) -> Loaded {
parse(text).expect("the document parses")
}
#[test]
fn a_setting_the_engine_could_not_honour_is_refused_by_name() {
for (document, expected) in [
("[defaults]\nmax_probe_rate = 0\n", "max_probe_rate"),
("[defaults]\nmin_probe_rate = 0\n", "min_probe_rate"),
(
"[defaults]\nhost_probe_interval = 0\n",
"host_probe_interval",
),
("[defaults]\nmax_attempts = 0\n", "max_attempts"),
("[defaults]\ntimeout_scale = 0.0\n", "timeout_scale"),
("[defaults]\ntimeout_scale = -1.5\n", "timeout_scale"),
("[defaults]\ntimeout_scale = nan\n", "timeout_scale"),
] {
let refused = read(&mut document.as_bytes()).expect_err(document);
let message = refused.to_string();
assert!(
message.contains(expected),
"{document:?} was refused without naming {expected}: {message}"
);
}
}
#[test]
fn the_smallest_usable_values_are_accepted() {
let mut document = &b"[defaults]\nmax_probe_rate = 1\nmin_probe_rate = 1\nmax_attempts = 1\ntimeout_scale = 0.001\n"[..];
let loaded = read(&mut document).expect("the smallest usable values are settings");
let settings = loaded.document.resolve(None).expect("resolves");
assert_eq!(settings.max_probe_rate, NonZeroU32::new(1));
assert_eq!(settings.min_probe_rate, NonZeroU32::new(1));
assert_eq!(settings.max_attempts, NonZeroU8::new(1));
assert_eq!(settings.timeout_scale.map(TimeoutScale::get), Some(0.001));
}
#[test]
fn every_layer_adds_its_exclusions_and_none_replaces_another() {
let mut administrator = document(
r#"
[defaults]
exclude = ["10.0.5.0/24"]
[profiles.audit]
exclude = ["10.0.9.0/24"]
"#,
)
.document;
let user = document(
r#"
[defaults]
exclude = ["192.168.1.50"]
"#,
)
.document;
administrator.defaults.overlay(&user.defaults);
let settings = administrator.resolve(Some("audit")).expect("the profile");
let mut config = ZondConfig::default();
settings.apply_to(&mut config);
for excluded in ["10.0.5.7", "192.168.1.50", "10.0.9.1"] {
assert!(
config
.exclusions
.excludes(&excluded.parse().expect("literal")),
"{excluded} was named by a layer and must still be excluded"
);
}
assert!(
!config
.exclusions
.excludes(&"10.0.6.7".parse().expect("literal"))
);
}
#[test]
fn applying_a_document_keeps_the_exclusions_the_caller_already_had() {
let mut from_the_command_line = IpSet::new();
from_the_command_line.insert_range("172.16.0.0/16".parse().expect("a valid range"));
let mut config = ZondConfig {
exclusions: Exclusions::new(from_the_command_line),
..Default::default()
};
document(
r#"
[defaults]
exclude = ["10.0.5.0/24"]
"#,
)
.document
.defaults
.apply_to(&mut config);
assert!(
config
.exclusions
.excludes(&"172.16.4.4".parse().expect("literal"))
);
assert!(
config
.exclusions
.excludes(&"10.0.5.7".parse().expect("literal"))
);
}
#[test]
fn a_malformed_exclusion_refuses_the_document() {
for written in ["lan", "db.internal", "10.0.5.0/33"] {
let error = parse(&format!(
r#"
[defaults]
exclude = ["{written}"]
"#
))
.expect_err("the document must not load");
assert!(
error.to_string().contains(written),
"the error names what was written: {error}"
);
}
}
#[test]
fn a_later_layer_overrides_only_what_it_mentions() {
let system = document(
r#"
[defaults]
redact = true
no_dns = true
max_probe_rate = 1000
"#,
);
let user = document(
r#"
[defaults]
redact = false
"#,
);
let mut settings = system.document.defaults.clone();
settings.overlay(&user.document.defaults);
assert_eq!(
settings.redact,
Some(false),
"the user file spoke about this"
);
assert_eq!(settings.no_dns, Some(true), "and said nothing about this");
assert_eq!(settings.max_probe_rate, NonZeroU32::new(1000));
}
#[test]
fn a_profile_layers_onto_the_defaults() {
let loaded = document(
r#"
[defaults]
effort = "balanced"
max_probe_rate = 20000
no_dns = true
[profiles.stealth]
effort = "thorough"
max_probe_rate = 200
"#,
);
let defaults = loaded.document.resolve(None).expect("resolves");
assert_eq!(defaults.effort, Some(ScanEffort::Balanced));
assert_eq!(defaults.max_probe_rate, NonZeroU32::new(20000));
let stealth = loaded.document.resolve(Some("stealth")).expect("resolves");
assert_eq!(stealth.effort, Some(ScanEffort::Thorough));
assert_eq!(stealth.max_probe_rate, NonZeroU32::new(200));
assert_eq!(stealth.no_dns, Some(true), "inherited from the defaults");
}
#[test]
fn an_unknown_profile_is_an_error_naming_the_ones_that_exist() {
let loaded = document(
r#"
[profiles.stealth]
effort = "thorough"
[profiles.sweep]
effort = "single"
"#,
);
match loaded.document.resolve(Some("quiet")).expect_err("refused") {
SettingsError::UnknownProfile { wanted, available } => {
assert_eq!(wanted, "quiet");
assert_eq!(available, vec!["stealth", "sweep"]);
}
other => panic!("expected an unknown profile, got {other:?}"),
}
}
#[test]
fn an_unknown_key_is_reported_with_the_nearest_one_that_exists() {
let loaded = document(
r#"
[defaults]
max_probe_rat = 500
invented_entirely = true
[profiles.stealth]
tcp_techniqu = "fin"
"#,
);
assert_eq!(loaded.warnings.len(), 3, "{:?}", loaded.warnings);
let find = |key: &str| {
loaded
.warnings
.iter()
.find(|warning| warning.key == key)
.unwrap_or_else(|| panic!("no warning for {key}: {:?}", loaded.warnings))
};
assert_eq!(
find("defaults.max_probe_rat").suggestion,
Some("max_probe_rate")
);
assert_eq!(
find("defaults.invented_entirely").suggestion,
None,
"nothing is close enough to this to be worth suggesting"
);
assert_eq!(
find("profiles.stealth.tcp_techniqu").suggestion,
Some("tcp_technique")
);
}
#[test]
fn a_name_outside_the_set_is_refused_at_load_and_says_what_would_have_worked() {
let error = parse(
r#"
[defaults]
tcp_technique = "stealth"
"#,
)
.expect_err("refused");
let message = error.to_string();
assert!(message.contains("stealth"), "{message}");
assert!(message.contains("syn"), "the accepted names: {message}");
}
#[test]
fn applying_settings_changes_only_what_they_name() {
let loaded = document(
r#"
[defaults]
no_dns = true
redact = true
tcp_technique = "xmas"
effort = "thorough"
max_attempts = 5
max_probe_rate = 750
send_mode = "ethernet"
"#,
);
let mut config = ZondConfig::default();
let before_sweep = config.segment_sweep;
loaded.document.defaults.apply_to(&mut config);
assert!(config.no_dns);
assert!(config.redact);
assert_eq!(config.tcp_technique, TcpScanTechnique::Xmas);
assert_eq!(config.retry.effort, ScanEffort::Thorough);
assert_eq!(config.retry.max_attempts, NonZeroU8::new(5));
assert_eq!(config.max_probe_rate, NonZeroU32::new(750));
assert_eq!(config.send_mode, SendMode::Ethernet);
assert_eq!(
config.segment_sweep, before_sweep,
"a file must not be able to turn a single-host scan into a segment sweep"
);
}
#[test]
fn an_empty_document_changes_no_configuration() {
let loaded = document("");
let mut config = ZondConfig::default();
loaded.document.defaults.apply_to(&mut config);
let untouched = ZondConfig::default();
assert_eq!(config.no_dns, untouched.no_dns);
assert_eq!(config.redact, untouched.redact);
assert_eq!(config.tcp_technique, untouched.tcp_technique);
assert_eq!(config.max_probe_rate, untouched.max_probe_rate);
assert_eq!(config.retry.effort, untouched.retry.effort);
}
#[test]
fn the_provisioned_template_parses_and_changes_nothing() {
let loaded = parse(TEMPLATE).expect("the shipped template is valid TOML");
assert!(
loaded.warnings.is_empty(),
"the template names a key this build does not know: {:?}",
loaded.warnings
);
assert_eq!(
loaded.document.defaults,
Settings::new(),
"the template must set nothing"
);
let mut config = ZondConfig::default();
loaded.document.defaults.apply_to(&mut config);
assert_eq!(config.redact, ZondConfig::default().redact);
assert_eq!(config.tcp_technique, ZondConfig::default().tcp_technique);
}
#[test]
fn the_template_documents_every_key_and_no_others() {
let known: std::collections::BTreeSet<&str> = KNOWN_KEYS.into_iter().collect();
let documented: std::collections::BTreeSet<&str> = TEMPLATE
.lines()
.filter_map(|line| {
line.trim_start()
.strip_prefix('#')
.unwrap_or(line)
.split_once('=')
})
.map(|(key, _)| key.trim())
.filter(|key| {
!key.is_empty() && key.chars().all(|c| c.is_ascii_lowercase() || c == '_')
})
.collect();
assert_eq!(
known.difference(&documented).collect::<Vec<_>>(),
Vec::<&&str>::new(),
"the template does not document a key this build reads"
);
assert_eq!(
documented.difference(&known).collect::<Vec<_>>(),
Vec::<&&str>::new(),
"the template documents a key this build ignores"
);
}
#[test]
fn a_port_specification_is_parsed_when_asked_for_and_not_before() {
let good = document(
r#"
[defaults]
default_ports = "22,80,u:53"
"#,
);
let ports = good
.document
.defaults
.ports()
.expect("names ports")
.unwrap();
assert!(ports.has_tcp(22));
assert!(ports.has_udp(53));
let bad = document(
r#"
[defaults]
default_ports = "http"
"#,
);
assert!(bad.document.defaults.ports().expect("names ports").is_err());
}
#[test]
fn a_document_that_is_not_toml_is_refused() {
assert!(matches!(
parse("this is not = = toml"),
Err(SettingsError::Malformed(_))
));
}
#[test]
fn provisioning_creates_once_and_never_overwrites() {
let dir = std::env::temp_dir().join(format!("zond-settings-{}", std::process::id()));
let path = dir.join(FILE_NAME);
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(provision(&path).expect("creates"), Provisioned::Created);
assert!(path.exists());
std::fs::write(&path, "[defaults]\nredact = true\n").expect("writes");
assert_eq!(
provision(&path).expect("finds"),
Provisioned::Existed,
"a second call must not report having created anything"
);
assert_eq!(
std::fs::read_to_string(&path).expect("reads"),
"[defaults]\nredact = true\n",
"provisioning overwrote a file somebody had edited"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn provisioning_then_loading_produces_settings_that_change_nothing() {
let dir = std::env::temp_dir().join(format!("zond-startup-{}", std::process::id()));
let path = dir.join(FILE_NAME);
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(provision(&path).expect("creates"), Provisioned::Created);
assert_eq!(provision(&path).expect("finds"), Provisioned::Existed);
let loaded = load(&path).expect("the file it just wrote is readable");
assert!(loaded.warnings.is_empty());
let settings = loaded.document.resolve(None).expect("resolves");
let mut config = ZondConfig::default();
settings.apply_to(&mut config);
let untouched = ZondConfig::default();
assert_eq!(config.redact, untouched.redact);
assert_eq!(config.tcp_technique, untouched.tcp_technique);
assert_eq!(config.retry.effort, untouched.retry.effort);
assert_eq!(config.max_probe_rate, untouched.max_probe_rate);
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(unix)]
#[test]
fn a_provisioned_file_is_readable_only_by_its_owner() {
use std::os::unix::fs::PermissionsExt;
let dir = std::env::temp_dir().join(format!("zond-modes-{}", std::process::id()));
let path = dir.join(FILE_NAME);
let _ = std::fs::remove_dir_all(&dir);
provision(&path).expect("creates");
let file = std::fs::metadata(&path).expect("stat").permissions().mode();
let directory = std::fs::metadata(&dir).expect("stat").permissions().mode();
assert_eq!(file & 0o077, 0, "the file is readable by somebody else");
assert_eq!(
directory & 0o077,
0,
"the directory is traversable by somebody else"
);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn edit_distance_is_the_ordinary_one() {
assert_eq!(edit_distance("quiet", "quiet"), 0);
assert_eq!(edit_distance("quie", "quiet"), 1);
assert_eq!(edit_distance("max_probe_rat", "max_probe_rate"), 1);
assert_eq!(edit_distance("", "abc"), 3);
}
}