feat(api,gui): implement target groups CRUD, scanner hot-reload, and CSV export
This commit is contained in:
1 parent
bc72dbffbd
commit
e8e529b09c
7 files changed
+1154
-41
No files matched your search
+117
-17
@@ -3,7 +3,7 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use chrono::{DateTime, TimeZone, Utc};
|
||||
use serde::Deserialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::schedule::{CronSpec, Jitter, ScheduleError};
|
||||
@@ -15,7 +15,7 @@ pub const MIN_INTERVAL_SECS: i64 = 300;
|
||||
const REFERENCE_INSTANT: i64 = 1_700_000_000;
|
||||
|
||||
/// Root configuration document.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct XexeuConfig {
|
||||
/// Authorized scope shared by every group.
|
||||
#[serde(rename = "escopo")]
|
||||
@@ -32,18 +32,22 @@ pub struct XexeuConfig {
|
||||
}
|
||||
|
||||
/// `[escopo]`: what the operator is allowed to touch.
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ScopeConfig {
|
||||
/// CIDRs and addresses that bound every expanded target.
|
||||
#[serde(rename = "autorizado", default)]
|
||||
pub authorized: Vec<String>,
|
||||
/// Person or team accountable for the authorization.
|
||||
#[serde(rename = "responsavel", default)]
|
||||
#[serde(
|
||||
rename = "responsavel",
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub responsible: Option<String>,
|
||||
}
|
||||
|
||||
/// `[padrao]`: values inherited by groups.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
pub struct DefaultsConfig {
|
||||
/// Cron expression for groups without their own.
|
||||
#[serde(rename = "cron", default = "default_cron")]
|
||||
@@ -52,16 +56,28 @@ pub struct DefaultsConfig {
|
||||
#[serde(rename = "jitter", default = "default_jitter")]
|
||||
pub jitter: String,
|
||||
/// Profile for groups without their own.
|
||||
#[serde(rename = "perfil", default)]
|
||||
#[serde(rename = "perfil", default, skip_serializing_if = "Option::is_none")]
|
||||
pub profile: Option<String>,
|
||||
/// Global packet-per-second budget shared by all groups.
|
||||
#[serde(rename = "taxa_maxima_pps", default)]
|
||||
#[serde(
|
||||
rename = "taxa_maxima_pps",
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub max_pps: Option<u32>,
|
||||
/// Hosts scanned concurrently.
|
||||
#[serde(rename = "hosts_simultaneos", default)]
|
||||
#[serde(
|
||||
rename = "hosts_simultaneos",
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub simultaneous_hosts: Option<usize>,
|
||||
/// Consecutive unanswered scans before a host is considered gone.
|
||||
#[serde(rename = "ausencias_para_sumir", default)]
|
||||
#[serde(
|
||||
rename = "ausencias_para_sumir",
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub absences_before_disappear: Option<u32>,
|
||||
/// Vulnerability feeds synchronization settings.
|
||||
#[serde(rename = "feeds", default)]
|
||||
@@ -69,7 +85,7 @@ pub struct DefaultsConfig {
|
||||
}
|
||||
|
||||
/// Vulnerability feeds synchronization settings under `[padrao.feeds]`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct FeedsConfig {
|
||||
/// Whether to automatically sync vulnerability feeds periodically in the server.
|
||||
#[serde(rename = "sincronizar_automaticamente", default = "default_false")]
|
||||
@@ -111,13 +127,13 @@ impl Default for DefaultsConfig {
|
||||
}
|
||||
|
||||
/// `[perfis.<nome>]`: how each group is scanned.
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ProfileConfig {
|
||||
/// TCP port selection, such as `top-1000` or `1-65535`.
|
||||
#[serde(rename = "tcp", default = "default_tcp")]
|
||||
pub tcp: String,
|
||||
/// UDP ports to probe.
|
||||
#[serde(rename = "udp", default)]
|
||||
#[serde(rename = "udp", default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub udp: Vec<String>,
|
||||
/// Scanner engine, such as `nativo` or `nmap`.
|
||||
#[serde(rename = "motor", default = "default_engine")]
|
||||
@@ -128,7 +144,7 @@ pub struct ProfileConfig {
|
||||
}
|
||||
|
||||
/// `[[grupo]]`: one set of targets with its own cadence.
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct GroupConfig {
|
||||
/// Group name, unique in the document.
|
||||
#[serde(rename = "nome", default)]
|
||||
@@ -137,16 +153,20 @@ pub struct GroupConfig {
|
||||
#[serde(rename = "alvos", default)]
|
||||
pub targets: Vec<String>,
|
||||
/// Ranges subtracted after expansion.
|
||||
#[serde(rename = "excluir", default)]
|
||||
#[serde(rename = "excluir", default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub exclude: Vec<String>,
|
||||
/// Cron expression overriding the default.
|
||||
#[serde(rename = "cron", default)]
|
||||
#[serde(rename = "cron", default, skip_serializing_if = "Option::is_none")]
|
||||
pub cron: Option<String>,
|
||||
/// Profile overriding the default.
|
||||
#[serde(rename = "perfil", default)]
|
||||
#[serde(rename = "perfil", default, skip_serializing_if = "Option::is_none")]
|
||||
pub profile: Option<String>,
|
||||
/// Free-form criticality label.
|
||||
#[serde(rename = "criticidade", default)]
|
||||
#[serde(
|
||||
rename = "criticidade",
|
||||
default,
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub criticality: Option<String>,
|
||||
}
|
||||
|
||||
@@ -257,6 +277,9 @@ pub enum ConfigError {
|
||||
/// Prefix length supplied.
|
||||
prefix: u8,
|
||||
},
|
||||
/// I/O error reading or writing configuration.
|
||||
#[error("erro de E/S na configuração: {0}")]
|
||||
Io(String),
|
||||
}
|
||||
|
||||
/// Result of a successful validation.
|
||||
@@ -300,6 +323,39 @@ impl XexeuConfig {
|
||||
})
|
||||
}
|
||||
|
||||
/// Serializes the configuration to a pretty TOML string.
|
||||
pub fn to_toml_string(&self) -> Result<String, ConfigError> {
|
||||
toml::to_string_pretty(self).map_err(|error| ConfigError::Toml {
|
||||
reason: error.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Saves the configuration to a file atomically via a temporary file in the same directory.
|
||||
pub fn save_to_file(&self, path: &std::path::Path) -> Result<(), ConfigError> {
|
||||
use std::io::Write;
|
||||
let content = self.to_toml_string()?;
|
||||
let parent = path.parent().unwrap_or_else(|| std::path::Path::new("."));
|
||||
let mut temp = tempfile::NamedTempFile::new_in(parent).map_err(|err| {
|
||||
ConfigError::Io(format!(
|
||||
"não foi possível criar arquivo temporário em {}: {err}",
|
||||
parent.display()
|
||||
))
|
||||
})?;
|
||||
temp.write_all(content.as_bytes()).map_err(|err| {
|
||||
ConfigError::Io(format!("erro escrevendo configuração temporária: {err}"))
|
||||
})?;
|
||||
temp.flush().map_err(|err| {
|
||||
ConfigError::Io(format!("erro descarregando configuração temporária: {err}"))
|
||||
})?;
|
||||
temp.persist(path).map_err(|err| {
|
||||
ConfigError::Io(format!(
|
||||
"não foi possível substituir {} atomicamente: {err}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Parses and validates the document.
|
||||
pub fn load_validated(raw: &str) -> Result<(Self, ValidationReport), ConfigError> {
|
||||
let config = Self::from_toml_str(raw)?;
|
||||
@@ -731,4 +787,48 @@ alvos = ["10.0.0.0/24"]
|
||||
let (_, report) = XexeuConfig::load_validated(&raw).expect("config is valid");
|
||||
assert_eq!(report.groups[0].addresses, 128);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toml_serialization_and_save_roundtrips() {
|
||||
let raw = r#"[escopo]
|
||||
autorizado = ["10.0.0.0/16", "192.168.1.0/24"]
|
||||
responsavel = "SecOps Team"
|
||||
|
||||
[padrao]
|
||||
cron = "@daily"
|
||||
jitter = "10%"
|
||||
taxa_maxima_pps = 500
|
||||
|
||||
[padrao.feeds]
|
||||
sincronizar_automaticamente = true
|
||||
intervalo_sincronizacao = "12h"
|
||||
|
||||
[perfis.padrao]
|
||||
tcp = "top-100"
|
||||
motor = "nativo"
|
||||
vulnerabilidades = true
|
||||
|
||||
[[grupo]]
|
||||
nome = "dmz"
|
||||
alvos = ["10.0.1.0/24"]
|
||||
excluir = ["10.0.1.1"]
|
||||
cron = "0 2 * * *"
|
||||
criticidade = "alta"
|
||||
"#;
|
||||
let (config, _) = XexeuConfig::load_validated(raw).expect("config parses and validates");
|
||||
let toml_str = config.to_toml_string().expect("serializes to toml");
|
||||
let (reloaded, _) =
|
||||
XexeuConfig::load_validated(&toml_str).expect("reloaded config is valid");
|
||||
assert_eq!(config, reloaded);
|
||||
|
||||
let temp_dir = tempfile::tempdir().expect("tempdir");
|
||||
let file_path = temp_dir.path().join("xexeu.toml");
|
||||
config
|
||||
.save_to_file(&file_path)
|
||||
.expect("save_to_file succeeds");
|
||||
let file_content = std::fs::read_to_string(&file_path).expect("read file");
|
||||
let (from_disk, _) =
|
||||
XexeuConfig::load_validated(&file_content).expect("from disk validates");
|
||||
assert_eq!(config, from_disk);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user