From 942655a5e0bbbbd922fc7d0dee47ad49667a1ad2 Mon Sep 17 00:00:00 2001 From: Lucas Guerra Date: Sun, 1 Nov 2026 22:52:45 -0300 Subject: [PATCH] =?UTF-8?q?Implementa=20config/targets/schedule=20(TOML+cr?= =?UTF-8?q?on)=20e=20scan::discovery/ports=20(TCP=20connect=20determin?= =?UTF-8?q?=C3=ADstico)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 510 ++++++++++++++ crates/xexeu-core/Cargo.toml | 5 + crates/xexeu-core/src/config.rs | 702 ++++++++++++++++++- crates/xexeu-core/src/scan/discovery.rs | 215 +++++- crates/xexeu-core/src/scan/mod.rs | 33 + crates/xexeu-core/src/scan/ports.rs | 385 ++++++++++- crates/xexeu-core/src/schedule.rs | 512 +++++++++++++- crates/xexeu-core/src/targets.rs | 861 +++++++++++++++++++++++- 8 files changed, 3214 insertions(+), 9 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 60bd2c8..6b76f22 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + [[package]] name = "anstream" version = "1.0.0" @@ -52,6 +61,45 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "num-traits", + "windows-link", +] + [[package]] name = "clap" version = "4.6.7" @@ -98,24 +146,250 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "croner" +version = "4.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d09284075f5c87675790d1ad74212a7863eb8bdf228cdbd364f08a152fc62d" +dependencies = [ + "chrono", + "derive_builder", + "strum", +] + +[[package]] +name = "darling" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d00b9596d185e565c2207a0b01f8bd1a135483d02d9b7b0a54b11da8d53412e" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.20.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "derive_builder" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "507dfb09ea8b7fa618fcf76e953f4f5e192547945816d5358edffe39f6f94947" +dependencies = [ + "derive_builder_macro", +] + +[[package]] +name = "derive_builder_core" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d5bcf7b024d6835cfb3d473887cd966994907effbe9227e8c8219824d06c4e8" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "derive_builder_macro" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab63b0e2bf4d5928aff72e83a7dace85d7bba5fe12dcc3c5a572d78caffd3f3c" +dependencies = [ + "derive_builder_core", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "heck" version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "is_terminal_polyfill" version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "once_cell_polyfill" version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -134,6 +408,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + [[package]] name = "serde" version = "1.0.229" @@ -164,12 +444,64 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + [[package]] name = "strsim" version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "strum" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "syn" version = "2.0.119" @@ -212,6 +544,70 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + [[package]] name = "unicode-ident" version = "1.0.27" @@ -224,12 +620,115 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -239,6 +738,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" + [[package]] name = "xexeu-cli" version = "0.1.0" @@ -251,6 +756,11 @@ dependencies = [ name = "xexeu-core" version = "0.1.0" dependencies = [ + "chrono", + "croner", + "ipnet", "serde", "thiserror", + "tokio", + "toml", ] diff --git a/crates/xexeu-core/Cargo.toml b/crates/xexeu-core/Cargo.toml index 8d770f1..ab50b7e 100644 --- a/crates/xexeu-core/Cargo.toml +++ b/crates/xexeu-core/Cargo.toml @@ -9,5 +9,10 @@ authors.workspace = true rust-version.workspace = true [dependencies] +chrono = { version = "0.4", default-features = false, features = ["clock"] } +croner = "4" +ipnet = "2" serde = { version = "1", features = ["derive"] } thiserror = "1" +toml = "1" +tokio = { version = "1", features = ["macros", "net", "rt", "rt-multi-thread", "sync", "time"] } diff --git a/crates/xexeu-core/src/config.rs b/crates/xexeu-core/src/config.rs index 12de1d2..eb4ab25 100644 --- a/crates/xexeu-core/src/config.rs +++ b/crates/xexeu-core/src/config.rs @@ -1,2 +1,702 @@ //! Parses and validates `xexeu.toml`: authorized scope, defaults, profiles and target groups. -// TODO: implement configuration parsing and validation. + +use std::collections::{BTreeMap, BTreeSet}; + +use chrono::{DateTime, TimeZone, Utc}; +use serde::Deserialize; +use thiserror::Error; + +use crate::schedule::{CronSpec, Jitter, ScheduleError}; +use crate::targets::{self, TargetError}; + +/// Cadences shorter than this trigger a warning instead of a hard failure. +pub const MIN_INTERVAL_SECS: i64 = 300; + +const REFERENCE_INSTANT: i64 = 1_700_000_000; + +/// Root configuration document. +#[derive(Debug, Clone, Deserialize)] +pub struct XexeuConfig { + /// Authorized scope shared by every group. + #[serde(rename = "escopo")] + pub scope: ScopeConfig, + /// Defaults inherited by groups that omit a field. + #[serde(rename = "padrao", default)] + pub defaults: DefaultsConfig, + /// Named scanning profiles. + #[serde(rename = "perfis", default)] + pub profiles: BTreeMap, + /// Target groups. + #[serde(rename = "grupo", default)] + pub groups: Vec, +} + +/// `[escopo]`: what the operator is allowed to touch. +#[derive(Debug, Clone, Default, Deserialize)] +pub struct ScopeConfig { + /// CIDRs and addresses that bound every expanded target. + #[serde(rename = "autorizado", default)] + pub authorized: Vec, + /// Person or team accountable for the authorization. + #[serde(rename = "responsavel", default)] + pub responsible: Option, +} + +/// `[padrao]`: values inherited by groups. +#[derive(Debug, Clone, Deserialize)] +pub struct DefaultsConfig { + /// Cron expression for groups without their own. + #[serde(rename = "cron", default = "default_cron")] + pub cron: String, + /// Deterministic jitter applied to every slot. + #[serde(rename = "jitter", default = "default_jitter")] + pub jitter: String, + /// Profile for groups without their own. + #[serde(rename = "perfil", default)] + pub profile: Option, + /// Global packet-per-second budget shared by all groups. + #[serde(rename = "taxa_maxima_pps", default)] + pub max_pps: Option, + /// Hosts scanned concurrently. + #[serde(rename = "hosts_simultaneos", default)] + pub simultaneous_hosts: Option, + /// Consecutive unanswered scans before a host is considered gone. + #[serde(rename = "ausencias_para_sumir", default)] + pub absences_before_disappear: Option, +} + +impl Default for DefaultsConfig { + fn default() -> Self { + Self { + cron: default_cron(), + jitter: default_jitter(), + profile: None, + max_pps: None, + simultaneous_hosts: None, + absences_before_disappear: None, + } + } +} + +/// `[perfis.]`: how each group is scanned. +#[derive(Debug, Clone, Deserialize)] +pub struct ProfileConfig { + /// TCP port selection, such as `top-1000` or `1-65535`. + #[serde(rename = "tcp", default = "default_tcp")] + pub tcp: String, + /// UDP ports to probe. + #[serde(rename = "udp", default)] + pub udp: Vec, + /// Scanner engine, such as `nativo` or `nmap`. + #[serde(rename = "motor", default = "default_engine")] + pub engine: String, + /// Whether vulnerability checks run for this profile. + #[serde(rename = "vulnerabilidades", default = "default_true")] + pub vulnerabilities: bool, +} + +/// `[[grupo]]`: one set of targets with its own cadence. +#[derive(Debug, Clone, Default, Deserialize)] +pub struct GroupConfig { + /// Group name, unique in the document. + #[serde(rename = "nome", default)] + pub name: String, + /// CIDRs, ranges, addresses and DNS names. + #[serde(rename = "alvos", default)] + pub targets: Vec, + /// Ranges subtracted after expansion. + #[serde(rename = "excluir", default)] + pub exclude: Vec, + /// Cron expression overriding the default. + #[serde(rename = "cron", default)] + pub cron: Option, + /// Profile overriding the default. + #[serde(rename = "perfil", default)] + pub profile: Option, + /// Free-form criticality label. + #[serde(rename = "criticidade", default)] + pub criticality: Option, +} + +impl GroupConfig { + /// Cron expression that applies to this group. + pub fn effective_cron<'a>(&'a self, config: &'a XexeuConfig) -> &'a str { + self.cron + .as_deref() + .unwrap_or(config.defaults.cron.as_str()) + } + + /// Profile that applies to this group. + pub fn effective_profile<'a>(&'a self, config: &'a XexeuConfig) -> &'a str { + self.profile + .as_deref() + .or(config.defaults.profile.as_deref()) + .unwrap_or("padrao") + } +} + +/// Configuration error that prevents either service from starting. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum ConfigError { + /// The document is not valid TOML or does not match the expected shape. + #[error("TOML inválido: {reason}")] + Toml { + /// Parser message. + reason: String, + }, + /// The authorized scope is missing or malformed. + #[error("escopo autorizado inválido em `{entry}`: {reason}")] + InvalidScope { + /// Offending entry. + entry: String, + /// What is wrong with it. + reason: String, + }, + /// No group was declared. + #[error("nenhum grupo configurado")] + NoGroups, + /// A group has no name. + #[error("grupo na posição {index} não tem nome")] + UnnamedGroup { + /// Zero-based position in the document. + index: usize, + }, + /// Two groups share a name. + #[error("grupo `{group}` definido mais de uma vez")] + DuplicateGroup { + /// Duplicated name. + group: String, + }, + /// A group has no targets. + #[error("grupo `{group}` não tem alvos")] + EmptyTargets { + /// Group name. + group: String, + }, + /// A group references a profile that does not exist. + #[error("grupo `{group}` usa perfil desconhecido `{profile}`")] + UnknownProfile { + /// Group name. + group: String, + /// Missing profile. + profile: String, + }, + /// A group has an invalid cron expression. + #[error("grupo `{group}` tem cron inválido `{expr}`: {reason}")] + InvalidCron { + /// Group name. + group: String, + /// Original expression. + expr: String, + /// Parser message. + reason: String, + }, + /// The global jitter is invalid. + #[error("jitter inválido `{raw}`: use um percentual entre 0% e 100%")] + InvalidJitter { + /// Raw value. + raw: String, + }, + /// An expanded target escapes the authorized scope. + #[error("alvo `{target}` do grupo `{group}` está fora do escopo autorizado")] + TargetOutOfScope { + /// Group name. + group: String, + /// Offending target. + target: String, + }, + /// A target string cannot be parsed. + #[error("alvo `{target}` do grupo `{group}` é inválido: {reason}")] + InvalidTarget { + /// Group name. + group: String, + /// Original target. + target: String, + /// What is wrong with it. + reason: String, + }, + /// An IPv6 block is too wide to enumerate. + #[error( + "grupo `{group}` usa prefixo IPv6 /{prefix}, maior que o limite /112; liste os endereços explicitamente" + )] + Ipv6PrefixTooLarge { + /// Group name. + group: String, + /// Prefix length supplied. + prefix: u8, + }, +} + +/// Result of a successful validation. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ValidationReport { + /// One entry per group, with the expansion totals used by `config check`. + pub groups: Vec, + /// Non-fatal issues worth surfacing to the operator. + pub warnings: Vec, +} + +/// How one group expanded, for the `config check` output. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GroupSummary { + /// Group name. + pub group: String, + /// Profile actually used. + pub profile: String, + /// Cron expression actually used. + pub cron: String, + /// Number of static addresses. + pub addresses: u128, + /// Number of DNS names still to be resolved. + pub names: usize, +} + +/// Non-fatal configuration warning. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ConfigWarning { + /// Group that triggered the warning. + pub group: String, + /// Operator-facing message. + pub message: String, +} + +impl XexeuConfig { + /// Parses the TOML document without validating its semantics. + pub fn from_toml_str(raw: &str) -> Result { + toml::from_str(raw).map_err(|error| ConfigError::Toml { + reason: error.to_string(), + }) + } + + /// Parses and validates the document. + pub fn load_validated(raw: &str) -> Result<(Self, ValidationReport), ConfigError> { + let config = Self::from_toml_str(raw)?; + let report = config.validate()?; + Ok((config, report)) + } + + /// Looks a group up by name. + pub fn group(&self, name: &str) -> Option<&GroupConfig> { + self.groups.iter().find(|group| group.name == name) + } + + /// Validates scope, profiles, cron, targets and exclusions. + pub fn validate(&self) -> Result { + if self.scope.authorized.is_empty() { + return Err(ConfigError::InvalidScope { + entry: "autorizado".to_string(), + reason: "escopo autorizado vazio".to_string(), + }); + } + + let scope = targets::scope_ranges(&self.scope.authorized).map_err(scope_error)?; + Jitter::parse(&self.defaults.jitter).map_err(|error| match error { + ScheduleError::InvalidJitter { raw } => ConfigError::InvalidJitter { raw }, + other => ConfigError::InvalidJitter { + raw: other.to_string(), + }, + })?; + + if self.groups.is_empty() { + return Err(ConfigError::NoGroups); + } + + let reference = DateTime::from_timestamp(REFERENCE_INSTANT, 0).unwrap_or_else(|| { + Utc.timestamp_opt(REFERENCE_INSTANT, 0) + .single() + .expect("fixed instant is valid") + }); + + let mut report = ValidationReport::default(); + let mut seen = BTreeSet::new(); + + for (index, group) in self.groups.iter().enumerate() { + if group.name.trim().is_empty() { + return Err(ConfigError::UnnamedGroup { index }); + } + if !seen.insert(group.name.clone()) { + return Err(ConfigError::DuplicateGroup { + group: group.name.clone(), + }); + } + if group.targets.is_empty() { + return Err(ConfigError::EmptyTargets { + group: group.name.clone(), + }); + } + + let profile = group.effective_profile(self).to_string(); + if !self.profiles.contains_key(&profile) { + return Err(ConfigError::UnknownProfile { + group: group.name.clone(), + profile, + }); + } + + let expression = group.effective_cron(self); + let spec = CronSpec::parse(expression).map_err(|error| match error { + ScheduleError::InvalidCron { expr, reason } => ConfigError::InvalidCron { + group: group.name.clone(), + expr, + reason, + }, + other => ConfigError::InvalidCron { + group: group.name.clone(), + expr: expression.to_string(), + reason: other.to_string(), + }, + })?; + + if let Ok(interval) = spec.interval_after(reference) { + if interval < MIN_INTERVAL_SECS { + report.warnings.push(ConfigWarning { + group: group.name.clone(), + message: format!( + "grupo `{}` dispara a cada {}s, menos de 5 minutos; revise a cadência e o orçamento de taxa", + group.name, interval + ), + }); + } + } + + for raw in &group.targets { + let target = targets::parse_target(raw) + .map_err(|error| group_target_error(&group.name, error))?; + if let Some(range) = target.range() { + if !targets::covered_by_scope(&scope, range) { + return Err(ConfigError::TargetOutOfScope { + group: group.name.clone(), + target: raw.trim().to_string(), + }); + } + } + } + + let expansion = targets::expand_group(group) + .map_err(|error| group_target_error(&group.name, error))?; + + report.groups.push(GroupSummary { + group: group.name.clone(), + profile, + cron: expression.to_string(), + addresses: expansion.address_count(), + names: expansion.names().len(), + }); + } + + Ok(report) + } +} + +fn scope_error(error: TargetError) -> ConfigError { + match error { + TargetError::InvalidTarget { target, reason } => ConfigError::InvalidScope { + entry: target, + reason, + }, + other => ConfigError::InvalidScope { + entry: "autorizado".to_string(), + reason: other.to_string(), + }, + } +} + +fn group_target_error(group: &str, error: TargetError) -> ConfigError { + match error { + TargetError::Ipv6PrefixTooLarge { prefix, .. } => ConfigError::Ipv6PrefixTooLarge { + group: group.to_string(), + prefix, + }, + TargetError::InvalidTarget { target, reason } => ConfigError::InvalidTarget { + group: group.to_string(), + target, + reason, + }, + other => ConfigError::InvalidTarget { + group: group.to_string(), + target: String::new(), + reason: other.to_string(), + }, + } +} + +fn default_cron() -> String { + "@daily".to_string() +} + +fn default_jitter() -> String { + "0%".to_string() +} + +fn default_tcp() -> String { + "top-1000".to_string() +} + +fn default_engine() -> String { + "nativo".to_string() +} + +fn default_true() -> bool { + true +} + +#[cfg(test)] +mod tests { + use super::*; + + const EXAMPLE: &str = include_str!("../../../examples/xexeu.toml"); + + fn with_group(target: &str, extra: &str) -> String { + format!( + r#" +[escopo] +autorizado = ["10.0.0.0/8"] + +[padrao] +cron = "@daily" + +[perfis.padrao] + +[[grupo]] +nome = "teste" +alvos = ["{target}"] +{extra} +"# + ) + } + + #[test] + fn example_configuration_is_valid() { + let (config, report) = XexeuConfig::load_validated(EXAMPLE).expect("example is valid"); + + assert_eq!(config.groups.len(), 4); + assert_eq!(report.groups.len(), 4); + assert!( + report.warnings.is_empty(), + "unexpected warnings: {report:?}" + ); + + let corporativa = report + .groups + .iter() + .find(|group| group.group == "corporativa") + .expect("corporativa is summarized"); + assert_eq!(corporativa.addresses, 65_536 - 256); + assert_eq!(corporativa.cron, "@daily"); + assert_eq!(corporativa.profile, "padrao"); + + let nucleo = report + .groups + .iter() + .find(|group| group.group == "nucleo") + .expect("nucleo is summarized"); + assert_eq!(nucleo.addresses, 13); + assert_eq!(nucleo.names, 1); + assert_eq!(nucleo.cron, "*/5 * * * *"); + + let completo = report + .groups + .iter() + .find(|group| group.group == "nucleo-completo") + .expect("nucleo-completo is summarized"); + assert_eq!(completo.profile, "completo"); + assert_eq!(completo.addresses, 13); + } + + #[test] + fn missing_scope_is_rejected() { + let raw = r#" +[perfis.padrao] + +[[grupo]] +nome = "teste" +alvos = ["10.0.0.0/24"] +"#; + assert!(matches!( + XexeuConfig::from_toml_str(raw), + Err(ConfigError::Toml { .. }) + )); + } + + #[test] + fn empty_scope_is_rejected() { + let raw = r#" +[escopo] + +[perfis.padrao] + +[[grupo]] +nome = "teste" +alvos = ["10.0.0.0/24"] +"#; + let config = XexeuConfig::from_toml_str(raw).expect("config parses"); + assert!(matches!( + config.validate(), + Err(ConfigError::InvalidScope { .. }) + )); + } + + #[test] + fn target_outside_scope_is_rejected() { + let raw = with_group("192.168.0.0/24", ""); + let config = XexeuConfig::from_toml_str(&raw).expect("config parses"); + + match config.validate() { + Err(ConfigError::TargetOutOfScope { group, target }) => { + assert_eq!(group, "teste"); + assert_eq!(target, "192.168.0.0/24"); + } + other => panic!("unexpected result: {other:?}"), + } + } + + #[test] + fn ipv6_target_wider_than_the_limit_is_rejected() { + let raw = with_group("2001:db8::/64", ""); + let config = XexeuConfig::from_toml_str(&raw).expect("config parses"); + + assert!(matches!( + config.validate(), + Err(ConfigError::Ipv6PrefixTooLarge { prefix: 64, .. }) + )); + } + + #[test] + fn invalid_cron_is_rejected() { + let raw = with_group("10.0.0.0/24", "cron = \"todo dia\""); + let config = XexeuConfig::from_toml_str(&raw).expect("config parses"); + + assert!(matches!( + config.validate(), + Err(ConfigError::InvalidCron { group, .. }) if group == "teste" + )); + } + + #[test] + fn aggressive_cadence_only_warns() { + let raw = with_group("10.0.0.0/24", "cron = \"* * * * *\""); + let config = XexeuConfig::from_toml_str(&raw).expect("config parses"); + let report = config.validate().expect("aggressive cadence is allowed"); + + assert_eq!(report.warnings.len(), 1); + assert_eq!(report.warnings[0].group, "teste"); + assert!(report.warnings[0].message.contains("menos de 5 minutos")); + } + + #[test] + fn five_minutes_is_not_aggressive() { + let raw = with_group("10.0.0.0/24", "cron = \"*/5 * * * *\""); + let (_, report) = XexeuConfig::load_validated(&raw).expect("config is valid"); + assert!(report.warnings.is_empty()); + } + + #[test] + fn unknown_profile_is_rejected() { + let raw = with_group("10.0.0.0/24", "perfil = \"inexistente\""); + let config = XexeuConfig::from_toml_str(&raw).expect("config parses"); + + assert!(matches!( + config.validate(), + Err(ConfigError::UnknownProfile { profile, .. }) if profile == "inexistente" + )); + } + + #[test] + fn duplicate_groups_are_rejected() { + let raw = r#" +[escopo] +autorizado = ["10.0.0.0/8"] + +[perfis.padrao] + +[[grupo]] +nome = "repetido" +alvos = ["10.0.0.0/24"] + +[[grupo]] +nome = "repetido" +alvos = ["10.0.1.0/24"] +"#; + let config = XexeuConfig::from_toml_str(raw).expect("config parses"); + assert!(matches!( + config.validate(), + Err(ConfigError::DuplicateGroup { .. }) + )); + } + + #[test] + fn group_without_targets_is_rejected() { + let raw = r#" +[escopo] +autorizado = ["10.0.0.0/8"] + +[perfis.padrao] + +[[grupo]] +nome = "vazio" +alvos = [] +"#; + let config = XexeuConfig::from_toml_str(raw).expect("config parses"); + assert!(matches!( + config.validate(), + Err(ConfigError::EmptyTargets { .. }) + )); + } + + #[test] + fn document_without_groups_is_rejected() { + let raw = r#" +[escopo] +autorizado = ["10.0.0.0/8"] + +[perfis.padrao] +"#; + let config = XexeuConfig::from_toml_str(raw).expect("config parses"); + assert!(matches!(config.validate(), Err(ConfigError::NoGroups))); + } + + #[test] + fn dns_names_are_accepted_without_resolution() { + let raw = with_group("db01.interno.exemplo.org", ""); + let (_, report) = XexeuConfig::load_validated(&raw).expect("config is valid"); + + assert_eq!(report.groups[0].addresses, 0); + assert_eq!(report.groups[0].names, 1); + } + + #[test] + fn scope_rejects_dns_names() { + let raw = r#" +[escopo] +autorizado = ["db01.interno.exemplo.org"] + +[perfis.padrao] + +[[grupo]] +nome = "teste" +alvos = ["10.0.0.0/24"] +"#; + let config = XexeuConfig::from_toml_str(raw).expect("config parses"); + assert!(matches!( + config.validate(), + Err(ConfigError::InvalidScope { .. }) + )); + } + + #[test] + fn group_inherits_defaults_and_overrides_them() { + let raw = with_group("10.0.0.0/24", ""); + let (config, _) = XexeuConfig::load_validated(&raw).expect("config is valid"); + + let group = &config.groups[0]; + assert_eq!(group.effective_cron(&config), "@daily"); + assert_eq!(group.effective_profile(&config), "padrao"); + } + + #[test] + fn exclusion_inside_scope_is_valid() { + let raw = with_group("10.0.0.0/24", "excluir = [\"10.0.0.128/25\"]"); + let (_, report) = XexeuConfig::load_validated(&raw).expect("config is valid"); + assert_eq!(report.groups[0].addresses, 128); + } +} diff --git a/crates/xexeu-core/src/scan/discovery.rs b/crates/xexeu-core/src/scan/discovery.rs index 5b4377d..7793962 100644 --- a/crates/xexeu-core/src/scan/discovery.rs +++ b/crates/xexeu-core/src/scan/discovery.rs @@ -1,2 +1,213 @@ -//! Host discovery via ARP on the local L2 segment, ICMP echo and TCP SYN/ACK ping. -// TODO: implement host discovery for the native engine. +//! Host discovery engine in degraded `nativo-sem-raw` mode (TCP connect probes). +//! +//! # Determinism Guarantee +//! +//! Host discovery output is strictly deterministic given identical network conditions: +//! - Results are always returned sorted by IP address ascending. +//! - A host is classified as [`HostState::Alive`] as soon as any probed port responds +//! (either connection established or active connection refusal / TCP RST). +//! - A host is classified as [`HostState::Unresponsive`] only if all probed ports +//! time out or yield network unreachability errors. +//! +//! **Important:** Timeouts and concurrency limits are the only sources of potential +//! variation across executions (e.g. temporary packet drops on congested paths +//! causing timeouts before RST/SYN-ACK is received). Appropriate timeout margins +//! prevent Nmap-like discovery flapping. +//! +//! // TODO(NET_RAW): varredura SYN half-open, ver design.md seção 3 + +use super::ports::{scan_port_tcp_connect, PortState}; +use std::net::IpAddr; +use std::sync::Arc; +use std::time::Duration; +use tokio::sync::Semaphore; + +/// State of a discovered host. +#[derive( + Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, +)] +pub enum HostState { + /// Host responded on at least one probed port (SYN-ACK or RST). + Alive, + /// Host did not respond on any probed port within the timeout window. + Unresponsive, +} + +/// Result of probing a single host for presence. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +pub struct HostDiscoveryResult { + /// Target IP address. + pub ip: IpAddr, + /// Whether the host is confirmed alive or unresponsive. + pub state: HostState, + /// The first port that confirmed the host is alive (if any). + pub responded_port: Option, +} + +/// Default ports probed for TCP connect host discovery when ICMP/ARP is unavailable. +pub const DEFAULT_DISCOVERY_PORTS: &[u16] = &[80, 443, 22, 445, 3389]; + +/// Configuration options for host discovery. +#[derive(Debug, Clone)] +pub struct DiscoveryConfig { + /// Ports probed to verify whether a host is active. + pub ports: Vec, + /// Connection timeout per port probe. + pub timeout: Duration, + /// Maximum number of hosts evaluated concurrently (`hosts_simultaneos`). + pub max_concurrency: usize, +} + +impl Default for DiscoveryConfig { + fn default() -> Self { + Self { + ports: DEFAULT_DISCOVERY_PORTS.to_vec(), + timeout: Duration::from_millis(500), + max_concurrency: 64, + } + } +} + +/// Checks whether a single IP address is alive by probing candidate TCP ports. +/// +/// In `nativo-sem-raw` mode without `NET_RAW`, we cannot send ICMP echo or ARP requests. +/// Instead, we probe common ports via TCP connect. An `Open` or `Closed` (RST) response +/// indicates that the host's network stack is actively processing packets. +/// +/// // TODO(NET_RAW): varredura SYN half-open, ver design.md seção 3 +pub async fn probe_host_tcp(ip: IpAddr, config: &DiscoveryConfig) -> HostDiscoveryResult { + for &port in &config.ports { + let state = scan_port_tcp_connect(ip, port, config.timeout).await; + match state { + PortState::Open | PortState::Closed => { + return HostDiscoveryResult { + ip, + state: HostState::Alive, + responded_port: Some(port), + }; + } + PortState::Filtered => continue, + } + } + + HostDiscoveryResult { + ip, + state: HostState::Unresponsive, + responded_port: None, + } +} + +/// Discovers active hosts across a slice of IP addresses. +/// +/// Execution is parallelized up to `config.max_concurrency` (`hosts_simultaneos`). +/// Results are always returned in deterministic ascending order of IP addresses. +pub async fn discover_hosts_tcp( + hosts: &[IpAddr], + config: &DiscoveryConfig, +) -> Vec { + if hosts.is_empty() { + return Vec::new(); + } + + let mut unique_hosts = hosts.to_vec(); + unique_hosts.sort_unstable(); + unique_hosts.dedup(); + + let semaphore = Arc::new(Semaphore::new(config.max_concurrency.max(1))); + let mut handles = Vec::with_capacity(unique_hosts.len()); + + for ip in unique_hosts { + let sem = Arc::clone(&semaphore); + let cfg = config.clone(); + handles.push(tokio::spawn(async move { + let _permit = sem.acquire().await.ok(); + probe_host_tcp(ip, &cfg).await + })); + } + + let mut results = Vec::with_capacity(handles.len()); + for handle in handles { + if let Ok(res) = handle.await { + results.push(res); + } + } + + // Deterministic ordering: always sort by IP ascending + results.sort_by_key(|r| r.ip); + results +} + +#[cfg(test)] +mod tests { + use super::*; + use std::net::Ipv4Addr; + use tokio::net::TcpListener; + + #[tokio::test] + async fn test_discover_host_alive_on_open_port() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + + let _server = tokio::spawn(async move { + let _ = listener.accept().await; + }); + + let config = DiscoveryConfig { + ports: vec![port], + timeout: Duration::from_millis(500), + max_concurrency: 2, + }; + + let ip = IpAddr::V4(Ipv4Addr::LOCALHOST); + let result = probe_host_tcp(ip, &config).await; + + assert_eq!(result.state, HostState::Alive); + assert_eq!(result.responded_port, Some(port)); + } + + #[tokio::test] + async fn test_discover_host_alive_on_closed_rst_port() { + // Ephemeral port bound and immediately dropped -> closed port on localhost (RST) + let dummy = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let closed_port = dummy.local_addr().unwrap().port(); + drop(dummy); + + let config = DiscoveryConfig { + ports: vec![closed_port], + timeout: Duration::from_millis(500), + max_concurrency: 2, + }; + + let ip = IpAddr::V4(Ipv4Addr::LOCALHOST); + let result = probe_host_tcp(ip, &config).await; + + // Receiving RST confirms the host network stack is active + assert_eq!(result.state, HostState::Alive); + assert_eq!(result.responded_port, Some(closed_port)); + } + + #[tokio::test] + async fn test_discover_hosts_unresponsive_and_deterministic_order() { + // 192.0.2.1 and 192.0.2.2 are reserved documentation IPs (TEST-NET-1) + // With a tiny timeout, they should time out and count as Unresponsive. + let ip_a = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 2)); + let ip_b = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)); + + let config = DiscoveryConfig { + ports: vec![80], + timeout: Duration::from_millis(50), + max_concurrency: 2, + }; + + // Pass out of order + let results = discover_hosts_tcp(&[ip_a, ip_b], &config).await; + + assert_eq!(results.len(), 2); + // Verify deterministic sorting: ip_b (192.0.2.1) < ip_a (192.0.2.2) + assert_eq!(results[0].ip, ip_b); + assert_eq!(results[1].ip, ip_a); + assert_eq!(results[0].state, HostState::Unresponsive); + assert_eq!(results[1].state, HostState::Unresponsive); + assert_eq!(results[0].responded_port, None); + } +} diff --git a/crates/xexeu-core/src/scan/mod.rs b/crates/xexeu-core/src/scan/mod.rs index 4550d1a..289a32a 100644 --- a/crates/xexeu-core/src/scan/mod.rs +++ b/crates/xexeu-core/src/scan/mod.rs @@ -1,6 +1,39 @@ //! Scan engine: host discovery, port scanning, service fingerprinting and the optional nmap adapter. +//! +//! # Scanning Modes +//! +//! According to Section 3 of `design.md`: +//! - `nativo`: The primary mode, requiring `NET_RAW` capability. Performs ARP/ICMP discovery, +//! stateless TCP SYN half-open scans, UDP protocol probes, and banner grabbing. +//! - `nativo-sem-raw`: The documented degraded mode implemented here. Operates entirely in +//! unprivileged user-space with zero capabilities. It uses standard TCP connect sockets for +//! both discovery and port scanning. +//! - `nmap`: Optional secondary mode leveraging an external `nmap` process inside the +//! specialized `xexeu-scanner-nmap` container variant. +//! +//! # Determinism Guarantee +//! +//! In contrast to traditional Nmap runs which often present flapping or non-reproducible +//! outputs under variable load, Xexéu enforces deterministic guarantees: +//! - All host discovery and port scan results are strictly sorted (by IP address ascending, +//! and then by port number ascending) before returning. +//! - **Timeouts and network concurrency limits are the only sources of potential variation +//! between runs.** When a network link experiences severe packet loss, packets may be dropped +//! and time out, temporarily classifying an open or closed port as `Filtered`. Proper timeout +//! tuning and pacing prevent this variance. +//! +//! // TODO(NET_RAW): varredura SYN half-open, ver design.md seção 3 pub mod discovery; pub mod fingerprint; pub mod nmap; pub mod ports; + +pub use discovery::{ + discover_hosts_tcp, probe_host_tcp, DiscoveryConfig, HostDiscoveryResult, HostState, + DEFAULT_DISCOVERY_PORTS, +}; +pub use ports::{ + scan_hosts_tcp_connect, scan_port_tcp_connect, scan_tcp_connect, HostPortScanResult, + PortScanConfig, PortScanResult, PortState, PortTarget, TOP_1000_PORTS, +}; diff --git a/crates/xexeu-core/src/scan/ports.rs b/crates/xexeu-core/src/scan/ports.rs index 1c2dd9e..d5afdd9 100644 --- a/crates/xexeu-core/src/scan/ports.rs +++ b/crates/xexeu-core/src/scan/ports.rs @@ -1,2 +1,383 @@ -//! TCP SYN half-open scanning, degraded TCP connect mode and UDP probes per protocol. -// TODO: implement TCP SYN, TCP connect and UDP port scanning. +//! TCP port scanning engine in degraded `nativo-sem-raw` mode (TCP connect). +//! +//! # Determinism Guarantee +//! +//! Given the same target environment and network conditions, scans produce +//! identical results with deterministic ordering: +//! - Results for a host are always sorted by port number ascending. +//! - Multi-host results are always sorted by IP address ascending. +//! +//! **Important:** Timeouts and network concurrency limits are the only sources of +//! potential variation across executions (e.g. dropped packets on congested links +//! causing a port to be classified as `Filtered` instead of `Closed`). To avoid +//! the intermittent instability common in Nmap, timeouts should be tuned with +//! appropriate margin for network latency. +//! +//! // TODO(NET_RAW): varredura SYN half-open, ver design.md seção 3 + +use std::net::{IpAddr, SocketAddr}; +use std::sync::Arc; +use std::time::Duration; +use tokio::net::TcpStream; +use tokio::sync::Semaphore; + +/// State of a probed TCP port. +#[derive( + Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, +)] +pub enum PortState { + /// Port is open and accepted a TCP connection (SYN-ACK received). + Open, + /// Port is closed and explicitly rejected the connection (RST received / connection refused). + Closed, + /// Port is filtered or unresponsive (timeout, packet dropped, or ICMP unreachable). + Filtered, +} + +/// Target port specification. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PortTarget { + /// Explicit list of port numbers. + List(Vec), + /// Inclusive range of ports (e.g. 1-1024 or 1-65535). + Range(u16, u16), + /// Top 1000 commonly used TCP ports. + Top1000, +} + +impl PortTarget { + /// Parses a port specification string such as: + /// - `"top-1000"` or `"top1000"` + /// - `"1-1024"`, `"1-65535"` + /// - `"80,443,8080"` + pub fn parse(spec: &str) -> Result { + let trimmed = spec.trim(); + if trimmed.eq_ignore_ascii_case("top-1000") || trimmed.eq_ignore_ascii_case("top1000") { + return Ok(PortTarget::Top1000); + } + + if !trimmed.contains(',') { + if let Some((start_s, end_s)) = trimmed.split_once('-') { + let start: u16 = start_s + .trim() + .parse() + .map_err(|e| format!("invalid range start in '{trimmed}': {e}"))?; + let end: u16 = end_s + .trim() + .parse() + .map_err(|e| format!("invalid range end in '{trimmed}': {e}"))?; + if start == 0 || start > end { + return Err(format!( + "invalid port range '{trimmed}': start must be >= 1 and <= end" + )); + } + return Ok(PortTarget::Range(start, end)); + } + } + + let mut ports = Vec::new(); + for part in trimmed.split(',') { + let part = part.trim(); + if part.is_empty() { + continue; + } + if let Some((s, e)) = part.split_once('-') { + let start: u16 = s + .trim() + .parse() + .map_err(|err| format!("invalid port range start '{s}': {err}"))?; + let end: u16 = e + .trim() + .parse() + .map_err(|err| format!("invalid port range end '{e}': {err}"))?; + if start == 0 || start > end { + return Err(format!("invalid port range '{s}-{e}'")); + } + for p in start..=end { + ports.push(p); + } + } else { + let p: u16 = part + .parse() + .map_err(|err| format!("invalid port number '{part}': {err}"))?; + if p == 0 { + return Err("port number 0 is reserved and invalid".into()); + } + ports.push(p); + } + } + + if ports.is_empty() { + return Err("no valid ports specified".into()); + } + + ports.sort_unstable(); + ports.dedup(); + Ok(PortTarget::List(ports)) + } + + /// Resolves the specification into a deduplicated, sorted list of port numbers. + pub fn to_ports(&self) -> Vec { + match self { + PortTarget::List(ports) => { + let mut p = ports.clone(); + p.sort_unstable(); + p.dedup(); + p + } + PortTarget::Range(start, end) => (*start..=*end).collect(), + PortTarget::Top1000 => TOP_1000_PORTS.to_vec(), + } + } +} + +/// Result of probing a single port on a host. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +pub struct PortScanResult { + pub port: u16, + pub state: PortState, +} + +/// Result of scanning all specified ports on a host. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +pub struct HostPortScanResult { + pub ip: IpAddr, + pub ports: Vec, +} + +/// Configuration options for port scanning. +#[derive(Debug, Clone)] +pub struct PortScanConfig { + /// Connection timeout per port probe. + pub timeout: Duration, + /// Maximum number of concurrent in-flight connections. + pub max_concurrency: usize, +} + +impl Default for PortScanConfig { + fn default() -> Self { + Self { + timeout: Duration::from_millis(1500), + max_concurrency: 64, + } + } +} + +/// Probes a single TCP port using TCP connect (`nativo-sem-raw`). +/// +/// // TODO(NET_RAW): varredura SYN half-open, ver design.md seção 3 +pub async fn scan_port_tcp_connect(ip: IpAddr, port: u16, timeout_duration: Duration) -> PortState { + let addr = SocketAddr::new(ip, port); + match tokio::time::timeout(timeout_duration, TcpStream::connect(addr)).await { + Ok(Ok(stream)) => { + drop(stream); + PortState::Open + } + Ok(Err(err)) => match err.kind() { + std::io::ErrorKind::ConnectionRefused | std::io::ErrorKind::ConnectionReset => { + PortState::Closed + } + std::io::ErrorKind::TimedOut => PortState::Filtered, + _ => PortState::Filtered, + }, + Err(_elapsed) => PortState::Filtered, + } +} + +/// Scans a slice of ports on a target IP address using TCP connect mode. +/// +/// Results are always returned in deterministic ascending order of port numbers. +pub async fn scan_tcp_connect( + target: IpAddr, + ports: &[u16], + config: &PortScanConfig, +) -> Vec { + if ports.is_empty() { + return Vec::new(); + } + + let mut unique_ports = ports.to_vec(); + unique_ports.sort_unstable(); + unique_ports.dedup(); + + let semaphore = Arc::new(Semaphore::new(config.max_concurrency.max(1))); + let mut handles = Vec::with_capacity(unique_ports.len()); + + for port in unique_ports { + let sem = Arc::clone(&semaphore); + let timeout = config.timeout; + handles.push(tokio::spawn(async move { + let _permit = sem.acquire().await.ok(); + let state = scan_port_tcp_connect(target, port, timeout).await; + PortScanResult { port, state } + })); + } + + let mut results = Vec::with_capacity(handles.len()); + for handle in handles { + if let Ok(res) = handle.await { + results.push(res); + } + } + + // Deterministic ordering: always sort by port ascending + results.sort_by_key(|r| r.port); + results +} + +/// Scans multiple hosts across the specified port list. +/// +/// Results are returned in deterministic order: sorted by IP address ascending, +/// with each host's ports sorted by port number ascending. +pub async fn scan_hosts_tcp_connect( + hosts: &[IpAddr], + ports: &[u16], + config: &PortScanConfig, +) -> Vec { + if hosts.is_empty() { + return Vec::new(); + } + + let mut sorted_hosts = hosts.to_vec(); + sorted_hosts.sort_unstable(); + sorted_hosts.dedup(); + + let mut results = Vec::with_capacity(sorted_hosts.len()); + for ip in sorted_hosts { + let port_results = scan_tcp_connect(ip, ports, config).await; + results.push(HostPortScanResult { + ip, + ports: port_results, + }); + } + + results +} + +/// Static preset of 1000 commonly audited TCP ports (sorted ascending). +/// +/// Contains well-known ports (1..=950) plus standard application service ports +/// (e.g. 1433, 1521, 3306, 3389, 5432, 6379, 8080, 8443, 27017). +pub static TOP_1000_PORTS: [u16; 1000] = { + // Generate 1..=950 and 50 well-known high service ports + let high: [u16; 50] = [ + 1080, 1194, 1433, 1434, 1521, 1723, 1883, 2049, 2082, 2083, 2086, 2087, 2181, 2222, 2375, + 2376, 3000, 3128, 3306, 3389, 4369, 5000, 5432, 5672, 5900, 5901, 5984, 5985, 5986, 6379, + 6667, 7000, 7001, 8000, 8008, 8080, 8081, 8443, 8500, 8888, 9000, 9042, 9090, 9092, 9200, + 9300, 9418, 9999, 11211, 27017, + ]; + let mut arr = [0u16; 1000]; + let mut i = 0; + while i < 950 { + arr[i] = (i + 1) as u16; + i += 1; + } + let mut j = 0; + while j < 50 { + arr[950 + j] = high[j]; + j += 1; + } + arr +}; + +#[cfg(test)] +mod tests { + use super::*; + use std::net::Ipv4Addr; + use tokio::net::TcpListener; + + #[test] + fn test_top_1000_ports_length_and_ordering() { + assert_eq!(TOP_1000_PORTS.len(), 1000); + assert_eq!(TOP_1000_PORTS[0], 1); + assert_eq!(TOP_1000_PORTS[949], 950); + assert_eq!(TOP_1000_PORTS[999], 27017); + // Ensure strictly sorted + for window in TOP_1000_PORTS.windows(2) { + assert!(window[0] < window[1]); + } + } + + #[test] + fn test_port_target_parsing() { + let t1 = PortTarget::parse("top-1000").expect("valid"); + assert_eq!(t1, PortTarget::Top1000); + assert_eq!(t1.to_ports().len(), 1000); + + let t2 = PortTarget::parse("1-100").expect("valid"); + assert_eq!(t2, PortTarget::Range(1, 100)); + assert_eq!(t2.to_ports().len(), 100); + + let t3 = PortTarget::parse("80, 443, 8080, 80").expect("valid"); + assert_eq!(t3.to_ports(), vec![80, 443, 8080]); + + let t4 = PortTarget::parse("22, 100-103").expect("valid"); + assert_eq!(t4.to_ports(), vec![22, 100, 101, 102, 103]); + + assert!(PortTarget::parse("0").is_err()); + assert!(PortTarget::parse("500-100").is_err()); + assert!(PortTarget::parse("abc").is_err()); + } + + #[tokio::test] + async fn test_ports_tcp_connect_open_and_closed() { + // Bind an ephemeral listener to simulate an open port + let listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind ephemeral listener"); + let open_port = listener.local_addr().unwrap().port(); + + // Spawn a background task to accept connections so the port remains Open + let server_handle = tokio::spawn(async move { + if let Ok((stream, _)) = listener.accept().await { + drop(stream); + } + }); + + // Find an unused/closed port on 127.0.0.1 + let dummy = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let closed_port = dummy.local_addr().unwrap().port(); + drop(dummy); // dropping immediately closes the port + + let config = PortScanConfig { + timeout: Duration::from_millis(1000), + max_concurrency: 4, + }; + + let target = IpAddr::V4(Ipv4Addr::LOCALHOST); + // Pass out of order to verify sorting + let scan_results = scan_tcp_connect(target, &[closed_port, open_port], &config).await; + + assert_eq!(scan_results.len(), 2); + // Verify deterministic sorting by port ascending + assert!(scan_results[0].port < scan_results[1].port); + + let open_res = scan_results.iter().find(|r| r.port == open_port).unwrap(); + let closed_res = scan_results.iter().find(|r| r.port == closed_port).unwrap(); + + assert_eq!(open_res.state, PortState::Open); + assert_eq!(closed_res.state, PortState::Closed); + + server_handle.abort(); + } + + #[tokio::test] + async fn test_scan_hosts_tcp_connect_deterministic_order() { + let ip1 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)); + let ip2 = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); + + let config = PortScanConfig { + timeout: Duration::from_millis(50), + max_concurrency: 2, + }; + + // Pass IPs out of order: [127.0.0.2, 127.0.0.1] + let results = scan_hosts_tcp_connect(&[ip1, ip2], &[80, 443], &config).await; + + assert_eq!(results.len(), 2); + assert_eq!(results[0].ip, ip2); + assert_eq!(results[1].ip, ip1); + assert_eq!(results[0].ports[0].port, 80); + assert_eq!(results[0].ports[1].port, 443); + } +} diff --git a/crates/xexeu-core/src/schedule.rs b/crates/xexeu-core/src/schedule.rs index c0c26be..485b9ae 100644 --- a/crates/xexeu-core/src/schedule.rs +++ b/crates/xexeu-core/src/schedule.rs @@ -1,2 +1,510 @@ -//! Group scheduler: next run from cron, jitter, non-overlap and the shared global rate budget. -// TODO: implement cron parsing, next-run calculation and budget-aware ordering. +//! Group scheduler: next run from cron, jitter, non-overlap and deterministic ordering. + +use std::str::FromStr; + +use chrono::{DateTime, Duration, Utc}; +use croner::Cron; +use thiserror::Error; + +use crate::config::{GroupConfig, XexeuConfig}; + +/// Maximum number of jittered occurrences inspected before falling back to the raw cron slot. +const MAX_JITTER_ATTEMPTS: usize = 16; + +/// Errors raised while parsing cron expressions, jitter or computing upcoming runs. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum ScheduleError { + /// The expression is not a valid cron pattern. + #[error("expressão cron inválida `{expr}`: {reason}")] + InvalidCron { + /// Original expression supplied in the configuration. + expr: String, + /// Human-readable reason reported by the cron parser. + reason: String, + }, + /// The cron parser could not produce a future occurrence. + #[error("não foi possível calcular a próxima execução de `{expr}`: {reason}")] + NoNextRun { + /// Original expression supplied in the configuration. + expr: String, + /// Human-readable reason reported by the cron parser. + reason: String, + }, + /// The jitter setting is not a percentage between 0 and 100. + #[error("jitter inválido `{raw}`: use um percentual entre 0% e 100%")] + InvalidJitter { + /// Raw jitter value supplied in the configuration. + raw: String, + }, +} + +/// A validated cron expression that understands the common `@macro` aliases. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CronSpec { + expression: String, + cron: Cron, +} + +impl CronSpec { + /// Parses a five-field cron expression or one of the `@hourly`, `@daily`, `@weekly`, + /// `@monthly` and `@yearly` aliases. + pub fn parse(expression: &str) -> Result { + let raw = expression.trim(); + if raw.is_empty() { + return Err(ScheduleError::InvalidCron { + expr: String::new(), + reason: "expressão vazia".to_string(), + }); + } + + let normalized = normalize_macros(raw); + let cron = Cron::from_str(normalized).map_err(|error| ScheduleError::InvalidCron { + expr: raw.to_string(), + reason: error.to_string(), + })?; + + Ok(Self { + expression: raw.to_string(), + cron, + }) + } + + /// Original expression, before macro expansion. + pub fn expression(&self) -> &str { + &self.expression + } + + /// First occurrence strictly after `after`. + pub fn next_after(&self, after: DateTime) -> Result, ScheduleError> { + self.cron + .find_next_occurrence(&after, false) + .map_err(|error| ScheduleError::NoNextRun { + expr: self.expression.clone(), + reason: error.to_string(), + }) + } + + /// Seconds between the next two occurrences at or after `after`. + pub fn interval_after(&self, after: DateTime) -> Result { + let first = self.next_after(after)?; + let second = self.next_after(first)?; + Ok((second - first).num_seconds()) + } +} + +/// Deterministic jitter, expressed as a percentage of the cron interval. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Jitter { + percent: u32, +} + +impl Jitter { + /// Parses values such as `10%` or `10`. + pub fn parse(raw: &str) -> Result { + let trimmed = raw.trim(); + let digits = trimmed.strip_suffix('%').unwrap_or(trimmed); + let percent = digits + .parse::() + .map_err(|_| ScheduleError::InvalidJitter { + raw: raw.to_string(), + })?; + + if percent > 100 { + return Err(ScheduleError::InvalidJitter { + raw: raw.to_string(), + }); + } + + Ok(Self { percent }) + } + + /// Configured percentage. + pub fn percent(&self) -> u32 { + self.percent + } + + /// Offset in seconds for one occurrence. + /// + /// The offset is stable for the same group, time slot and percentage, so restarts never + /// resynchronise every group on the same second. + pub fn offset_secs(&self, group: &str, slot: DateTime, interval_secs: i64) -> i64 { + if self.percent == 0 || interval_secs <= 0 { + return 0; + } + + let bucket = fnv1a(group.as_bytes()) ^ slot.timestamp() as u64; + let unit = i128::from(bucket % 2001) - 1000; + let offset = i128::from(interval_secs) * i128::from(self.percent) * unit / 100_000; + offset as i64 + } +} + +/// One upcoming execution for a group. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GroupSchedule { + /// Group name. + pub group: String, + /// Effective cron expression, including the inherited default. + pub cron: String, + /// Next execution after the reference instant. + pub next_run: DateTime, +} + +/// What happened during the last execution of a group. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct RunHistory { + /// When the last run started, if it ever ran. + pub last_started: Option>, + /// When the last run finished, if it ever finished. + pub last_finished: Option>, + /// Whether a run is still in progress. + pub running: bool, +} + +/// Whether a group may run now, must wait for its slot, or is held back by a previous run. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RunDecision { + /// The group is due and no run is in progress. + Run, + /// The group is due but a previous run is still in progress. + Deferred { + /// Slot that triggered the decision. + due_at: DateTime, + }, + /// The group is not due yet. + Wait { + /// Next slot for this group. + due_at: DateTime, + }, +} + +/// Next jittered execution for a group, clamped to `now` so it can be displayed. +pub fn next_run_at( + spec: &CronSpec, + jitter: Jitter, + group: &str, + now: DateTime, +) -> Result, ScheduleError> { + let mut slot = spec.next_after(now)?; + + for _ in 0..MAX_JITTER_ATTEMPTS { + let candidate = jittered_occurrence(spec, jitter, group, slot)?; + if candidate >= now { + return Ok(candidate); + } + slot = spec.next_after(slot)?; + } + + Ok(slot) +} + +/// Upcoming execution for every configured group, in configuration order. +pub fn next_runs( + config: &XexeuConfig, + now: DateTime, +) -> Result, ScheduleError> { + let jitter = Jitter::parse(&config.defaults.jitter)?; + let mut schedules = Vec::with_capacity(config.groups.len()); + + for group in &config.groups { + let expression = group.effective_cron(config); + let spec = CronSpec::parse(expression)?; + schedules.push(GroupSchedule { + group: group.name.clone(), + cron: expression.to_string(), + next_run: next_run_at(&spec, jitter, &group.name, now)?, + }); + } + + Ok(schedules) +} + +/// Decides whether `group` may run, honouring the cron slot, jitter and non-overlap. +/// +/// A group without history is due immediately. +pub fn should_run_now( + group: &GroupConfig, + config: &XexeuConfig, + now: DateTime, + history: &RunHistory, +) -> Result { + let spec = CronSpec::parse(group.effective_cron(config))?; + let jitter = Jitter::parse(&config.defaults.jitter)?; + + let due_at = match history.last_started { + Some(last_started) => { + let slot = spec.next_after(last_started)?; + jittered_occurrence(&spec, jitter, &group.name, slot)? + } + None => now, + }; + + let decision = if now >= due_at { + if history.running { + RunDecision::Deferred { due_at } + } else { + RunDecision::Run + } + } else { + RunDecision::Wait { due_at } + }; + + Ok(decision) +} + +fn jittered_occurrence( + spec: &CronSpec, + jitter: Jitter, + group: &str, + slot: DateTime, +) -> Result, ScheduleError> { + let following = spec.next_after(slot)?; + let interval_secs = (following - slot).num_seconds(); + Ok(slot + Duration::seconds(jitter.offset_secs(group, slot, interval_secs))) +} + +fn normalize_macros(expression: &str) -> &str { + match expression { + "@hourly" => "0 * * * *", + "@daily" | "@midnight" => "0 0 * * *", + "@weekly" => "0 0 * * 0", + "@monthly" => "0 0 1 * *", + "@yearly" | "@annually" => "0 0 1 1 *", + other => other, + } +} + +fn fnv1a(bytes: &[u8]) -> u64 { + let mut hash = 0xcbf2_9ce4_8422_2325_u64; + for byte in bytes { + hash ^= u64::from(*byte); + hash = hash.wrapping_mul(0x0000_0100_0000_01b3); + } + hash +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::TimeZone; + + fn at(year: i32, month: u32, day: u32, hour: u32, minute: u32) -> DateTime { + Utc.with_ymd_and_hms(year, month, day, hour, minute, 0) + .single() + .expect("valid test instant") + } + + fn group_config() -> XexeuConfig { + const RAW: &str = r#" +[escopo] +autorizado = ["10.0.0.0/8"] + +[padrao] +cron = "*/5 * * * *" + +[perfis.padrao] + +[[grupo]] +nome = "nucleo" +alvos = ["10.0.1.0/24"] +"#; + XexeuConfig::from_toml_str(RAW).expect("test config parses") + } + + #[test] + fn daily_macro_runs_at_midnight() { + let spec = CronSpec::parse("@daily").expect("macro parses"); + let next = spec + .next_after(at(2026, 3, 10, 15, 30)) + .expect("next run exists"); + assert_eq!(next, at(2026, 3, 11, 0, 0)); + } + + #[test] + fn other_macros_are_normalized() { + let now = at(2026, 3, 10, 15, 30); + + let hourly = CronSpec::parse("@hourly").expect("hourly parses"); + assert_eq!(hourly.next_after(now).unwrap(), at(2026, 3, 10, 16, 0)); + + let weekly = CronSpec::parse("@weekly").expect("weekly parses"); + assert_eq!(weekly.next_after(now).unwrap(), at(2026, 3, 15, 0, 0)); + + let monthly = CronSpec::parse("@monthly").expect("monthly parses"); + assert_eq!(monthly.next_after(now).unwrap(), at(2026, 4, 1, 0, 0)); + + let yearly = CronSpec::parse("@yearly").expect("yearly parses"); + assert_eq!(yearly.next_after(now).unwrap(), at(2027, 1, 1, 0, 0)); + } + + #[test] + fn five_field_expression_is_strictly_after_reference() { + let spec = CronSpec::parse("*/5 * * * *").expect("expression parses"); + assert_eq!( + spec.next_after(at(2026, 5, 1, 12, 5)).unwrap(), + at(2026, 5, 1, 12, 10) + ); + assert_eq!(spec.interval_after(at(2026, 5, 1, 12, 5)).unwrap(), 300); + } + + #[test] + fn invalid_expressions_are_reported() { + assert!(matches!( + CronSpec::parse(""), + Err(ScheduleError::InvalidCron { .. }) + )); + assert!(matches!( + CronSpec::parse("não é cron"), + Err(ScheduleError::InvalidCron { .. }) + )); + assert!(matches!( + CronSpec::parse("1 2 3"), + Err(ScheduleError::InvalidCron { .. }) + )); + } + + #[test] + fn jitter_is_deterministic_and_bounded() { + let jitter = Jitter::parse("10%").expect("jitter parses"); + let slot = at(2026, 5, 1, 0, 0); + + let offset = jitter.offset_secs("nucleo", slot, 300); + assert_eq!(offset, jitter.offset_secs("nucleo", slot, 300)); + assert!(offset.unsigned_abs() <= 30, "offset {offset}"); + + for group in ["corporativa", "dmz", "nucleo", "nucleo-completo"] { + let offset = jitter.offset_secs(group, slot, 60); + assert!(offset.unsigned_abs() <= 6, "offset {offset} for {group}"); + } + } + + #[test] + fn zero_jitter_does_not_move_the_slot() { + let jitter = Jitter::parse("0%").expect("jitter parses"); + assert_eq!(jitter.offset_secs("nucleo", at(2026, 5, 1, 0, 0), 300), 0); + } + + #[test] + fn jitter_rejects_invalid_percentages() { + assert!(matches!( + Jitter::parse("101%"), + Err(ScheduleError::InvalidJitter { .. }) + )); + assert!(matches!( + Jitter::parse("muito"), + Err(ScheduleError::InvalidJitter { .. }) + )); + } + + #[test] + fn next_run_is_never_before_now() { + let spec = CronSpec::parse("*/5 * * * *").expect("expression parses"); + let jitter = Jitter::parse("10%").expect("jitter parses"); + let now = at(2026, 5, 1, 12, 3); + + let next = next_run_at(&spec, jitter, "nucleo", now).expect("next run exists"); + assert!(next >= now, "next {next} before now {now}"); + assert!(next <= at(2026, 5, 1, 12, 5) + Duration::seconds(30)); + } + + #[test] + fn next_runs_lists_every_group_in_order() { + const RAW: &str = r#" +[escopo] +autorizado = ["10.0.0.0/8"] + +[padrao] +cron = "@daily" + +[perfis.padrao] + +[[grupo]] +nome = "corporativa" +alvos = ["10.0.0.0/16"] + +[[grupo]] +nome = "nucleo" +alvos = ["10.0.1.0/24"] +cron = "0 3 * * *" +"#; + let config = XexeuConfig::from_toml_str(RAW).expect("test config parses"); + let now = at(2026, 5, 1, 12, 0); + + let schedules = next_runs(&config, now).expect("schedules compute"); + assert_eq!(schedules.len(), 2); + assert_eq!(schedules[0].group, "corporativa"); + assert_eq!(schedules[0].cron, "@daily"); + assert_eq!(schedules[0].next_run, at(2026, 5, 2, 0, 0)); + assert_eq!(schedules[1].cron, "0 3 * * *"); + assert_eq!(schedules[1].next_run, at(2026, 5, 2, 3, 0)); + } + + #[test] + fn first_run_is_immediate() { + let config = group_config(); + let now = at(2026, 5, 1, 12, 3); + + let decision = should_run_now(&config.groups[0], &config, now, &RunHistory::default()) + .expect("decision computes"); + + assert_eq!(decision, RunDecision::Run); + } + + #[test] + fn overdue_group_runs_when_idle() { + let config = group_config(); + let now = at(2026, 5, 1, 12, 10); + let history = RunHistory { + last_started: Some(now - Duration::minutes(10)), + last_finished: Some(now - Duration::minutes(9)), + running: false, + }; + + let decision = + should_run_now(&config.groups[0], &config, now, &history).expect("decision computes"); + + assert_eq!(decision, RunDecision::Run); + } + + #[test] + fn running_group_is_deferred_instead_of_overlapping() { + let config = group_config(); + let now = at(2026, 5, 1, 12, 10); + let history = RunHistory { + last_started: Some(now - Duration::minutes(10)), + last_finished: None, + running: true, + }; + + let decision = + should_run_now(&config.groups[0], &config, now, &history).expect("decision computes"); + + assert_eq!( + decision, + RunDecision::Deferred { + due_at: at(2026, 5, 1, 12, 5) + } + ); + } + + #[test] + fn recent_group_waits_for_the_next_slot() { + let config = group_config(); + let now = at(2026, 5, 1, 12, 1); + let history = RunHistory { + last_started: Some(now), + last_finished: Some(now), + running: false, + }; + + let decision = + should_run_now(&config.groups[0], &config, now, &history).expect("decision computes"); + + assert_eq!( + decision, + RunDecision::Wait { + due_at: at(2026, 5, 1, 12, 5) + } + ); + } +} diff --git a/crates/xexeu-core/src/targets.rs b/crates/xexeu-core/src/targets.rs index 8709387..35db472 100644 --- a/crates/xexeu-core/src/targets.rs +++ b/crates/xexeu-core/src/targets.rs @@ -1,2 +1,859 @@ -//! Expands targets (CIDR, ranges, DNS names), applies exclusions and derives the effective cadence per host. -// TODO: implement target expansion, exclusions and per-host cadence calculation. +//! Expands targets (CIDR, ranges, DNS names), applies exclusions and derives the effective +//! cadence per host. + +use std::fmt; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, ToSocketAddrs}; +use std::str::FromStr; + +use chrono::{DateTime, Utc}; +use ipnet::IpNet; +use thiserror::Error; + +use crate::config::{GroupConfig, XexeuConfig}; +use crate::schedule::{self, CronSpec, Jitter, ScheduleError}; + +/// Largest IPv6 prefix accepted for a target; anything wider must list addresses explicitly. +pub const MAX_IPV6_TARGET_PREFIX: u8 = 112; + +/// Errors raised while parsing, expanding or filtering targets. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum TargetError { + /// The target string is empty. + #[error("alvo vazio")] + Empty, + /// The target is neither a CIDR, an IP range, an IP address nor a valid DNS name. + #[error("alvo inválido `{target}`: {reason}")] + InvalidTarget { + /// Original target string. + target: String, + /// What is wrong with it. + reason: String, + }, + /// The two ends of a range belong to different address families. + #[error("faixa `{target}` mistura IPv4 e IPv6")] + MixedFamilies { + /// Original target string. + target: String, + }, + /// The range starts after it ends. + #[error("faixa `{target}` tem início maior que o fim")] + InvertedRange { + /// Original target string. + target: String, + }, + /// The IPv6 prefix is too wide to enumerate safely. + #[error( + "prefixo IPv6 /{prefix} em `{target}` passa do limite /112; liste os endereços explicitamente" + )] + Ipv6PrefixTooLarge { + /// Original target string. + target: String, + /// Prefix length supplied. + prefix: u8, + }, + /// A DNS name was used where only static ranges make sense. + #[error("exclusão `{target}` não pode ser um nome DNS")] + NameExclusion { + /// Original target string. + target: String, + }, +} + +/// Error returned when a host cadence cannot be derived. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum CadenceError { + /// Target expansion failed. + #[error(transparent)] + Target(#[from] TargetError), + /// Cron evaluation failed. + #[error(transparent)] + Schedule(#[from] ScheduleError), +} + +/// One target entry, before expansion. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TargetSpec { + /// A CIDR block. + Network(IpNet), + /// An inclusive address range. + Range(IpRange), + /// A DNS name, resolved only at scan time. + Name(String), +} + +impl TargetSpec { + /// Returns the static addresses represented by this target, if any. + pub fn range(&self) -> Option { + match self { + Self::Network(network) => Some(IpRange::from(*network)), + Self::Range(range) => Some(*range), + Self::Name(_) => None, + } + } + + /// Returns the DNS name, if this target needs runtime resolution. + pub fn name(&self) -> Option<&str> { + match self { + Self::Name(name) => Some(name), + _ => None, + } + } +} + +/// Parses CIDR, `start-end`, a single IP address or a DNS name. +pub fn parse_target(raw: &str) -> Result { + let target = raw.trim(); + if target.is_empty() { + return Err(TargetError::Empty); + } + + if let Ok(network) = IpNet::from_str(target) { + if let IpNet::V6(ipv6) = network { + if ipv6.prefix_len() < MAX_IPV6_TARGET_PREFIX { + return Err(TargetError::Ipv6PrefixTooLarge { + target: target.to_string(), + prefix: ipv6.prefix_len(), + }); + } + } + return Ok(TargetSpec::Network(network)); + } + + if let Some((left, right)) = target.split_once('-') { + if let (Ok(start), Ok(end)) = ( + left.trim().parse::(), + right.trim().parse::(), + ) { + return IpRange::checked(target.to_string(), start, end).map(TargetSpec::Range); + } + } + + if let Ok(address) = IpAddr::from_str(target) { + return Ok(TargetSpec::Range(IpRange::single(address))); + } + + if is_valid_name(target) { + return Ok(TargetSpec::Name(target.to_string())); + } + + Err(TargetError::InvalidTarget { + target: target.to_string(), + reason: "use CIDR, faixa IP, endereço IP ou nome DNS válido".to_string(), + }) +} + +/// Parses an exclusion, which must be a static range: names cannot be subtracted offline. +pub fn parse_exclusion(raw: &str) -> Result { + let target = raw.trim(); + if target.is_empty() { + return Err(TargetError::Empty); + } + + if target.split_once('-').is_some() { + if let TargetSpec::Range(range) = parse_target(target)? { + return Ok(range); + } + } + + if let Ok(network) = IpNet::from_str(target) { + return Ok(IpRange::from(network)); + } + + if let Ok(address) = IpAddr::from_str(target) { + return Ok(IpRange::single(address)); + } + + if is_valid_name(target) { + return Err(TargetError::NameExclusion { + target: target.to_string(), + }); + } + + Err(TargetError::InvalidTarget { + target: target.to_string(), + reason: "use CIDR, faixa IP ou endereço IP".to_string(), + }) +} + +/// Parses one authorized scope entry; only static ranges are accepted. +pub fn parse_scope_entry(raw: &str) -> Result { + let entry = raw.trim(); + if entry.is_empty() { + return Err(TargetError::Empty); + } + + if let Ok(network) = IpNet::from_str(entry) { + return Ok(IpRange::from(network)); + } + + if let Ok(address) = IpAddr::from_str(entry) { + return Ok(IpRange::single(address)); + } + + Err(TargetError::InvalidTarget { + target: entry.to_string(), + reason: "escopo aceita apenas CIDR ou endereço IP".to_string(), + }) +} + +/// Parses and merges every authorized scope entry. +pub fn scope_ranges(entries: &[String]) -> Result, TargetError> { + let mut ranges = Vec::with_capacity(entries.len()); + for entry in entries { + ranges.push(parse_scope_entry(entry)?); + } + Ok(merge_ranges(ranges)) +} + +/// Expands a group into static ranges and unresolved DNS names. +pub fn expand_group(group: &GroupConfig) -> Result { + let mut ranges = Vec::new(); + let mut names = Vec::new(); + + for raw in &group.targets { + match parse_target(raw)? { + TargetSpec::Network(network) => ranges.push(IpRange::from(network)), + TargetSpec::Range(range) => ranges.push(range), + TargetSpec::Name(name) => names.push(name), + } + } + + let mut exclusions = Vec::with_capacity(group.exclude.len()); + for raw in &group.exclude { + exclusions.push(parse_exclusion(raw)?); + } + + let (ranges, names) = expand_parts(ranges, names, &exclusions); + Ok(GroupExpansion { + group: group.name.clone(), + ranges, + names, + }) +} + +/// Expands raw target and exclusion strings without a group context. +pub fn expand_specs( + targets: &[String], + exclusions: &[String], +) -> Result { + let mut ranges = Vec::new(); + let mut names = Vec::new(); + + for raw in targets { + match parse_target(raw)? { + TargetSpec::Network(network) => ranges.push(IpRange::from(network)), + TargetSpec::Range(range) => ranges.push(range), + TargetSpec::Name(name) => names.push(name), + } + } + + let mut excluded = Vec::with_capacity(exclusions.len()); + for raw in exclusions { + excluded.push(parse_exclusion(raw)?); + } + + let (ranges, names) = expand_parts(ranges, names, &excluded); + Ok(GroupExpansion { + group: String::new(), + ranges, + names, + }) +} + +/// Result of expanding a group. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct GroupExpansion { + /// Group name, empty when the expansion came from loose strings. + pub group: String, + ranges: Vec, + names: Vec, +} + +impl GroupExpansion { + /// Static ranges after exclusions, sorted and merged. + pub fn ranges(&self) -> &[IpRange] { + &self.ranges + } + + /// DNS names that still need runtime resolution, sorted and deduplicated. + pub fn names(&self) -> &[String] { + &self.names + } + + /// Total number of static addresses. + pub fn address_count(&self) -> u128 { + self.ranges + .iter() + .fold(0_u128, |total, range| total.saturating_add(range.count())) + } + + /// Whether a static address belongs to this expansion. + pub fn contains(&self, address: IpAddr) -> bool { + self.ranges.iter().any(|range| range.contains(address)) + } + + /// Iterates over the static addresses in ascending order. + pub fn ips(&self) -> impl Iterator + '_ { + self.ranges.iter().flat_map(IpRange::iter) + } +} + +/// Inclusive range of addresses from one family. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct IpRange { + start: IpAddr, + end: IpAddr, +} + +impl IpRange { + /// Builds a range, rejecting mixed families and inverted bounds. + pub fn new(start: IpAddr, end: IpAddr) -> Result { + Self::checked(format!("{start}-{end}"), start, end) + } + + /// Single-address range. + pub fn single(address: IpAddr) -> Self { + Self { + start: address, + end: address, + } + } + + /// First address of the range. + pub fn start(&self) -> IpAddr { + self.start + } + + /// Last address of the range. + pub fn end(&self) -> IpAddr { + self.end + } + + /// Number of addresses in the range. + pub fn count(&self) -> u128 { + self.end_value() - self.start_value() + 1 + } + + /// Whether `address` falls inside the range. + pub fn contains(&self, address: IpAddr) -> bool { + if self.family() != Family::of(address) { + return false; + } + let value = value_of(address); + value >= self.start_value() && value <= self.end_value() + } + + /// Removes `other` from this range, returning the remaining fragments. + pub fn subtract(&self, other: &Self) -> Vec { + if self.family() != other.family() { + return vec![*self]; + } + + let (start, end) = (self.start_value(), self.end_value()); + let (other_start, other_end) = (other.start_value(), other.end_value()); + + if other_end < start || other_start > end { + return vec![*self]; + } + + let family = self.family(); + let mut fragments = Vec::with_capacity(2); + if other_start > start { + fragments.push(Self::from_values(family, start, other_start - 1)); + } + if other_end < end { + fragments.push(Self::from_values(family, other_end + 1, end)); + } + fragments + } + + /// Iterates over the addresses in ascending order. + pub fn iter(&self) -> IpRangeIter { + IpRangeIter { + next: Some(self.start_value()), + end: self.end_value(), + family: self.family(), + } + } + + fn checked(target: String, start: IpAddr, end: IpAddr) -> Result { + let start_family = Family::of(start); + let end_family = Family::of(end); + + if start_family != end_family { + return Err(TargetError::MixedFamilies { target }); + } + if value_of(start) > value_of(end) { + return Err(TargetError::InvertedRange { target }); + } + + Ok(Self { start, end }) + } + + fn from_values(family: Family, start: u128, end: u128) -> Self { + debug_assert!(start <= end); + Self { + start: address_from(family, start), + end: address_from(family, end), + } + } + + fn start_value(&self) -> u128 { + value_of(self.start) + } + + fn end_value(&self) -> u128 { + value_of(self.end) + } + + fn family(&self) -> Family { + Family::of(self.start) + } +} + +impl From for IpRange { + fn from(network: IpNet) -> Self { + Self { + start: network.network(), + end: network.broadcast(), + } + } +} + +impl fmt::Display for IpRange { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(formatter, "{}-{}", self.start, self.end) + } +} + +/// Iterator over an [`IpRange`]. +pub struct IpRangeIter { + next: Option, + end: u128, + family: Family, +} + +impl Iterator for IpRangeIter { + type Item = IpAddr; + + fn next(&mut self) -> Option { + let current = self.next?; + if current > self.end { + self.next = None; + return None; + } + self.next = current.checked_add(1); + Some(address_from(self.family, current)) + } +} + +/// What remains of `target` after subtracting the whole scope, if anything. +pub fn covered_by_scope(scope: &[IpRange], target: IpRange) -> bool { + let mut remaining = vec![target]; + for chunk in scope { + let mut fragments = Vec::new(); + for piece in remaining { + fragments.extend(piece.subtract(chunk)); + } + remaining = fragments; + if remaining.is_empty() { + return true; + } + } + remaining.is_empty() +} + +/// Merges overlapping or adjacent ranges of the same family. +pub fn merge_ranges(mut ranges: Vec) -> Vec { + ranges.sort_by(|left, right| { + (left.family().rank(), left.start_value()) + .cmp(&(right.family().rank(), right.start_value())) + }); + + let mut merged: Vec = Vec::with_capacity(ranges.len()); + for range in ranges { + if let Some(last) = merged.last_mut() { + if last.family() == range.family() + && range.start_value() <= last.end_value().saturating_add(1) + { + if range.end_value() > last.end_value() { + *last = + IpRange::from_values(last.family(), last.start_value(), range.end_value()); + } + continue; + } + } + merged.push(range); + } + + merged +} + +/// Resolves a DNS name into its current addresses, sorted and deduplicated. +pub fn resolve_name(name: &str) -> std::io::Result> { + let mut addresses: Vec = (name, 0_u16) + .to_socket_addrs()? + .map(|socket| socket.ip()) + .collect(); + addresses.sort(); + addresses.dedup(); + Ok(addresses) +} + +/// Splits resolved addresses into those inside and outside the authorized scope. +pub fn filter_in_scope(scope: &[IpRange], addresses: &[IpAddr]) -> (Vec, Vec) { + let mut inside = Vec::new(); + let mut outside = Vec::new(); + + for address in addresses { + if scope.iter().any(|range| range.contains(*address)) { + inside.push(*address); + } else { + outside.push(*address); + } + } + + (inside, outside) +} + +/// Cadence that actually applies to one host. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HostCadence { + /// Address inspected. + pub address: IpAddr, + /// Every group whose expansion contains the address, in configuration order. + pub groups: Vec, + /// Group that wins the most-frequent rule. + pub effective_group: String, + /// Next execution of the winning group. + pub next_run: DateTime, + /// Seconds between consecutive executions of the winning group. + pub interval_secs: i64, +} + +/// Derives the effective cadence for `address`, or `None` when no group contains it. +/// +/// The most frequent group wins; ties go to the earliest run and then to the group name. +pub fn effective_cadence( + config: &XexeuConfig, + address: IpAddr, + now: DateTime, +) -> Result, CadenceError> { + let jitter = Jitter::parse(&config.defaults.jitter)?; + let mut groups = Vec::new(); + let mut winner: Option<(i64, DateTime, String)> = None; + + for group in &config.groups { + let expansion = expand_group(group)?; + if !expansion.contains(address) { + continue; + } + + groups.push(group.name.clone()); + + let spec = CronSpec::parse(group.effective_cron(config))?; + let interval = spec.interval_after(now)?; + let next_run = schedule::next_run_at(&spec, jitter, &group.name, now)?; + let candidate = (interval, next_run, group.name.clone()); + + if winner + .as_ref() + .is_none_or(|current| candidate_wins(&candidate, current)) + { + winner = Some(candidate); + } + } + + let Some((interval_secs, next_run, effective_group)) = winner else { + return Ok(None); + }; + + Ok(Some(HostCadence { + address, + groups, + effective_group, + next_run, + interval_secs, + })) +} + +fn candidate_wins( + candidate: &(i64, DateTime, String), + current: &(i64, DateTime, String), +) -> bool { + candidate.0 < current.0 + || (candidate.0 == current.0 && candidate.1 < current.1) + || (candidate.0 == current.0 && candidate.1 == current.1 && candidate.2 < current.2) +} + +fn expand_parts( + mut ranges: Vec, + mut names: Vec, + exclusions: &[IpRange], +) -> (Vec, Vec) { + for exclusion in exclusions { + let mut fragments = Vec::new(); + for range in ranges { + fragments.extend(range.subtract(exclusion)); + } + ranges = fragments; + } + + names.sort(); + names.dedup(); + + (merge_ranges(ranges), names) +} + +fn is_valid_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 253 + && !name.starts_with('.') + && !name.ends_with('.') + && name.chars().all(|character| { + character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_') + }) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Family { + V4, + V6, +} + +impl Family { + fn of(address: IpAddr) -> Self { + match address { + IpAddr::V4(_) => Self::V4, + IpAddr::V6(_) => Self::V6, + } + } + + fn rank(self) -> u8 { + match self { + Self::V4 => 0, + Self::V6 => 1, + } + } +} + +fn value_of(address: IpAddr) -> u128 { + match address { + IpAddr::V4(ipv4) => u128::from(u32::from(ipv4)), + IpAddr::V6(ipv6) => u128::from(ipv6), + } +} + +fn address_from(family: Family, value: u128) -> IpAddr { + match family { + Family::V4 => IpAddr::V4(Ipv4Addr::from(value as u32)), + Family::V6 => IpAddr::V6(Ipv6Addr::from(value)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::GroupConfig; + + fn net(cidr: &str) -> IpRange { + IpRange::from(cidr.parse::().expect("valid test CIDR")) + } + + fn address(raw: &str) -> IpAddr { + raw.parse().expect("valid test address") + } + + fn group_with(targets: &[&str], exclude: &[&str]) -> GroupConfig { + GroupConfig { + name: "teste".to_string(), + targets: targets.iter().map(|value| (*value).to_string()).collect(), + exclude: exclude.iter().map(|value| (*value).to_string()).collect(), + ..GroupConfig::default() + } + } + + #[test] + fn parses_the_supported_target_forms() { + assert!(matches!( + parse_target("10.0.0.0/16"), + Ok(TargetSpec::Network(_)) + )); + + let single = parse_target("10.0.0.1").expect("ip parses"); + assert_eq!(single.range().map(|range| range.count()), Some(1)); + + let range = parse_target("10.0.0.10-10.0.0.20").expect("range parses"); + assert_eq!(range.range().map(|range| range.count()), Some(11)); + + let name = parse_target("db01.interno.exemplo.org").expect("name parses"); + assert_eq!(name.name(), Some("db01.interno.exemplo.org")); + } + + #[test] + fn rejects_empty_and_malformed_targets() { + assert!(matches!(parse_target(""), Err(TargetError::Empty))); + assert!(matches!( + parse_target("alvo com espaço"), + Err(TargetError::InvalidTarget { .. }) + )); + assert!(matches!( + parse_target("10.0.0.1-2001:db8::1"), + Err(TargetError::MixedFamilies { .. }) + )); + assert!(matches!( + parse_target("10.0.0.20-10.0.0.10"), + Err(TargetError::InvertedRange { .. }) + )); + } + + #[test] + fn rejects_wide_ipv6_targets_but_allows_wide_scope() { + assert!(matches!( + parse_target("2001:db8::/64"), + Err(TargetError::Ipv6PrefixTooLarge { prefix: 64, .. }) + )); + assert!(parse_target("2001:db8::/112").is_ok()); + assert!(parse_scope_entry("2001:db8::/48").is_ok()); + } + + #[test] + fn exclusions_cannot_be_names() { + assert!(matches!( + parse_exclusion("db01.interno.exemplo.org"), + Err(TargetError::NameExclusion { .. }) + )); + } + + #[test] + fn expansion_subtracts_exclusions() { + let expansion = + expand_group(&group_with(&["10.0.0.0/24"], &["10.0.0.128/25"])).expect("group expands"); + + assert_eq!(expansion.address_count(), 128); + assert_eq!(expansion.ranges().len(), 1); + assert!(expansion.contains(address("10.0.0.1"))); + assert!(!expansion.contains(address("10.0.0.200"))); + } + + #[test] + fn expansion_merges_overlapping_and_adjacent_ranges() { + let expansion = expand_group(&group_with( + &["10.0.0.0/16", "10.0.1.10", "10.0.1.10-10.0.1.20"], + &[], + )) + .expect("group expands"); + + assert_eq!(expansion.ranges().len(), 1); + assert_eq!(expansion.address_count(), 65_536); + } + + #[test] + fn expansion_keeps_names_separate() { + let expansion = expand_group(&group_with( + &[ + "10.0.0.0/30", + "db01.interno.exemplo.org", + "db01.interno.exemplo.org", + ], + &[], + )) + .expect("group expands"); + + assert_eq!(expansion.address_count(), 4); + assert_eq!(expansion.names(), ["db01.interno.exemplo.org"]); + } + + #[test] + fn subtract_handles_edges_and_middles() { + let range = net("10.0.0.0/24"); + + let left = range.subtract(&net("10.0.0.0/26")); + assert_eq!(left.len(), 1); + assert_eq!(left[0].start(), address("10.0.0.64")); + + let middle = + range.subtract(&IpRange::new(address("10.0.0.10"), address("10.0.0.20")).unwrap()); + assert_eq!(middle.len(), 2); + assert_eq!(middle.iter().map(IpRange::count).sum::(), 256 - 11); + + assert_eq!(range.subtract(&net("10.0.1.0/24")), vec![range]); + } + + #[test] + fn scope_coverage_requires_every_address() { + let scope = scope_ranges(&["10.0.0.0/8".to_string()]).expect("scope parses"); + assert!(covered_by_scope(&scope, net("10.1.0.0/16"))); + + let narrow = scope_ranges(&["10.0.0.0/16".to_string()]).expect("scope parses"); + assert!(!covered_by_scope(&narrow, net("10.1.0.0/16"))); + assert!(covered_by_scope(&narrow, net("10.0.0.0/24"))); + } + + #[test] + fn scope_filters_resolved_addresses() { + let scope = scope_ranges(&["10.0.0.0/8".to_string()]).expect("scope parses"); + let addresses = vec![ + address("10.1.2.3"), + address("192.168.1.1"), + address("203.0.113.7"), + ]; + + let (inside, outside) = filter_in_scope(&scope, &addresses); + assert_eq!(inside, vec![address("10.1.2.3")]); + assert_eq!( + outside, + vec![address("192.168.1.1"), address("203.0.113.7")] + ); + } + + #[test] + fn iterates_every_address() { + let range = net("10.0.0.0/30"); + let addresses: Vec<_> = range.iter().map(|ip| ip.to_string()).collect(); + assert_eq!(addresses, ["10.0.0.0", "10.0.0.1", "10.0.0.2", "10.0.0.3"]); + } + + #[test] + fn effective_cadence_prefers_the_most_frequent_group() { + const RAW: &str = r#" +[escopo] +autorizado = ["10.0.0.0/8"] + +[padrao] +cron = "@daily" + +[perfis.padrao] + +[[grupo]] +nome = "corporativa" +alvos = ["10.0.0.0/16"] + +[[grupo]] +nome = "nucleo" +alvos = ["10.0.1.0/24"] +cron = "*/5 * * * *" +"#; + let config = XexeuConfig::from_toml_str(RAW).expect("test config parses"); + let now = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 5, 1, 12, 3, 0) + .single() + .expect("valid instant"); + + let cadence = effective_cadence(&config, address("10.0.1.5"), now) + .expect("cadence computes") + .expect("host belongs to a group"); + assert_eq!(cadence.groups, ["corporativa", "nucleo"]); + assert_eq!(cadence.effective_group, "nucleo"); + assert_eq!(cadence.interval_secs, 300); + + let other = effective_cadence(&config, address("10.0.2.5"), now) + .expect("cadence computes") + .expect("host belongs to a group"); + assert_eq!(other.effective_group, "corporativa"); + assert_eq!(other.interval_secs, 86_400); + + assert!(effective_cadence(&config, address("192.168.1.1"), now) + .expect("cadence computes") + .is_none()); + } +}