From a814e100fb1e990f909997d5bd37cec688294360 Mon Sep 17 00:00:00 2001 From: Lucas Guerra Date: Sun, 1 Nov 2026 23:41:55 -0300 Subject: [PATCH] =?UTF-8?q?Implementa=20batch/storage/diff,=20correla?= =?UTF-8?q?=C3=A7=C3=A3o=20de=20vulnerabilidades=20(CPE/CVE/KEV)=20e=20lig?= =?UTF-8?q?a=20config=20check=20/=20scan=20--once=20na=20CLI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Cargo.lock | 703 ++++++++++++++++- crates/xexeu-cli/Cargo.toml | 8 + crates/xexeu-cli/src/main.rs | 393 +++++++++- crates/xexeu-cli/tests/scan_once.rs | 83 ++ crates/xexeu-core/Cargo.toml | 12 +- crates/xexeu-core/src/batch.rs | 732 ++++++++++++++++- crates/xexeu-core/src/diff.rs | 1038 ++++++++++++++++++++++++- crates/xexeu-core/src/storage.rs | 590 +++++++++++++- crates/xexeu-core/src/vuln/checks.rs | 457 ++++++++++- crates/xexeu-core/src/vuln/feeds.rs | 551 ++++++++++++- crates/xexeu-core/src/vuln/matcher.rs | 557 ++++++++++++- crates/xexeu-core/src/vuln/mod.rs | 12 + 12 files changed, 5093 insertions(+), 43 deletions(-) create mode 100644 crates/xexeu-cli/tests/scan_once.rs diff --git a/Cargo.lock b/Cargo.lock index 6b76f22..2fe9e9d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,20 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "const-random", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + [[package]] name = "android_system_properties" version = "0.1.6" @@ -61,18 +75,134 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "arrow-array" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f3d22a41d3df78b71df0b685af219ae3a94188ab98d6fb29c958eb55c3247f4" +dependencies = [ + "ahash", + "arrow-buffer", + "arrow-data", + "arrow-schema", + "chrono", + "half", + "hashbrown", + "num-complex", + "num-integer", + "num-traits", +] + +[[package]] +name = "arrow-buffer" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7bd46a530bc1a8e763102fc36c1dc0f51f3ffa150c78e7f5658ccb54b1458ade" +dependencies = [ + "bytes", + "half", + "num-bigint", + "num-traits", +] + +[[package]] +name = "arrow-cmp" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1913e57a64fbf2c4502fa6d54b547d6a1ae59e3146cbc15321d47468c937abd1" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-schema", +] + +[[package]] +name = "arrow-data" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "415b7fbc4cf56b080bb5677a4ae74211b5c79e571ed37a1d547633ec07f3b43b" +dependencies = [ + "arrow-buffer", + "arrow-schema", + "half", + "num-integer", + "num-traits", +] + +[[package]] +name = "arrow-ipc" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45f3e766bccf5a0cb57a5de52a4cba450dea5171547c2cb5939b486d08887cba" +dependencies = [ + "arrow-array", + "arrow-buffer", + "arrow-data", + "arrow-schema", + "arrow-select", + "flatbuffers", +] + +[[package]] +name = "arrow-schema" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de2c8e714b466404cdc1189e89f892426efea614d938e16c15518c340cd43ba3" + +[[package]] +name = "arrow-select" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5af3f6656c5f2c6944f93d9a357a7f204c93d5f349385a44cf46c4a26fbcf30" +dependencies = [ + "ahash", + "arrow-array", + "arrow-buffer", + "arrow-cmp", + "arrow-data", + "arrow-schema", + "num-traits", +] + [[package]] name = "autocfg" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "bumpalo" version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + [[package]] name = "cc" version = "1.10.0" @@ -89,6 +219,17 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core", +] + [[package]] name = "chrono" version = "0.4.45" @@ -96,7 +237,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" dependencies = [ "iana-time-zone", + "js-sys", "num-traits", + "serde", + "wasm-bindgen", "windows-link", ] @@ -146,12 +290,50 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "const-random" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359" +dependencies = [ + "const-random-macro", +] + +[[package]] +name = "const-random-macro" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e" +dependencies = [ + "getrandom 0.2.17", + "once_cell", + "tiny-keccak", +] + [[package]] name = "core-foundation-sys" version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "croner" version = "4.0.2" @@ -163,6 +345,22 @@ dependencies = [ "strum", ] +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "darling" version = "0.20.11" @@ -229,24 +427,78 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + [[package]] name = "equivalent" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fallible-streaming-iterator" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + [[package]] name = "find-msvc-tools" version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" +[[package]] +name = "flatbuffers" +version = "25.12.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3" +dependencies = [ + "bitflags", + "rustc_version", +] + [[package]] name = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + [[package]] name = "futures-core" version = "0.3.34" @@ -271,11 +523,80 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "rand_core", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashlink" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb" +dependencies = [ + "hashbrown", +] [[package]] name = "heck" @@ -335,6 +656,12 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + [[package]] name = "js-sys" version = "0.3.107" @@ -352,12 +679,41 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libsqlite3-sys" +version = "0.39.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14a5f01b87b92705d07b433c06f96cbc764637d81a0bffb5734ce17cf0f9a2b3" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "log" version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + [[package]] name = "mio" version = "1.2.4" @@ -369,6 +725,34 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "num-bigint" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -376,20 +760,59 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", + "libm", ] +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + [[package]] name = "once_cell_polyfill" version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "parquet" +version = "60.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "806eaa0f1c0436dcb43bee8e6a82bf2efff90521a60172f8281cb9ef577b43a4" +dependencies = [ + "ahash", + "arrow-array", + "arrow-buffer", + "arrow-data", + "arrow-ipc", + "arrow-schema", + "arrow-select", + "base64", + "bytes", + "chrono", + "half", + "hashbrown", + "num-bigint", + "num-integer", + "num-traits", + "seq-macro", + "snap", + "twox-hash", +] + [[package]] name = "pin-project-lite" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -408,12 +831,99 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rsqlite-vfs" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353b74f9810d5b085b6c42c9d86a5f0fdb795553235cdd48753b32e3809d18a7" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "rusqlite" +version = "0.41.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da9bba6f3506135e120a6586df05be18b48d18896600646a4bec8f993d91a594" +dependencies = [ + "bitflags", + "fallible-iterator", + "fallible-streaming-iterator", + "hashlink", + "libsqlite3-sys", + "smallvec", + "sqlite-wasm-rs", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys", +] + [[package]] name = "rustversion" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "seq-macro" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" + [[package]] name = "serde" version = "1.0.229" @@ -444,6 +954,19 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + [[package]] name = "serde_spanned" version = "1.1.2" @@ -453,6 +976,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + [[package]] name = "shlex" version = "2.0.1" @@ -465,6 +999,18 @@ version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "snap" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "199905e6153d6405f9728fe44daace35f8f837bbf830bb6e85fbd5828709a886" + [[package]] name = "socket2" version = "0.6.5" @@ -475,6 +1021,16 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "sqlite-wasm-rs" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36bd8e29bf08189a005b2df1df99823aa0861cabe9044e5f31ed54ca292ee618" +dependencies = [ + "cc", + "rsqlite-vfs", +] + [[package]] name = "strsim" version = "0.11.1" @@ -524,13 +1080,35 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys", +] + [[package]] name = "thiserror" version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" dependencies = [ - "thiserror-impl", + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", ] [[package]] @@ -544,12 +1122,33 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tiny-keccak" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" +dependencies = [ + "crunchy", +] + [[package]] name = "tokio" version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ + "bytes", "libc", "mio", "pin-project-lite", @@ -608,6 +1207,29 @@ version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "ulid" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "947dde63b6d514cc5e044edad4e0ca7261afd1099d16c83d942cb2b2f348689c" +dependencies = [ + "rand", + "serde", + "web-time", +] + [[package]] name = "unicode-ident" version = "1.0.27" @@ -620,12 +1242,33 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" version = "0.2.130" @@ -670,6 +1313,16 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -744,11 +1397,23 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + [[package]] name = "xexeu-cli" version = "0.1.0" dependencies = [ + "chrono", "clap", + "libc", + "serde", + "serde_json", + "tempfile", + "tokio", "xexeu-core", ] @@ -756,11 +1421,45 @@ dependencies = [ name = "xexeu-core" version = "0.1.0" dependencies = [ + "arrow-array", + "arrow-schema", "chrono", "croner", "ipnet", + "parquet", + "rusqlite", "serde", - "thiserror", + "serde_json", + "sha2", + "tempfile", + "thiserror 1.0.69", "tokio", "toml", + "ulid", ] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/crates/xexeu-cli/Cargo.toml b/crates/xexeu-cli/Cargo.toml index 1547fbc..aa2f566 100644 --- a/crates/xexeu-cli/Cargo.toml +++ b/crates/xexeu-cli/Cargo.toml @@ -14,4 +14,12 @@ path = "src/main.rs" [dependencies] xexeu-core = { path = "../xexeu-core" } +chrono = { version = "0.4", features = ["clock"] } clap = { version = "4", features = ["derive"] } +libc = "0.2" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tokio = { version = "1", features = ["macros", "rt-multi-thread"] } + +[dev-dependencies] +tempfile = "3" diff --git a/crates/xexeu-cli/src/main.rs b/crates/xexeu-cli/src/main.rs index 95a5612..09831b8 100644 --- a/crates/xexeu-cli/src/main.rs +++ b/crates/xexeu-cli/src/main.rs @@ -1,5 +1,24 @@ +use std::collections::{BTreeSet, HashSet}; +use std::fs; +use std::net::IpAddr; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; +use std::time::Duration; + +use chrono::Utc; use clap::{Parser, Subcommand}; -use std::path::PathBuf; +use serde::Serialize; +use xexeu_core::batch::{EngineMode, SweepBatch, SweepManifest, SweepStatus}; +use xexeu_core::config::{ValidationReport, XexeuConfig}; +use xexeu_core::scan::{ + discover_hosts_tcp, scan_hosts_tcp_connect, DiscoveryConfig, HostState, PortScanConfig, + PortState, PortTarget, DEFAULT_DISCOVERY_PORTS, +}; +use xexeu_core::targets::{ + effective_cadence, expand_group, filter_in_scope, resolve_name, scope_ranges, IpRange, +}; + +const DEFAULT_CONFIG: &str = "config/xexeu.toml"; #[derive(Parser)] #[command( @@ -98,37 +117,357 @@ enum FeedsAction { }, } -fn main() { +#[tokio::main] +async fn main() -> ExitCode { let cli = Cli::parse(); match cli.command { - Command::Serve { - bind: _, - config: _, - sweeps: _, - data_dir: _, - } => not_implemented("serve"), - Command::Scanner { config: _, out: _ } => not_implemented("scanner"), Command::Scan { - group: _, - once: _, - config: _, - out: _, - } => not_implemented("scan"), - Command::Config { action: _ } => not_implemented("config"), - Command::Feeds { action: _ } => not_implemented("feeds"), - Command::Changes { - since: _, - data_dir: _, - } => not_implemented("changes"), - Command::Export { - format: _, - data_dir: _, - } => not_implemented("export"), - Command::Doctor { json: _ } => not_implemented("doctor"), + group, + once, + config, + out, + } => match scan_once(group, once, &config, &out).await { + Ok(()) => ExitCode::SUCCESS, + Err(message) => fail(&message), + }, + Command::Config { action } => match action { + ConfigAction::Check { config } => run_config_check(&config), + }, + Command::Doctor { json } => run_doctor(json), + Command::Serve { .. } => not_implemented("serve"), + Command::Scanner { .. } => not_implemented("scanner"), + Command::Feeds { .. } => not_implemented("feeds"), + Command::Changes { .. } => not_implemented("changes"), + Command::Export { .. } => not_implemented("export"), } } -fn not_implemented(command: &str) -> ! { +fn fail(message: &str) -> ExitCode { + eprintln!("{message}"); + ExitCode::FAILURE +} + +fn not_implemented(command: &str) -> ExitCode { eprintln!("{command}: não implementado ainda"); - std::process::exit(1); + ExitCode::FAILURE +} + +fn validated_config(path: &Path) -> Result<(XexeuConfig, ValidationReport), String> { + let raw = fs::read_to_string(path) + .map_err(|error| format!("não foi possível ler {}: {error}", path.display()))?; + XexeuConfig::load_validated(&raw) + .map_err(|error| format!("configuração inválida em {}: {error}", path.display())) +} + +fn run_config_check(path: &Path) -> ExitCode { + let (config, report) = match validated_config(path) { + Ok(loaded) => loaded, + Err(message) => return fail(&message), + }; + + println!("Configuração válida: {}", path.display()); + for group in &report.groups { + println!( + "grupo {}: {} endereço(s), {} nome(s), perfil {}, cron {}", + group.group, group.addresses, group.names, group.profile, group.cron + ); + } + + for warning in &report.warnings { + println!("aviso: grupo {}: {}", warning.group, warning.message); + } + + let now = Utc::now(); + match overlapping_ranges(&config) { + Ok(overlaps) if overlaps.is_empty() => {} + Ok(overlaps) => { + println!("\nSobreposições:"); + for range in overlaps { + match effective_cadence(&config, range.start(), now) { + Ok(Some(cadence)) => println!( + " {} ({} endereço(s)): grupos [{}], efetivo {} a cada {}s, próxima {}", + range, + range.count(), + cadence.groups.join(", "), + cadence.effective_group, + cadence.interval_secs, + cadence.next_run.to_rfc3339() + ), + Ok(None) => println!( + " {} ({} endereço(s)): nenhum grupo cobre a sobreposição", + range, + range.count() + ), + Err(error) => { + println!(" {}: falha ao calcular a cadência efetiva: {error}", range) + } + } + } + } + Err(message) => return fail(&message), + } + + ExitCode::SUCCESS +} + +fn overlapping_ranges(config: &XexeuConfig) -> Result, String> { + let expansions = config + .groups + .iter() + .map(expand_group) + .collect::, _>>() + .map_err(|error| format!("falha ao expandir os grupos: {error}"))?; + + let mut seen = HashSet::new(); + let mut overlaps = Vec::new(); + for (index, left_group) in expansions.iter().enumerate() { + for right_group in expansions.iter().skip(index + 1) { + for left in left_group.ranges() { + for right in right_group.ranges() { + let start = left.start().max(right.start()); + let end = left.end().min(right.end()); + if start > end { + continue; + } + if let Ok(range) = IpRange::new(start, end) { + if seen.insert(range.to_string()) { + overlaps.push(range); + } + } + } + } + } + } + + overlaps.sort_by_key(|range| (range.start().is_ipv6(), ip_value(range.start()))); + Ok(overlaps) +} + +fn ip_value(address: IpAddr) -> u128 { + match address { + IpAddr::V4(ip) => u32::from(ip) as u128, + IpAddr::V6(ip) => u128::from(ip), + } +} + +async fn scan_once( + group: Option, + once: bool, + config_path: &Path, + out: &Path, +) -> Result<(), String> { + if !once { + return Err("varredura contínua pertence ao comando scanner; use --once".to_string()); + } + let name = group.ok_or_else(|| "informe o grupo com --group".to_string())?; + let (config, _report) = validated_config(config_path)?; + let group = config + .group(&name) + .ok_or_else(|| format!("grupo '{name}' não existe na configuração"))?; + let expansion = expand_group(group).map_err(|error| format!("grupo '{name}': {error}"))?; + let scope = + scope_ranges(&config.scope.authorized).map_err(|error| format!("escopo: {error}"))?; + + let mut addresses: BTreeSet = expansion.ips().collect(); + for hostname in expansion.names() { + match resolve_name(hostname) { + Ok(resolved) => { + let (inside, outside) = filter_in_scope(&scope, &resolved); + for address in outside { + eprintln!( + "aviso: {hostname} resolve para {address}, fora do escopo autorizado; ignorado" + ); + } + if inside.is_empty() { + eprintln!( + "aviso: {hostname} não resolve para nenhum endereço dentro do escopo autorizado" + ); + } + addresses.extend(inside); + } + Err(error) => eprintln!("aviso: não foi possível resolver {hostname}: {error}"), + } + } + + if addresses.is_empty() { + return Err("nenhum alvo dentro do escopo autorizado".to_string()); + } + + let profile_name = group.effective_profile(&config); + let profile = config + .profiles + .get(profile_name) + .ok_or_else(|| format!("perfil '{profile_name}' não definido"))?; + if profile.engine != "nativo" && profile.engine != "nativo-sem-raw" { + return Err(format!( + "motor '{}' do perfil '{profile_name}' não implementado; use nativo", + profile.engine + )); + } + let ports = PortTarget::parse(&profile.tcp) + .map_err(|error| format!("perfil '{profile_name}': {error}"))? + .to_ports(); + if ports.is_empty() { + return Err(format!("perfil '{profile_name}' não seleciona portas TCP")); + } + + let targets: Vec = addresses.iter().copied().collect(); + let concurrency = config.defaults.simultaneous_hosts.unwrap_or(16).max(1); + let started_at = Utc::now(); + + let hosts = discover_hosts_tcp( + &targets, + &DiscoveryConfig { + ports: DEFAULT_DISCOVERY_PORTS.to_vec(), + timeout: Duration::from_millis(600), + max_concurrency: concurrency, + }, + ) + .await; + + let alive: Vec = hosts + .iter() + .filter(|host| host.state == HostState::Alive) + .map(|host| host.ip) + .collect(); + + let port_results = if alive.is_empty() { + Vec::new() + } else { + scan_hosts_tcp_connect( + &alive, + &ports, + &PortScanConfig { + timeout: Duration::from_millis(1200), + max_concurrency: concurrency.saturating_mul(4).max(16), + }, + ) + .await + }; + + let mut manifest = SweepManifest::new( + group.name.clone(), + expansion.ranges().iter().map(ToString::to_string).collect(), + profile_name, + EngineMode::NativeWithoutRaw, + started_at, + ); + manifest.finish(SweepStatus::Complete, Utc::now()); + + let batch = SweepBatch::new(manifest, hosts, port_results); + let directory = batch + .write(out) + .map_err(|error| format!("falha ao gravar o lote: {error}"))?; + + println!( + "lote {} (grupo {}, perfil {}) gravado em {}", + batch.manifest.sweep_id, + group.name, + profile_name, + directory.display() + ); + println!("alvos: {}; vivos: {}", targets.len(), alive.len()); + for result in &batch.ports { + let open: Vec = result + .ports + .iter() + .filter(|port| port.state == PortState::Open) + .map(|port| port.port.to_string()) + .collect(); + if !open.is_empty() { + println!(" {}: {}", result.ip, open.join(", ")); + } + } + + Ok(()) +} + +#[derive(Serialize)] +struct DoctorReport { + version: &'static str, + config: DoctorConfig, + root: bool, + net_raw: Option, +} + +#[derive(Serialize)] +struct DoctorConfig { + path: String, + exists: bool, + valid: bool, + error: Option, +} + +fn run_doctor(as_json: bool) -> ExitCode { + let path = Path::new(DEFAULT_CONFIG); + let exists = path.exists(); + let (valid, error) = if exists { + match fs::read_to_string(path) { + Ok(raw) => match XexeuConfig::load_validated(&raw) { + Ok(_) => (true, None), + Err(error) => (false, Some(error.to_string())), + }, + Err(error) => (false, Some(format!("não foi possível ler: {error}"))), + } + } else { + ( + false, + Some("arquivo de configuração não encontrado".to_string()), + ) + }; + + let report = DoctorReport { + version: env!("CARGO_PKG_VERSION"), + config: DoctorConfig { + path: path.display().to_string(), + exists, + valid, + error, + }, + // SAFETY: geteuid takes no arguments, cannot fail and only reads the process identity. + root: unsafe { libc::geteuid() == 0 }, + net_raw: net_raw_capability(), + }; + + if as_json { + match serde_json::to_string_pretty(&report) { + Ok(json) => println!("{json}"), + Err(error) => return fail(&format!("falha ao serializar o diagnóstico: {error}")), + } + return ExitCode::SUCCESS; + } + + println!("xexeu {}", report.version); + match ( + &report.config.error, + report.config.exists, + report.config.valid, + ) { + (_, true, true) => println!("config {}: presente e válida", report.config.path), + (Some(error), true, false) => println!("config {}: inválida: {error}", report.config.path), + (Some(error), false, _) => println!("config {}: {error}", report.config.path), + _ => println!("config {}: inválida", report.config.path), + } + println!("root: {}", yes_no(report.root)); + match report.net_raw { + Some(value) => println!("NET_RAW: {}", yes_no(value)), + None => println!("NET_RAW: desconhecido"), + } + + ExitCode::SUCCESS +} + +fn yes_no(value: bool) -> &'static str { + if value { + "sim" + } else { + "não" + } +} + +fn net_raw_capability() -> Option { + let status = fs::read_to_string("/proc/self/status").ok()?; + let line = status.lines().find(|line| line.starts_with("CapEff:"))?; + let mask = u64::from_str_radix(line.split_whitespace().nth(1)?, 16).ok()?; + Some(mask & (1 << 13) != 0) } diff --git a/crates/xexeu-cli/tests/scan_once.rs b/crates/xexeu-cli/tests/scan_once.rs new file mode 100644 index 0000000..2aacc8a --- /dev/null +++ b/crates/xexeu-cli/tests/scan_once.rs @@ -0,0 +1,83 @@ +use std::fs; +use std::net::TcpListener; +use std::process::Command; + +use tempfile::TempDir; +use xexeu_core::batch::{SweepBatch, SweepStatus}; + +#[test] +fn scan_once_writes_a_complete_batch_with_the_open_port() { + let listener = TcpListener::bind("127.0.0.1:0").expect("bind loopback listener"); + let port = listener.local_addr().expect("listener address").port(); + std::thread::spawn(move || { + for stream in listener.incoming() { + if stream.is_err() { + break; + } + } + }); + + let workspace = TempDir::new().expect("temporary directory"); + let config = workspace.path().join("xexeu.toml"); + fs::write( + &config, + format!( + r#" +[escopo] +autorizado = ["127.0.0.1/32"] +responsavel = "teste" + +[padrao] +cron = "@daily" +hosts_simultaneos = 2 + +[perfis.padrao] +tcp = "{port}" + +[[grupo]] +nome = "local" +alvos = ["127.0.0.1/32"] +"# + ), + ) + .expect("write configuration"); + + let sweeps = workspace.path().join("sweeps"); + let output = Command::new(env!("CARGO_BIN_EXE_xexeu")) + .args([ + "scan", + "--group", + "local", + "--once", + "--config", + config.to_str().expect("config path"), + "--out", + sweeps.to_str().expect("sweeps path"), + ]) + .output() + .expect("run xexeu scan"); + + assert!( + output.status.success(), + "scan failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(stdout.contains("vivos: 1"), "unexpected stdout: {stdout}"); + + let group_dir = sweeps.join("local"); + let sweep_dir = fs::read_dir(&group_dir) + .expect("group directory") + .next() + .expect("one sweep") + .expect("sweep entry") + .path(); + + let batch = SweepBatch::read(&sweep_dir).expect("read batch"); + assert_eq!(batch.manifest.status, SweepStatus::Complete); + assert_eq!(batch.manifest.group, "local"); + assert_eq!(batch.alive_hosts().count(), 1); + + let open: Vec = batch.open_ports("127.0.0.1".parse().expect("ip")).collect(); + assert_eq!(open, vec![port]); +} diff --git a/crates/xexeu-core/Cargo.toml b/crates/xexeu-core/Cargo.toml index ab50b7e..c979bfe 100644 --- a/crates/xexeu-core/Cargo.toml +++ b/crates/xexeu-core/Cargo.toml @@ -9,10 +9,18 @@ authors.workspace = true rust-version.workspace = true [dependencies] -chrono = { version = "0.4", default-features = false, features = ["clock"] } +arrow-array = "60" +arrow-schema = "60" +chrono = { version = "0.4", default-features = false, features = ["clock", "serde"] } croner = "4" ipnet = "2" +parquet = { version = "60", default-features = false, features = ["arrow", "snap"] } +rusqlite = { version = "0.41", features = ["bundled"] } serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha2 = "0.10" +tempfile = "3" thiserror = "1" +ulid = { version = "3", features = ["serde"] } toml = "1" -tokio = { version = "1", features = ["macros", "net", "rt", "rt-multi-thread", "sync", "time"] } +tokio = { version = "1", features = ["io-util", "macros", "net", "rt", "rt-multi-thread", "sync", "time"] } diff --git a/crates/xexeu-core/src/batch.rs b/crates/xexeu-core/src/batch.rs index a7c272d..daa2d9e 100644 --- a/crates/xexeu-core/src/batch.rs +++ b/crates/xexeu-core/src/batch.rs @@ -1,2 +1,730 @@ -//! Sweep batch format: atomically written by the scanner and idempotently read by the server. -// TODO: implement batch writing, manifest handling and idempotent ingestion. +//! Sweep batch format: atomically written by the scanner and read back by the server. +//! +//! A sweep lives in `///` and contains: +//! +//! - `observations.parquet`: one row per probed host and one row per probed port; +//! - `manifest.json`: written **last**, through an atomic rename, so a partially written +//! batch is never mistaken for a complete one. +//! +//! The manifest carries a SHA-256 of the Parquet file, which is verified on read. + +use std::collections::BTreeMap; +use std::fs::{self, File}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; + +use arrow_array::{Array, ArrayRef, RecordBatch, StringArray, UInt16Array}; +use arrow_schema::{DataType, Field, Schema, SchemaRef}; +use chrono::{DateTime, Utc}; +use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder; +use parquet::arrow::ArrowWriter; +use parquet::basic::Compression; +use parquet::file::properties::WriterProperties; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use tempfile::NamedTempFile; +use thiserror::Error; +use ulid::Ulid; + +use crate::scan::{HostDiscoveryResult, HostPortScanResult, HostState, PortScanResult, PortState}; + +/// Name of the observations file inside a sweep directory. +pub const OBSERVATIONS_FILE: &str = "observations.parquet"; +/// Name of the manifest file inside a sweep directory. +pub const MANIFEST_FILE: &str = "manifest.json"; + +const COL_IP: usize = 0; +const COL_HOST_STATE: usize = 1; +const COL_RESPONDED_PORT: usize = 2; +const COL_PORT: usize = 3; +const COL_PORT_STATE: usize = 4; +const COL_PRODUCT: usize = 5; +const COL_VERSION: usize = 6; +const COL_CPE: usize = 7; +const COL_SWEEP_ID: usize = 8; + +/// Engine that produced a sweep. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum EngineMode { + /// Raw-socket engine requiring `NET_RAW`. + #[serde(rename = "nativo")] + Native, + /// Unprivileged TCP-connect engine. + #[serde(rename = "nativo-sem-raw")] + NativeWithoutRaw, + /// Optional nmap adapter. + #[serde(rename = "nmap")] + Nmap, +} + +impl EngineMode { + /// Value stored in the manifest and in human-readable output. + pub fn as_str(&self) -> &'static str { + match self { + Self::Native => "nativo", + Self::NativeWithoutRaw => "nativo-sem-raw", + Self::Nmap => "nmap", + } + } +} + +/// How much of the group was actually covered by a sweep. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum SweepStatus { + /// Every target was probed. + #[serde(rename = "completa")] + Complete, + /// Only part of the targets was probed; never used to infer disappearances. + #[serde(rename = "parcial")] + Partial, + /// The sweep was interrupted. + #[serde(rename = "abortada")] + Aborted, +} + +impl SweepStatus { + /// Value stored in the manifest. + pub fn as_str(&self) -> &'static str { + match self { + Self::Complete => "completa", + Self::Partial => "parcial", + Self::Aborted => "abortada", + } + } +} + +/// Metadata for one sweep, persisted as `manifest.json`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct SweepManifest { + /// Unique sweep identifier. + #[serde(rename = "sweep_id")] + pub sweep_id: Ulid, + /// Group that produced the sweep. + #[serde(rename = "grupo")] + pub group: String, + /// Expanded scope, as `start-end` ranges or CIDRs. + #[serde(rename = "escopo")] + pub scope: Vec, + /// Port profile used. + #[serde(rename = "perfil")] + pub profile: String, + /// Engine mode used. + #[serde(rename = "modo_motor")] + pub engine_mode: EngineMode, + /// When the sweep started. + #[serde(rename = "inicio")] + pub started_at: DateTime, + /// When the sweep finished; `None` while it is still running. + #[serde(rename = "fim")] + pub finished_at: Option>, + /// Coverage status. + #[serde(rename = "status")] + pub status: SweepStatus, + /// Xexéu version that wrote the batch. + #[serde(rename = "versao")] + pub version: String, + /// SHA-256 of `observations.parquet`, filled by [`SweepBatch::write`]. + #[serde(rename = "hash")] + pub content_hash: Option, +} + +impl SweepManifest { + /// Creates a manifest for a sweep that is still in progress. + pub fn new( + group: impl Into, + scope: Vec, + profile: impl Into, + engine_mode: EngineMode, + started_at: DateTime, + ) -> Self { + Self { + sweep_id: Ulid::generate(), + group: group.into(), + scope, + profile: profile.into(), + engine_mode, + started_at, + finished_at: None, + status: SweepStatus::Partial, + version: env!("CARGO_PKG_VERSION").to_string(), + content_hash: None, + } + } + + /// Marks the sweep as finished. + pub fn finish(&mut self, status: SweepStatus, finished_at: DateTime) { + self.status = status; + self.finished_at = Some(finished_at); + } + + /// Whether the sweep covered every target. + pub fn is_complete(&self) -> bool { + self.status == SweepStatus::Complete + } +} + +/// Service attributes observed on an open port. +/// +/// The fingerprinting engine is still a stub, so the scanner leaves this empty today; the +/// fields are already persisted and diffed so the integration needs no format change. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ServiceObservation { + /// Host that owns the port. + pub ip: std::net::IpAddr, + /// Open TCP port. + pub port: u16, + /// Product name, when known. + pub product: Option, + /// Product version, when known. + pub version: Option, + /// CPE identifier, when known. + pub cpe: Option, +} + +/// Everything produced by one sweep. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SweepBatch { + /// Sweep metadata. + pub manifest: SweepManifest, + /// Host discovery results, including unresponsive hosts. + pub hosts: Vec, + /// Port results for the hosts that answered discovery. + pub ports: Vec, + /// Optional service attributes for open ports. + pub services: Vec, +} + +impl SweepBatch { + /// Builds a batch without service attributes. + pub fn new( + manifest: SweepManifest, + hosts: Vec, + ports: Vec, + ) -> Self { + Self { + manifest, + hosts, + ports, + services: Vec::new(), + } + } + + /// Attaches service attributes. + pub fn with_services(mut self, services: Vec) -> Self { + self.services = services; + self + } + + /// Hosts that answered discovery. + pub fn alive_hosts(&self) -> impl Iterator { + self.hosts + .iter() + .filter(|host| host.state == HostState::Alive) + } + + /// Open ports advertised by a host. + pub fn open_ports(&self, ip: std::net::IpAddr) -> impl Iterator + '_ { + self.ports + .iter() + .filter(move |result| result.ip == ip) + .flat_map(|result| result.ports.iter()) + .filter(|port| port.state == PortState::Open) + .map(|port| port.port) + } + + /// Writes the batch atomically under `///` and returns that directory. + /// + /// The Parquet file is moved into place first and the manifest last, so a reader never sees + /// a manifest without its observations. + pub fn write(&self, root: &Path) -> Result { + if self.manifest.finished_at.is_none() { + return Err(BatchError::NotFinished); + } + + let group = safe_component(&self.manifest.group)?; + let directory = root.join(group).join(self.manifest.sweep_id.to_string()); + fs::create_dir_all(&directory)?; + + let batch = self.to_record_batch()?; + let parquet_path = directory.join(OBSERVATIONS_FILE); + + let temporary = NamedTempFile::new_in(&directory)?; + let properties = WriterProperties::builder() + .set_compression(Compression::SNAPPY) + .build(); + let mut writer = ArrowWriter::try_new(temporary.as_file(), schema(), Some(properties))?; + writer.write(&batch)?; + writer.close()?; + + let content_hash = hash_file(temporary.path())?; + temporary + .persist(&parquet_path) + .map_err(|error| error.error)?; + + let mut manifest = self.manifest.clone(); + manifest.content_hash = Some(content_hash); + let json = serde_json::to_vec_pretty(&manifest)?; + + let mut temporary = NamedTempFile::new_in(&directory)?; + temporary.write_all(&json)?; + temporary.as_file().sync_all()?; + temporary + .persist(directory.join(MANIFEST_FILE)) + .map_err(|error| error.error)?; + + Ok(directory) + } + + /// Reads a batch previously written by [`SweepBatch::write`]. + pub fn read(directory: &Path) -> Result { + let manifest_path = directory.join(MANIFEST_FILE); + let manifest: SweepManifest = serde_json::from_slice(&fs::read(&manifest_path)?)?; + + let parquet_path = directory.join(OBSERVATIONS_FILE); + let actual = hash_file(&parquet_path)?; + match manifest.content_hash.as_deref() { + Some(expected) if expected == actual => {} + Some(expected) => { + return Err(BatchError::HashMismatch { + expected: expected.to_string(), + actual, + }); + } + None => { + return Err(BatchError::Corrupt( + "manifesto sem hash de conteúdo".to_string(), + )); + } + } + + let reader = + ParquetRecordBatchReaderBuilder::try_new(File::open(&parquet_path)?)?.build()?; + + let mut hosts = Vec::new(); + let mut port_results: BTreeMap> = BTreeMap::new(); + let mut services = Vec::new(); + + for batch in reader { + let batch = batch?; + let sweep_ids = string_column(&batch, COL_SWEEP_ID)?; + + for row in 0..batch.num_rows() { + let sweep_id = sweep_ids.value(row); + if sweep_id != manifest.sweep_id.to_string() { + return Err(BatchError::Corrupt(format!( + "sweep_id `{sweep_id}` não confere com o manifesto" + ))); + } + + let ip: std::net::IpAddr = string_column(&batch, COL_IP)? + .value(row) + .parse() + .map_err(|error| BatchError::Corrupt(format!("IP inválido: {error}")))?; + + let host_state = optional_string(&batch, COL_HOST_STATE, row); + let port = optional_u16(&batch, COL_PORT, row); + + match (host_state, port) { + (Some(state), None) => { + let responded_port = optional_u16(&batch, COL_RESPONDED_PORT, row); + hosts.push(HostDiscoveryResult { + ip, + state: parse_host_state(&state)?, + responded_port, + }); + } + (None, Some(port)) => { + let state = optional_string(&batch, COL_PORT_STATE, row) + .ok_or_else(|| BatchError::Corrupt("porta sem estado".to_string()))?; + port_results.entry(ip).or_default().push(PortScanResult { + port, + state: parse_port_state(&state)?, + }); + + let product = optional_string(&batch, COL_PRODUCT, row); + let version = optional_string(&batch, COL_VERSION, row); + let cpe = optional_string(&batch, COL_CPE, row); + if product.is_some() || version.is_some() || cpe.is_some() { + services.push(ServiceObservation { + ip, + port, + product, + version, + cpe, + }); + } + } + _ => { + return Err(BatchError::Corrupt(format!( + "linha {row} sem host nem porta" + ))); + } + } + } + } + + let mut ports: Vec = port_results + .into_iter() + .map(|(ip, mut ports)| { + ports.sort_by_key(|port| port.port); + HostPortScanResult { ip, ports } + }) + .collect(); + ports.sort_by_key(|result| result.ip); + hosts.sort_by_key(|host| host.ip); + services.sort_by_key(|left| (left.ip, left.port)); + + Ok(Self { + manifest, + hosts, + ports, + services, + }) + } + + fn to_record_batch(&self) -> Result { + let services: BTreeMap<(std::net::IpAddr, u16), &ServiceObservation> = self + .services + .iter() + .map(|service| ((service.ip, service.port), service)) + .collect(); + + let mut hosts: Vec<&HostDiscoveryResult> = self.hosts.iter().collect(); + hosts.sort_by_key(|host| host.ip); + let mut host_ports: Vec<&HostPortScanResult> = self.ports.iter().collect(); + host_ports.sort_by_key(|result| result.ip); + + let mut ips = Vec::new(); + let mut host_states = Vec::new(); + let mut responded_ports = Vec::new(); + let mut ports = Vec::new(); + let mut port_states = Vec::new(); + let mut products = Vec::new(); + let mut versions = Vec::new(); + let mut cpes = Vec::new(); + let mut sweep_ids = Vec::new(); + let sweep_id = self.manifest.sweep_id.to_string(); + + for host in hosts { + ips.push(host.ip.to_string()); + host_states.push(Some(host_state_str(host.state).to_string())); + responded_ports.push(host.responded_port); + ports.push(None); + port_states.push(None); + products.push(None); + versions.push(None); + cpes.push(None); + sweep_ids.push(sweep_id.clone()); + } + + for result in host_ports { + let mut declared: BTreeMap = BTreeMap::new(); + for port in &result.ports { + declared.insert(port.port, port.state); + } + + for (port, state) in declared { + ips.push(result.ip.to_string()); + host_states.push(None); + responded_ports.push(None); + ports.push(Some(port)); + port_states.push(Some(port_state_str(state).to_string())); + let service = services.get(&(result.ip, port)); + products.push(service.and_then(|service| service.product.clone())); + versions.push(service.and_then(|service| service.version.clone())); + cpes.push(service.and_then(|service| service.cpe.clone())); + sweep_ids.push(sweep_id.clone()); + } + } + + let columns: Vec = vec![ + Arc::new(StringArray::from(ips)), + Arc::new(StringArray::from(host_states)), + Arc::new(UInt16Array::from(responded_ports)), + Arc::new(UInt16Array::from(ports)), + Arc::new(StringArray::from(port_states)), + Arc::new(StringArray::from(products)), + Arc::new(StringArray::from(versions)), + Arc::new(StringArray::from(cpes)), + Arc::new(StringArray::from(sweep_ids)), + ]; + + Ok(RecordBatch::try_new(schema(), columns)?) + } +} + +/// Errors raised while writing or reading a sweep batch. +#[derive(Debug, Error)] +pub enum BatchError { + /// Filesystem failure. + #[error("erro de E/S: {0}")] + Io(#[from] io::Error), + /// Parquet failure. + #[error("erro de Parquet: {0}")] + Parquet(#[from] parquet::errors::ParquetError), + /// Arrow failure. + #[error("erro de Arrow: {0}")] + Arrow(#[from] arrow_schema::ArrowError), + /// JSON failure. + #[error("manifesto inválido: {0}")] + Json(#[from] serde_json::Error), + /// The batch was written before being marked as finished. + #[error("lote não finalizado: marque o status e o fim antes de gravar")] + NotFinished, + /// The group name cannot be used as a directory name. + #[error("grupo inválido para caminho: `{0}`")] + InvalidGroup(String), + /// The manifest hash does not match the observations file. + #[error("hash do lote não confere: esperado {expected}, encontrado {actual}")] + HashMismatch { + /// Hash recorded in the manifest. + expected: String, + /// Hash computed from the file. + actual: String, + }, + /// The observations file is structurally invalid. + #[error("observações corrompidas: {0}")] + Corrupt(String), +} + +fn schema() -> SchemaRef { + Arc::new(Schema::new(vec![ + Field::new("ip", DataType::Utf8, false), + Field::new("host_state", DataType::Utf8, true), + Field::new("responded_port", DataType::UInt16, true), + Field::new("port", DataType::UInt16, true), + Field::new("port_state", DataType::Utf8, true), + Field::new("product", DataType::Utf8, true), + Field::new("version", DataType::Utf8, true), + Field::new("cpe", DataType::Utf8, true), + Field::new("sweep_id", DataType::Utf8, false), + ])) +} + +fn host_state_str(state: HostState) -> &'static str { + match state { + HostState::Alive => "alive", + HostState::Unresponsive => "unresponsive", + } +} + +fn parse_host_state(value: &str) -> Result { + match value { + "alive" => Ok(HostState::Alive), + "unresponsive" => Ok(HostState::Unresponsive), + other => Err(BatchError::Corrupt(format!("estado de host `{other}`"))), + } +} + +fn port_state_str(state: PortState) -> &'static str { + match state { + PortState::Open => "open", + PortState::Closed => "closed", + PortState::Filtered => "filtered", + } +} + +fn parse_port_state(value: &str) -> Result { + match value { + "open" => Ok(PortState::Open), + "closed" => Ok(PortState::Closed), + "filtered" => Ok(PortState::Filtered), + other => Err(BatchError::Corrupt(format!("estado de porta `{other}`"))), + } +} + +fn string_column(batch: &RecordBatch, index: usize) -> Result<&StringArray, BatchError> { + batch + .column(index) + .as_any() + .downcast_ref::() + .ok_or_else(|| BatchError::Corrupt(format!("coluna {index} não é texto"))) +} + +fn optional_string(batch: &RecordBatch, index: usize, row: usize) -> Option { + let array = batch.column(index).as_any().downcast_ref::()?; + if array.is_null(row) { + None + } else { + Some(array.value(row).to_string()) + } +} + +fn optional_u16(batch: &RecordBatch, index: usize, row: usize) -> Option { + let array = batch.column(index).as_any().downcast_ref::()?; + if array.is_null(row) { + None + } else { + Some(array.value(row)) + } +} + +fn safe_component(group: &str) -> Result<&str, BatchError> { + let valid = !group.is_empty() + && group != "." + && group != ".." + && group.chars().all(|character| { + character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.') + }); + + if valid { + Ok(group) + } else { + Err(BatchError::InvalidGroup(group.to_string())) + } +} + +fn hash_file(path: &Path) -> Result { + let mut hasher = Sha256::new(); + let mut file = File::open(path)?; + let mut buffer = [0_u8; 16 * 1024]; + + loop { + let read = io::Read::read(&mut file, &mut buffer)?; + if read == 0 { + break; + } + hasher.update(&buffer[..read]); + } + + Ok(hasher + .finalize() + .iter() + .map(|byte| format!("{byte:02x}")) + .collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::net::{IpAddr, Ipv4Addr}; + use tempfile::tempdir; + + fn now() -> DateTime { + DateTime::from_timestamp(1_700_000_000, 0).expect("valid instant") + } + + fn manifest() -> SweepManifest { + let mut manifest = SweepManifest::new( + "dmz", + vec!["203.0.113.0-203.0.113.255".to_string()], + "padrao", + EngineMode::NativeWithoutRaw, + now(), + ); + manifest.finish(SweepStatus::Complete, now()); + manifest + } + + fn batch() -> SweepBatch { + let alive = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 5)); + let gone = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)); + + SweepBatch::new( + manifest(), + vec![ + HostDiscoveryResult { + ip: alive, + state: HostState::Alive, + responded_port: Some(22), + }, + HostDiscoveryResult { + ip: gone, + state: HostState::Unresponsive, + responded_port: None, + }, + ], + vec![HostPortScanResult { + ip: alive, + ports: vec![ + PortScanResult { + port: 22, + state: PortState::Open, + }, + PortScanResult { + port: 443, + state: PortState::Closed, + }, + ], + }], + ) + .with_services(vec![ServiceObservation { + ip: alive, + port: 22, + product: Some("OpenSSH".to_string()), + version: Some("9.3p1".to_string()), + cpe: Some("cpe:2.3:a:openbsd:openssh:9.3p1".to_string()), + }]) + } + + #[test] + fn round_trips_through_parquet_and_manifest() { + let root = tempdir().expect("temporary directory"); + let original = batch(); + + let directory = original.write(root.path()).expect("batch is written"); + assert!(directory.join(OBSERVATIONS_FILE).exists()); + assert!(directory.join(MANIFEST_FILE).exists()); + + let restored = SweepBatch::read(&directory).expect("batch is read"); + let mut expected = original.clone(); + expected.manifest.content_hash = restored.manifest.content_hash.clone(); + assert_eq!(restored, expected); + assert!(restored.manifest.content_hash.is_some()); + assert_eq!(restored.manifest.status, SweepStatus::Complete); + } + + #[test] + fn write_leaves_no_temporary_files_behind() { + let root = tempdir().expect("temporary directory"); + let directory = batch().write(root.path()).expect("batch is written"); + + let entries: Vec<_> = fs::read_dir(&directory) + .expect("directory is readable") + .map(|entry| entry.expect("entry is readable").file_name()) + .collect(); + assert_eq!(entries.len(), 2, "unexpected files: {entries:?}"); + } + + #[test] + fn unfinished_batch_is_rejected() { + let root = tempdir().expect("temporary directory"); + let mut unfinished = batch(); + unfinished.manifest.finished_at = None; + + assert!(matches!( + unfinished.write(root.path()), + Err(BatchError::NotFinished) + )); + } + + #[test] + fn tampered_observations_are_rejected() { + let root = tempdir().expect("temporary directory"); + let directory = batch().write(root.path()).expect("batch is written"); + + let mut file = fs::OpenOptions::new() + .append(true) + .open(directory.join(OBSERVATIONS_FILE)) + .expect("file is writable"); + file.write_all(b"tampered").expect("file is appended"); + + assert!(matches!( + SweepBatch::read(&directory), + Err(BatchError::HashMismatch { .. }) + )); + } + + #[test] + fn group_name_that_escapes_the_directory_is_rejected() { + let root = tempdir().expect("temporary directory"); + let mut unsafe_batch = batch(); + unsafe_batch.manifest.group = "../fora".to_string(); + + assert!(matches!( + unsafe_batch.write(root.path()), + Err(BatchError::InvalidGroup(_)) + )); + } +} diff --git a/crates/xexeu-core/src/diff.rs b/crates/xexeu-core/src/diff.rs index 71796c8..396e098 100644 --- a/crates/xexeu-core/src/diff.rs +++ b/crates/xexeu-core/src/diff.rs @@ -1,2 +1,1036 @@ -//! Compares a sweep with the current state inside the swept scope and emits deterministic change events. -// TODO: implement the scoped diff algorithm and event ordering. +//! Compares a sweep with the current state inside the swept scope and emits deterministic +//! change events. +//! +//! Rules from Section 6.1 of `design.md`: +//! +//! - Partial or aborted sweeps may produce appearance events, never disappearance events. +//! - A port that was not in the scanned profile is never reported as closed. +//! - Disappearances only happen after `ausencias_para_sumir` consecutive sweeps without a +//! positive observation. +//! - Events are emitted by phase (host, port, service), sorted by asset and port, so the same +//! batch and the same previous state produce the same ordering. +//! +//! The `rede_logica` component of the asset key is the sweep group in this slice. The server can +//! refine it to the smallest containing group when it owns the full configuration. + +use std::collections::BTreeMap; +use std::net::IpAddr; + +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use thiserror::Error; +use ulid::Ulid; + +use crate::batch::{SweepBatch, SweepStatus}; +use crate::scan::{HostState, PortState}; +use crate::targets::{parse_target, IpRange}; + +/// How many consecutive sweeps without a positive observation are needed before an asset or +/// port is considered gone. +pub const DEFAULT_ABSENCES_BEFORE_DISAPPEAR: u32 = 2; + +/// Knobs for the diff algorithm. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DiffOptions { + /// Consecutive unanswered sweeps before a host or port is marked as gone/closed. + pub absences_before_disappear: u32, +} + +impl Default for DiffOptions { + fn default() -> Self { + Self { + absences_before_disappear: DEFAULT_ABSENCES_BEFORE_DISAPPEAR, + } + } +} + +/// Lifecycle of an asset in the current state. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AssetStatus { + /// The asset answered the last sweep that covered it. + Active, + /// The asset missed enough consecutive sweeps to be considered gone. + Gone, +} + +impl AssetStatus { + /// Value stored in SQLite. + pub fn as_str(&self) -> &'static str { + match self { + Self::Active => "ativo", + Self::Gone => "sumido", + } + } +} + +/// Lifecycle of a port in the current state. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PortStatus { + /// The port accepted a connection in the last sweep that covered it. + Open, + /// The port was confirmed closed enough times. + Closed, +} + +impl PortStatus { + /// Value stored in SQLite. + pub fn as_str(&self) -> &'static str { + match self { + Self::Open => "aberta", + Self::Closed => "fechada", + } + } +} + +/// Current state of one port. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ServiceState { + /// Transport protocol; only `tcp` is produced today. + pub protocol: String, + /// Port number. + pub port: u16, + /// Open/closed lifecycle. + pub status: PortStatus, + /// Consecutive sweeps without the port open. + pub absences: u32, + /// First time the port was seen. + pub first_seen: DateTime, + /// Last time the port was seen open. + pub last_seen: DateTime, + /// Observed product. + pub product: Option, + /// Observed version. + pub version: Option, + /// Observed CPE. + pub cpe: Option, +} + +/// Current state of one asset. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AssetState { + /// `(rede_logica, ip)` identity. + pub asset_key: String, + /// Logical network, currently the sweep group. + pub network: String, + /// Address. + pub ip: IpAddr, + /// Active/gone lifecycle. + pub status: AssetStatus, + /// Consecutive sweeps without a response. + pub absences: u32, + /// First time the asset was seen. + pub first_seen: DateTime, + /// Last time the asset answered. + pub last_seen: DateTime, + /// Ports known for this asset, sorted by port. + pub ports: Vec, +} + +/// Deduplicated current state, as stored by [`crate::storage`]. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct CurrentState { + /// Assets sorted by `asset_key`. + pub assets: Vec, +} + +impl CurrentState { + /// Builds a state and sorts the assets by key. + pub fn new(mut assets: Vec) -> Self { + assets.sort_by(|left, right| left.asset_key.cmp(&right.asset_key)); + Self { assets } + } + + /// Looks an asset up by its key. + pub fn find(&self, asset_key: &str) -> Option<&AssetState> { + self.assets + .iter() + .find(|asset| asset.asset_key == asset_key) + } +} + +/// Kind of change detected by the diff. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum EventKind { + /// A host that had never been seen answered. + #[serde(rename = "host_novo")] + HostNew, + /// A host previously marked as gone answered again. + #[serde(rename = "host_voltou")] + HostReturned, + /// A host missed enough consecutive sweeps. + #[serde(rename = "host_sumiu")] + HostDisappeared, + /// A port became open, including a previously closed port that reopened. + #[serde(rename = "porta_nova")] + PortNew, + /// A port missed enough consecutive sweeps. + #[serde(rename = "porta_fechada")] + PortClosed, + /// Product, version or CPE changed on an open port. + #[serde(rename = "servico_alterado")] + ServiceChanged, +} + +impl EventKind { + /// Value stored in SQLite. + pub fn as_str(&self) -> &'static str { + match self { + Self::HostNew => "host_novo", + Self::HostReturned => "host_voltou", + Self::HostDisappeared => "host_sumiu", + Self::PortNew => "porta_nova", + Self::PortClosed => "porta_fechada", + Self::ServiceChanged => "servico_alterado", + } + } + + /// Diff phase used for stable ordering. + fn phase(&self) -> u8 { + match self { + Self::HostNew | Self::HostReturned | Self::HostDisappeared => 0, + Self::PortNew | Self::PortClosed => 1, + Self::ServiceChanged => 2, + } + } +} + +/// Service reference embedded in an event. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct EventService { + /// Transport protocol. + #[serde(rename = "proto")] + pub protocol: String, + /// Port number. + #[serde(rename = "porta")] + pub port: u16, + /// Product, when known. + #[serde(rename = "produto", skip_serializing_if = "Option::is_none")] + pub product: Option, + /// Version, when known. + #[serde(rename = "versao", skip_serializing_if = "Option::is_none")] + pub version: Option, + /// CPE, when known. + #[serde(rename = "cpe", skip_serializing_if = "Option::is_none")] + pub cpe: Option, +} + +/// Append-only change event. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Event { + /// Unique event identifier. + #[serde(rename = "event_id")] + pub event_id: Ulid, + /// Sweep that produced the event. + #[serde(rename = "sweep_id")] + pub sweep_id: Ulid, + /// Group that produced the sweep. + #[serde(rename = "grupo")] + pub group: String, + /// Kind of change. + #[serde(rename = "tipo")] + pub kind: EventKind, + /// `(rede_logica, ip)` identity. + #[serde(rename = "asset_key")] + pub asset_key: String, + /// Port and service affected, for port/service events. + #[serde(rename = "servico", skip_serializing_if = "Option::is_none")] + pub service: Option, + /// State before the change, when applicable. + #[serde(rename = "anterior", skip_serializing_if = "Option::is_none")] + pub previous: Option, + /// State after the change, when applicable. + #[serde(rename = "atual", skip_serializing_if = "Option::is_none")] + pub current: Option, + /// Structured evidence for the event. + #[serde(rename = "evidencia")] + pub evidence: Value, + /// When the change was observed. + #[serde(rename = "ocorrido_em")] + pub occurred_at: DateTime, +} + +/// Next state plus the events that explain the transition. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct DiffResult { + /// Events in deterministic order. + pub events: Vec, + /// State for the assets covered by this sweep. + pub state: Vec, +} + +/// Errors raised while diffing a batch. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum DiffError { + /// The manifest contains an unparsable scope entry. + #[error("escopo do lote inválido em `{entry}`: {reason}")] + InvalidScope { + /// Offending entry. + entry: String, + /// Parser message. + reason: String, + }, +} + +/// Compares a batch with the previous state and returns the events and the next state. +pub fn diff_batch( + previous: &CurrentState, + batch: &SweepBatch, + options: &DiffOptions, +) -> Result { + let scope = swept_ranges(batch)?; + let threshold = options.absences_before_disappear.max(1); + let complete = batch.manifest.status == SweepStatus::Complete; + let occurred_at = batch + .manifest + .finished_at + .unwrap_or(batch.manifest.started_at); + let network = batch.manifest.group.as_str(); + + let previous_by_key: BTreeMap<&str, &AssetState> = previous + .assets + .iter() + .map(|asset| (asset.asset_key.as_str(), asset)) + .collect(); + + let mut next_assets = Vec::new(); + let mut host_events = Vec::new(); + let mut port_events = Vec::new(); + let mut service_events = Vec::new(); + + let mut hosts: Vec<_> = batch.hosts.iter().collect(); + hosts.sort_by_key(|host| host.ip); + + for host in hosts { + if !scope.iter().any(|range| range.contains(host.ip)) { + continue; + } + + let asset_key = format!("{network}/{}", host.ip); + let previous_asset = previous_by_key.get(asset_key.as_str()).copied(); + + match host.state { + HostState::Alive => { + let first_seen = previous_asset + .map(|asset| asset.first_seen) + .unwrap_or(occurred_at); + let mut asset = AssetState { + asset_key: asset_key.clone(), + network: network.to_string(), + ip: host.ip, + status: AssetStatus::Active, + absences: 0, + first_seen, + last_seen: occurred_at, + ports: Vec::new(), + }; + + match previous_asset { + None => host_events.push(event( + batch, + EventKind::HostNew, + &asset_key, + None, + None, + Some(json!({ "estado": "ativo" })), + json!({ "estado": "ativo" }), + occurred_at, + )), + Some(previous) if previous.status == AssetStatus::Gone => { + host_events.push(event( + batch, + EventKind::HostReturned, + &asset_key, + None, + Some(json!({ "estado": "sumido" })), + Some(json!({ "estado": "ativo" })), + json!({ "estado": "ativo" }), + occurred_at, + )); + } + Some(_) => {} + } + + let scanned = scanned_ports(batch, host.ip); + let current_services = current_services(batch, host.ip); + let mut state_ports: BTreeMap = previous_asset + .map(|asset| { + asset + .ports + .iter() + .cloned() + .map(|port| (port.port, port)) + .collect() + }) + .unwrap_or_default(); + + for (port, port_state) in &scanned { + match port_state { + PortState::Open => { + let observed_service = current_services.get(port).copied(); + match state_ports.get_mut(port) { + Some(service) if service.status == PortStatus::Open => { + service.last_seen = occurred_at; + service.absences = 0; + let before = service.clone(); + if apply_service(service, observed_service) { + service_events.push(event( + batch, + EventKind::ServiceChanged, + &asset_key, + Some(event_service(service)), + port_snapshot(&before), + port_snapshot(service), + json!({ "porta": port, "proto": service.protocol }), + occurred_at, + )); + } + } + Some(service) => { + let before = service.clone(); + service.status = PortStatus::Open; + service.absences = 0; + service.last_seen = occurred_at; + apply_service(service, observed_service); + port_events.push(event( + batch, + EventKind::PortNew, + &asset_key, + Some(event_service(service)), + port_snapshot(&before), + port_snapshot(service), + json!({ "porta": port, "proto": service.protocol }), + occurred_at, + )); + } + None => { + let mut service = ServiceState { + protocol: "tcp".to_string(), + port: *port, + status: PortStatus::Open, + absences: 0, + first_seen: occurred_at, + last_seen: occurred_at, + product: None, + version: None, + cpe: None, + }; + apply_service(&mut service, observed_service); + port_events.push(event( + batch, + EventKind::PortNew, + &asset_key, + Some(event_service(&service)), + None, + port_snapshot(&service), + json!({ "porta": port, "proto": "tcp" }), + occurred_at, + )); + state_ports.insert(*port, service); + } + } + } + PortState::Closed if complete => { + if let Some(service) = state_ports.get_mut(port) { + if service.status == PortStatus::Open { + service.absences += 1; + if service.absences >= threshold { + service.status = PortStatus::Closed; + port_events.push(event( + batch, + EventKind::PortClosed, + &asset_key, + Some(event_service(service)), + port_snapshot(service), + Some(json!({ "estado": "fechada" })), + json!({ + "porta": port, + "ausencias": service.absences + }), + occurred_at, + )); + } + } + } + } + _ => {} + } + } + + asset.ports = state_ports.into_values().collect(); + next_assets.push(asset); + } + HostState::Unresponsive => { + if !complete { + if let Some(previous) = previous_asset { + next_assets.push(previous.clone()); + } + continue; + } + + let Some(previous) = previous_asset else { + continue; + }; + + let mut asset = previous.clone(); + if asset.status == AssetStatus::Active { + asset.absences += 1; + if asset.absences >= threshold { + asset.status = AssetStatus::Gone; + host_events.push(event( + batch, + EventKind::HostDisappeared, + &asset_key, + None, + Some(json!({ "estado": "ativo" })), + Some(json!({ "estado": "sumido" })), + json!({ "ausencias": asset.absences }), + occurred_at, + )); + } + } + next_assets.push(asset); + } + } + } + + next_assets.sort_by(|left, right| left.asset_key.cmp(&right.asset_key)); + + host_events.sort_by(|left, right| left.asset_key.cmp(&right.asset_key)); + port_events.sort_by(|left, right| { + let left_port = left.service.as_ref().map(|service| service.port); + let right_port = right.service.as_ref().map(|service| service.port); + left.asset_key + .cmp(&right.asset_key) + .then_with(|| left_port.cmp(&right_port)) + }); + service_events.sort_by(|left, right| { + let left_port = left.service.as_ref().map(|service| service.port); + let right_port = right.service.as_ref().map(|service| service.port); + left.asset_key + .cmp(&right.asset_key) + .then_with(|| left_port.cmp(&right_port)) + }); + + let mut events = + Vec::with_capacity(host_events.len() + port_events.len() + service_events.len()); + events.extend(host_events); + events.extend(port_events); + events.extend(service_events); + + debug_assert!(events + .windows(2) + .all(|pair| pair[0].kind.phase() <= pair[1].kind.phase())); + + Ok(DiffResult { + events, + state: next_assets, + }) +} + +/// Placeholder for vulnerability events. +/// +/// The `vuln::*` module is being implemented in parallel. Once it exposes a `Finding` type, +/// this function should receive `&[Finding]` instead of a generic slice and emit +/// `vulnerabilidade_nova`, `vulnerabilidade_corrigida` and `vulnerabilidade_reaberta`. +// TODO(vuln): replace the generic placeholder with `&[vuln::Finding]`. +pub fn diff_vulnerabilities(_previous: &[T], _current: &[T]) -> Vec { + Vec::new() +} + +fn swept_ranges(batch: &SweepBatch) -> Result, DiffError> { + let mut ranges = Vec::with_capacity(batch.manifest.scope.len()); + + for entry in &batch.manifest.scope { + let parsed = parse_target(entry).map_err(|error| DiffError::InvalidScope { + entry: entry.clone(), + reason: error.to_string(), + })?; + let range = parsed.range().ok_or_else(|| DiffError::InvalidScope { + entry: entry.clone(), + reason: "escopo do lote deve conter apenas faixas estáticas".to_string(), + })?; + ranges.push(range); + } + + Ok(ranges) +} + +fn scanned_ports(batch: &SweepBatch, ip: IpAddr) -> BTreeMap { + batch + .ports + .iter() + .filter(|result| result.ip == ip) + .flat_map(|result| result.ports.iter()) + .map(|port| (port.port, port.state)) + .collect() +} + +fn current_services( + batch: &SweepBatch, + ip: IpAddr, +) -> BTreeMap { + batch + .services + .iter() + .filter(|service| service.ip == ip) + .map(|service| (service.port, service)) + .collect() +} + +fn apply_service( + target: &mut ServiceState, + observed: Option<&crate::batch::ServiceObservation>, +) -> bool { + let Some(observed) = observed else { + return false; + }; + + let mut changed = false; + + if let Some(product) = &observed.product { + if target.product.as_deref() != Some(product.as_str()) { + target.product = Some(product.clone()); + changed = true; + } + } + if let Some(version) = &observed.version { + if target.version.as_deref() != Some(version.as_str()) { + target.version = Some(version.clone()); + changed = true; + } + } + if let Some(cpe) = &observed.cpe { + if target.cpe.as_deref() != Some(cpe.as_str()) { + target.cpe = Some(cpe.clone()); + changed = true; + } + } + + changed +} + +fn event_service(service: &ServiceState) -> EventService { + EventService { + protocol: service.protocol.clone(), + port: service.port, + product: service.product.clone(), + version: service.version.clone(), + cpe: service.cpe.clone(), + } +} + +fn port_snapshot(service: &ServiceState) -> Option { + Some(json!({ + "estado": service.status.as_str(), + "produto": service.product, + "versao": service.version, + "cpe": service.cpe, + })) +} + +#[allow(clippy::too_many_arguments)] +fn event( + batch: &SweepBatch, + kind: EventKind, + asset_key: &str, + service: Option, + previous: Option, + current: Option, + evidence: Value, + occurred_at: DateTime, +) -> Event { + Event { + event_id: Ulid::generate(), + sweep_id: batch.manifest.sweep_id, + group: batch.manifest.group.clone(), + kind, + asset_key: asset_key.to_string(), + service, + previous, + current, + evidence, + occurred_at, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::batch::{EngineMode, ServiceObservation, SweepManifest}; + use crate::scan::{HostDiscoveryResult, HostPortScanResult, PortScanResult}; + + fn at(seconds: i64) -> DateTime { + DateTime::from_timestamp(1_700_000_000 + seconds, 0).expect("valid instant") + } + + fn ip(raw: &str) -> IpAddr { + raw.parse().expect("valid test address") + } + + fn batch( + status: SweepStatus, + scope: &[&str], + hosts: Vec<(IpAddr, HostState)>, + ports: Vec<(IpAddr, Vec<(u16, PortState)>)>, + services: Vec, + ) -> SweepBatch { + let mut manifest = SweepManifest::new( + "dmz", + scope.iter().map(|value| (*value).to_string()).collect(), + "padrao", + EngineMode::NativeWithoutRaw, + at(0), + ); + manifest.finish(status, at(60)); + + SweepBatch::new( + manifest, + hosts + .into_iter() + .map(|(ip, state)| HostDiscoveryResult { + ip, + state, + responded_port: (state == HostState::Alive).then_some(22), + }) + .collect(), + ports + .into_iter() + .map(|(ip, ports)| HostPortScanResult { + ip, + ports: ports + .into_iter() + .map(|(port, state)| PortScanResult { port, state }) + .collect(), + }) + .collect(), + ) + .with_services(services) + } + + fn asset(ip_raw: &str, absences: u32, ports: Vec) -> AssetState { + AssetState { + asset_key: format!("dmz/{}", ip(ip_raw)), + network: "dmz".to_string(), + ip: ip(ip_raw), + status: AssetStatus::Active, + absences, + first_seen: at(0), + last_seen: at(0), + ports, + } + } + + fn open_port(port: u16) -> ServiceState { + ServiceState { + protocol: "tcp".to_string(), + port, + status: PortStatus::Open, + absences: 0, + first_seen: at(0), + last_seen: at(0), + product: None, + version: None, + cpe: None, + } + } + + fn kinds(result: &DiffResult) -> Vec { + result.events.iter().map(|event| event.kind).collect() + } + + #[test] + fn new_host_and_new_port_are_reported() { + let previous = CurrentState::default(); + let batch = batch( + SweepStatus::Complete, + &["203.0.113.0/24"], + vec![(ip("203.0.113.5"), HostState::Alive)], + vec![(ip("203.0.113.5"), vec![(22, PortState::Open)])], + vec![], + ); + + let result = diff_batch(&previous, &batch, &DiffOptions::default()).expect("diff succeeds"); + + assert_eq!(kinds(&result), vec![EventKind::HostNew, EventKind::PortNew]); + assert_eq!(result.state.len(), 1); + assert_eq!(result.state[0].status, AssetStatus::Active); + assert_eq!(result.state[0].ports.len(), 1); + assert_eq!(result.state[0].ports[0].status, PortStatus::Open); + } + + #[test] + fn host_disappears_only_after_the_configured_absences() { + let previous = CurrentState::new(vec![asset("203.0.113.5", 0, vec![open_port(22)])]); + let options = DiffOptions { + absences_before_disappear: 2, + }; + + let first = diff_batch( + &previous, + &batch( + SweepStatus::Complete, + &["203.0.113.0/24"], + vec![(ip("203.0.113.5"), HostState::Unresponsive)], + vec![], + vec![], + ), + &options, + ) + .expect("first diff succeeds"); + assert!(first.events.is_empty()); + assert_eq!(first.state[0].absences, 1); + assert_eq!(first.state[0].status, AssetStatus::Active); + + let second = diff_batch( + &CurrentState::new(first.state), + &batch( + SweepStatus::Complete, + &["203.0.113.0/24"], + vec![(ip("203.0.113.5"), HostState::Unresponsive)], + vec![], + vec![], + ), + &options, + ) + .expect("second diff succeeds"); + assert_eq!(kinds(&second), vec![EventKind::HostDisappeared]); + assert_eq!(second.state[0].status, AssetStatus::Gone); + } + + #[test] + fn partial_sweep_never_reports_a_disappearance() { + let previous = CurrentState::new(vec![asset("203.0.113.5", 0, vec![open_port(22)])]); + + let result = diff_batch( + &previous, + &batch( + SweepStatus::Partial, + &["203.0.113.0/24"], + vec![(ip("203.0.113.5"), HostState::Unresponsive)], + vec![], + vec![], + ), + &DiffOptions::default(), + ) + .expect("diff succeeds"); + + assert!(result.events.is_empty()); + assert_eq!(result.state[0].absences, 0); + assert_eq!(result.state[0].status, AssetStatus::Active); + } + + #[test] + fn uncovered_hosts_are_left_untouched() { + let previous = CurrentState::new(vec![asset("203.0.113.5", 0, vec![open_port(22)])]); + + let result = diff_batch( + &previous, + &batch( + SweepStatus::Complete, + &["203.0.113.128/25"], + vec![], + vec![], + vec![], + ), + &DiffOptions::default(), + ) + .expect("diff succeeds"); + + assert!(result.events.is_empty()); + assert!(result.state.is_empty()); + } + + #[test] + fn ports_outside_the_scanned_profile_are_not_closed() { + let previous = CurrentState::new(vec![asset("203.0.113.5", 0, vec![open_port(22)])]); + + let result = diff_batch( + &previous, + &batch( + SweepStatus::Complete, + &["203.0.113.0/24"], + vec![(ip("203.0.113.5"), HostState::Alive)], + vec![(ip("203.0.113.5"), vec![(80, PortState::Open)])], + vec![], + ), + &DiffOptions::default(), + ) + .expect("diff succeeds"); + + assert_eq!(kinds(&result), vec![EventKind::PortNew]); + let ports = &result.state[0].ports; + assert_eq!(ports.len(), 2); + assert!(ports + .iter() + .any(|port| port.port == 22 && port.status == PortStatus::Open)); + assert!(ports + .iter() + .any(|port| port.port == 80 && port.status == PortStatus::Open)); + } + + #[test] + fn closed_port_disappears_only_after_the_configured_absences() { + let previous = CurrentState::new(vec![asset("203.0.113.5", 0, vec![open_port(22)])]); + let options = DiffOptions { + absences_before_disappear: 2, + }; + let closed = batch( + SweepStatus::Complete, + &["203.0.113.0/24"], + vec![(ip("203.0.113.5"), HostState::Alive)], + vec![(ip("203.0.113.5"), vec![(22, PortState::Closed)])], + vec![], + ); + + let first = diff_batch(&previous, &closed, &options).expect("first diff succeeds"); + assert!(first.events.is_empty()); + assert_eq!(first.state[0].ports[0].absences, 1); + + let second = diff_batch(&CurrentState::new(first.state), &closed, &options) + .expect("second diff succeeds"); + assert_eq!(kinds(&second), vec![EventKind::PortClosed]); + assert_eq!(second.state[0].ports[0].status, PortStatus::Closed); + } + + #[test] + fn partial_sweep_never_closes_a_port() { + let previous = CurrentState::new(vec![asset("203.0.113.5", 0, vec![open_port(22)])]); + + let result = diff_batch( + &previous, + &batch( + SweepStatus::Partial, + &["203.0.113.0/24"], + vec![(ip("203.0.113.5"), HostState::Alive)], + vec![(ip("203.0.113.5"), vec![(22, PortState::Closed)])], + vec![], + ), + &DiffOptions::default(), + ) + .expect("diff succeeds"); + + assert!(result.events.is_empty()); + assert_eq!(result.state[0].ports[0].status, PortStatus::Open); + assert_eq!(result.state[0].ports[0].absences, 0); + } + + #[test] + fn service_change_is_reported_with_before_and_after() { + let mut previous_port = open_port(22); + previous_port.product = Some("OpenSSH".to_string()); + previous_port.version = Some("9.3p1".to_string()); + let previous = CurrentState::new(vec![asset("203.0.113.5", 0, vec![previous_port])]); + + let result = diff_batch( + &previous, + &batch( + SweepStatus::Complete, + &["203.0.113.0/24"], + vec![(ip("203.0.113.5"), HostState::Alive)], + vec![(ip("203.0.113.5"), vec![(22, PortState::Open)])], + vec![ServiceObservation { + ip: ip("203.0.113.5"), + port: 22, + product: Some("OpenSSH".to_string()), + version: Some("9.8p1".to_string()), + cpe: None, + }], + ), + &DiffOptions::default(), + ) + .expect("diff succeeds"); + + assert_eq!(kinds(&result), vec![EventKind::ServiceChanged]); + let event = &result.events[0]; + assert_eq!( + event + .current + .as_ref() + .and_then(|value| value["versao"].as_str()), + Some("9.8p1") + ); + assert_eq!( + event + .previous + .as_ref() + .and_then(|value| value["versao"].as_str()), + Some("9.3p1") + ); + } + + #[test] + fn returning_host_is_reported() { + let mut gone = asset("203.0.113.5", 2, vec![]); + gone.status = AssetStatus::Gone; + + let result = diff_batch( + &CurrentState::new(vec![gone]), + &batch( + SweepStatus::Complete, + &["203.0.113.0/24"], + vec![(ip("203.0.113.5"), HostState::Alive)], + vec![], + vec![], + ), + &DiffOptions::default(), + ) + .expect("diff succeeds"); + + assert_eq!(kinds(&result), vec![EventKind::HostReturned]); + assert_eq!(result.state[0].status, AssetStatus::Active); + } + + #[test] + fn events_are_ordered_by_phase_and_key() { + let previous = CurrentState::default(); + let batch = batch( + SweepStatus::Complete, + &["203.0.113.0/24"], + vec![ + (ip("203.0.113.9"), HostState::Alive), + (ip("203.0.113.5"), HostState::Alive), + ], + vec![ + (ip("203.0.113.9"), vec![(443, PortState::Open)]), + (ip("203.0.113.5"), vec![(22, PortState::Open)]), + ], + vec![], + ); + + let result = diff_batch(&previous, &batch, &DiffOptions::default()).expect("diff succeeds"); + + assert_eq!( + kinds(&result), + vec![ + EventKind::HostNew, + EventKind::HostNew, + EventKind::PortNew, + EventKind::PortNew, + ] + ); + assert_eq!(result.events[0].asset_key, "dmz/203.0.113.5"); + assert_eq!(result.events[1].asset_key, "dmz/203.0.113.9"); + } + + #[test] + fn manifest_scope_is_parsed_as_ranges() { + let ranges = swept_ranges(&batch( + SweepStatus::Complete, + &["10.0.0.0-10.0.0.255"], + vec![], + vec![], + vec![], + )) + .expect("scope parses"); + + assert!(ranges[0].contains(ip("10.0.0.7"))); + assert_eq!(ranges[0].count(), 256); + } + + #[test] + fn vulnerability_placeholder_is_empty() { + let findings = [1_u8, 2, 3]; + assert!(diff_vulnerabilities(&findings, &findings).is_empty()); + } +} diff --git a/crates/xexeu-core/src/storage.rs b/crates/xexeu-core/src/storage.rs index 2170641..3001fd9 100644 --- a/crates/xexeu-core/src/storage.rs +++ b/crates/xexeu-core/src/storage.rs @@ -1,2 +1,588 @@ -//! DuckDB + Parquet storage for sweeps, observations, the deduplicated current state and events. -// TODO: implement the storage layer with the server as the single writer. +//! Local-first persistence for sweeps, the deduplicated current state and the event log. +//! +//! # Why SQLite in this slice +//! +//! `design.md` targets DuckDB. Binding `libduckdb` requires a system or prebuilt library, which +//! would make `cargo build` depend on infrastructure that is not available on every developer +//! machine yet. The [`Storage`] trait isolates the SQL surface, so the server can switch to a +//! DuckDB implementation later without touching the diff engine. The first concrete +//! implementation, [`SqliteStorage`], uses `rusqlite` with the bundled SQLite, which embeds +//! cleanly and lets the pipeline run end to end today. +//! +//! Tables: +//! +//! - `sweeps`: idempotency key for ingestion; +//! - `assets`: deduplicated state keyed by `asset_key = (rede_logica, ip)`; +//! - `services`: ports per asset, keyed by `(asset_key, proto, porta)`; +//! - `events`: append-only log with the full event JSON as evidence. + +use std::collections::BTreeMap; +use std::fs; +use std::io; +use std::net::IpAddr; +use std::path::Path; + +use chrono::{DateTime, SecondsFormat, Utc}; +use rusqlite::{params, Connection}; +use thiserror::Error; + +use crate::batch::{SweepBatch, SweepManifest}; +use crate::diff::{ + AssetState, AssetStatus, CurrentState, DiffResult, Event, PortStatus, ServiceState, +}; +use crate::targets::IpRange; + +/// Persistence contract for the current state and the event log. +pub trait Storage { + /// Records a sweep, returning `false` when it had already been ingested. + fn record_sweep(&mut self, manifest: &SweepManifest) -> Result; + + /// Loads the deduplicated state, optionally restricted to a scope. + /// + /// An empty scope means "no filter". + fn load_state(&self, scope: &[IpRange]) -> Result; + + /// Applies a diff result: upserts the next state and appends its events. + fn apply_diff(&mut self, diff: &DiffResult) -> Result<(), StorageError>; + + /// Idempotently ingests a batch and its diff in one transaction. + /// + /// Returns `false` when the sweep had already been ingested. + fn ingest(&mut self, batch: &SweepBatch, diff: &DiffResult) -> Result; + + /// Returns events ordered by occurrence, optionally filtered by a lower bound. + fn events(&self, since: Option>) -> Result, StorageError>; +} + +/// Errors raised by the storage layer. +#[derive(Debug, Error)] +pub enum StorageError { + /// SQLite failure. + #[error("erro de banco: {0}")] + Sqlite(#[from] rusqlite::Error), + /// Filesystem failure. + #[error("erro de E/S: {0}")] + Io(#[from] io::Error), + /// Stored JSON is invalid. + #[error("evento armazenado inválido: {0}")] + Json(#[from] serde_json::Error), + /// Stored value does not match the expected shape. + #[error("estado corrompido: {0}")] + Corrupt(String), +} + +/// SQLite implementation of [`Storage`]. +#[derive(Debug)] +pub struct SqliteStorage { + connection: Connection, +} + +impl SqliteStorage { + /// Opens (and creates, if needed) the database at `path`. + pub fn open(path: &Path) -> Result { + if let Some(parent) = path.parent() { + if !parent.as_os_str().is_empty() { + fs::create_dir_all(parent)?; + } + } + + let connection = Connection::open(path)?; + Self::initialize(connection) + } + + /// Opens a private in-memory database, useful for tests and ephemeral runs. + pub fn open_in_memory() -> Result { + Self::initialize(Connection::open_in_memory()?) + } + + fn initialize(connection: Connection) -> Result { + connection.pragma_update(None, "journal_mode", "WAL")?; + connection.pragma_update(None, "foreign_keys", "ON")?; + connection.execute_batch( + " + CREATE TABLE IF NOT EXISTS sweeps ( + sweep_id TEXT PRIMARY KEY, + group_name TEXT NOT NULL, + profile TEXT NOT NULL, + engine TEXT NOT NULL, + status TEXT NOT NULL, + started_at TEXT NOT NULL, + finished_at TEXT, + content_hash TEXT + ); + + CREATE TABLE IF NOT EXISTS assets ( + asset_key TEXT PRIMARY KEY, + network TEXT NOT NULL, + ip TEXT NOT NULL, + status TEXT NOT NULL, + absences INTEGER NOT NULL DEFAULT 0, + first_seen TEXT NOT NULL, + last_seen TEXT NOT NULL + ); + + CREATE INDEX IF NOT EXISTS idx_assets_ip ON assets(ip); + + CREATE TABLE IF NOT EXISTS services ( + asset_key TEXT NOT NULL, + proto TEXT NOT NULL, + port INTEGER NOT NULL, + status TEXT NOT NULL, + absences INTEGER NOT NULL DEFAULT 0, + first_seen TEXT NOT NULL, + last_seen TEXT NOT NULL, + product TEXT, + version TEXT, + cpe TEXT, + PRIMARY KEY (asset_key, proto, port), + FOREIGN KEY (asset_key) REFERENCES assets(asset_key) ON DELETE CASCADE + ); + + CREATE TABLE IF NOT EXISTS events ( + event_id TEXT PRIMARY KEY, + sweep_id TEXT NOT NULL, + group_name TEXT NOT NULL, + kind TEXT NOT NULL, + asset_key TEXT NOT NULL, + payload TEXT NOT NULL, + occurred_at TEXT NOT NULL + ); + + CREATE INDEX IF NOT EXISTS idx_events_time ON events(occurred_at); + ", + )?; + + Ok(Self { connection }) + } + + /// Number of stored events, useful for diagnostics. + pub fn event_count(&self) -> Result { + let count: i64 = self + .connection + .query_row("SELECT COUNT(*) FROM events", [], |row| row.get(0))?; + Ok(count as usize) + } +} + +impl Storage for SqliteStorage { + fn record_sweep(&mut self, manifest: &SweepManifest) -> Result { + insert_sweep(&self.connection, manifest) + } + + fn load_state(&self, scope: &[IpRange]) -> Result { + let mut statement = self.connection.prepare( + "SELECT asset_key, network, ip, status, absences, first_seen, last_seen + FROM assets ORDER BY asset_key", + )?; + + let mut assets = BTreeMap::new(); + let rows = statement.query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, String>(2)?, + row.get::<_, String>(3)?, + row.get::<_, i64>(4)?, + row.get::<_, String>(5)?, + row.get::<_, String>(6)?, + )) + })?; + + for row in rows { + let (asset_key, network, ip, status, absences, first_seen, last_seen) = row?; + let ip = parse_ip(&ip)?; + if !scope.is_empty() && !scope.iter().any(|range| range.contains(ip)) { + continue; + } + + assets.insert( + asset_key.clone(), + AssetState { + asset_key, + network, + ip, + status: parse_asset_status(&status)?, + absences: absences as u32, + first_seen: parse_time(&first_seen)?, + last_seen: parse_time(&last_seen)?, + ports: Vec::new(), + }, + ); + } + + let mut statement = self.connection.prepare( + "SELECT asset_key, proto, port, status, absences, first_seen, last_seen, + product, version, cpe + FROM services ORDER BY asset_key, port", + )?; + + let rows = statement.query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, i64>(2)?, + row.get::<_, String>(3)?, + row.get::<_, i64>(4)?, + row.get::<_, String>(5)?, + row.get::<_, String>(6)?, + row.get::<_, Option>(7)?, + row.get::<_, Option>(8)?, + row.get::<_, Option>(9)?, + )) + })?; + + for row in rows { + let ( + asset_key, + protocol, + port, + status, + absences, + first_seen, + last_seen, + product, + version, + cpe, + ) = row?; + if let Some(asset) = assets.get_mut(&asset_key) { + asset.ports.push(ServiceState { + protocol, + port: port as u16, + status: parse_port_status(&status)?, + absences: absences as u32, + first_seen: parse_time(&first_seen)?, + last_seen: parse_time(&last_seen)?, + product, + version, + cpe, + }); + } + } + + Ok(CurrentState::new(assets.into_values().collect())) + } + + fn apply_diff(&mut self, diff: &DiffResult) -> Result<(), StorageError> { + let transaction = self.connection.transaction()?; + apply_state(&transaction, diff)?; + insert_events(&transaction, diff)?; + transaction.commit()?; + Ok(()) + } + + fn ingest(&mut self, batch: &SweepBatch, diff: &DiffResult) -> Result { + let transaction = self.connection.transaction()?; + if !insert_sweep(&transaction, &batch.manifest)? { + return Ok(false); + } + apply_state(&transaction, diff)?; + insert_events(&transaction, diff)?; + transaction.commit()?; + Ok(true) + } + + fn events(&self, since: Option>) -> Result, StorageError> { + let mut events = Vec::new(); + + match since { + Some(since) => { + let mut statement = self.connection.prepare( + "SELECT payload FROM events WHERE occurred_at >= ?1 + ORDER BY occurred_at, event_id", + )?; + let rows = + statement.query_map([format_time(since)], |row| row.get::<_, String>(0))?; + for payload in rows { + events.push(serde_json::from_str(&payload?)?); + } + } + None => { + let mut statement = self + .connection + .prepare("SELECT payload FROM events ORDER BY occurred_at, event_id")?; + let rows = statement.query_map([], |row| row.get::<_, String>(0))?; + for payload in rows { + events.push(serde_json::from_str(&payload?)?); + } + } + } + + Ok(events) + } +} + +fn insert_sweep(connection: &Connection, manifest: &SweepManifest) -> Result { + let inserted = connection.execute( + "INSERT OR IGNORE INTO sweeps + (sweep_id, group_name, profile, engine, status, started_at, finished_at, content_hash) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)", + params![ + manifest.sweep_id.to_string(), + manifest.group, + manifest.profile, + manifest.engine_mode.as_str(), + manifest.status.as_str(), + format_time(manifest.started_at), + manifest.finished_at.map(format_time), + manifest.content_hash, + ], + )?; + Ok(inserted == 1) +} + +fn apply_state(connection: &Connection, diff: &DiffResult) -> Result<(), StorageError> { + for asset in &diff.state { + connection.execute( + "INSERT INTO assets + (asset_key, network, ip, status, absences, first_seen, last_seen) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) + ON CONFLICT(asset_key) DO UPDATE SET + network = excluded.network, + ip = excluded.ip, + status = excluded.status, + absences = excluded.absences, + last_seen = excluded.last_seen", + params![ + asset.asset_key, + asset.network, + asset.ip.to_string(), + asset.status.as_str(), + i64::from(asset.absences), + format_time(asset.first_seen), + format_time(asset.last_seen), + ], + )?; + + for service in &asset.ports { + connection.execute( + "INSERT INTO services + (asset_key, proto, port, status, absences, first_seen, last_seen, + product, version, cpe) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10) + ON CONFLICT(asset_key, proto, port) DO UPDATE SET + status = excluded.status, + absences = excluded.absences, + last_seen = excluded.last_seen, + product = excluded.product, + version = excluded.version, + cpe = excluded.cpe", + params![ + asset.asset_key, + service.protocol, + i64::from(service.port), + service.status.as_str(), + i64::from(service.absences), + format_time(service.first_seen), + format_time(service.last_seen), + service.product, + service.version, + service.cpe, + ], + )?; + } + } + + Ok(()) +} + +fn insert_events(connection: &Connection, diff: &DiffResult) -> Result<(), StorageError> { + for event in &diff.events { + connection.execute( + "INSERT OR IGNORE INTO events + (event_id, sweep_id, group_name, kind, asset_key, payload, occurred_at) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![ + event.event_id.to_string(), + event.sweep_id.to_string(), + event.group, + event.kind.as_str(), + event.asset_key, + serde_json::to_string(event)?, + format_time(event.occurred_at), + ], + )?; + } + Ok(()) +} + +fn format_time(value: DateTime) -> String { + value.to_rfc3339_opts(SecondsFormat::Secs, true) +} + +fn parse_time(raw: &str) -> Result, StorageError> { + DateTime::parse_from_rfc3339(raw) + .map(|value| value.with_timezone(&Utc)) + .map_err(|error| StorageError::Corrupt(format!("data inválida `{raw}`: {error}"))) +} + +fn parse_ip(raw: &str) -> Result { + raw.parse() + .map_err(|error| StorageError::Corrupt(format!("IP inválido `{raw}`: {error}"))) +} + +fn parse_asset_status(raw: &str) -> Result { + match raw { + "ativo" => Ok(AssetStatus::Active), + "sumido" => Ok(AssetStatus::Gone), + other => Err(StorageError::Corrupt(format!("status de ativo `{other}`"))), + } +} + +fn parse_port_status(raw: &str) -> Result { + match raw { + "aberta" => Ok(PortStatus::Open), + "fechada" => Ok(PortStatus::Closed), + other => Err(StorageError::Corrupt(format!("status de porta `{other}`"))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::batch::{EngineMode, SweepBatch, SweepStatus}; + use crate::diff::{diff_batch, DiffOptions}; + use crate::scan::{ + HostDiscoveryResult, HostPortScanResult, HostState, PortScanResult, PortState, + }; + use std::net::Ipv4Addr; + + fn at(seconds: i64) -> DateTime { + DateTime::from_timestamp(1_700_000_000 + seconds, 0).expect("valid instant") + } + + fn batch( + status: SweepStatus, + host_state: HostState, + ports: Vec<(u16, PortState)>, + ) -> SweepBatch { + let ip = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 5)); + let mut manifest = SweepManifest::new( + "dmz", + vec!["203.0.113.0/24".to_string()], + "padrao", + EngineMode::NativeWithoutRaw, + at(0), + ); + manifest.finish(status, at(60)); + SweepBatch::new( + manifest, + vec![HostDiscoveryResult { + ip, + state: host_state, + responded_port: (host_state == HostState::Alive).then_some(22), + }], + vec![HostPortScanResult { + ip, + ports: ports + .into_iter() + .map(|(port, state)| PortScanResult { port, state }) + .collect(), + }], + ) + } + + #[test] + fn ingests_state_and_events_end_to_end() { + let mut storage = SqliteStorage::open_in_memory().expect("database opens"); + let batch = batch( + SweepStatus::Complete, + HostState::Alive, + vec![(22, PortState::Open)], + ); + let diff = diff_batch(&CurrentState::default(), &batch, &DiffOptions::default()) + .expect("diff succeeds"); + + assert!(storage.ingest(&batch, &diff).expect("ingest succeeds")); + + let state = storage.load_state(&[]).expect("state loads"); + assert_eq!(state.assets.len(), 1); + assert_eq!(state.assets[0].asset_key, "dmz/203.0.113.5"); + assert_eq!(state.assets[0].ports.len(), 1); + assert_eq!(state.assets[0].ports[0].status, PortStatus::Open); + + let events = storage.events(None).expect("events load"); + assert_eq!(events.len(), 2); + assert!(events + .iter() + .any(|event| event.kind.as_str() == "host_novo")); + } + + #[test] + fn ingestion_is_idempotent_per_sweep() { + let mut storage = SqliteStorage::open_in_memory().expect("database opens"); + let batch = batch( + SweepStatus::Complete, + HostState::Alive, + vec![(22, PortState::Open)], + ); + let diff = diff_batch(&CurrentState::default(), &batch, &DiffOptions::default()) + .expect("diff succeeds"); + + assert!(storage.ingest(&batch, &diff).expect("first ingest")); + assert!(!storage.ingest(&batch, &diff).expect("second ingest")); + assert_eq!(storage.event_count().expect("count"), 2); + } + + #[test] + fn absence_counter_survives_a_reload() { + let mut storage = SqliteStorage::open_in_memory().expect("database opens"); + let first = batch( + SweepStatus::Complete, + HostState::Alive, + vec![(22, PortState::Open)], + ); + let first_diff = diff_batch(&CurrentState::default(), &first, &DiffOptions::default()) + .expect("first diff"); + storage.ingest(&first, &first_diff).expect("first ingest"); + + let state = storage.load_state(&[]).expect("state loads"); + let second = batch(SweepStatus::Complete, HostState::Unresponsive, vec![]); + let second_diff = + diff_batch(&state, &second, &DiffOptions::default()).expect("second diff"); + storage + .ingest(&second, &second_diff) + .expect("second ingest"); + + let state = storage.load_state(&[]).expect("state reloads"); + assert_eq!(state.assets[0].absences, 1); + assert_eq!(state.assets[0].status, AssetStatus::Active); + // The unresponsive sweep produced no disappearance event. + assert_eq!(storage.event_count().expect("count"), 2); + } + + #[test] + fn load_state_respects_the_scope_filter() { + let mut storage = SqliteStorage::open_in_memory().expect("database opens"); + let batch = batch( + SweepStatus::Complete, + HostState::Alive, + vec![(22, PortState::Open)], + ); + let diff = diff_batch(&CurrentState::default(), &batch, &DiffOptions::default()) + .expect("diff succeeds"); + storage.ingest(&batch, &diff).expect("ingest succeeds"); + + let outside = [ + IpRange::new("10.0.0.1".parse().unwrap(), "10.0.0.9".parse().unwrap()).expect("range"), + ]; + assert!(storage + .load_state(&outside) + .expect("state loads") + .assets + .is_empty()); + + let inside = [IpRange::new( + "203.0.113.0".parse().unwrap(), + "203.0.113.255".parse().unwrap(), + ) + .expect("range")]; + assert_eq!( + storage + .load_state(&inside) + .expect("state loads") + .assets + .len(), + 1 + ); + } +} diff --git a/crates/xexeu-core/src/vuln/checks.rs b/crates/xexeu-core/src/vuln/checks.rs index 157862f..ace8eab 100644 --- a/crates/xexeu-core/src/vuln/checks.rs +++ b/crates/xexeu-core/src/vuln/checks.rs @@ -1,2 +1,455 @@ -//! Safe configuration checks: weak TLS, expiring certificates, weak SSH algorithms, exposed admin services and cleartext protocols. -// TODO: implement non-intrusive configuration checks. +//! Safe, non-intrusive configuration security checks. +//! +//! Checks in this module observe standard service responses without sending +//! intrusive, destabilizing, or exploit payloads. +//! +//! Implemented checks: +//! 1. **TLS Certificate Expiration:** Detects certificates that are already expired +//! or expiring in less than 30 days. +//! 2. **Unencrypted Administrative Service:** Detects sensitive administrative interfaces +//! (e.g. ports 8080, 9090, 8000, 8888, 9000) answering cleartext HTTP without TLS redirection. + +use super::matcher::{Confidence, Finding, FindingType}; +use chrono::{DateTime, Utc}; +use std::net::SocketAddr; +use std::time::Duration; +use thiserror::Error; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; + +/// Error encountered during configuration checks. +#[derive(Debug, Error)] +pub enum CheckError { + #[error("I/O error during check: {0}")] + Io(#[from] std::io::Error), + #[error("X.509 DER certificate parsing error: {0}")] + DerParsing(String), +} + +// --------------------------------------------------------------------------- +// Check 1: TLS Certificate Expiration +// --------------------------------------------------------------------------- + +/// Parses an X.509 DER-encoded certificate and evaluates whether it is expired +/// or expiring in less than 30 days. +/// +/// Accepts an optional `now_utc` for deterministic testing. +pub fn check_tls_certificate_der( + der: &[u8], + now_utc: Option>, +) -> Result, CheckError> { + let now = now_utc.unwrap_or_else(Utc::now); + let not_after = parse_x509_der_not_after(der) + .map_err(|e| CheckError::DerParsing(format!("failed to parse validity: {e}")))?; + + let remaining_seconds = not_after.signed_duration_since(now).num_seconds(); + let remaining_days = remaining_seconds as f64 / 86400.0; + + if remaining_seconds <= 0 { + // Expired certificate + let days_expired = (-remaining_days).ceil() as i64; + Ok(Some(Finding { + tipo: FindingType::Check, + id: "tls-cert-expired".into(), + cvss: Some(7.5), + kev: false, + confianca: Confidence::Alto, + title: "Certificado TLS Expirado".into(), + description: format!( + "O certificado TLS expirou há {} dias ({}) e causará falhas de validação de clientes.", + days_expired, + not_after.to_rfc3339() + ), + evidencia: serde_json::json!({ + "not_after": not_after.to_rfc3339(), + "current_time": now.to_rfc3339(), + "expired": true, + "days_expired": days_expired, + }), + })) + } else if remaining_days < 30.0 { + // Expiring in less than 30 days + let days_left = remaining_days.floor() as i64; + Ok(Some(Finding { + tipo: FindingType::Check, + id: "tls-cert-expiring".into(), + cvss: Some(5.3), + kev: false, + confianca: Confidence::Alto, + title: "Certificado TLS Expirando em Menos de 30 Dias".into(), + description: format!( + "O certificado TLS expira em {} dias ({}) e deve ser renovado prontamente.", + days_left, + not_after.to_rfc3339() + ), + evidencia: serde_json::json!({ + "not_after": not_after.to_rfc3339(), + "current_time": now.to_rfc3339(), + "expired": false, + "days_remaining": days_left, + }), + })) + } else { + // Certificate is valid with ample time + Ok(None) + } +} + +/// Minimal, zero-dependency X.509 DER parser to extract the `notAfter` validity timestamp. +/// +/// Navigates: +/// Certificate (SEQUENCE) -> TBSCertificate (SEQUENCE) -> Validity (SEQUENCE) -> notAfter +pub fn parse_x509_der_not_after(der: &[u8]) -> Result, String> { + if der.is_empty() || der[0] != 0x30 { + return Err("expected Certificate SEQUENCE".into()); + } + + let (_, mut off) = read_der_len(der, 1)?; + + // TBSCertificate (SEQUENCE) + if off >= der.len() || der[off] != 0x30 { + return Err("expected TBSCertificate SEQUENCE".into()); + } + let (tbs_len, next_off) = read_der_len(der, off + 1)?; + off = next_off; + let tbs_end = off + tbs_len; + if tbs_end > der.len() { + return Err("TBSCertificate length exceeds buffer".into()); + } + + // Element 1: version [0] EXPLICIT (optional in X.509) + if off < tbs_end && der[off] == 0xA0 { + let (v_len, next_off) = read_der_len(der, off + 1)?; + off = next_off + v_len; + } + + // Element 2: serialNumber (INTEGER) + if off >= tbs_end || der[off] != 0x02 { + return Err("expected serialNumber INTEGER".into()); + } + let (s_len, next_off) = read_der_len(der, off + 1)?; + off = next_off + s_len; + + // Element 3: signature (AlgorithmIdentifier SEQUENCE) + if off >= tbs_end || der[off] != 0x30 { + return Err("expected signature AlgorithmIdentifier SEQUENCE".into()); + } + let (sig_len, next_off) = read_der_len(der, off + 1)?; + off = next_off + sig_len; + + // Element 4: issuer (Name SEQUENCE) + if off >= tbs_end || der[off] != 0x30 { + return Err("expected issuer SEQUENCE".into()); + } + let (iss_len, next_off) = read_der_len(der, off + 1)?; + off = next_off + iss_len; + + // Element 5: Validity (SEQUENCE) + if off >= tbs_end || der[off] != 0x30 { + return Err("expected validity SEQUENCE".into()); + } + let (_val_len, next_off) = read_der_len(der, off + 1)?; + off = next_off; + + // Inside Validity: notBefore (UTCTime: 0x17 or GeneralizedTime: 0x18) + if off >= tbs_end || (der[off] != 0x17 && der[off] != 0x18) { + return Err("expected notBefore UTCTime/GeneralizedTime".into()); + } + let (nb_len, next_off) = read_der_len(der, off + 1)?; + off = next_off + nb_len; + + // notAfter (UTCTime: 0x17 or GeneralizedTime: 0x18) + if off >= tbs_end || (der[off] != 0x17 && der[off] != 0x18) { + return Err("expected notAfter UTCTime/GeneralizedTime".into()); + } + let is_utc_time = der[off] == 0x17; + let (na_len, next_off) = read_der_len(der, off + 1)?; + off = next_off; + + if off + na_len > der.len() { + return Err("notAfter length exceeds buffer".into()); + } + + let time_str = std::str::from_utf8(&der[off..off + na_len]) + .map_err(|e| format!("notAfter is not UTF-8: {e}"))?; + + parse_asn1_time_string(time_str, is_utc_time) +} + +fn read_der_len(data: &[u8], offset: usize) -> Result<(usize, usize), String> { + if offset >= data.len() { + return Err("unexpected EOF reading DER length".into()); + } + let b = data[offset]; + if b < 0x80 { + Ok((b as usize, offset + 1)) + } else { + let count = (b & 0x7F) as usize; + if count == 0 || count > 4 { + return Err("unsupported DER multi-byte length".into()); + } + if offset + 1 + count > data.len() { + return Err("unexpected EOF in multi-byte length".into()); + } + let mut len: usize = 0; + for i in 0..count { + len = (len << 8) | (data[offset + 1 + i] as usize); + } + Ok((len, offset + 1 + count)) + } +} + +fn parse_asn1_time_string(s: &str, is_utc: bool) -> Result, String> { + let clean = s.trim_end_matches('Z'); + if is_utc { + // YYMMDDHHMMSS + if clean.len() < 12 { + return Err(format!("UTCTime too short: '{s}'")); + } + let yy: i32 = clean[0..2] + .parse() + .map_err(|e| format!("invalid year: {e}"))?; + let year = if yy >= 50 { 1900 + yy } else { 2000 + yy }; + let month: u32 = clean[2..4] + .parse() + .map_err(|e| format!("invalid month: {e}"))?; + let day: u32 = clean[4..6] + .parse() + .map_err(|e| format!("invalid day: {e}"))?; + let hour: u32 = clean[6..8] + .parse() + .map_err(|e| format!("invalid hour: {e}"))?; + let min: u32 = clean[8..10] + .parse() + .map_err(|e| format!("invalid minute: {e}"))?; + let sec: u32 = clean[10..12] + .parse() + .map_err(|e| format!("invalid second: {e}"))?; + + let naive = chrono::NaiveDate::from_ymd_opt(year, month, day) + .and_then(|d| d.and_hms_opt(hour, min, sec)) + .ok_or_else(|| format!("invalid date/time values in '{s}'"))?; + Ok(DateTime::from_naive_utc_and_offset(naive, Utc)) + } else { + // YYYYMMDDHHMMSS + if clean.len() < 14 { + return Err(format!("GeneralizedTime too short: '{s}'")); + } + let year: i32 = clean[0..4] + .parse() + .map_err(|e| format!("invalid year: {e}"))?; + let month: u32 = clean[4..6] + .parse() + .map_err(|e| format!("invalid month: {e}"))?; + let day: u32 = clean[6..8] + .parse() + .map_err(|e| format!("invalid day: {e}"))?; + let hour: u32 = clean[8..10] + .parse() + .map_err(|e| format!("invalid hour: {e}"))?; + let min: u32 = clean[10..12] + .parse() + .map_err(|e| format!("invalid minute: {e}"))?; + let sec: u32 = clean[12..14] + .parse() + .map_err(|e| format!("invalid second: {e}"))?; + + let naive = chrono::NaiveDate::from_ymd_opt(year, month, day) + .and_then(|d| d.and_hms_opt(hour, min, sec)) + .ok_or_else(|| format!("invalid date/time values in '{s}'"))?; + Ok(DateTime::from_naive_utc_and_offset(naive, Utc)) + } +} + +// --------------------------------------------------------------------------- +// Check 2: Unencrypted Administrative Service Exposal +// --------------------------------------------------------------------------- + +/// Well-known administrative and management TCP ports. +pub const COMMON_ADMIN_PORTS: &[u16] = &[8080, 8000, 8888, 9090, 9000, 8443, 10000]; + +/// Evaluates a raw HTTP response from a probed management port. +/// +/// If the service answers with plain HTTP and does NOT issue a redirect to HTTPS, +/// it is considered an unencrypted administrative interface exposure. +pub fn evaluate_http_admin_response(port: u16, response_headers: &str) -> Option { + let first_line = response_headers.lines().next().unwrap_or(""); + if !first_line.starts_with("HTTP/1.0") && !first_line.starts_with("HTTP/1.1") { + return None; + } + + let status_code: u16 = first_line + .split_whitespace() + .nth(1) + .and_then(|s| s.parse().ok()) + .unwrap_or(0); + + // If it is a redirect (301, 302, 307, 308) to HTTPS, it is properly secured + let is_https_redirect = + (status_code == 301 || status_code == 302 || status_code == 307 || status_code == 308) + && response_headers + .lines() + .any(|l| l.to_lowercase().starts_with("location:") && l.contains("https://")); + + if is_https_redirect { + return None; + } + + // HTTP 200, 401 (Auth required), 403 (Forbidden), 404 served in cleartext + Some(Finding { + tipo: FindingType::Check, + id: "admin-http-unencrypted".into(), + cvss: Some(6.5), + kev: false, + confianca: Confidence::Alto, + title: "Serviço Administrativo Exposto Sem TLS".into(), + description: format!( + "Porta de administração ({}) respondeu em HTTP claro (status {}) sem redirecionamento obrigatório para HTTPS, permitindo interceptação e roubo de credenciais.", + port, status_code + ), + evidencia: serde_json::json!({ + "port": port, + "status_code": status_code, + "first_line": first_line, + "is_redirect_to_https": false, + }), + }) +} + +/// Actively probes a TCP endpoint with an HTTP request to detect cleartext exposure. +pub async fn probe_unencrypted_admin_service( + addr: SocketAddr, + timeout_duration: Duration, +) -> Result, CheckError> { + let connect_future = TcpStream::connect(addr); + let mut stream = match tokio::time::timeout(timeout_duration, connect_future).await { + Ok(Ok(s)) => s, + _ => return Ok(None), + }; + + let req = format!( + "GET / HTTP/1.1\r\nHost: {}\r\nUser-Agent: xexeu-audit/0.1\r\nConnection: close\r\n\r\n", + addr + ); + + if (tokio::time::timeout(timeout_duration, stream.write_all(req.as_bytes())).await).is_err() { + return Ok(None); + } + + let mut buf = vec![0u8; 2048]; + let n = match tokio::time::timeout(timeout_duration, stream.read(&mut buf)).await { + Ok(Ok(n)) if n > 0 => n, + _ => return Ok(None), + }; + + let response_text = String::from_utf8_lossy(&buf[..n]); + Ok(evaluate_http_admin_response(addr.port(), &response_text)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::net::{IpAddr, Ipv4Addr}; + use tokio::net::TcpListener; + + #[test] + fn test_x509_der_not_after_parsing_and_expiring_check() { + // Construct a synthetic minimal DER certificate structure with notAfter = 2026-11-20 + // UTCTime format: "261120000000Z" + let not_before = b"261101000000Z"; + let not_after = b"261120000000Z"; + + // Build Validity SEQUENCE + let mut validity = vec![0x30]; + validity.push((2 + not_before.len() + 2 + not_after.len()) as u8); + validity.push(0x17); + validity.push(not_before.len() as u8); + validity.extend_from_slice(not_before); + validity.push(0x17); + validity.push(not_after.len() as u8); + validity.extend_from_slice(not_after); + + // Build minimal TBSCertificate: + // serialNumber (0x02, 0x01, 0x01), signature (0x30, 0x00), issuer (0x30, 0x00), validity + let mut tbs = vec![0x02, 0x01, 0x01, 0x30, 0x00, 0x30, 0x00]; + tbs.extend_from_slice(&validity); + + let mut tbs_seq = vec![0x30, tbs.len() as u8]; + tbs_seq.extend_from_slice(&tbs); + + // Wrap into Certificate SEQUENCE + let mut cert = vec![0x30, tbs_seq.len() as u8]; + cert.extend_from_slice(&tbs_seq); + + let parsed = parse_x509_der_not_after(&cert).expect("DER parse success"); + assert_eq!( + parsed, + DateTime::parse_from_rfc3339("2026-11-20T00:00:00Z").unwrap() + ); + + // Case A: Evaluated on 2026-11-01 -> 19 days remaining (< 30 days -> expiring) + let eval_time = DateTime::parse_from_rfc3339("2026-11-01T00:00:00Z") + .unwrap() + .with_timezone(&Utc); + let finding = check_tls_certificate_der(&cert, Some(eval_time)) + .unwrap() + .expect("finding emitted"); + assert_eq!(finding.id, "tls-cert-expiring"); + assert_eq!(finding.confianca, Confidence::Alto); + + // Case B: Evaluated on 2026-12-01 -> expired + let eval_expired = DateTime::parse_from_rfc3339("2026-12-01T00:00:00Z") + .unwrap() + .with_timezone(&Utc); + let finding_exp = check_tls_certificate_der(&cert, Some(eval_expired)) + .unwrap() + .expect("finding emitted"); + assert_eq!(finding_exp.id, "tls-cert-expired"); + + // Case C: Evaluated on 2026-10-01 -> 50 days remaining (>= 30 days -> no finding) + let eval_safe = DateTime::parse_from_rfc3339("2026-10-01T00:00:00Z") + .unwrap() + .with_timezone(&Utc); + let finding_safe = check_tls_certificate_der(&cert, Some(eval_safe)).unwrap(); + assert!(finding_safe.is_none()); + } + + #[test] + fn test_evaluate_http_admin_response() { + // Plain HTTP 200 on port 8080 without TLS + let resp_plain = + "HTTP/1.1 200 OK\r\nServer: Tomcat\r\nContent-Length: 10\r\n\r\nHello Admin"; + let finding = evaluate_http_admin_response(8080, resp_plain).expect("finding expected"); + assert_eq!(finding.id, "admin-http-unencrypted"); + assert_eq!(finding.cvss, Some(6.5)); + + // HTTP 301 Redirect to HTTPS + let resp_redirect = + "HTTP/1.1 301 Moved Permanently\r\nLocation: https://example.org:8443/\r\n\r\n"; + let no_finding = evaluate_http_admin_response(8080, resp_redirect); + assert!(no_finding.is_none()); + } + + #[tokio::test] + async fn test_probe_unencrypted_admin_service_live_listener() { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + + tokio::spawn(async move { + if let Ok((mut socket, _)) = listener.accept().await { + let mut buf = [0u8; 512]; + let _ = socket.read(&mut buf).await; + let reply = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK"; + let _ = socket.write_all(reply.as_bytes()).await; + } + }); + + let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port); + let finding = probe_unencrypted_admin_service(addr, Duration::from_millis(500)) + .await + .unwrap() + .expect("should detect exposed HTTP admin"); + + assert_eq!(finding.id, "admin-http-unencrypted"); + } +} diff --git a/crates/xexeu-core/src/vuln/feeds.rs b/crates/xexeu-core/src/vuln/feeds.rs index 0f87748..0495d3b 100644 --- a/crates/xexeu-core/src/vuln/feeds.rs +++ b/crates/xexeu-core/src/vuln/feeds.rs @@ -1,2 +1,549 @@ -//! Imports and incrementally syncs NVD CVE JSON 2.0 and the CISA KEV catalog into the local base. -// TODO: implement feed sync and offline import. +//! Vulnerability feed ingestion for NVD CVE JSON 2.0 and CISA KEV catalogs (offline mode). +//! +//! This module provides deterministic parsers for local NVD and CISA KEV feeds, +//! indexing them into memory for fast lookup during service banner correlation. + +use serde::{Deserialize, Serialize}; +use std::collections::{HashMap, HashSet}; +use std::fs::File; +use std::io::{BufRead, BufReader}; +use std::path::Path; +use thiserror::Error; + +/// Error encountered during feed import. +#[derive(Debug, Error)] +pub enum FeedError { + #[error("I/O error reading feed file '{path}': {source}")] + Io { + path: String, + #[source] + source: std::io::Error, + }, + #[error("JSON parsing error in '{path}': {source}")] + Json { + path: String, + #[source] + source: serde_json::Error, + }, + #[error("Invalid feed format in '{path}': {detail}")] + Format { path: String, detail: String }, +} + +/// Structured Common Platform Enumeration (CPE) representation. +/// +/// Supports CPE 2.3 format (`cpe:2.3:part:vendor:product:version:...`) +/// as well as CPE 2.2 URI format (`cpe:/part:vendor:product:version`). +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct Cpe { + /// Part: "a" (application), "o" (operating system), "h" (hardware). + pub part: String, + /// Vendor name (e.g. "openbsd", "apache", "f5"). + pub vendor: String, + /// Product name (e.g. "openssh", "http_server", "nginx"). + pub product: String, + /// Version string, or "*" / "-" if unconstrained. + pub version: String, + /// Update/patch string, or "*". + pub update: String, +} + +impl Cpe { + /// Parses a CPE 2.3 or 2.2 string. + pub fn parse(s: &str) -> Result { + let trimmed = s.trim(); + if trimmed.starts_with("cpe:2.3:") { + let parts: Vec<&str> = trimmed.split(':').collect(); + if parts.len() < 6 { + return Err(format!("CPE 2.3 string has too few components: '{s}'")); + } + Ok(Self { + part: parts[2].to_lowercase(), + vendor: parts[3].to_lowercase(), + product: parts[4].to_lowercase(), + version: parts[5].to_string(), + update: parts.get(6).unwrap_or(&"*").to_string(), + }) + } else if let Some(body) = trimmed.strip_prefix("cpe:/") { + let parts: Vec<&str> = body.split(':').collect(); + if parts.len() < 3 { + return Err(format!("CPE 2.2 URI has too few components: '{s}'")); + } + Ok(Self { + part: parts[0].to_lowercase(), + vendor: parts[1].to_lowercase(), + product: parts[2].to_lowercase(), + version: parts.get(3).unwrap_or(&"*").to_string(), + update: parts.get(4).unwrap_or(&"*").to_string(), + }) + } else { + Err(format!("unrecognized CPE format: '{s}'")) + } + } + + /// Formats as standard CPE 2.3 string. + pub fn to_cpe23(&self) -> String { + format!( + "cpe:2.3:{}:{}:{}:{}:{}:*:*:*:*:*:*", + self.part, self.vendor, self.product, self.version, self.update + ) + } +} + +/// CPE match criteria inside an NVD configuration node. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct CpeMatchCriteria { + pub criteria: String, + pub cpe: Cpe, + pub version_start_including: Option, + pub version_start_excluding: Option, + pub version_end_including: Option, + pub version_end_excluding: Option, +} + +/// Normalized CVE record from the NVD feed. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct CveRecord { + pub id: String, + pub description: String, + pub cvss_score: Option, + pub cvss_vector: Option, + pub cpe_matches: Vec, +} + +/// In-memory catalog of NVD vulnerabilities. +#[derive(Debug, Clone, Default)] +pub struct NvdCatalog { + pub records: HashMap, +} + +/// In-memory catalog of CISA Known Exploited Vulnerabilities (KEV). +#[derive(Debug, Clone, Default)] +pub struct KevCatalog { + pub cve_ids: HashSet, +} + +/// Combined local vulnerability database. +#[derive(Debug, Clone, Default)] +pub struct VulnDatabase { + pub nvd: NvdCatalog, + pub kev: KevCatalog, +} + +impl VulnDatabase { + /// Loads both NVD and CISA KEV feeds from local files (offline mode). + pub fn load_offline(nvd_path: &Path, kev_path: Option<&Path>) -> Result { + let nvd = import_nvd(nvd_path)?; + let kev = if let Some(kp) = kev_path { + import_kev(kp)? + } else { + KevCatalog::default() + }; + Ok(Self { nvd, kev }) + } + + /// Checks if a CVE ID is listed in the CISA KEV catalog. + pub fn is_in_kev(&self, cve_id: &str) -> bool { + self.kev.cve_ids.contains(cve_id) + } +} + +// --------------------------------------------------------------------------- +// NVD JSON 2.0 Deserialization DTOs +// --------------------------------------------------------------------------- + +#[derive(Deserialize)] +struct NvdFeedDto { + #[serde(default)] + vulnerabilities: Vec, +} + +#[derive(Deserialize)] +struct NvdVulnItemDto { + cve: NvdCveDto, +} + +#[derive(Deserialize)] +struct NvdCveDto { + id: String, + #[serde(default)] + descriptions: Vec, + #[serde(default)] + metrics: Option, + #[serde(default)] + configurations: Vec, +} + +#[derive(Deserialize)] +struct NvdDescriptionDto { + lang: String, + value: String, +} + +#[derive(Deserialize)] +struct NvdMetricsDto { + #[serde(rename = "cvssMetricV31")] + cvss_v31: Option>, + #[serde(rename = "cvssMetricV30")] + cvss_v30: Option>, + #[serde(rename = "cvssMetricV2")] + cvss_v2: Option>, +} + +#[derive(Deserialize)] +struct NvdCvssMetricItemDto { + #[serde(rename = "cvssData")] + cvss_data: NvdCvssDataDto, +} + +#[derive(Deserialize)] +struct NvdCvssDataDto { + #[serde(rename = "baseScore")] + base_score: f32, + #[serde(rename = "vectorString")] + vector_string: Option, +} + +#[derive(Deserialize)] +struct NvdCvssMetricV2ItemDto { + #[serde(rename = "cvssData")] + cvss_data: NvdCvssDataDto, +} + +#[derive(Deserialize)] +struct NvdConfigurationDto { + #[serde(default)] + nodes: Vec, +} + +#[derive(Deserialize)] +struct NvdNodeDto { + #[serde(rename = "cpeMatch", default)] + cpe_match: Vec, +} + +#[derive(Deserialize)] +struct NvdCpeMatchDto { + criteria: String, + #[serde(default = "default_true")] + vulnerable: bool, + #[serde(rename = "versionStartIncluding")] + version_start_including: Option, + #[serde(rename = "versionStartExcluding")] + version_start_excluding: Option, + #[serde(rename = "versionEndIncluding")] + version_end_including: Option, + #[serde(rename = "versionEndExcluding")] + version_end_excluding: Option, +} + +fn default_true() -> bool { + true +} + +/// Imports an NVD CVE JSON 2.0 file from disk. +pub fn import_nvd(path: &Path) -> Result { + let file = File::open(path).map_err(|e| FeedError::Io { + path: path.display().to_string(), + source: e, + })?; + let reader = BufReader::new(file); + + let dto: NvdFeedDto = serde_json::from_reader(reader).map_err(|e| FeedError::Json { + path: path.display().to_string(), + source: e, + })?; + + let mut records = HashMap::with_capacity(dto.vulnerabilities.len()); + + for item in dto.vulnerabilities { + let cve_id = item.cve.id; + let description = item + .cve + .descriptions + .iter() + .find(|d| d.lang == "en") + .map(|d| d.value.clone()) + .unwrap_or_else(|| { + item.cve + .descriptions + .first() + .map(|d| d.value.clone()) + .unwrap_or_default() + }); + + let mut cvss_score = None; + let mut cvss_vector = None; + + if let Some(metrics) = item.cve.metrics { + if let Some(v31) = metrics.cvss_v31.and_then(|v| v.into_iter().next()) { + cvss_score = Some(v31.cvss_data.base_score); + cvss_vector = v31.cvss_data.vector_string; + } else if let Some(v30) = metrics.cvss_v30.and_then(|v| v.into_iter().next()) { + cvss_score = Some(v30.cvss_data.base_score); + cvss_vector = v30.cvss_data.vector_string; + } else if let Some(v2) = metrics.cvss_v2.and_then(|v| v.into_iter().next()) { + cvss_score = Some(v2.cvss_data.base_score); + cvss_vector = v2.cvss_data.vector_string; + } + } + + let mut cpe_matches = Vec::new(); + for config in item.cve.configurations { + for node in config.nodes { + for m in node.cpe_match { + if !m.vulnerable { + continue; + } + if let Ok(cpe) = Cpe::parse(&m.criteria) { + cpe_matches.push(CpeMatchCriteria { + criteria: m.criteria, + cpe, + version_start_including: m.version_start_including, + version_start_excluding: m.version_start_excluding, + version_end_including: m.version_end_including, + version_end_excluding: m.version_end_excluding, + }); + } + } + } + } + + records.insert( + cve_id.clone(), + CveRecord { + id: cve_id, + description, + cvss_score, + cvss_vector, + cpe_matches, + }, + ); + } + + Ok(NvdCatalog { records }) +} + +// --------------------------------------------------------------------------- +// CISA KEV Ingestion (JSON and CSV) +// --------------------------------------------------------------------------- + +#[derive(Deserialize)] +struct KevJsonDto { + #[serde(default)] + vulnerabilities: Vec, +} + +#[derive(Deserialize)] +struct KevItemDto { + #[serde(rename = "cveID")] + cve_id: String, +} + +/// Imports CISA Known Exploited Vulnerabilities from a JSON or CSV file. +pub fn import_kev(path: &Path) -> Result { + let file = File::open(path).map_err(|e| FeedError::Io { + path: path.display().to_string(), + source: e, + })?; + let mut reader = BufReader::new(file); + + // Peek the first non-whitespace character to distinguish JSON from CSV + let mut first_line = String::new(); + reader + .read_line(&mut first_line) + .map_err(|e| FeedError::Io { + path: path.display().to_string(), + source: e, + })?; + + let trimmed = first_line.trim_start(); + let mut cve_ids = HashSet::new(); + + if trimmed.starts_with('{') { + // Re-read entire JSON + let file = File::open(path).map_err(|e| FeedError::Io { + path: path.display().to_string(), + source: e, + })?; + let dto: KevJsonDto = + serde_json::from_reader(BufReader::new(file)).map_err(|e| FeedError::Json { + path: path.display().to_string(), + source: e, + })?; + for item in dto.vulnerabilities { + cve_ids.insert(item.cve_id); + } + } else { + // CSV parsing: column 0 is typically cveID + if !trimmed.starts_with("cveID") && trimmed.contains("CVE-") { + if let Some(id) = extract_cve_from_line(trimmed) { + cve_ids.insert(id); + } + } + for line_res in reader.lines() { + let line = line_res.map_err(|e| FeedError::Io { + path: path.display().to_string(), + source: e, + })?; + if let Some(id) = extract_cve_from_line(&line) { + cve_ids.insert(id); + } + } + } + + Ok(KevCatalog { cve_ids }) +} + +fn extract_cve_from_line(line: &str) -> Option { + let col = line.split(',').next()?.trim().trim_matches('"'); + if col.starts_with("CVE-") { + Some(col.to_string()) + } else { + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + use tempfile::NamedTempFile; + + #[test] + fn test_cpe_parsing() { + let cpe23 = Cpe::parse("cpe:2.3:a:openbsd:openssh:9.3p1:*:*:*:*:*:*:*").unwrap(); + assert_eq!(cpe23.part, "a"); + assert_eq!(cpe23.vendor, "openbsd"); + assert_eq!(cpe23.product, "openssh"); + assert_eq!(cpe23.version, "9.3p1"); + + let cpe22 = Cpe::parse("cpe:/a:apache:http_server:2.4.49").unwrap(); + assert_eq!(cpe22.part, "a"); + assert_eq!(cpe22.vendor, "apache"); + assert_eq!(cpe22.product, "http_server"); + assert_eq!(cpe22.version, "2.4.49"); + } + + #[test] + fn test_import_nvd_fixture() { + let nvd_json = r#"{ + "format": "NVD_CVE", + "version": "2.0", + "vulnerabilities": [ + { + "cve": { + "id": "CVE-2024-6387", + "descriptions": [ + {"lang": "en", "value": "A signal handler race condition was found in OpenSSH..."} + ], + "metrics": { + "cvssMetricV31": [ + { + "cvssData": { + "version": "3.1", + "vectorString": "CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H", + "baseScore": 8.1 + } + } + ] + }, + "configurations": [ + { + "nodes": [ + { + "cpeMatch": [ + { + "criteria": "cpe:2.3:a:openbsd:openssh:*:*:*:*:*:*:*:*", + "versionStartIncluding": "8.5p1", + "versionEndExcluding": "9.8p1", + "vulnerable": true + } + ] + } + ] + } + ] + } + }, + { + "cve": { + "id": "CVE-2021-41773", + "descriptions": [ + {"lang": "en", "value": "A flaw was found in a change made to path normalization in Apache HTTP Server 2.4.49."} + ], + "metrics": { + "cvssMetricV31": [ + { + "cvssData": { + "baseScore": 7.5 + } + } + ] + }, + "configurations": [ + { + "nodes": [ + { + "cpeMatch": [ + { + "criteria": "cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*", + "vulnerable": true + } + ] + } + ] + } + ] + } + } + ] + }"#; + + let mut file = NamedTempFile::new().unwrap(); + file.write_all(nvd_json.as_bytes()).unwrap(); + + let catalog = import_nvd(file.path()).unwrap(); + assert_eq!(catalog.records.len(), 2); + + let openssh = catalog.records.get("CVE-2024-6387").unwrap(); + assert_eq!(openssh.cvss_score, Some(8.1)); + assert_eq!(openssh.cpe_matches.len(), 1); + assert_eq!( + openssh.cpe_matches[0].version_start_including.as_deref(), + Some("8.5p1") + ); + assert_eq!( + openssh.cpe_matches[0].version_end_excluding.as_deref(), + Some("9.8p1") + ); + + let apache = catalog.records.get("CVE-2021-41773").unwrap(); + assert_eq!(apache.cvss_score, Some(7.5)); + assert_eq!(apache.cpe_matches[0].cpe.version, "2.4.49"); + } + + #[test] + fn test_import_kev_json_and_csv() { + // Test JSON format + let kev_json = r#"{ + "title": "CISA KEV", + "vulnerabilities": [ + {"cveID": "CVE-2021-41773"} + ] + }"#; + let mut f_json = NamedTempFile::new().unwrap(); + f_json.write_all(kev_json.as_bytes()).unwrap(); + + let kev = import_kev(f_json.path()).unwrap(); + assert!(kev.cve_ids.contains("CVE-2021-41773")); + assert!(!kev.cve_ids.contains("CVE-2024-6387")); + + // Test CSV format + let kev_csv = "cveID,vendorProject,product\nCVE-2024-6387,OpenBSD,OpenSSH\n"; + let mut f_csv = NamedTempFile::new().unwrap(); + f_csv.write_all(kev_csv.as_bytes()).unwrap(); + + let kev_csv_parsed = import_kev(f_csv.path()).unwrap(); + assert!(kev_csv_parsed.cve_ids.contains("CVE-2024-6387")); + } +} diff --git a/crates/xexeu-core/src/vuln/matcher.rs b/crates/xexeu-core/src/vuln/matcher.rs index 297fa71..29139f1 100644 --- a/crates/xexeu-core/src/vuln/matcher.rs +++ b/crates/xexeu-core/src/vuln/matcher.rs @@ -1,2 +1,555 @@ -//! Correlates a candidate CPE with NVD configurations, honoring version ranges and assigning a confidence level. -// TODO: implement CPE-to-CVE matching with version-range comparison. +//! Banner normalization, candidate CPE derivation, and deterministic CVE correlation. +//! +//! # Heuristic Banner Parsing Limitations +//! +//! Service banner fingerprinting has inherent real-world limitations: +//! 1. **Distribution Backports:** Linux distributions (Debian, Ubuntu, RHEL) frequently +//! backport security patches to older upstream versions (e.g. `OpenSSH_8.9p1 Ubuntu-3ubuntu0.10`). +//! In such cases, a pure version check will flag a CVE that may already be patched downstream. +//! When distribution indicators are present, the match confidence is reduced to +//! [`Confidence::Medio`] (`provavel`) and a backport note is added to the evidence JSON. +//! 2. **Custom / Stripped Banners:** Some administrators obfuscate or truncate banners +//! (e.g. `Server: Apache` without version). In this case, no CVE findings are emitted +//! or only informative low-confidence events are produced. +//! 3. **Non-Standard Formats:** Non-standard daemon banners without delimiters may not +//! yield clean CPE candidate records. + +use super::feeds::{Cpe, CpeMatchCriteria, VulnDatabase}; +use serde::{Deserialize, Serialize}; +use std::cmp::Ordering; + +/// Finding classification type. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum FindingType { + Cve, + Check, +} + +/// Assessment confidence level for a vulnerability finding. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum Confidence { + /// Exact product and version extracted from banner matched the vulnerable range, + /// with no unresolved distribution backport suffixes (`confirmada-por-versao`). + #[serde(rename = "confirmada-por-versao", alias = "alto", alias = "Alto")] + Alto, + /// Product matched and version fell within criteria, but distribution backport + /// indicators (e.g. `Ubuntu-`, `Debian-`) suggest the flaw might be patched (`provavel`). + #[serde(rename = "provavel", alias = "medio", alias = "Medio")] + Medio, + /// Product identified with ambiguous version or generic heuristic (`indeterminada`). + #[serde(rename = "indeterminada", alias = "baixo", alias = "Baixo")] + Baixo, +} + +/// Vulnerability or configuration security finding. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Finding { + /// Finding category: CVE or configuration check. + pub tipo: FindingType, + /// Unique identifier: e.g. "CVE-2024-6387" or "tls-cert-expiring". + pub id: String, + /// CVSS base score (0.0 to 10.0), if available. + pub cvss: Option, + /// Whether the vulnerability is cataloged in CISA KEV (actively exploited). + pub kev: bool, + /// Confidence level in the finding's accuracy. + pub confianca: Confidence, + /// Short summary title. + pub title: String, + /// Explanatory description. + pub description: String, + /// Verifiable deterministic JSON evidence. + pub evidencia: serde_json::Value, +} + +/// Candidate information parsed from a raw service banner. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BannerInfo { + /// Normalized candidate CPE. + pub cpe: Cpe, + /// Detected product display name. + pub product_name: String, + /// Extracted version string (if any). + pub version: Option, + /// Whether distribution-specific backport indicators were observed. + pub is_backport: bool, + /// The original raw banner. + pub raw_banner: String, +} + +/// Heuristically derives a candidate [`BannerInfo`] and [`Cpe`] from a banner string. +pub fn parse_banner_to_cpe(banner: &str) -> Option { + let trimmed = banner.trim(); + if trimmed.is_empty() { + return None; + } + + let is_backport = trimmed.contains("Ubuntu") + || trimmed.contains("Debian") + || trimmed.contains("CentOS") + || trimmed.contains("Red Hat") + || trimmed.contains("RHEL") + || trimmed.contains("el7") + || trimmed.contains("el8") + || trimmed.contains("el9"); + + // Case 1: SSH banner (e.g. "SSH-2.0-OpenSSH_8.9p1 Ubuntu-3ubuntu0.10" or "OpenSSH_9.3p1") + if let Some(pos) = trimmed.find("OpenSSH") { + let after = &trimmed[pos + "OpenSSH".len()..]; + let after = after.trim_start_matches(['_', '/', ' ']); + let version_token = after.split_whitespace().next().unwrap_or(""); + let version = clean_version_token(version_token); + + let cpe = Cpe { + part: "a".into(), + vendor: "openbsd".into(), + product: "openssh".into(), + version: if version.is_empty() { + "*".into() + } else { + version.clone() + }, + update: "*".into(), + }; + + return Some(BannerInfo { + cpe, + product_name: "OpenSSH".into(), + version: if version.is_empty() { + None + } else { + Some(version) + }, + is_backport, + raw_banner: trimmed.into(), + }); + } + + // Case 2: Apache HTTP Server (e.g. "Server: Apache/2.4.49 (Unix)" or "Apache/2.4.49") + if let Some(pos) = trimmed.find("Apache") { + let after = &trimmed[pos + "Apache".len()..]; + let after = after.trim_start_matches(['/', ' ']); + let version_token = after.split_whitespace().next().unwrap_or(""); + let version = clean_version_token(version_token); + + let cpe = Cpe { + part: "a".into(), + vendor: "apache".into(), + product: "http_server".into(), + version: if version.is_empty() { + "*".into() + } else { + version.clone() + }, + update: "*".into(), + }; + + return Some(BannerInfo { + cpe, + product_name: "Apache HTTP Server".into(), + version: if version.is_empty() { + None + } else { + Some(version) + }, + is_backport, + raw_banner: trimmed.into(), + }); + } + + // Case 3: Nginx (e.g. "Server: nginx/1.18.0" or "nginx/1.24.0") + if let Some(pos) = trimmed.to_lowercase().find("nginx") { + let after = &trimmed[pos + "nginx".len()..]; + let after = after.trim_start_matches(['/', ' ']); + let version_token = after.split_whitespace().next().unwrap_or(""); + let version = clean_version_token(version_token); + + let cpe = Cpe { + part: "a".into(), + vendor: "f5".into(), + product: "nginx".into(), + version: if version.is_empty() { + "*".into() + } else { + version.clone() + }, + update: "*".into(), + }; + + return Some(BannerInfo { + cpe, + product_name: "nginx".into(), + version: if version.is_empty() { + None + } else { + Some(version) + }, + is_backport, + raw_banner: trimmed.into(), + }); + } + + // Case 4: Generic HTTP "Server: Product/Version" or "Product/Version" + let probe = if let Some(stripped) = trimmed.strip_prefix("Server:") { + stripped.trim() + } else { + trimmed + }; + + if let Some((prod, rest)) = probe.split_once('/') { + let prod = prod.trim(); + let version_token = rest.split_whitespace().next().unwrap_or(""); + let version = clean_version_token(version_token); + + if !prod.is_empty() && !version.is_empty() { + let prod_lower = prod.to_lowercase(); + let cpe = Cpe { + part: "a".into(), + vendor: prod_lower.clone(), + product: prod_lower, + version: version.clone(), + update: "*".into(), + }; + + return Some(BannerInfo { + cpe, + product_name: prod.into(), + version: Some(version), + is_backport, + raw_banner: trimmed.into(), + }); + } + } + + None +} + +fn clean_version_token(s: &str) -> String { + let s = s.trim_matches(|c: char| !c.is_alphanumeric() && c != '.'); + s.to_string() +} + +// --------------------------------------------------------------------------- +// Deterministic Version Parsing & Comparison +// --------------------------------------------------------------------------- + +#[derive(Debug, Clone, PartialEq, Eq)] +enum VersionChunk { + Num(u64), + Str(String), +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct ParsedVersion { + chunks: Vec, +} + +impl ParsedVersion { + fn parse(v: &str) -> Self { + let mut chunks = Vec::new(); + let mut current_num: Option = None; + let mut current_str = String::new(); + + for ch in v.chars() { + if ch.is_ascii_digit() { + if !current_str.is_empty() { + chunks.push(VersionChunk::Str(std::mem::take(&mut current_str))); + } + let digit = ch.to_digit(10).unwrap() as u64; + current_num = Some( + current_num + .unwrap_or(0) + .saturating_mul(10) + .saturating_add(digit), + ); + } else if ch.is_alphabetic() { + if let Some(n) = current_num.take() { + chunks.push(VersionChunk::Num(n)); + } + current_str.push(ch.to_ascii_lowercase()); + } else { + // delimiter (e.g. '.', '-', '_') + if let Some(n) = current_num.take() { + chunks.push(VersionChunk::Num(n)); + } + if !current_str.is_empty() { + chunks.push(VersionChunk::Str(std::mem::take(&mut current_str))); + } + } + } + + if let Some(n) = current_num { + chunks.push(VersionChunk::Num(n)); + } + if !current_str.is_empty() { + chunks.push(VersionChunk::Str(current_str)); + } + + Self { chunks } + } +} + +impl PartialOrd for ParsedVersion { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for ParsedVersion { + fn cmp(&self, other: &Self) -> Ordering { + let min_len = self.chunks.len().min(other.chunks.len()); + for i in 0..min_len { + match (&self.chunks[i], &other.chunks[i]) { + (VersionChunk::Num(a), VersionChunk::Num(b)) => { + let ord = a.cmp(b); + if ord != Ordering::Equal { + return ord; + } + } + (VersionChunk::Str(a), VersionChunk::Str(b)) => { + let ord = a.cmp(b); + if ord != Ordering::Equal { + return ord; + } + } + (VersionChunk::Num(_), VersionChunk::Str(_)) => return Ordering::Greater, + (VersionChunk::Str(_), VersionChunk::Num(_)) => return Ordering::Less, + } + } + self.chunks.len().cmp(&other.chunks.len()) + } +} + +fn version_matches_criteria(candidate_v: &str, criteria: &CpeMatchCriteria) -> bool { + let cand = ParsedVersion::parse(candidate_v); + + // Exact version in criteria (if specified and not wildcard) + if criteria.cpe.version != "*" && criteria.cpe.version != "-" { + let crit_ver = ParsedVersion::parse(&criteria.cpe.version); + if cand != crit_ver { + return false; + } + } + + if let Some(start_inc) = &criteria.version_start_including { + if cand < ParsedVersion::parse(start_inc) { + return false; + } + } + if let Some(start_exc) = &criteria.version_start_excluding { + if cand <= ParsedVersion::parse(start_exc) { + return false; + } + } + if let Some(end_inc) = &criteria.version_end_including { + if cand > ParsedVersion::parse(end_inc) { + return false; + } + } + if let Some(end_exc) = &criteria.version_end_excluding { + if cand >= ParsedVersion::parse(end_exc) { + return false; + } + } + + true +} + +/// Matches a candidate [`BannerInfo`] against the local vulnerability database. +/// +/// Returns a deterministically sorted list of [`Finding`]s. +pub fn match_banner(banner_info: &BannerInfo, db: &VulnDatabase) -> Vec { + let mut findings = Vec::new(); + let cand_cpe = &banner_info.cpe; + + for (cve_id, record) in &db.nvd.records { + for criteria in &record.cpe_matches { + // Check product match (vendor and product) + let vendor_match = criteria.cpe.vendor == cand_cpe.vendor + || (criteria.cpe.vendor == "f5" && cand_cpe.vendor == "nginx") + || (criteria.cpe.vendor == "nginx" && cand_cpe.vendor == "f5"); + + let product_match = criteria.cpe.product == cand_cpe.product; + + if !vendor_match || !product_match { + continue; + } + + // Check version range match + if cand_cpe.version == "*" { + // If candidate has no version, do not generate false CVE positives + continue; + } + + if version_matches_criteria(&cand_cpe.version, criteria) { + let kev = db.is_in_kev(cve_id); + let confianca = if banner_info.is_backport { + Confidence::Medio + } else { + Confidence::Alto + }; + + let rule_str = format!( + "criteria={}; start_inc={:?}; end_exc={:?}", + criteria.criteria, + criteria.version_start_including, + criteria.version_end_excluding + ); + + findings.push(Finding { + tipo: FindingType::Cve, + id: cve_id.clone(), + cvss: record.cvss_score, + kev, + confianca, + title: format!("{}: {}", cve_id, banner_info.product_name), + description: record.description.clone(), + evidencia: serde_json::json!({ + "banner": banner_info.raw_banner, + "cpe": cand_cpe.to_cpe23(), + "matched_criteria": criteria.criteria, + "rule": rule_str, + "distribution_backport_suspected": banner_info.is_backport, + }), + }); + break; // One match per CVE record is sufficient + } + } + } + + // Deterministic sorting: + // 1. KEV first (actively exploited) + // 2. Highest CVSS score first (None sorted last) + // 3. Alphabetical by CVE ID ascending + findings.sort_by(|a, b| { + b.kev + .cmp(&a.kev) + .then_with(|| { + let cvss_a = a.cvss.unwrap_or(0.0); + let cvss_b = b.cvss.unwrap_or(0.0); + cvss_b.partial_cmp(&cvss_a).unwrap_or(Ordering::Equal) + }) + .then_with(|| a.id.cmp(&b.id)) + }); + + findings +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::vuln::feeds::{CveRecord, KevCatalog, NvdCatalog}; + use std::collections::{HashMap, HashSet}; + + #[test] + fn test_version_ordering() { + assert!(ParsedVersion::parse("8.5p1") < ParsedVersion::parse("9.3p1")); + assert!(ParsedVersion::parse("9.3p1") < ParsedVersion::parse("9.8p1")); + assert!(ParsedVersion::parse("2.4.48") < ParsedVersion::parse("2.4.49")); + assert!(ParsedVersion::parse("2.4.49") < ParsedVersion::parse("2.4.50")); + assert_eq!( + ParsedVersion::parse("2.4.49"), + ParsedVersion::parse("2.4.49") + ); + } + + #[test] + fn test_parse_banner_openssh_with_backport() { + let banner = "SSH-2.0-OpenSSH_8.9p1 Ubuntu-3ubuntu0.10"; + let info = parse_banner_to_cpe(banner).unwrap(); + + assert_eq!(info.product_name, "OpenSSH"); + assert_eq!(info.cpe.vendor, "openbsd"); + assert_eq!(info.cpe.product, "openssh"); + assert_eq!(info.cpe.version, "8.9p1"); + assert!(info.is_backport); + } + + #[test] + fn test_parse_banner_apache() { + let banner = "Server: Apache/2.4.49 (Unix) OpenSSL/1.1.1k"; + let info = parse_banner_to_cpe(banner).unwrap(); + + assert_eq!(info.product_name, "Apache HTTP Server"); + assert_eq!(info.cpe.vendor, "apache"); + assert_eq!(info.cpe.product, "http_server"); + assert_eq!(info.cpe.version, "2.4.49"); + assert!(!info.is_backport); + } + + #[test] + fn test_matcher_deterministic_ranking() { + let mut records = HashMap::new(); + + // CVE-2024-6387: OpenSSH 8.5p1 - 9.8p1 (cvss 8.1, not in KEV) + records.insert( + "CVE-2024-6387".into(), + CveRecord { + id: "CVE-2024-6387".into(), + description: "OpenSSH regreSSHion flaw".into(), + cvss_score: Some(8.1), + cvss_vector: None, + cpe_matches: vec![CpeMatchCriteria { + criteria: "cpe:2.3:a:openbsd:openssh:*:*:*:*:*:*:*:*".into(), + cpe: Cpe::parse("cpe:2.3:a:openbsd:openssh:*:*:*:*:*:*:*:*").unwrap(), + version_start_including: Some("8.5p1".into()), + version_start_excluding: None, + version_end_including: None, + version_end_excluding: Some("9.8p1".into()), + }], + }, + ); + + // CVE-2021-41773: Apache 2.4.49 (cvss 7.5, IN KEV) + records.insert( + "CVE-2021-41773".into(), + CveRecord { + id: "CVE-2021-41773".into(), + description: "Apache path traversal".into(), + cvss_score: Some(7.5), + cvss_vector: None, + cpe_matches: vec![CpeMatchCriteria { + criteria: "cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*".into(), + cpe: Cpe::parse("cpe:2.3:a:apache:http_server:2.4.49:*:*:*:*:*:*:*").unwrap(), + version_start_including: None, + version_start_excluding: None, + version_end_including: None, + version_end_excluding: None, + }], + }, + ); + + let mut kev_ids = HashSet::new(); + kev_ids.insert("CVE-2021-41773".into()); + + let db = VulnDatabase { + nvd: NvdCatalog { records }, + kev: KevCatalog { cve_ids: kev_ids }, + }; + + // Match OpenSSH 9.3p1 (clean, no backport) + let info_clean = parse_banner_to_cpe("SSH-2.0-OpenSSH_9.3p1").unwrap(); + let findings_clean = match_banner(&info_clean, &db); + assert_eq!(findings_clean.len(), 1); + assert_eq!(findings_clean[0].id, "CVE-2024-6387"); + assert_eq!(findings_clean[0].confianca, Confidence::Alto); + assert!(!findings_clean[0].kev); + + // Match OpenSSH 8.9p1 Ubuntu (backport detected) + let info_backport = + parse_banner_to_cpe("SSH-2.0-OpenSSH_8.9p1 Ubuntu-3ubuntu0.10").unwrap(); + let findings_backport = match_banner(&info_backport, &db); + assert_eq!(findings_backport.len(), 1); + assert_eq!(findings_backport[0].confianca, Confidence::Medio); + + // Match Apache 2.4.49 (listed in KEV) + let info_apache = parse_banner_to_cpe("Server: Apache/2.4.49 (Unix)").unwrap(); + let findings_apache = match_banner(&info_apache, &db); + assert_eq!(findings_apache.len(), 1); + assert_eq!(findings_apache[0].id, "CVE-2021-41773"); + assert!(findings_apache[0].kev); + assert_eq!(findings_apache[0].confianca, Confidence::Alto); + } +} diff --git a/crates/xexeu-core/src/vuln/mod.rs b/crates/xexeu-core/src/vuln/mod.rs index 4972708..1ac972e 100644 --- a/crates/xexeu-core/src/vuln/mod.rs +++ b/crates/xexeu-core/src/vuln/mod.rs @@ -3,3 +3,15 @@ pub mod checks; pub mod feeds; pub mod matcher; + +pub use checks::{ + check_tls_certificate_der, evaluate_http_admin_response, parse_x509_der_not_after, + probe_unencrypted_admin_service, CheckError, COMMON_ADMIN_PORTS, +}; +pub use feeds::{ + import_kev, import_nvd, Cpe, CpeMatchCriteria, CveRecord, FeedError, KevCatalog, NvdCatalog, + VulnDatabase, +}; +pub use matcher::{ + match_banner, parse_banner_to_cpe, BannerInfo, Confidence, Finding, FindingType, +};