diff --git a/agent/README.md b/agent/README.md index a858a8d..67d6322 100644 --- a/agent/README.md +++ b/agent/README.md @@ -35,7 +35,7 @@ and returns liveness only. The complete route table is in `../docs/architecture.md`. Limits default to 64 KiB bodies, 32 concurrent calls, five-second requests, 10 read rps, 2 write rps, and burst 20. -System data comes from `/proc` and `/sys`; fixed `ip`, `nft`/`iptables`, +System data comes from `/proc` and `/sys`; fixed `ip`, `iptables`, `fail2ban-client`, `wg`, and `systemctl` invocations augment it. User input is never part of a command string. Jail names and IPs are validated, and systemd names must exactly match the configuration allow-list. @@ -49,15 +49,17 @@ administrator must opt in after review. ## systemd and privilege -Install `packaging/vps-agent.service`. It caps memory at 64 MiB, CPU at 10%, +Install `packaging/vps-agent.service`, `vps-agent-helper.socket`, and +`vps-agent-helper@.service`. The daemon unit caps memory at 64 MiB, CPU at 10%, tasks at 64, removes all capabilities, sets `NoNewPrivileges`, and enables filesystem/kernel/namespace hardening. The agent logs to journald and does not write successful polls or metrics to disk. Read APIs work unprivileged on ordinary supported distributions. Process owners -may be absent due to `/proc` permissions. Fail2Ban changes and service restarts -will return an error unless the administrator adds narrowly scoped polkit/sudo -policy; the installer deliberately grants none. Firewall is read-only in v1. +may be absent due to `/proc` permissions. The socket-activated root helper runs +one typed request at a time and has no shell/command endpoint. Writes remain off +until their local allow-lists and `management_enabled` flags are configured. +Firewall persistence requires `iptables-persistent`/`netfilter-persistent`. ## Lifecycle and troubleshooting diff --git a/agent/config/config.toml b/agent/config/config.toml index 507b029..ad38c48 100644 --- a/agent/config/config.toml +++ b/agent/config/config.toml @@ -15,13 +15,25 @@ burst = 20.0 command_timeout_seconds = 4 [services] -allowed = ["nginx", "fail2ban", "wg-quick@wg0"] +allowed = ["nginx.service", "fail2ban.service", "wg-quick@wg0.service"] +inventory_limit = 512 +install_enabled = false +install_timeout_seconds = 300 +packages = { "nginx.service" = "nginx", "fail2ban.service" = "fail2ban" } [firewall] management_enabled = false +persistence_enabled = true +allowed_interfaces = [] +allowed_sources = [] +allowed_ports = [] rollback_timeout_seconds = 60 max_snapshots = 5 +[fail2ban] +management_enabled = false +allowed_jails = ["sshd"] + [logging] level = "info" diff --git a/agent/packaging/vps-agent-helper.socket b/agent/packaging/vps-agent-helper.socket new file mode 100644 index 0000000..0045dad --- /dev/null +++ b/agent/packaging/vps-agent-helper.socket @@ -0,0 +1,15 @@ +[Unit] +Description=VPS Control privileged helper socket + +[Socket] +ListenStream=/run/vps-agent-helper/control.sock +Accept=yes +MaxConnections=1 +SocketUser=vps-agent +SocketGroup=vps-agent +SocketMode=0600 +DirectoryMode=0750 +RemoveOnStop=yes + +[Install] +WantedBy=sockets.target diff --git a/agent/packaging/vps-agent-helper@.service b/agent/packaging/vps-agent-helper@.service new file mode 100644 index 0000000..bcde4fe --- /dev/null +++ b/agent/packaging/vps-agent-helper@.service @@ -0,0 +1,26 @@ +[Unit] +Description=VPS Control privileged helper request +Documentation=https://github.com/example/vps-control + +[Service] +Type=oneshot +ExecStart=/usr/local/bin/vps-agent --privileged-helper --config /etc/vps-agent/config.toml +StandardInput=socket +StandardOutput=socket +StandardError=journal +User=root +Group=root +TimeoutStartSec=330 +UMask=0077 +PrivateTmp=true +ProtectHome=true +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectKernelLogs=true +ProtectControlGroups=true +ProtectClock=true +ProtectHostname=true +RestrictSUIDSGID=true +LockPersonality=true +RestrictRealtime=true +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK diff --git a/agent/src/api.rs b/agent/src/api.rs index 4b7a240..8a98e1c 100644 --- a/agent/src/api.rs +++ b/agent/src/api.rs @@ -10,7 +10,7 @@ use axum::{ http::{header::AUTHORIZATION, Method, Request, StatusCode}, middleware::{self, Next}, response::{IntoResponse, Response}, - routing::{get, post}, + routing::{delete, get, post}, Json, Router, }; use serde_json::{json, Value}; @@ -113,13 +113,22 @@ pub fn router(state: Arc) -> Router { .route("/v1/network/listeners", get(network_listeners)) .route("/v1/network/connections", get(network_connections)) .route("/v1/firewall/rules", get(firewall_rules)) + .route("/v1/firewall/rules", post(firewall_add)) + .route("/v1/firewall/rules/:id", delete(firewall_delete)) + .route( + "/v1/firewall/transactions/:id/confirm", + post(firewall_confirm), + ) + .route("/v1/rate-limits", get(rate_limits).post(rate_limit_add)) + .route("/v1/rate-limits/:id", delete(rate_limit_delete)) .route("/v1/fail2ban/status", get(fail2ban_status)) .route("/v1/fail2ban/jails/:jail", get(fail2ban_jail)) .route("/v1/fail2ban/ban", post(fail2ban_ban)) .route("/v1/fail2ban/unban", post(fail2ban_unban)) + .route("/v1/fail2ban/configure", post(fail2ban_configure)) .route("/v1/wireguard/status", get(wireguard_status)) .route("/v1/services", get(service_list)) - .route("/v1/services/:name/restart", post(service_restart)) + .route("/v1/services/:name/:operation", post(service_mutation)) .route("/v1/logs", get(log_entries)) .layer(DefaultBodyLimit::max(max_body)) .layer(middleware::from_fn_with_state( @@ -286,11 +295,74 @@ async fn network_connections( } async fn firewall_rules(State(state): State>) -> Json { - Json(firewall::status(command_timeout(&state)).await) + Json(firewall::status(&state.config, command_timeout(&state)).await) +} + +async fn firewall_add( + State(state): State>, + Json(request): Json, +) -> Result, ApiError> { + let transaction_id = firewall::add(&state.config, request, command_timeout(&state)).await?; + tracing::info!("managed firewall rule added"); + Ok(Json( + json!({"status":"pending_confirmation","transaction_id":transaction_id}), + )) +} + +async fn firewall_delete( + State(state): State>, + Path(id): Path, +) -> Result, ApiError> { + let transaction_id = firewall::delete(&state.config, &id, command_timeout(&state)).await?; + tracing::info!(rule_id = id, "managed firewall rule deleted"); + Ok(Json( + json!({"status":"pending_confirmation","transaction_id":transaction_id}), + )) +} + +async fn rate_limits(State(state): State>) -> Json> { + let mut rules = firewall::status(&state.config, command_timeout(&state)) + .await + .rules; + rules.retain(|rule| rule.rate_limit && rule.managed); + Json(rules) +} + +async fn rate_limit_add( + State(state): State>, + Json(request): Json, +) -> Result, ApiError> { + let transaction_id = + firewall::add_rate_limit(&state.config, request, command_timeout(&state)).await?; + tracing::info!("managed L4 rate-limit policy added"); + Ok(Json( + json!({"status":"pending_confirmation","transaction_id":transaction_id}), + )) +} + +async fn rate_limit_delete( + State(state): State>, + Path(id): Path, +) -> Result, ApiError> { + let transaction_id = + firewall::delete_rate_limit(&state.config, &id, command_timeout(&state)).await?; + tracing::info!(policy_id = id, "managed L4 rate-limit policy deleted"); + Ok(Json( + json!({"status":"pending_confirmation","transaction_id":transaction_id}), + )) +} + +async fn firewall_confirm( + State(state): State>, + Path(id): Path, +) -> Result, ApiError> { + firewall::confirm(&id, command_timeout(&state)).await?; + tracing::info!(transaction_id = id, "firewall transaction confirmed"); + Ok(Json(json!({"status":"ok"}))) } async fn fail2ban_status(State(state): State>) -> Json { - Json(fail2ban::status(command_timeout(&state)).await) + Json(fail2ban::status(&state.config, command_timeout(&state)).await) } async fn fail2ban_jail( @@ -326,7 +398,7 @@ async fn mutate_ban( .ip .parse::() .map_err(|_| ApiError::bad_request("invalid IP address"))?; - fail2ban::ban(&request, unban, command_timeout(state)).await?; + fail2ban::ban(&state.config, &request, unban, command_timeout(state)).await?; let action = if unban { "unban" } else { "ban" }; tracing::info!( action, @@ -337,6 +409,15 @@ async fn mutate_ban( Ok(Json(json!({"status": "ok"}))) } +async fn fail2ban_configure( + State(state): State>, + Json(request): Json, +) -> Result, ApiError> { + fail2ban::configure(&state.config, request, command_timeout(&state)).await?; + tracing::info!("managed Fail2Ban configuration updated"); + Ok(Json(json!({"status":"ok"}))) +} + async fn wireguard_status( State(state): State>, ) -> Result>, ApiError> { @@ -344,33 +425,34 @@ async fn wireguard_status( } async fn service_list(State(state): State>) -> Json> { - Json(services::list(&state.config.services.allowed, command_timeout(&state)).await) + Json(services::list(&state.config.services, command_timeout(&state)).await) } -async fn service_restart( +async fn service_mutation( State(state): State>, - Path(name): Path, + Path((name, operation)): Path<(String, String)>, ) -> Result, ApiError> { - if !state - .config - .services - .allowed - .iter() - .any(|item| item == &name) - { - return Err(ApiError::new( - StatusCode::FORBIDDEN, - "service is not allow-listed", - "not_allowed", - )); + if operation == "install" { + services::install( + &name, + &state.config.services, + Duration::from_secs(state.config.services.install_timeout_seconds), + ) + .await?; + } else { + services::action( + &name, + &operation, + &state.config.services, + command_timeout(&state), + ) + .await?; } - services::restart( - &name, - &state.config.services.allowed, - command_timeout(&state), - ) - .await?; - tracing::info!(service = name, "allow-listed service restarted"); + tracing::info!( + service = name, + operation, + "allow-listed service mutation completed" + ); Ok(Json(json!({"status": "ok"}))) } diff --git a/agent/src/config.rs b/agent/src/config.rs index 93e1276..1acac30 100644 --- a/agent/src/config.rs +++ b/agent/src/config.rs @@ -1,6 +1,6 @@ use anyhow::{bail, Context, Result}; use serde::Deserialize; -use std::{net::SocketAddr, path::Path}; +use std::{collections::HashMap, net::SocketAddr, path::Path}; #[derive(Clone, Debug, Default, Deserialize)] #[serde(default, deny_unknown_fields)] @@ -10,6 +10,7 @@ pub struct Config { pub limits: Limits, pub services: Services, pub firewall: Firewall, + pub fail2ban: Fail2Ban, pub logging: Logging, pub telemetry: Telemetry, pub logs: Logs, @@ -41,20 +42,35 @@ pub struct Limits { pub command_timeout_seconds: u64, } -#[derive(Clone, Debug, Default, Deserialize)] +#[derive(Clone, Debug, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct Services { pub allowed: Vec, + pub inventory_limit: usize, + pub install_enabled: bool, + pub install_timeout_seconds: u64, + pub packages: HashMap, } #[derive(Clone, Debug, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct Firewall { pub management_enabled: bool, + pub persistence_enabled: bool, + pub allowed_interfaces: Vec, + pub allowed_sources: Vec, + pub allowed_ports: Vec, pub rollback_timeout_seconds: u64, pub max_snapshots: usize, } +#[derive(Clone, Debug, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Fail2Ban { + pub management_enabled: bool, + pub allowed_jails: Vec, +} + #[derive(Clone, Debug, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct Logging { @@ -118,10 +134,35 @@ impl Default for Limits { } } +impl Default for Services { + fn default() -> Self { + Self { + allowed: Vec::new(), + inventory_limit: 512, + install_enabled: false, + install_timeout_seconds: 300, + packages: HashMap::new(), + } + } +} + +impl Default for Fail2Ban { + fn default() -> Self { + Self { + management_enabled: false, + allowed_jails: vec!["sshd".into()], + } + } +} + impl Default for Firewall { fn default() -> Self { Self { management_enabled: false, + persistence_enabled: true, + allowed_interfaces: Vec::new(), + allowed_sources: Vec::new(), + allowed_ports: Vec::new(), rollback_timeout_seconds: 60, max_snapshots: 5, } @@ -190,6 +231,9 @@ impl Config { if self.services.allowed.len() > 128 { bail!("at most 128 services may be allow-listed") } + if !(1..=2048).contains(&self.services.inventory_limit) { + bail!("services.inventory_limit must be between 1 and 2048") + } if self.logs.allowed_units.len() > 128 || !(1..=1000).contains(&self.logs.max_entries_per_request) || !(1024..=65_536).contains(&self.logs.max_message_bytes) @@ -209,8 +253,68 @@ impl Config { bail!("invalid allow-listed service name") } } - if self.firewall.management_enabled { - bail!("firewall management requires the v2 privileged helper and is unavailable") + if !(30..=1800).contains(&self.services.install_timeout_seconds) { + bail!("services.install_timeout_seconds must be between 30 and 1800") + } + if self.services.packages.len() > 128 { + bail!("at most 128 service packages may be configured") + } + for (service, package) in &self.services.packages { + if !self.services.allowed.iter().any(|name| name == service) + || !valid_package_name(package) + { + bail!("invalid service package mapping") + } + } + if self.services.install_enabled && self.services.packages.is_empty() { + bail!("services.packages must not be empty when installation is enabled") + } + if self.firewall.allowed_interfaces.len() > 32 + || self.firewall.allowed_sources.len() > 128 + || self.firewall.allowed_ports.len() > 512 + { + bail!("firewall allow-list is too large") + } + for interface in &self.firewall.allowed_interfaces { + if !valid_interface_name(interface) { + bail!("invalid firewall interface") + } + } + for source in &self.firewall.allowed_sources { + if !valid_cidr(source) + || !source + .split_once('/') + .and_then(|(address, _)| address.parse::().ok()) + .is_some_and(|address| address.is_ipv4()) + { + bail!("invalid IPv4 firewall source CIDR") + } + } + if self.firewall.allowed_ports.contains(&0) { + bail!("firewall ports must be between 1 and 65535") + } + if self.firewall.management_enabled + && (self.firewall.allowed_interfaces.is_empty() + || self.firewall.allowed_sources.is_empty() + || self.firewall.allowed_ports.is_empty()) + { + bail!("firewall allow-lists must not be empty when management is enabled") + } + if !(10..=300).contains(&self.firewall.rollback_timeout_seconds) + || !(1..=20).contains(&self.firewall.max_snapshots) + { + bail!("firewall rollback or snapshot limits are invalid") + } + if self.fail2ban.allowed_jails.len() > 64 { + bail!("at most 64 Fail2Ban jails may be allow-listed") + } + for jail in &self.fail2ban.allowed_jails { + if !valid_simple_name(jail) { + bail!("invalid allow-listed Fail2Ban jail") + } + } + if self.fail2ban.management_enabled && self.fail2ban.allowed_jails.is_empty() { + bail!("fail2ban.allowed_jails must not be empty when management is enabled") } if !matches!( self.logging.level.as_str(), @@ -235,6 +339,43 @@ pub fn valid_service_name(name: &str) -> bool { .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.' | b'@' | b':')) } +pub fn valid_simple_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 64 + && name + .bytes() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_' | b'.')) +} + +pub fn valid_package_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 128 + && name.bytes().all(|c| { + c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, b'+' | b'.' | b'-') + }) +} + +pub fn valid_interface_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 15 + && name + .bytes() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.')) +} + +pub fn valid_cidr(value: &str) -> bool { + let Some((address, prefix)) = value.split_once('/') else { + return false; + }; + let Ok(address) = address.parse::() else { + return false; + }; + let Ok(prefix) = prefix.parse::() else { + return false; + }; + prefix <= if address.is_ipv4() { 32 } else { 128 } +} + #[cfg(test)] mod tests { use super::*; @@ -260,4 +401,15 @@ mod tests { assert!(!valid_service_name("nginx;reboot")); assert!(!valid_service_name("../../etc/passwd")); } + + #[test] + fn validates_privileged_allow_lists() { + assert!(valid_package_name("nginx-core")); + assert!(!valid_package_name("nginx;reboot")); + assert!(valid_interface_name("wg-home")); + assert!(!valid_interface_name("../../eth0")); + assert!(valid_cidr("192.168.50.4/32")); + assert!(valid_cidr("2001:db8::/64")); + assert!(!valid_cidr("192.168.50.4/99")); + } } diff --git a/agent/src/fail2ban.rs b/agent/src/fail2ban.rs index f96b570..69f9b05 100644 --- a/agent/src/fail2ban.rs +++ b/agent/src/fail2ban.rs @@ -1,4 +1,4 @@ -use crate::command; +use crate::{command, config::Config, privileged}; use anyhow::{bail, Result}; use serde::{Deserialize, Serialize}; use std::{net::IpAddr, time::Duration}; @@ -9,6 +9,9 @@ pub struct Status { pub running: bool, pub version: Option, pub jails: Vec, + pub jail_statuses: Vec, + pub management_enabled: bool, + pub manageable_jails: Vec, } #[derive(Debug, Default, Serialize, PartialEq)] @@ -28,7 +31,7 @@ pub struct BanRequest { pub ip: String, } -pub async fn status(timeout: Duration) -> Status { +pub async fn status(config: &Config, timeout: Duration) -> Status { let version = match command::run("fail2ban-client", &["--version"], timeout).await { Ok(output) => Some(output.stdout.trim().to_owned()), Err(_) => { @@ -37,21 +40,47 @@ pub async fn status(timeout: Duration) -> Status { running: false, version: None, jails: vec![], + jail_statuses: vec![], + management_enabled: false, + manageable_jails: config.fail2ban.allowed_jails.clone(), } } }; match command::run("fail2ban-client", &["status"], timeout).await { - Ok(output) => Status { - installed: true, - running: true, - version, - jails: parse_jail_list(&output.stdout), - }, + Ok(output) => { + let jails = parse_jail_list(&output.stdout); + let mut jail_statuses = Vec::new(); + let mut tasks = tokio::task::JoinSet::new(); + for name in jails.iter().take(64) { + let name = name.clone(); + tasks.spawn(async move { jail(&name, timeout).await }); + } + while let Some(result) = tasks.join_next().await { + if let Ok(Ok(status)) = result { + jail_statuses.push(status); + } + } + jail_statuses.sort_by(|left, right| left.jail.cmp(&right.jail)); + Status { + installed: true, + running: true, + version, + jails, + jail_statuses, + management_enabled: config.fail2ban.management_enabled + && privileged::socket_available(), + manageable_jails: config.fail2ban.allowed_jails.clone(), + } + } Err(_) => Status { installed: true, running: false, version, jails: vec![], + jail_statuses: vec![], + management_enabled: config.fail2ban.management_enabled + && privileged::socket_available(), + manageable_jails: config.fail2ban.allowed_jails.clone(), }, } } @@ -62,21 +91,71 @@ pub async fn jail(name: &str, timeout: Duration) -> Result { Ok(parse_jail_status(name, &output.stdout)) } -pub async fn ban(request: &BanRequest, unban: bool, timeout: Duration) -> Result<()> { +pub async fn ban( + config: &Config, + request: &BanRequest, + unban: bool, + timeout: Duration, +) -> Result<()> { validate_jail(&request.jail)?; let ip: IpAddr = request .ip .parse() .map_err(|_| anyhow::anyhow!("invalid IP address"))?; - let operation = if unban { "unbanip" } else { "banip" }; - command::run( - "fail2ban-client", - &[ - "set", - request.jail.as_str(), - operation, - ip.to_string().as_str(), - ], + if !config + .fail2ban + .allowed_jails + .iter() + .any(|value| value == &request.jail) + { + bail!("jail is not allow-listed") + } + privileged::call( + &privileged::Request::Fail2BanAction { + jail: request.jail.clone(), + ip: ip.to_string(), + operation: if unban { "unban".into() } else { "ban".into() }, + }, + timeout, + ) + .await?; + Ok(()) +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ConfigureRequest { + pub jail: String, + pub enabled: bool, + pub bantime_seconds: u32, + pub findtime_seconds: u32, + pub maxretry: u16, +} + +pub async fn configure( + config: &Config, + request: ConfigureRequest, + timeout: Duration, +) -> Result<()> { + validate_jail(&request.jail)?; + if !config + .fail2ban + .allowed_jails + .iter() + .any(|value| value == &request.jail) + { + bail!("jail is not allow-listed") + } + privileged::call( + &privileged::Request::Fail2BanConfigure { + settings: privileged::Fail2BanSettings { + jail: request.jail, + enabled: request.enabled, + bantime_seconds: request.bantime_seconds, + findtime_seconds: request.findtime_seconds, + maxretry: request.maxretry, + }, + }, timeout, ) .await?; diff --git a/agent/src/firewall.rs b/agent/src/firewall.rs index 46d5ada..23c6bfc 100644 --- a/agent/src/firewall.rs +++ b/agent/src/firewall.rs @@ -1,68 +1,379 @@ -use crate::command; -use serde::Serialize; -use serde_json::Value; +use crate::{command, config::Config, privileged}; +use anyhow::{bail, Result}; +use serde::{Deserialize, Serialize}; use std::time::Duration; +pub const MANAGED_CHAIN: &str = "VPS_CONTROL_INPUT"; +pub const RATE_CHAIN: &str = "VPS_CONTROL_RATE"; + #[derive(Debug, Serialize)] pub struct FirewallStatus { pub backend: String, pub management_enabled: bool, - pub managed_table: String, - pub ruleset: Value, + pub persistence_enabled: bool, + pub managed_chain: String, + pub allowed_interfaces: Vec, + pub allowed_sources: Vec, + pub allowed_ports: Vec, + pub rules: Vec, pub warning: Option, } -pub async fn status(timeout: Duration) -> FirewallStatus { - if command::run("nft", &["--version"], timeout).await.is_ok() { - return match command::run("nft", &["--json", "list", "ruleset"], timeout).await { - Ok(output) => FirewallStatus { - backend: "nftables".into(), - management_enabled: false, - managed_table: "inet vps_control".into(), - ruleset: serde_json::from_str(&output.stdout).unwrap_or(Value::Null), - warning: None, - }, - Err(error) => FirewallStatus { - backend: "nftables".into(), - management_enabled: false, - managed_table: "inet vps_control".into(), - ruleset: Value::Null, - warning: Some(format!("rules unavailable: {error}")), - }, - }; - } +#[derive(Clone, Debug, Serialize, PartialEq)] +pub struct FirewallRule { + pub id: String, + pub table: String, + pub chain: String, + pub protocol: String, + pub source: String, + pub destination: String, + pub in_interface: String, + pub out_interface: String, + pub destination_port: Option, + pub target: String, + pub packets: u64, + pub bytes: u64, + pub comment: String, + pub managed: bool, + pub rate_limit: bool, +} - for (program, backend) in [ - ("iptables-nft", "iptables-nft"), - ("iptables", "iptables-legacy"), - ] { - if let Ok(version) = command::run(program, &["--version"], timeout).await { - let detected = if version.stdout.contains("nf_tables") { - "iptables-nft" +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct AddRuleRequest { + pub interface: String, + pub source: String, + pub protocol: String, + pub port: u16, + pub target: String, + #[serde(default)] + pub comment: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct RateLimitRequest { + pub interface: String, + pub source: String, + pub protocol: String, + pub port: u16, + pub rate_per_second: u32, + pub burst: u32, + #[serde(default)] + pub comment: String, +} + +pub async fn status(config: &Config, timeout: Duration) -> FirewallStatus { + let helper_available = privileged::socket_available(); + let management_enabled = config.firewall.management_enabled && helper_available; + let dump = if helper_available { + privileged::call(&privileged::Request::FirewallDump, timeout) + .await + .ok() + .and_then(|response| response.data) + .and_then(|value| value.as_str().map(str::to_owned)) + } else { + command::run("iptables-save", &["-c"], timeout) + .await + .ok() + .map(|output| output.stdout) + }; + match dump { + Some(text) => FirewallStatus { + backend: "iptables".into(), + management_enabled, + persistence_enabled: config.firewall.persistence_enabled, + managed_chain: MANAGED_CHAIN.into(), + allowed_interfaces: config.firewall.allowed_interfaces.clone(), + allowed_sources: config.firewall.allowed_sources.clone(), + allowed_ports: config.firewall.allowed_ports.clone(), + rules: parse_iptables_save(&text), + warning: if config.firewall.management_enabled && !helper_available { + Some("privileged helper socket is unavailable; writes are disabled".into()) } else { - backend - }; - let rules = command::run(program, &["-S"], timeout) - .await - .ok() - .map(|v| v.stdout); - return FirewallStatus { - backend: detected.into(), - management_enabled: false, - managed_table: "inet vps_control".into(), - ruleset: rules.map(Value::String).unwrap_or(Value::Null), - warning: Some( - "legacy-compatible firewall view is read-only and has limited structure".into(), - ), - }; - } - } - - FirewallStatus { - backend: "unavailable".into(), - management_enabled: false, - managed_table: "inet vps_control".into(), - ruleset: Value::Null, - warning: Some("no supported firewall userspace utility found".into()), + None + }, + }, + None => FirewallStatus { + backend: "unavailable".into(), + management_enabled: false, + persistence_enabled: config.firewall.persistence_enabled, + managed_chain: MANAGED_CHAIN.into(), + allowed_interfaces: config.firewall.allowed_interfaces.clone(), + allowed_sources: config.firewall.allowed_sources.clone(), + allowed_ports: config.firewall.allowed_ports.clone(), + rules: Vec::new(), + warning: Some("iptables-save is unavailable or access was denied".into()), + }, + } +} + +pub async fn add(config: &Config, request: AddRuleRequest, timeout: Duration) -> Result { + validate_common( + config, + &request.interface, + &request.source, + &request.protocol, + request.port, + )?; + if !matches!(request.target.as_str(), "ACCEPT" | "DROP" | "REJECT") { + bail!("target must be ACCEPT, DROP, or REJECT") + } + let response = privileged::call( + &privileged::Request::FirewallAdd { + rule: privileged::FirewallRuleRequest { + interface: request.interface, + source: request.source, + protocol: request.protocol, + port: request.port, + target: request.target, + comment: request.comment, + }, + }, + timeout, + ) + .await?; + transaction_id(response) +} + +pub async fn delete(config: &Config, id: &str, timeout: Duration) -> Result { + if !config.firewall.management_enabled || !valid_id(id) { + bail!("firewall management disabled or invalid rule id") + } + let response = privileged::call( + &privileged::Request::FirewallDelete { id: id.into() }, + timeout, + ) + .await?; + transaction_id(response) +} + +pub async fn add_rate_limit( + config: &Config, + request: RateLimitRequest, + timeout: Duration, +) -> Result { + validate_common( + config, + &request.interface, + &request.source, + &request.protocol, + request.port, + )?; + if !(1..=100_000).contains(&request.rate_per_second) || !(1..=10_000).contains(&request.burst) { + bail!("rate_per_second or burst is outside the supported range") + } + let response = privileged::call( + &privileged::Request::RateLimitAdd { + policy: privileged::RateLimitRequest { + interface: request.interface, + source: request.source, + protocol: request.protocol, + port: request.port, + rate_per_second: request.rate_per_second, + burst: request.burst, + comment: request.comment, + }, + }, + timeout, + ) + .await?; + transaction_id(response) +} + +pub async fn delete_rate_limit(config: &Config, id: &str, timeout: Duration) -> Result { + if !config.firewall.management_enabled || !valid_id(id) { + bail!("policy management disabled or invalid policy id") + } + let response = privileged::call( + &privileged::Request::RateLimitDelete { id: id.into() }, + timeout, + ) + .await?; + transaction_id(response) +} + +pub async fn confirm(id: &str, timeout: Duration) -> Result<()> { + if !valid_id(id) { + bail!("invalid transaction id") + } + privileged::call( + &privileged::Request::FirewallConfirm { id: id.into() }, + timeout, + ) + .await?; + Ok(()) +} + +fn transaction_id(response: privileged::Response) -> Result { + let id = response + .data + .and_then(|value| { + value + .get("transaction_id") + .and_then(|value| value.as_str()) + .map(str::to_owned) + }) + .ok_or_else(|| anyhow::anyhow!("helper did not return a transaction id"))?; + if !valid_id(&id) { + bail!("helper returned an invalid transaction id") + } + Ok(id) +} + +fn validate_common( + config: &Config, + interface: &str, + source: &str, + protocol: &str, + port: u16, +) -> Result<()> { + if !config.firewall.management_enabled { + bail!("firewall management is disabled") + } + if !config + .firewall + .allowed_interfaces + .iter() + .any(|value| value == interface) + || !config + .firewall + .allowed_sources + .iter() + .any(|value| value == source) + || !config.firewall.allowed_ports.contains(&port) + || !matches!(protocol, "tcp" | "udp") + { + bail!("firewall request is outside the configured allow-list") + } + Ok(()) +} + +pub fn valid_id(value: &str) -> bool { + value.len() == 16 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +fn parse_iptables_save(text: &str) -> Vec { + let mut table = "filter".to_owned(); + let mut result = Vec::new(); + for (index, line) in text.lines().enumerate() { + if let Some(name) = line.strip_prefix('*') { + table = name.to_owned(); + continue; + } + if let Some(definition) = line.strip_prefix(':') { + let fields: Vec<_> = definition.split_whitespace().collect(); + if fields.len() >= 3 { + let (packets, bytes) = fields[2] + .strip_prefix('[') + .and_then(|value| value.strip_suffix(']')) + .and_then(|value| value.split_once(':')) + .map(|(left, right)| (left.parse().unwrap_or(0), right.parse().unwrap_or(0))) + .unwrap_or((0, 0)); + result.push(FirewallRule { + id: format!("policy-{}-{}", table, fields[0]), + table: table.clone(), + chain: fields[0].into(), + protocol: "all".into(), + source: "all".into(), + destination: "all".into(), + in_interface: String::new(), + out_interface: String::new(), + destination_port: None, + target: format!("POLICY {}", fields[1]), + packets, + bytes, + comment: String::new(), + managed: false, + rate_limit: false, + }); + } + continue; + } + if !line.contains(" -A ") && !line.starts_with("-A ") { + continue; + } + let tokens = split_arguments(line); + let chain = option(&tokens, "-A").unwrap_or_default(); + let comment = option(&tokens, "--comment").unwrap_or_default(); + let counters = tokens + .first() + .and_then(|token| token.strip_prefix('[')) + .and_then(|token| token.strip_suffix(']')); + let (packets, bytes) = counters + .and_then(|value| value.split_once(':')) + .map(|(a, b)| (a.parse().unwrap_or(0), b.parse().unwrap_or(0))) + .unwrap_or((0, 0)); + let managed = matches!(chain.as_str(), MANAGED_CHAIN | RATE_CHAIN) + && comment.starts_with("vps-control:"); + let id = comment + .strip_prefix("vps-control:") + .and_then(|value| value.split(':').next()) + .filter(|value| valid_id(value)) + .map(str::to_owned) + .unwrap_or_else(|| format!("rule-{index}")); + result.push(FirewallRule { + id, + table: table.clone(), + chain: chain.clone(), + protocol: option(&tokens, "-p").unwrap_or_else(|| "all".into()), + source: option(&tokens, "-s").unwrap_or_else(|| "0.0.0.0/0".into()), + destination: option(&tokens, "-d").unwrap_or_else(|| "0.0.0.0/0".into()), + in_interface: option(&tokens, "-i").unwrap_or_default(), + out_interface: option(&tokens, "-o").unwrap_or_default(), + destination_port: option(&tokens, "--dport").and_then(|value| value.parse().ok()), + target: option(&tokens, "-j").unwrap_or_default(), + packets, + bytes, + rate_limit: tokens.iter().any(|token| token == "hashlimit") || chain == RATE_CHAIN, + comment, + managed, + }); + } + result +} + +fn option(tokens: &[String], name: &str) -> Option { + tokens + .iter() + .position(|token| token == name) + .and_then(|index| tokens.get(index + 1)) + .cloned() +} + +fn split_arguments(line: &str) -> Vec { + let mut result = Vec::new(); + let mut current = String::new(); + let mut quoted = false; + for character in line.chars() { + match character { + '"' => quoted = !quoted, + ' ' | '\t' if !quoted => { + if !current.is_empty() { + result.push(std::mem::take(&mut current)); + } + } + _ => current.push(character), + } + } + if !current.is_empty() { + result.push(current); + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_structured_rules_and_counters() { + let input = "*filter\n[12:840] -A INPUT -i wg0 -s 10.20.0.0/24 -p tcp -m tcp --dport 9105 -j ACCEPT\n[3:180] -A VPS_CONTROL_INPUT -i wg0 -s 10.20.0.2/32 -p tcp --dport 22 -m comment --comment \"vps-control:0123456789abcdef:ssh\" -j ACCEPT\nCOMMIT\n"; + let rules = parse_iptables_save(input); + assert_eq!(rules.len(), 2); + assert_eq!(rules[0].packets, 12); + assert_eq!(rules[0].destination_port, Some(9105)); + assert!(rules[1].managed); + assert_eq!(rules[1].id, "0123456789abcdef"); } } diff --git a/agent/src/main.rs b/agent/src/main.rs index a3b194c..b731c20 100644 --- a/agent/src/main.rs +++ b/agent/src/main.rs @@ -5,6 +5,7 @@ mod fail2ban; mod firewall; mod logs; mod network; +mod privileged; mod services; mod system; mod wireguard; @@ -17,7 +18,14 @@ use tracing_subscriber::EnvFilter; #[tokio::main(flavor = "multi_thread", worker_threads = 2)] async fn main() -> Result<()> { - let config_path = parse_args()?; + let arguments = parse_args()?; + if arguments.privileged_helper { + return privileged::serve_once(&arguments.config_path); + } + if let Some(transaction) = arguments.firewall_rollback { + return privileged::rollback_firewall(&arguments.config_path, &transaction); + } + let config_path = arguments.config_path; let config = Config::load(&config_path)?; tracing_subscriber::fmt() .with_env_filter( @@ -54,9 +62,17 @@ async fn main() -> Result<()> { Ok(()) } -fn parse_args() -> Result { +struct Arguments { + config_path: PathBuf, + privileged_helper: bool, + firewall_rollback: Option, +} + +fn parse_args() -> Result { let mut args = env::args().skip(1); let mut config = PathBuf::from("/etc/vps-agent/config.toml"); + let mut privileged_helper = false; + let mut firewall_rollback = None; while let Some(argument) = args.next() { match argument.as_str() { "--config" => { @@ -65,6 +81,10 @@ fn parse_args() -> Result { .map(PathBuf::from) .context("--config needs a path")? } + "--privileged-helper" => privileged_helper = true, + "--firewall-rollback" => { + firewall_rollback = Some(args.next().context("--firewall-rollback needs an id")?) + } "--version" | "-V" => { println!("vps-agent {}", env!("CARGO_PKG_VERSION")); std::process::exit(0); @@ -76,7 +96,11 @@ fn parse_args() -> Result { _ => anyhow::bail!("unknown argument: {argument}"), } } - Ok(config) + Ok(Arguments { + config_path: config, + privileged_helper, + firewall_rollback, + }) } async fn wait_for_shutdown() { diff --git a/agent/src/privileged.rs b/agent/src/privileged.rs new file mode 100644 index 0000000..d0b4f08 --- /dev/null +++ b/agent/src/privileged.rs @@ -0,0 +1,915 @@ +use crate::config::{valid_interface_name, valid_service_name, valid_simple_name, Config}; +use anyhow::{bail, Context, Result}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::{ + fs::{self, OpenOptions}, + io::{BufRead, BufReader, Read, Write}, + os::unix::fs::OpenOptionsExt, + path::{Path, PathBuf}, + process::{Command, Stdio}, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::UnixStream, +}; + +pub const SOCKET_PATH: &str = "/run/vps-agent-helper/control.sock"; +const MANAGED_CHAIN: &str = "VPS_CONTROL_INPUT"; +const MAX_MESSAGE_BYTES: usize = 64 * 1024; +const MAX_SNAPSHOT_BYTES: usize = 2 * 1024 * 1024; +const SNAPSHOT_DIRECTORY: &str = "/var/lib/vps-agent/firewall"; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)] +pub enum Request { + FirewallDump, + FirewallAdd { + rule: FirewallRuleRequest, + }, + FirewallDelete { + id: String, + }, + FirewallConfirm { + id: String, + }, + RateLimitAdd { + policy: RateLimitRequest, + }, + RateLimitDelete { + id: String, + }, + ServiceInstall { + service: String, + }, + ServiceAction { + service: String, + operation: String, + }, + Fail2BanAction { + jail: String, + ip: String, + operation: String, + }, + Fail2BanConfigure { + settings: Fail2BanSettings, + }, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct FirewallRuleRequest { + pub interface: String, + pub source: String, + pub protocol: String, + pub port: u16, + pub target: String, + #[serde(default)] + pub comment: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct RateLimitRequest { + pub interface: String, + pub source: String, + pub protocol: String, + pub port: u16, + pub rate_per_second: u32, + pub burst: u32, + #[serde(default)] + pub comment: String, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct Fail2BanSettings { + pub jail: String, + pub enabled: bool, + pub bantime_seconds: u32, + pub findtime_seconds: u32, + pub maxretry: u16, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct Response { + pub ok: bool, + pub changed: bool, + pub error: Option, + pub data: Option, +} + +impl Response { + fn success(changed: bool) -> Self { + Self { + ok: true, + changed, + error: None, + data: None, + } + } + + fn with_data(data: Value) -> Self { + Self { + ok: true, + changed: false, + error: None, + data: Some(data), + } + } + + fn transaction(id: &str) -> Self { + Self { + ok: true, + changed: true, + error: None, + data: Some(serde_json::json!({"transaction_id": id})), + } + } + + fn failure(error: impl Into) -> Self { + Self { + ok: false, + changed: false, + error: Some(error.into()), + data: None, + } + } +} + +pub async fn call(request: &Request, timeout_duration: Duration) -> Result { + tokio::time::timeout(timeout_duration, async { + let mut stream = UnixStream::connect(SOCKET_PATH) + .await + .context("connect privileged helper")?; + let mut payload = serde_json::to_vec(request).context("encode helper request")?; + if payload.len() > MAX_MESSAGE_BYTES - 1 { + bail!("helper request is too large") + } + payload.push(b'\n'); + stream + .write_all(&payload) + .await + .context("write helper request")?; + stream.shutdown().await.context("finish helper request")?; + let mut response = Vec::new(); + stream + .take((MAX_MESSAGE_BYTES + 1) as u64) + .read_to_end(&mut response) + .await + .context("read helper response")?; + if response.len() > MAX_MESSAGE_BYTES { + bail!("helper response is too large") + } + let response: Response = + serde_json::from_slice(&response).context("decode helper response")?; + if !response.ok { + bail!( + "privileged helper: {}", + response.error.as_deref().unwrap_or("operation failed") + ) + } + Ok(response) + }) + .await + .context("privileged helper timed out")? +} + +pub fn serve_once(config_path: &Path) -> Result<()> { + let uid = Command::new("id") + .arg("-u") + .output() + .context("determine helper uid")?; + if !uid.status.success() || String::from_utf8_lossy(&uid.stdout).trim() != "0" { + bail!("privileged helper must run as root") + } + let response = match read_request().and_then(|request| execute(config_path, request)) { + Ok(response) => response, + Err(error) => Response::failure(format!("{error:#}")), + }; + serde_json::to_writer(std::io::stdout().lock(), &response).context("write helper response")?; + Ok(()) +} + +fn read_request() -> Result { + let mut reader = BufReader::new(std::io::stdin().lock()).take((MAX_MESSAGE_BYTES + 1) as u64); + let mut payload = Vec::new(); + reader.read_until(b'\n', &mut payload)?; + if payload.len() > MAX_MESSAGE_BYTES { + bail!("helper request is too large") + } + serde_json::from_slice(&payload).context("decode helper request") +} + +fn execute(config_path: &Path, request: Request) -> Result { + let config = Config::load(config_path)?; + match request { + Request::FirewallDump => dump_firewall(), + Request::FirewallAdd { rule } => add_firewall_rule(&config, &rule), + Request::FirewallDelete { id } => delete_managed_rule(&config, MANAGED_CHAIN, &id), + Request::FirewallConfirm { id } => confirm_firewall(&id), + Request::RateLimitAdd { policy } => add_rate_limit(&config, &policy), + Request::RateLimitDelete { id } => delete_managed_rule(&config, "VPS_CONTROL_RATE", &id), + Request::ServiceInstall { service } => install_service(&config, &service), + Request::ServiceAction { service, operation } => { + service_action(&config, &service, &operation) + } + Request::Fail2BanAction { + jail, + ip, + operation, + } => fail2ban_action(&config, &jail, &ip, &operation), + Request::Fail2BanConfigure { settings } => configure_fail2ban(&config, &settings), + } +} + +fn dump_firewall() -> Result { + let output = Command::new("iptables-save") + .arg("-c") + .output() + .context("execute iptables-save")?; + if !output.status.success() || output.stdout.len() > MAX_SNAPSHOT_BYTES { + bail!("iptables-save failed or exceeded size limit") + } + let rules = String::from_utf8(output.stdout).context("iptables-save output is not UTF-8")?; + Ok(Response::with_data(Value::String(rules))) +} + +fn add_firewall_rule(config: &Config, rule: &FirewallRuleRequest) -> Result { + if !config.firewall.management_enabled { + bail!("firewall management is disabled") + } + if !valid_interface_name(&rule.interface) + || !config + .firewall + .allowed_interfaces + .iter() + .any(|value| value == &rule.interface) + { + bail!("interface is not allow-listed") + } + if !config + .firewall + .allowed_sources + .iter() + .any(|value| value == &rule.source) + { + bail!("source is not allow-listed") + } + if !matches!(rule.protocol.as_str(), "tcp" | "udp") { + bail!("protocol must be tcp or udp") + } + if !matches!(rule.target.as_str(), "ACCEPT" | "DROP" | "REJECT") { + bail!("unsupported firewall target") + } + if rule.port == 0 || !config.firewall.allowed_ports.contains(&rule.port) { + bail!("port is not allow-listed") + } + if rule.comment.len() > 80 + || !rule + .comment + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b' ' | b'.' | b'_' | b'-')) + { + bail!("comment contains unsupported characters") + } + + let (transaction, snapshot) = prepare_firewall_transaction(config)?; + let result = apply_firewall_rule(rule).and_then(|changed| { + if config.firewall.persistence_enabled { + run_status("netfilter-persistent", &["save"]) + .context("persist firewall with netfilter-persistent")?; + } + if !changed { + bail!("firewall rule was not changed") + } + Ok(Response::transaction(&transaction)) + }); + rollback_on_error(result, &transaction, &snapshot, config) +} + +fn apply_firewall_rule(rule: &FirewallRuleRequest) -> Result { + if !command_succeeds("iptables", &["-w", "5", "-S", MANAGED_CHAIN]) { + run_status("iptables", &["-w", "5", "-N", MANAGED_CHAIN])?; + } + if !command_succeeds("iptables", &["-w", "5", "-C", "INPUT", "-j", MANAGED_CHAIN]) { + run_status( + "iptables", + &["-w", "5", "-I", "INPUT", "1", "-j", MANAGED_CHAIN], + )?; + } + + let port = rule.port.to_string(); + let id = random_id()?; + let suffix = if rule.comment.is_empty() { + format!("{}-{}", rule.protocol, rule.port) + } else { + rule.comment.clone() + }; + let comment = format!("vps-control:{id}:{suffix}"); + let arguments = [ + "-w", + "5", + "-C", + MANAGED_CHAIN, + "-i", + &rule.interface, + "-s", + &rule.source, + "-p", + &rule.protocol, + "--dport", + &port, + "-m", + "conntrack", + "--ctstate", + "NEW,ESTABLISHED", + "-m", + "comment", + "--comment", + &comment, + "-j", + &rule.target, + ]; + if command_succeeds("iptables", &arguments) { + return Ok(false); + } + let mut append_arguments = arguments; + append_arguments[2] = "-A"; + run_status("iptables", &append_arguments)?; + Ok(true) +} + +fn add_rate_limit(config: &Config, policy: &RateLimitRequest) -> Result { + validate_firewall_common( + config, + &policy.interface, + &policy.source, + &policy.protocol, + policy.port, + &policy.comment, + )?; + if !(1..=100_000).contains(&policy.rate_per_second) || !(1..=10_000).contains(&policy.burst) { + bail!("rate limit is outside the supported range") + } + let (transaction, snapshot) = prepare_firewall_transaction(config)?; + let result = apply_rate_limit(policy).and_then(|changed| { + persist_if_enabled(config)?; + if !changed { + bail!("rate-limit policy was not changed") + } + Ok(Response::transaction(&transaction)) + }); + rollback_on_error(result, &transaction, &snapshot, config) +} + +fn apply_rate_limit(policy: &RateLimitRequest) -> Result { + const CHAIN: &str = "VPS_CONTROL_RATE"; + ensure_chain(CHAIN, 1)?; + let id = random_id()?; + let suffix = if policy.comment.is_empty() { + format!("{}-{}", policy.protocol, policy.port) + } else { + policy.comment.clone() + }; + let allow_comment = format!("vps-control:{id}:rate:{suffix}"); + let drop_comment = format!("vps-control:{id}:rate-drop:{suffix}"); + let port = policy.port.to_string(); + let rate = format!("{}/second", policy.rate_per_second); + let burst = policy.burst.to_string(); + let hash_name = format!("vp_{}", &id[..12]); + run_status( + "iptables", + &[ + "-w", + "5", + "-A", + CHAIN, + "-i", + &policy.interface, + "-s", + &policy.source, + "-p", + &policy.protocol, + "--dport", + &port, + "-m", + "conntrack", + "--ctstate", + "NEW", + "-m", + "hashlimit", + "--hashlimit-upto", + &rate, + "--hashlimit-burst", + &burst, + "--hashlimit-mode", + "srcip", + "--hashlimit-name", + &hash_name, + "-m", + "comment", + "--comment", + &allow_comment, + "-j", + "ACCEPT", + ], + )?; + if let Err(error) = run_status( + "iptables", + &[ + "-w", + "5", + "-A", + CHAIN, + "-i", + &policy.interface, + "-s", + &policy.source, + "-p", + &policy.protocol, + "--dport", + &port, + "-m", + "conntrack", + "--ctstate", + "NEW", + "-m", + "comment", + "--comment", + &drop_comment, + "-j", + "DROP", + ], + ) { + let _ = delete_rules_by_comment(CHAIN, &id); + return Err(error); + } + Ok(true) +} + +fn delete_managed_rule(config: &Config, chain: &str, id: &str) -> Result { + if !config.firewall.management_enabled || !valid_id(id) { + bail!("firewall management disabled or invalid rule id") + } + if !matches!(chain, MANAGED_CHAIN | "VPS_CONTROL_RATE") { + bail!("unmanaged chain") + } + let (transaction, snapshot) = prepare_firewall_transaction(config)?; + let result = delete_rules_by_comment(chain, id).and_then(|changed| { + persist_if_enabled(config)?; + if !changed { + bail!("managed rule was not found") + } + Ok(Response::transaction(&transaction)) + }); + rollback_on_error(result, &transaction, &snapshot, config) +} + +fn delete_rules_by_comment(chain: &str, id: &str) -> Result { + let output = Command::new("iptables") + .args(["-w", "5", "-S", chain]) + .output() + .context("list managed firewall chain")?; + if !output.status.success() { + bail!("list managed firewall chain failed") + } + let marker = format!("vps-control:{id}:"); + let text = String::from_utf8(output.stdout).context("iptables output is not UTF-8")?; + let mut matches: Vec> = text + .lines() + .filter(|line| line.contains(&marker)) + .map(split_command_line) + .collect(); + let changed = !matches.is_empty(); + matches.reverse(); + for mut arguments in matches { + if arguments.first().map(String::as_str) != Some("-A") { + bail!("unexpected managed firewall rule") + } + arguments[0] = "-D".into(); + let references: Vec<&str> = arguments.iter().map(String::as_str).collect(); + run_status("iptables", &[&["-w", "5"], references.as_slice()].concat())?; + } + Ok(changed) +} + +fn ensure_chain(chain: &str, input_position: u8) -> Result<()> { + if !command_succeeds("iptables", &["-w", "5", "-S", chain]) { + run_status("iptables", &["-w", "5", "-N", chain])?; + } + if !command_succeeds("iptables", &["-w", "5", "-C", "INPUT", "-j", chain]) { + let position = input_position.to_string(); + run_status( + "iptables", + &["-w", "5", "-I", "INPUT", &position, "-j", chain], + )?; + } + Ok(()) +} + +fn validate_firewall_common( + config: &Config, + interface: &str, + source: &str, + protocol: &str, + port: u16, + comment: &str, +) -> Result<()> { + if !config.firewall.management_enabled + || !valid_interface_name(interface) + || !config + .firewall + .allowed_interfaces + .iter() + .any(|value| value == interface) + || !config + .firewall + .allowed_sources + .iter() + .any(|value| value == source) + || !config.firewall.allowed_ports.contains(&port) + || !matches!(protocol, "tcp" | "udp") + { + bail!("firewall request is outside the configured allow-list") + } + if comment.len() > 80 + || !comment + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b' ' | b'.' | b'_' | b'-')) + { + bail!("comment contains unsupported characters") + } + Ok(()) +} + +fn service_action(config: &Config, service: &str, operation: &str) -> Result { + if !valid_service_name(service) || !config.services.allowed.iter().any(|value| value == service) + { + bail!("service is not allow-listed") + } + match operation { + "start" | "stop" | "restart" | "enable" | "disable" => {} + _ => bail!("unsupported service operation"), + } + if matches!(operation, "start" | "stop" | "restart") { + run_status("systemctl", &[operation, "--no-block", "--", service])?; + } else { + run_status("systemctl", &[operation, "--", service])?; + } + Ok(Response::success(true)) +} + +fn fail2ban_action(config: &Config, jail: &str, ip: &str, operation: &str) -> Result { + if !config.fail2ban.management_enabled + || !valid_simple_name(jail) + || !config + .fail2ban + .allowed_jails + .iter() + .any(|value| value == jail) + { + bail!("Fail2Ban jail is not allow-listed") + } + let address: std::net::IpAddr = ip.parse().context("invalid IP address")?; + let command = match operation { + "ban" => "banip", + "unban" => "unbanip", + _ => bail!("unsupported Fail2Ban operation"), + }; + run_status( + "fail2ban-client", + &["set", jail, command, &address.to_string()], + )?; + Ok(Response::success(true)) +} + +fn configure_fail2ban(config: &Config, settings: &Fail2BanSettings) -> Result { + if !config.fail2ban.management_enabled + || !valid_simple_name(&settings.jail) + || !config + .fail2ban + .allowed_jails + .iter() + .any(|value| value == &settings.jail) + || !(10..=2_592_000).contains(&settings.bantime_seconds) + || !(10..=86_400).contains(&settings.findtime_seconds) + || !(1..=100).contains(&settings.maxretry) + { + bail!("invalid or non-allow-listed Fail2Ban settings") + } + let directory = Path::new("/etc/fail2ban/jail.d"); + fs::create_dir_all(directory).context("create Fail2Ban jail directory")?; + let path = directory.join(format!("vps-control-{}.local", settings.jail)); + let backup = fs::read(&path).ok(); + let temporary = directory.join(format!(".vps-control-{}.tmp", settings.jail)); + let content = format!( + "# Managed by VPS Control; manual changes will be replaced.\n[{}]\nenabled = {}\nbantime = {}\nfindtime = {}\nmaxretry = {}\n", + settings.jail, + if settings.enabled { "true" } else { "false" }, + settings.bantime_seconds, + settings.findtime_seconds, + settings.maxretry + ); + let mut file = OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .mode(0o644) + .open(&temporary)?; + file.write_all(content.as_bytes())?; + file.sync_all()?; + fs::rename(&temporary, &path)?; + if let Err(error) = run_status("fail2ban-client", &["-t"]) + .and_then(|_| run_status("systemctl", &["reload", "fail2ban.service"])) + { + match backup { + Some(previous) => fs::write(&path, previous)?, + None => { + let _ = fs::remove_file(&path); + } + } + let _ = run_status("systemctl", &["reload", "fail2ban.service"]); + bail!("Fail2Ban validation failed and configuration was rolled back: {error:#}") + } + Ok(Response::success(true)) +} + +fn persist_if_enabled(config: &Config) -> Result<()> { + if config.firewall.persistence_enabled { + run_status("netfilter-persistent", &["save"]) + .context("persist firewall with netfilter-persistent")?; + } + Ok(()) +} + +fn prepare_firewall_transaction(config: &Config) -> Result<(String, PathBuf)> { + if fs::read_dir(SNAPSHOT_DIRECTORY) + .ok() + .into_iter() + .flatten() + .filter_map(Result::ok) + .any(|entry| entry.file_name().to_string_lossy().starts_with("pending-")) + { + bail!("another firewall transaction is pending confirmation") + } + let snapshot = create_snapshot(config.firewall.max_snapshots)?; + let id = random_id()?; + let pending = Path::new(SNAPSHOT_DIRECTORY).join(format!("pending-{id}.rules")); + fs::rename(&snapshot, &pending).context("mark firewall snapshot pending")?; + let unit = format!("vps-agent-firewall-rollback-{id}"); + let delay = format!("{}s", config.firewall.rollback_timeout_seconds); + let status = Command::new("systemd-run") + .args([ + "--unit", + &unit, + "--on-active", + &delay, + "--timer-property=AccuracySec=1s", + "/usr/local/bin/vps-agent", + "--firewall-rollback", + &id, + "--config", + "/etc/vps-agent/config.toml", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .context("schedule firewall safety rollback")?; + if !status.success() { + let _ = fs::remove_file(&pending); + bail!("firewall safety rollback could not be scheduled") + } + Ok((id, pending)) +} + +fn confirm_firewall(id: &str) -> Result { + if !valid_id(id) { + bail!("invalid firewall transaction id") + } + let pending = Path::new(SNAPSHOT_DIRECTORY).join(format!("pending-{id}.rules")); + if !pending.is_file() { + bail!("firewall transaction is not pending") + } + cancel_rollback(id); + fs::remove_file(pending).context("remove confirmed firewall snapshot")?; + Ok(Response::success(true)) +} + +pub fn rollback_firewall(config_path: &Path, id: &str) -> Result<()> { + if !valid_id(id) { + bail!("invalid firewall transaction id") + } + let config = Config::load(config_path)?; + let pending = Path::new(SNAPSHOT_DIRECTORY).join(format!("pending-{id}.rules")); + if !pending.is_file() { + return Ok(()); + } + restore_snapshot(&pending)?; + persist_if_enabled(&config)?; + fs::remove_file(pending)?; + Ok(()) +} + +fn cancel_rollback(id: &str) { + let timer = format!("vps-agent-firewall-rollback-{id}.timer"); + let service = format!("vps-agent-firewall-rollback-{id}.service"); + let _ = command_succeeds("systemctl", &["stop", &timer]); + let _ = command_succeeds("systemctl", &["stop", &service]); +} + +fn rollback_on_error( + result: Result, + transaction: &str, + snapshot: &Path, + config: &Config, +) -> Result { + match result { + Ok(response) => Ok(response), + Err(error) => { + cancel_rollback(transaction); + if let Err(rollback_error) = restore_snapshot(snapshot) { + bail!("operation failed: {error:#}; rollback failed: {rollback_error:#}") + } + let _ = persist_if_enabled(config); + let _ = fs::remove_file(snapshot); + bail!("operation failed and was rolled back: {error:#}") + } + } +} + +fn random_id() -> Result { + let mut bytes = [0_u8; 8]; + fs::File::open("/dev/urandom")?.read_exact(&mut bytes)?; + Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect()) +} + +fn valid_id(value: &str) -> bool { + value.len() == 16 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) +} + +fn split_command_line(line: &str) -> Vec { + let mut values = Vec::new(); + let mut value = String::new(); + let mut quoted = false; + for character in line.chars() { + match character { + '"' => quoted = !quoted, + ' ' | '\t' if !quoted => { + if !value.is_empty() { + values.push(std::mem::take(&mut value)); + } + } + _ => value.push(character), + } + } + if !value.is_empty() { + values.push(value); + } + values +} + +fn install_service(config: &Config, service: &str) -> Result { + if !config.services.install_enabled { + bail!("service installation is disabled") + } + if !valid_service_name(service) || !config.services.allowed.iter().any(|item| item == service) { + bail!("service is not allow-listed") + } + let package = config + .services + .packages + .get(service) + .context("service has no package mapping")?; + let unit = format!("vps-agent-install-{}.service", random_id()?); + let timeout_seconds = format!("{}s", config.services.install_timeout_seconds); + let runtime_property = format!("RuntimeMaxSec={timeout_seconds}"); + let status = Command::new("systemd-run") + .args([ + "--unit", + &unit, + "--collect", + "--no-block", + "--property", + &runtime_property, + "--setenv=DEBIAN_FRONTEND=noninteractive", + "/usr/bin/apt-get", + "-q", + "-y", + "--no-install-recommends", + "-o", + "DPkg::Lock::Timeout=30", + "install", + package, + ]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .context("queue allow-listed package installation")?; + if !status.success() { + bail!("package installation could not be queued") + } + Ok(Response::success(true)) +} + +fn create_snapshot(maximum: usize) -> Result { + fs::create_dir_all(SNAPSHOT_DIRECTORY).context("create firewall snapshot directory")?; + let output = Command::new("iptables-save") + .arg("-c") + .output() + .context("execute iptables-save")?; + if !output.status.success() || output.stdout.len() > MAX_SNAPSHOT_BYTES { + bail!("iptables snapshot failed or exceeded size limit") + } + let timestamp = SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos(); + let path = Path::new(SNAPSHOT_DIRECTORY).join(format!("snapshot-{timestamp}.rules")); + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&path) + .context("create firewall snapshot")?; + file.write_all(&output.stdout)?; + file.sync_all()?; + prune_snapshots(maximum)?; + Ok(path) +} + +fn prune_snapshots(maximum: usize) -> Result<()> { + let mut snapshots: Vec<_> = fs::read_dir(SNAPSHOT_DIRECTORY)? + .filter_map(Result::ok) + .filter(|entry| entry.file_name().to_string_lossy().starts_with("snapshot-")) + .collect(); + snapshots.sort_by_key(|entry| entry.file_name()); + let remove_count = snapshots.len().saturating_sub(maximum); + for entry in snapshots.into_iter().take(remove_count) { + fs::remove_file(entry.path())?; + } + Ok(()) +} + +fn restore_snapshot(path: &Path) -> Result<()> { + let file = fs::File::open(path).context("open firewall snapshot")?; + let mut child = Command::new("iptables-restore") + .arg("-c") + .stdin(Stdio::from(file)) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .context("execute iptables-restore")?; + if !child.wait()?.success() { + bail!("iptables-restore failed") + } + Ok(()) +} + +fn command_succeeds(program: &str, arguments: &[&str]) -> bool { + Command::new(program) + .args(arguments) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|status| status.success()) +} + +fn run_status(program: &str, arguments: &[&str]) -> Result<()> { + let status = Command::new(program) + .args(arguments) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .with_context(|| format!("execute {program}"))?; + if !status.success() { + bail!("{program} failed") + } + Ok(()) +} + +pub fn socket_available() -> bool { + Path::new(SOCKET_PATH).exists() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn helper_request_rejects_unknown_fields() { + let payload = br#"{"action":"firewall_add","rule":{"interface":"wg0","source":"10.0.0.1/32","protocol":"tcp","port":22,"extra":true}}"#; + assert!(serde_json::from_slice::(payload).is_err()); + } + + #[test] + fn helper_request_is_typed() { + let payload = br#"{"action":"service_install","service":"nginx.service"}"#; + assert!(matches!( + serde_json::from_slice::(payload).unwrap(), + Request::ServiceInstall { .. } + )); + } +} diff --git a/agent/src/services.rs b/agent/src/services.rs index f531070..e423ffe 100644 --- a/agent/src/services.rs +++ b/agent/src/services.rs @@ -1,4 +1,8 @@ -use crate::{command, config::valid_service_name}; +use crate::{ + command, + config::{valid_service_name, Services}, + privileged, +}; use anyhow::{bail, Result}; use serde::Serialize; use std::{collections::HashMap, time::Duration}; @@ -6,100 +10,190 @@ use std::{collections::HashMap, time::Duration}; #[derive(Debug, Serialize)] pub struct ServiceStatus { pub name: String, + pub load_state: String, pub active_state: String, pub sub_state: String, - pub pid: u32, - pub memory_bytes: Option, - pub active_since_monotonic_us: Option, + pub description: String, + pub unit_file_state: String, + pub managed: bool, + pub install_available: bool, } -pub async fn list(allowed: &[String], timeout: Duration) -> Vec { - let mut result = Vec::with_capacity(allowed.len()); - for name in allowed { - match inspect(name, timeout).await { - Ok(status) => result.push(status), - Err(_) => result.push(ServiceStatus { - name: name.clone(), - active_state: "unavailable".into(), - sub_state: "unknown".into(), - pid: 0, - memory_bytes: None, - active_since_monotonic_us: None, - }), - } - } - result -} - -pub async fn restart(name: &str, allowed: &[String], timeout: Duration) -> Result<()> { - if !valid_service_name(name) || !allowed.iter().any(|item| item == name) { - bail!("service is not allow-listed") - } - command::run("systemctl", &["restart", "--", name], timeout).await?; - Ok(()) -} - -async fn inspect(name: &str, timeout: Duration) -> Result { - if !valid_service_name(name) { - bail!("invalid service name") - } - let output = command::run( +pub async fn list(config: &Services, timeout: Duration) -> Vec { + let units_future = command::run( "systemctl", &[ - "show", + "list-units", + "--type=service", + "--all", + "--no-legend", "--no-pager", - "--property=ActiveState,SubState,MainPID,MemoryCurrent,ActiveEnterTimestampMonotonic", - "--", - name, + "--plain", ], timeout, + ); + let files_future = command::run( + "systemctl", + &[ + "list-unit-files", + "--type=service", + "--no-legend", + "--no-pager", + ], + timeout, + ); + let (units_output, files_output) = tokio::join!(units_future, files_future); + let unit_files = files_output + .ok() + .map(|output| parse_unit_files(&output.stdout)) + .unwrap_or_default(); + let mut rows = match units_output { + Ok(output) => parse_units(&output.stdout, config), + Err(_) => Vec::new(), + }; + for row in &mut rows { + row.unit_file_state = unit_files + .get(&row.name) + .cloned() + .unwrap_or_else(|| "unknown".into()); + } + for (name, state) in &unit_files { + if !rows.iter().any(|item| &item.name == name) { + let managed = config.allowed.iter().any(|item| item == name); + rows.push(ServiceStatus { + name: name.clone(), + load_state: "loaded".into(), + active_state: "inactive".into(), + sub_state: "dead".into(), + description: "Installed unit file".into(), + unit_file_state: state.clone(), + managed, + install_available: false, + }); + } + } + for name in &config.allowed { + if !rows.iter().any(|item| &item.name == name) { + rows.push(ServiceStatus { + name: name.clone(), + load_state: "not-found".into(), + active_state: "inactive".into(), + sub_state: "dead".into(), + description: config + .packages + .get(name) + .map(|package| format!("Not installed (package: {package})")) + .unwrap_or_else(|| "Not installed".into()), + unit_file_state: "not-found".into(), + managed: true, + install_available: config.install_enabled && config.packages.contains_key(name), + }); + } + } + rows.sort_by(|left, right| { + right + .managed + .cmp(&left.managed) + .then_with(|| left.name.cmp(&right.name)) + }); + rows.truncate(config.inventory_limit); + rows +} + +pub async fn action( + name: &str, + operation: &str, + config: &Services, + timeout: Duration, +) -> Result<()> { + validate_managed(name, config)?; + if !matches!( + operation, + "start" | "stop" | "restart" | "enable" | "disable" + ) { + bail!("unsupported service operation") + } + privileged::call( + &privileged::Request::ServiceAction { + service: name.into(), + operation: operation.into(), + }, + timeout, ) .await?; - let values: HashMap<_, _> = output - .stdout - .lines() - .filter_map(|line| line.split_once('=')) - .collect(); - Ok(ServiceStatus { - name: name.to_owned(), - active_state: values - .get("ActiveState") - .copied() - .unwrap_or("unknown") - .to_owned(), - sub_state: values - .get("SubState") - .copied() - .unwrap_or("unknown") - .to_owned(), - pid: values - .get("MainPID") - .and_then(|v| v.parse().ok()) - .unwrap_or_default(), - memory_bytes: values.get("MemoryCurrent").and_then(|v| v.parse().ok()), - active_since_monotonic_us: values - .get("ActiveEnterTimestampMonotonic") - .and_then(|v| v.parse().ok()), - }) + Ok(()) +} + +pub async fn install(name: &str, config: &Services, timeout: Duration) -> Result<()> { + validate_managed(name, config)?; + if !config.install_enabled || !config.packages.contains_key(name) { + bail!("service installation is disabled or unavailable") + } + privileged::call( + &privileged::Request::ServiceInstall { + service: name.into(), + }, + timeout, + ) + .await?; + Ok(()) +} + +fn validate_managed(name: &str, config: &Services) -> Result<()> { + if !valid_service_name(name) || !config.allowed.iter().any(|item| item == name) { + bail!("service is not allow-listed") + } + Ok(()) +} + +fn parse_units(text: &str, config: &Services) -> Vec { + text.lines() + .filter_map(|line| { + let mut fields = line.split_whitespace(); + let name = fields.next()?.trim_start_matches(['●', ' ']).to_owned(); + let load_state = fields.next()?.to_owned(); + let active_state = fields.next()?.to_owned(); + let sub_state = fields.next()?.to_owned(); + let description = fields.collect::>().join(" "); + let managed = config.allowed.iter().any(|item| item == &name); + Some(ServiceStatus { + install_available: managed + && config.install_enabled + && config.packages.contains_key(&name), + name, + load_state, + active_state, + sub_state, + description, + unit_file_state: "unknown".into(), + managed, + }) + }) + .collect() +} + +fn parse_unit_files(text: &str) -> HashMap { + text.lines() + .filter_map(|line| { + let mut fields = line.split_whitespace(); + Some((fields.next()?.to_owned(), fields.next()?.to_owned())) + }) + .collect() } #[cfg(test)] mod tests { use super::*; - #[tokio::test] - async fn rejects_service_outside_allowlist_without_execution() { - assert!( - restart("postgresql", &["nginx".into()], Duration::from_secs(1)) - .await - .is_err() - ); - assert!(restart( - "nginx;reboot", - &["nginx;reboot".into()], - Duration::from_secs(1) - ) - .await - .is_err()); + #[test] + fn parses_systemd_inventory() { + let config = Services { + allowed: vec!["nginx.service".into()], + ..Services::default() + }; + let rows = parse_units("nginx.service loaded active running A web server\nssh.service loaded inactive dead SSH daemon\n", &config); + assert_eq!(rows.len(), 2); + assert!(rows[0].managed); + assert_eq!(rows[0].description, "A web server"); } } diff --git a/control-plane/README.md b/control-plane/README.md index 57a288a..655749c 100644 --- a/control-plane/README.md +++ b/control-plane/README.md @@ -45,8 +45,8 @@ Roles are Viewer (read), Operator (Fail2Ban and service actions), and Administrator (server/firewall/policy administration). Every current mutation is audited with actor, target, result, time, and source IP. Secrets are excluded. -The backend creates schema on startup. One-minute metric samples are retained 30 -days (`METRICS_RETENTION=720h`) and agent logs seven days +The backend creates schema on startup. One-minute metric and connection samples +are retained 30 days (`METRICS_RETENTION=720h`); agent logs and Fail2Ban history seven days (`LOGS_RETENTION=168h`). PostgreSQL is the only durable history store. ## Grafana and Loki-compatible access diff --git a/control-plane/backend/agent.go b/control-plane/backend/agent.go index 92f02be..5405d0a 100644 --- a/control-plane/backend/agent.go +++ b/control-plane/backend/agent.go @@ -127,6 +127,9 @@ func (client *AgentClient) Do(ctx context.Context, server Server, method, path s if err != nil { return 0, nil, err } + if method != http.MethodGet && method != http.MethodHead { + request.Close = true + } request.Header.Set("Authorization", "Bearer "+token) request.Header.Set("Accept", "application/json") if len(body) > 0 { diff --git a/control-plane/backend/api.go b/control-plane/backend/api.go index 6d2c5bf..b38a051 100644 --- a/control-plane/backend/api.go +++ b/control-plane/backend/api.go @@ -5,6 +5,7 @@ import ( "crypto/subtle" "encoding/json" "errors" + "fmt" "io" "log" "net" @@ -275,6 +276,7 @@ func (app *App) serverRoute(writer http.ResponseWriter, request *http.Request, u "listeners": "/v1/network/listeners", "connections": "/v1/network/connections", "firewall": "/v1/firewall/rules", "fail2ban": "/v1/fail2ban/status", "wireguard": "/v1/wireguard/status", "services": "/v1/services", + "rate-limits": "/v1/rate-limits", } if len(parts) == 2 && request.Method == http.MethodGet { if parts[1] == "metrics" { @@ -295,6 +297,25 @@ func (app *App) serverRoute(writer http.ResponseWriter, request *http.Request, u writeJSON(writer, 200, entries) return } + if parts[1] == "connection-history" { + hours := queryHours(request, 24, 24*30) + history, historyErr := app.store.ConnectionHistory(request.Context(), server.ID, time.Now().Add(-time.Duration(hours)*time.Hour)) + if historyErr != nil { + writeInternal(writer, historyErr) + return + } + writeJSON(writer, 200, history) + return + } + if parts[1] == "fail2ban-history" { + events, eventErr := app.store.Fail2BanEvents(request.Context(), server.ID, queryLimit(request, 200, 1000)) + if eventErr != nil { + writeInternal(writer, eventErr) + return + } + writeJSON(writer, 200, events) + return + } if agentPath, found := readRoutes[parts[1]]; found { app.proxyRead(writer, request, server, agentPath) return @@ -311,11 +332,51 @@ func (app *App) serverRoute(writer http.ResponseWriter, request *http.Request, u app.fail2banMutation(writer, request, user, server, parts[2]) return } - if len(parts) == 4 && request.Method == http.MethodPost && parts[1] == "services" && parts[3] == "restart" && validServiceName(parts[2]) { - if !app.authorize(writer, request, user, csrfHash, RoleOperator) { + if len(parts) == 3 && request.Method == http.MethodPost && parts[1] == "fail2ban" && parts[2] == "configure" { + if !app.authorize(writer, request, user, csrfHash, RoleAdministrator) { return } - app.serviceMutation(writer, request, user, server, parts[2]) + app.fail2banConfigure(writer, request, user, server) + return + } + if len(parts) == 4 && request.Method == http.MethodPost && parts[1] == "services" && validServiceName(parts[2]) { + operation := parts[3] + requiredRole := RoleOperator + if operation == "install" { + requiredRole = RoleAdministrator + } + if !app.authorize(writer, request, user, csrfHash, requiredRole) { + return + } + app.serviceMutation(writer, request, user, server, parts[2], operation) + return + } + if len(parts) == 3 && parts[1] == "firewall" && parts[2] == "rules" && request.Method == http.MethodPost { + if !app.authorize(writer, request, user, csrfHash, RoleAdministrator) { + return + } + app.firewallAdd(writer, request, user, server) + return + } + if len(parts) == 4 && parts[1] == "firewall" && parts[2] == "rules" && request.Method == http.MethodDelete { + if !app.authorize(writer, request, user, csrfHash, RoleAdministrator) { + return + } + app.managedDelete(writer, request, user, server, "firewall", parts[3]) + return + } + if len(parts) == 2 && parts[1] == "rate-limits" && request.Method == http.MethodPost { + if !app.authorize(writer, request, user, csrfHash, RoleAdministrator) { + return + } + app.rateLimitAdd(writer, request, user, server) + return + } + if len(parts) == 3 && parts[1] == "rate-limits" && request.Method == http.MethodDelete { + if !app.authorize(writer, request, user, csrfHash, RoleAdministrator) { + return + } + app.managedDelete(writer, request, user, server, "rate-limits", parts[2]) return } writeError(writer, 404, "not found", "not_found") @@ -352,18 +413,25 @@ func (app *App) fail2banMutation(writer http.ResponseWriter, request *http.Reque writeError(writer, 502, "agent unavailable", "agent_unavailable") return } + if status < 300 { + app.store.AddFail2BanEvent(request.Context(), server.ID, input.Jail, input.IP, action, "operator") + } writeAgentResponse(writer, status, response) } -func (app *App) serviceMutation(writer http.ResponseWriter, request *http.Request, user User, server Server, name string) { +func (app *App) serviceMutation(writer http.ResponseWriter, request *http.Request, user User, server Server, name, operation string) { + if !contains([]string{"start", "stop", "restart", "enable", "disable", "install"}, operation) { + writeError(writer, 400, "invalid service operation", "invalid_request") + return + } status, response, err := app.agent.Do(request.Context(), server, http.MethodPost, - "/v1/services/"+url.PathEscape(name)+"/restart", []byte("{}")) + "/v1/services/"+url.PathEscape(name)+"/"+operation, []byte("{}")) result := "success" if err != nil || status >= 300 { result = "failure" } - app.store.Audit(request.Context(), &user, server.ID, "service.restart", name, nil, - map[string]string{"requested": "restart"}, result, app.clientIP(request)) + app.store.Audit(request.Context(), &user, server.ID, "service."+operation, name, nil, + map[string]string{"requested": operation}, result, app.clientIP(request)) if err != nil { writeError(writer, 502, "agent unavailable", "agent_unavailable") return @@ -371,6 +439,141 @@ func (app *App) serviceMutation(writer http.ResponseWriter, request *http.Reques writeAgentResponse(writer, status, response) } +func (app *App) firewallAdd(writer http.ResponseWriter, request *http.Request, user User, server Server) { + var input struct { + Interface string `json:"interface"` + Source string `json:"source"` + Protocol string `json:"protocol"` + Port int `json:"port"` + Target string `json:"target"` + Comment string `json:"comment"` + } + if decodeJSON(writer, request, &input) != nil || !validInterface(input.Interface) || !validIPv4CIDR(input.Source) || !contains([]string{"tcp", "udp"}, input.Protocol) || input.Port < 1 || input.Port > 65535 || !contains([]string{"ACCEPT", "DROP", "REJECT"}, input.Target) || !validComment(input.Comment) { + writeError(writer, 400, "invalid firewall rule", "invalid_request") + return + } + app.forwardMutation(writer, request, user, server, "firewall.add", fmt.Sprintf("%s/%s:%d", input.Source, input.Protocol, input.Port), "/v1/firewall/rules", http.MethodPost, input) +} + +func (app *App) rateLimitAdd(writer http.ResponseWriter, request *http.Request, user User, server Server) { + var input struct { + Interface string `json:"interface"` + Source string `json:"source"` + Protocol string `json:"protocol"` + Port int `json:"port"` + Rate int `json:"rate_per_second"` + Burst int `json:"burst"` + Comment string `json:"comment"` + } + if decodeJSON(writer, request, &input) != nil || !validInterface(input.Interface) || !validIPv4CIDR(input.Source) || !contains([]string{"tcp", "udp"}, input.Protocol) || input.Port < 1 || input.Port > 65535 || input.Rate < 1 || input.Rate > 100000 || input.Burst < 1 || input.Burst > 10000 || !validComment(input.Comment) { + writeError(writer, 400, "invalid rate-limit policy", "invalid_request") + return + } + app.forwardMutation(writer, request, user, server, "rate_limit.add", fmt.Sprintf("%s/%s:%d", input.Source, input.Protocol, input.Port), "/v1/rate-limits", http.MethodPost, input) +} + +func (app *App) managedDelete(writer http.ResponseWriter, request *http.Request, user User, server Server, kind, id string) { + if len(id) != 16 { + writeError(writer, 400, "invalid managed object id", "invalid_request") + return + } + for _, character := range id { + if !((character >= '0' && character <= '9') || (character >= 'a' && character <= 'f') || (character >= 'A' && character <= 'F')) { + writeError(writer, 400, "invalid managed object id", "invalid_request") + return + } + } + path := "/v1/firewall/rules/" + id + action := "firewall.delete" + if kind == "rate-limits" { + path = "/v1/rate-limits/" + id + action = "rate_limit.delete" + } + app.forwardMutation(writer, request, user, server, action, id, path, http.MethodDelete, map[string]string{"id": id}) +} + +func (app *App) fail2banConfigure(writer http.ResponseWriter, request *http.Request, user User, server Server) { + var input struct { + Jail string `json:"jail"` + Enabled bool `json:"enabled"` + BanTime int `json:"bantime_seconds"` + FindTime int `json:"findtime_seconds"` + MaxRetry int `json:"maxretry"` + } + if decodeJSON(writer, request, &input) != nil || !validSimpleName(input.Jail) || input.BanTime < 10 || input.BanTime > 2592000 || input.FindTime < 10 || input.FindTime > 86400 || input.MaxRetry < 1 || input.MaxRetry > 100 { + writeError(writer, 400, "invalid Fail2Ban settings", "invalid_request") + return + } + app.forwardMutation(writer, request, user, server, "fail2ban.configure", input.Jail, "/v1/fail2ban/configure", http.MethodPost, input) +} + +func (app *App) forwardMutation(writer http.ResponseWriter, request *http.Request, user User, server Server, action, target, path, method string, input any) { + body, _ := json.Marshal(input) + status, response, err := app.agent.Do(request.Context(), server, method, path, body) + if err == nil && status < 300 && (strings.HasPrefix(action, "firewall.") || strings.HasPrefix(action, "rate_limit.")) { + var pending struct { + TransactionID string `json:"transaction_id"` + } + if json.Unmarshal(response, &pending) != nil || len(pending.TransactionID) != 16 { + err = errors.New("agent returned invalid firewall transaction") + } else { + confirmPath := "/v1/firewall/transactions/" + pending.TransactionID + "/confirm" + confirmStatus, confirmResponse, confirmErr := app.agent.Do(request.Context(), server, http.MethodPost, confirmPath, []byte("{}")) + if confirmErr != nil || confirmStatus >= 300 { + err = errors.New("firewall confirmation failed; safety rollback remains armed") + } else { + status = confirmStatus + response = confirmResponse + } + } + } + result := "success" + if err != nil || status >= 300 { + result = "failure" + } + app.store.Audit(request.Context(), &user, server.ID, action, target, nil, input, result, app.clientIP(request)) + if err != nil { + writeError(writer, 502, "agent unavailable", "agent_unavailable") + return + } + writeAgentResponse(writer, status, response) +} + +func contains(values []string, wanted string) bool { + for _, value := range values { + if value == wanted { + return true + } + } + return false +} +func validInterface(value string) bool { + if len(value) < 1 || len(value) > 15 { + return false + } + for _, c := range value { + if !(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z') && !(c >= '0' && c <= '9') && !strings.ContainsRune("_.-", c) { + return false + } + } + return true +} +func validIPv4CIDR(value string) bool { + ip, _, err := net.ParseCIDR(value) + return err == nil && ip.To4() != nil +} +func validComment(value string) bool { + if len(value) > 80 { + return false + } + for _, c := range value { + if !(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z') && !(c >= '0' && c <= '9') && !strings.ContainsRune(" ._-", c) { + return false + } + } + return true +} + func (app *App) clientIP(request *http.Request) string { if app.config.TrustProxy { if value := request.Header.Get("X-Real-IP"); net.ParseIP(value) != nil { @@ -434,6 +637,17 @@ func queryLimit(request *http.Request, fallback, maximum int) int { return value } +func queryHours(request *http.Request, fallback, maximum int) int { + value, err := strconv.Atoi(request.URL.Query().Get("hours")) + if err != nil || value < 1 { + return fallback + } + if value > maximum { + return maximum + } + return value +} + func writeAgentResponse(writer http.ResponseWriter, status int, payload []byte) { if status < 100 || status > 599 { status = http.StatusBadGateway diff --git a/control-plane/backend/api_test.go b/control-plane/backend/api_test.go index 08465ad..f9283cb 100644 --- a/control-plane/backend/api_test.go +++ b/control-plane/backend/api_test.go @@ -54,6 +54,15 @@ func TestValidators(t *testing.T) { if !validServiceName("wg-quick@wg0") || validServiceName("nginx/restart") { t.Fatal("service validation failed") } + if !validInterface("wg0") || validInterface("../../eth0") { + t.Fatal("interface validation failed") + } + if !validIPv4CIDR("192.168.50.0/24") || validIPv4CIDR("2001:db8::/64") || validIPv4CIDR("0.0.0.0/99") { + t.Fatal("firewall CIDR validation failed") + } + if !validComment("web access") || validComment("bad;reboot") { + t.Fatal("firewall comment validation failed") + } } func TestPercent(t *testing.T) { diff --git a/control-plane/backend/db.go b/control-plane/backend/db.go index ce2ddea..ccc095a 100644 --- a/control-plane/backend/db.go +++ b/control-plane/backend/db.go @@ -75,6 +75,35 @@ CREATE TABLE IF NOT EXISTS agent_log_entries ( ); CREATE INDEX IF NOT EXISTS agent_log_entries_time_idx ON agent_log_entries(event_at DESC); CREATE INDEX IF NOT EXISTS agent_log_entries_server_time_idx ON agent_log_entries(server_id, event_at DESC); +CREATE TABLE IF NOT EXISTS connection_samples ( + server_id text NOT NULL REFERENCES servers(id) ON DELETE CASCADE, + sampled_at timestamptz NOT NULL DEFAULT now(), + protocol text NOT NULL, + local_address text NOT NULL, + local_port integer NOT NULL CHECK (local_port BETWEEN 0 AND 65535), + remote_address text NOT NULL, + remote_port integer NOT NULL CHECK (remote_port BETWEEN 0 AND 65535), + state text NOT NULL, + process text NOT NULL DEFAULT '', + connection_count integer NOT NULL CHECK (connection_count > 0) +); +CREATE INDEX IF NOT EXISTS connection_samples_server_time_idx ON connection_samples(server_id, sampled_at DESC); +CREATE TABLE IF NOT EXISTS fail2ban_events ( + id bigserial PRIMARY KEY, + server_id text NOT NULL REFERENCES servers(id) ON DELETE CASCADE, + event_at timestamptz NOT NULL DEFAULT now(), + jail text NOT NULL, + ip text NOT NULL, + action text NOT NULL CHECK (action IN ('ban','unban')), + source text NOT NULL +); +CREATE INDEX IF NOT EXISTS fail2ban_events_server_time_idx ON fail2ban_events(server_id, event_at DESC); +CREATE TABLE IF NOT EXISTS fail2ban_ban_state ( + server_id text NOT NULL REFERENCES servers(id) ON DELETE CASCADE, + jail text NOT NULL, + ip text NOT NULL, + PRIMARY KEY(server_id,jail,ip) +); CREATE TABLE IF NOT EXISTS audit_events ( id bigserial PRIMARY KEY, user_id text REFERENCES users(id) ON DELETE SET NULL, @@ -139,6 +168,37 @@ type AgentLogEntry struct { PID *int `json:"pid,omitempty"` } +type ConnectionHistoryRow struct { + Protocol string `json:"protocol"` + LocalAddress string `json:"local_address"` + LocalPort int `json:"local_port"` + RemoteAddress string `json:"remote_address"` + Process string `json:"process"` + Samples int64 `json:"samples"` + Peak int `json:"peak"` + FirstSeen time.Time `json:"first_seen"` + LastSeen time.Time `json:"last_seen"` +} + +type ConnectionTimelinePoint struct { + SampledAt time.Time `json:"sampled_at"` + Count int64 `json:"count"` +} + +type ConnectionHistory struct { + Rows []ConnectionHistoryRow `json:"rows"` + Timeline []ConnectionTimelinePoint `json:"timeline"` +} + +type Fail2BanEvent struct { + ID int64 `json:"id"` + EventAt time.Time `json:"event_at"` + Jail string `json:"jail"` + IP string `json:"ip"` + Action string `json:"action"` + Source string `json:"source"` +} + type MetricPoint struct { ServerID string ServerName string @@ -372,6 +432,84 @@ func (store *Store) Logs(ctx context.Context, serverID string, limit int) ([]Age return entries, rows.Err() } +func (store *Store) ConnectionHistory(ctx context.Context, serverID string, since time.Time) (ConnectionHistory, error) { + result := ConnectionHistory{Rows: []ConnectionHistoryRow{}, Timeline: []ConnectionTimelinePoint{}} + rows, err := store.pool.Query(ctx, `SELECT protocol,local_address,local_port,remote_address,process, + SUM(connection_count),MAX(connection_count),MIN(sampled_at),MAX(sampled_at) + FROM connection_samples WHERE server_id=$1 AND sampled_at >= $2 + GROUP BY protocol,local_address,local_port,remote_address,process + ORDER BY SUM(connection_count) DESC LIMIT 500`, serverID, since) + if err != nil { + return result, err + } + defer rows.Close() + for rows.Next() { + var row ConnectionHistoryRow + if err = rows.Scan(&row.Protocol, &row.LocalAddress, &row.LocalPort, &row.RemoteAddress, &row.Process, &row.Samples, &row.Peak, &row.FirstSeen, &row.LastSeen); err != nil { + return result, err + } + result.Rows = append(result.Rows, row) + } + if err = rows.Err(); err != nil { + return result, err + } + timeline, err := store.pool.Query(ctx, `SELECT date_bin(interval '5 minutes',sampled_at,timestamptz 'epoch'),SUM(connection_count) + FROM connection_samples WHERE server_id=$1 AND sampled_at >= $2 + GROUP BY 1 ORDER BY 1 LIMIT 9000`, serverID, since) + if err != nil { + return result, err + } + defer timeline.Close() + for timeline.Next() { + var point ConnectionTimelinePoint + if err = timeline.Scan(&point.SampledAt, &point.Count); err != nil { + return result, err + } + result.Timeline = append(result.Timeline, point) + } + return result, timeline.Err() +} + +func (store *Store) Fail2BanEvents(ctx context.Context, serverID string, limit int) ([]Fail2BanEvent, error) { + rows, err := store.pool.Query(ctx, `SELECT id,event_at,jail,ip,action,source FROM fail2ban_events + WHERE server_id=$1 ORDER BY event_at DESC LIMIT $2`, serverID, limit) + if err != nil { + return nil, err + } + defer rows.Close() + events := []Fail2BanEvent{} + for rows.Next() { + var event Fail2BanEvent + if err = rows.Scan(&event.ID, &event.EventAt, &event.Jail, &event.IP, &event.Action, &event.Source); err != nil { + return nil, err + } + events = append(events, event) + } + return events, rows.Err() +} + +func (store *Store) AddFail2BanEvent(ctx context.Context, serverID, jail, ip, action, source string) { + tx, err := store.pool.Begin(ctx) + if err != nil { + log.Printf("write Fail2Ban event: %v", err) + return + } + defer tx.Rollback(ctx) + if _, err = tx.Exec(ctx, `INSERT INTO fail2ban_events(server_id,jail,ip,action,source) VALUES($1,$2,$3,$4,$5)`, serverID, jail, ip, action, source); err == nil { + if action == "ban" { + _, err = tx.Exec(ctx, `INSERT INTO fail2ban_ban_state(server_id,jail,ip) VALUES($1,$2,$3) ON CONFLICT DO NOTHING`, serverID, jail, ip) + } else { + _, err = tx.Exec(ctx, `DELETE FROM fail2ban_ban_state WHERE server_id=$1 AND jail=$2 AND ip=$3`, serverID, jail, ip) + } + } + if err == nil { + err = tx.Commit(ctx) + } + if err != nil { + log.Printf("write Fail2Ban event: %v", err) + } +} + func (store *Store) MetricSeries(ctx context.Context) ([]map[string]string, error) { rows, err := store.pool.Query(ctx, "SELECT id,name FROM servers ORDER BY id LIMIT 1000") if err != nil { diff --git a/control-plane/backend/poller.go b/control-plane/backend/poller.go index 4a72aed..76712ff 100644 --- a/control-plane/backend/poller.go +++ b/control-plane/backend/poller.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "log" + "net" "net/http" "net/url" "regexp" @@ -41,6 +42,8 @@ func (poller *Poller) Run(ctx context.Context) { if _, err := poller.store.pool.Exec(ctx, "DELETE FROM agent_log_entries WHERE event_at < $1", time.Now().Add(-poller.logRetention)); err != nil { log.Printf("log retention cleanup: %v", err) } + _, _ = poller.store.pool.Exec(ctx, "DELETE FROM connection_samples WHERE sampled_at < $1", time.Now().Add(-poller.metricRetention)) + _, _ = poller.store.pool.Exec(ctx, "DELETE FROM fail2ban_events WHERE event_at < $1", time.Now().Add(-poller.logRetention)) _, _ = poller.store.pool.Exec(ctx, "DELETE FROM sessions WHERE expires_at < now()") } } @@ -119,13 +122,26 @@ func (poller *Poller) pollServer(ctx context.Context, server Server) { } } } + type socket struct { + Protocol string `json:"protocol"` + LocalAddress string `json:"local_address"` + LocalPort int `json:"local_port"` + RemoteAddress string `json:"remote_address"` + RemotePort int `json:"remote_port"` + State string `json:"state"` + Process *string `json:"process"` + } connections := 0 + connectionRows := []socket{} if code, payload, callErr := poller.agent.Do(ctx, server, http.MethodGet, "/v1/network/connections", nil); callErr == nil && code == 200 { - var items []json.RawMessage - if json.Unmarshal(payload, &items) == nil { - connections = len(items) + if json.Unmarshal(payload, &connectionRows) == nil { + if len(connectionRows) > 10000 { + connectionRows = connectionRows[:10000] + } + connections = len(connectionRows) } } + bans := poller.pollFail2Ban(ctx, server) txDB, err := poller.store.pool.Begin(ctx) if err != nil { return @@ -134,7 +150,41 @@ func (poller *Poller) pollServer(ctx context.Context, server Server) { _, err = txDB.Exec(ctx, "UPDATE servers SET status='online',hostname=$2,last_seen=now(),updated_at=now() WHERE id=$1", server.ID, status.Hostname) if err == nil { _, err = txDB.Exec(ctx, `INSERT INTO metric_samples(server_id,cpu,memory,disk,rx,tx,connections,bans) - VALUES($1,$2,$3,$4,$5,$6,$7,0)`, server.ID, status.CPU, memory, disk, rx, tx, connections) + VALUES($1,$2,$3,$4,$5,$6,$7,$8)`, server.ID, status.CPU, memory, disk, rx, tx, connections, bans) + } + if err == nil { + type aggregate struct { + row socket + count int + } + grouped := map[string]aggregate{} + for _, row := range connectionRows { + if net.ParseIP(row.LocalAddress) == nil || net.ParseIP(row.RemoteAddress) == nil || row.LocalPort < 0 || row.LocalPort > 65535 || row.RemotePort < 0 || row.RemotePort > 65535 || len(row.Protocol) > 8 || len(row.State) > 32 { + continue + } + process := "" + if row.Process != nil { + process = truncateUTF8(*row.Process, 128) + } + key := fmt.Sprintf("%s\x00%s\x00%d\x00%s\x00%d\x00%s\x00%s", row.Protocol, row.LocalAddress, row.LocalPort, row.RemoteAddress, row.RemotePort, row.State, process) + entry := grouped[key] + entry.row = row + entry.row.Process = &process + entry.count++ + grouped[key] = entry + } + inserted := 0 + for _, entry := range grouped { + if inserted >= 2000 { + break + } + _, err = txDB.Exec(ctx, `INSERT INTO connection_samples(server_id,protocol,local_address,local_port,remote_address,remote_port,state,process,connection_count) + VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`, server.ID, entry.row.Protocol, entry.row.LocalAddress, entry.row.LocalPort, entry.row.RemoteAddress, entry.row.RemotePort, entry.row.State, *entry.row.Process, entry.count) + if err != nil { + break + } + inserted++ + } } if err == nil { err = txDB.Commit(ctx) @@ -145,6 +195,78 @@ func (poller *Poller) pollServer(ctx context.Context, server Server) { poller.pollLogs(ctx, server) } +func (poller *Poller) pollFail2Ban(ctx context.Context, server Server) int { + status, payload, err := poller.agent.Do(ctx, server, http.MethodGet, "/v1/fail2ban/status", nil) + if err != nil || status != http.StatusOK { + return 0 + } + var response struct { + JailStatuses []struct { + Jail string `json:"jail"` + Banned []string `json:"banned_ips"` + } `json:"jail_statuses"` + } + if json.Unmarshal(payload, &response) != nil || len(response.JailStatuses) > 64 { + return 0 + } + current := map[string][2]string{} + total := 0 + for _, jail := range response.JailStatuses { + if !validSimpleName(jail.Jail) || len(jail.Banned) > 10000 { + continue + } + for _, ip := range jail.Banned { + if net.ParseIP(ip) != nil { + current[jail.Jail+"\x00"+ip] = [2]string{jail.Jail, ip} + total++ + } + } + } + rows, err := poller.store.pool.Query(ctx, "SELECT jail,ip FROM fail2ban_ban_state WHERE server_id=$1", server.ID) + if err != nil { + return total + } + previous := map[string][2]string{} + for rows.Next() { + var jail, ip string + if rows.Scan(&jail, &ip) == nil { + previous[jail+"\x00"+ip] = [2]string{jail, ip} + } + } + rows.Close() + tx, err := poller.store.pool.Begin(ctx) + if err != nil { + return total + } + defer tx.Rollback(ctx) + for key, value := range current { + if _, found := previous[key]; !found { + _, err = tx.Exec(ctx, "INSERT INTO fail2ban_events(server_id,jail,ip,action,source) VALUES($1,$2,$3,'ban','agent')", server.ID, value[0], value[1]) + if err != nil { + return total + } + } + } + for key, value := range previous { + if _, found := current[key]; !found { + _, err = tx.Exec(ctx, "INSERT INTO fail2ban_events(server_id,jail,ip,action,source) VALUES($1,$2,$3,'unban','agent')", server.ID, value[0], value[1]) + if err != nil { + return total + } + } + } + if _, err = tx.Exec(ctx, "DELETE FROM fail2ban_ban_state WHERE server_id=$1", server.ID); err != nil { + return total + } + for _, value := range current { + if _, err = tx.Exec(ctx, "INSERT INTO fail2ban_ban_state(server_id,jail,ip) VALUES($1,$2,$3)", server.ID, value[0], value[1]); err != nil { + return total + } + } + _ = tx.Commit(ctx) + return total +} + func (poller *Poller) pollLogs(ctx context.Context, server Server) { var cursor string var since time.Time diff --git a/control-plane/frontend/src/App.tsx b/control-plane/frontend/src/App.tsx index 08204cf..60db41e 100644 --- a/control-plane/frontend/src/App.tsx +++ b/control-plane/frontend/src/App.tsx @@ -7,7 +7,7 @@ import { } from 'lucide-react' import { api, APIError, formatBytes, formatDuration } from './api' import type { - AgentLogEntry, AuditEvent, FirewallStatus, Interface, JailStatus, MetricSample, Role, Server, Service, + AgentLogEntry, AuditEvent, ConnectionHistory, Fail2BanEvent, FirewallRule, FirewallStatus, Interface, JailStatus, MetricSample, Role, Server, Service, SocketInfo, SystemStatus, User, WireGuardInterface, } from './types' @@ -108,14 +108,14 @@ function PageContent({page,server,servers,user}:{page:Page;server?:Server;server switch (page) { case 'Overview': return case 'Network': return - case 'Firewall': return + case 'Firewall': return case 'Connections': return case 'Security': return case 'Fail2Ban': return case 'WireGuard': return case 'Services': return case 'Logs': return - case 'Rate Limits': return + case 'Rate Limits': return default: return null } } @@ -160,19 +160,28 @@ function NetworkPage({server}:{server:Server}) {
{JSON.stringify(routes.data,null,2)}
} -function FirewallPage({server}:{server:Server}) { - const firewall = useServerData(server,'firewall',30_000) - return
{firewall.data?.backend ?? 'Unknown'} backendRules are read-only in v1. Unknown and external rules are never mutated.
- - {firewall.data?.warning&&
{firewall.data.warning}
}
{JSON.stringify(firewall.data?.ruleset,null,2)}
+function FirewallPage({server,role}:{server:Server;role:Role}) { + const queryClient=useQueryClient(); const firewall=useServerData(server,'firewall',15_000) + const add=useMutation({mutationFn:(body:unknown)=>api(`/servers/${server.id}/firewall/rules`,{method:'POST',body:JSON.stringify(body)}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'firewall']})}) + const remove=useMutation({mutationFn:(id:string)=>api(`/servers/${server.id}/firewall/rules/${id}`,{method:'DELETE'}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'firewall']})}) + const submit=(event:FormEvent)=>{event.preventDefault();const data=new FormData(event.currentTarget);add.mutate({interface:data.get('interface'),source:data.get('source'),protocol:data.get('protocol'),port:Number(data.get('port')),target:data.get('target'),comment:data.get('comment')})} + const rules=firewall.data?.rules??[] + return
{firewall.data?.backend??'Unknown'} · persistent {firewall.data?.persistence_enabled?'on':'off'}All chains are visible. VPS Control only mutates rules marked as managed in {firewall.data?.managed_chain}.
+ {firewall.data?.warning&&
{firewall.data.warning}
} +
{add.error&&{add.error.message}}
+ [rule.managed?'Yes':'External',{rule.table} / {rule.chain},rule.protocol,{rule.source},rule.in_interface||'—',rule.destination_port??'—',,`${rule.packets} / ${formatBytes(rule.bytes)}`,rule.managed&&!rule.rate_limit?:'—'])}/> + } function ConnectionsPage({server}:{server:Server}) { const connections = useServerData(server,'connections',10_000) - const [filter,setFilter] = useState('') + const [filter,setFilter] = useState(''); const [hours,setHours]=useState(24) + const history=useServerData(server,`connection-history?hours=${hours}`,30_000) const rows=(connections.data??[]).filter((item)=>`${item.protocol} ${item.remote_address} ${item.local_port} ${item.state}`.toLowerCase().includes(filter.toLowerCase())) const states=useMemo(()=>Object.entries(rows.reduce>((all,item)=>({...all,[item.state]:(all[item.state]??0)+1}),{})).sort((a,b)=>b[1]-a[1]),[rows]) - return
{states.slice(0,4).map(([name,count])=>)}
setFilter(e.target.value)}/>}>
[item.protocol.toUpperCase(),{item.local_address}:{item.local_port},{item.remote_address}:{item.remote_port},,item.process?`${item.process} · ${item.pid}`:'—'])}/> + return
{states.slice(0,4).map(([name,count])=>)}
setFilter(e.target.value)}/>}>
[item.protocol.toUpperCase(),{item.local_address}:{item.local_port},{item.remote_address}:{item.remote_port},,item.process?`${item.process} · ${item.pid}`:'—'])}/> + setHours(Number(event.target.value))}>}>
[{item.remote_address},{item.local_address}:{item.local_port},item.protocol.toUpperCase(),item.process||'—',item.samples,item.peak,{new Date(item.first_seen).toLocaleString()}
{new Date(item.last_seen).toLocaleString()}
])}/> + } function SecurityPage({server}:{server:Server}) { @@ -183,10 +192,15 @@ function SecurityPage({server}:{server:Server}) { } function Fail2BanPage({server,role}:{server:Server;role:Role}) { - const queryClient=useQueryClient(); const status=useServerData(server,'fail2ban',15_000) + const queryClient=useQueryClient(); const status=useServerData(server,'fail2ban',15_000); const history=useServerData(server,'fail2ban-history?limit=500',30_000) const mutation=useMutation({mutationFn:(input:{action:'ban'|'unban';jail:string;ip:string})=>api(`/servers/${server.id}/fail2ban/${input.action}`,{method:'POST',body:JSON.stringify(input)}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'fail2ban']})}) + const configure=useMutation({mutationFn:(body:unknown)=>api(`/servers/${server.id}/fail2ban/configure`,{method:'POST',body:JSON.stringify(body)}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'fail2ban']})}) const submit=(event:FormEvent)=>{event.preventDefault();const data=new FormData(event.currentTarget);mutation.mutate({action:data.get('action') as 'ban'|'unban',jail:String(data.get('jail')),ip:String(data.get('ip'))})} - return
{status.data?.jails.map(jail=>{jail})}
{role==='viewer'&&Operator role required.}{mutation.error&&{mutation.error.message}}
+ const submitConfig=(event:FormEvent)=>{event.preventDefault();const data=new FormData(event.currentTarget);configure.mutate({jail:data.get('jail'),enabled:data.get('enabled')==='on',bantime_seconds:Number(data.get('bantime')),findtime_seconds:Number(data.get('findtime')),maxretry:Number(data.get('maxretry'))})} + return
[jail.jail,jail.currently_failed,jail.currently_banned,jail.total_banned,jail.banned_ips.join(', ')||'—'])}/>
{mutation.error&&{mutation.error.message}}
+
{configure.error&&{configure.error.message}}
+
[new Date(event.event_at).toLocaleString(),event.jail,{event.ip},,event.source])}/> + } function WireGuardPage({server}:{server:Server}) { @@ -196,8 +210,8 @@ function WireGuardPage({server}:{server:Server}) { function ServicesPage({server,role}:{server:Server;role:Role}) { const queryClient=useQueryClient(); const query=useServerData(server,'services',15_000) - const mutation=useMutation({mutationFn:(name:string)=>api(`/servers/${server.id}/services/${encodeURIComponent(name)}/restart`,{method:'POST',body:'{}'}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'services']})}) - return
[,{item.name},item.sub_state,item.pid||'—',formatBytes(item.memory_bytes),])}/> + const mutation=useMutation({mutationFn:(input:{name:string;operation:string})=>api(`/servers/${server.id}/services/${encodeURIComponent(input.name)}/${input.operation}`,{method:'POST',body:'{}'}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'services']})}) + return
[,{item.name},`${item.load_state} / ${item.sub_state}`,item.unit_file_state,item.description,item.managed?
{item.load_state==='not-found'&&item.install_available?:<>}
:'Read only'])}/> } function ServersPage({servers,user}:{servers:Server[];user:User}) { @@ -223,7 +237,13 @@ function LogsPage({server}:{server:Server}) { ])}/> } -function RateLimitsPage(){return
Policy engine is not enabled in v1L4 nftables policies require the crash-safe privileged helper. L7 provider configuration is planned separately; arbitrary nginx edits will not be supported.
} +function RateLimitsPage({server,role}:{server:Server;role:Role}){ + const queryClient=useQueryClient(); const query=useServerData(server,'rate-limits',15_000); const firewall=useServerData(server,'firewall',30_000) + const add=useMutation({mutationFn:(body:unknown)=>api(`/servers/${server.id}/rate-limits`,{method:'POST',body:JSON.stringify(body)}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'rate-limits']})}) + const remove=useMutation({mutationFn:(id:string)=>api(`/servers/${server.id}/rate-limits/${id}`,{method:'DELETE'}),onSuccess:()=>void queryClient.invalidateQueries({queryKey:['server',server.id,'rate-limits']})}) + const submit=(event:FormEvent)=>{event.preventDefault();const data=new FormData(event.currentTarget);add.mutate({interface:data.get('interface'),source:data.get('source'),protocol:data.get('protocol'),port:Number(data.get('port')),rate_per_second:Number(data.get('rate')),burst:Number(data.get('burst')),comment:data.get('comment')})} + return
L4 policy enginePolicies use iptables hashlimit in a dedicated chain. Nginx configuration is not edited.
{add.error&&{add.error.message}}
rule.target==='ACCEPT').map(rule=>[{rule.id},{rule.source},rule.in_interface,`${rule.protocol}/${rule.destination_port??'—'}`,`${rule.packets} / ${formatBytes(rule.bytes)}`,])}/> +} function SettingsPage({user,server}:{user:User;server?:Server}){return
} function Metric({label,value,sub,level}:{label:string;value:string;sub:string;level?:number}){return
{label}{value}{sub}{level!==undefined&&
}
} diff --git a/control-plane/frontend/src/styles.css b/control-plane/frontend/src/styles.css index e0845ef..31e99de 100644 --- a/control-plane/frontend/src/styles.css +++ b/control-plane/frontend/src/styles.css @@ -5,3 +5,4 @@ @media(max-width:1050px){.metric-grid{grid-template-columns:repeat(2,1fr)}.overview-grid,.split{grid-template-columns:1fr}.action-form{grid-template-columns:1fr 1fr}.action-form button{grid-column:2}.compact{grid-template-columns:repeat(3,1fr)}} @media(max-width:760px){.shell{display:block}.sidebar{position:fixed;left:-250px;width:236px;transition:left .2s}.sidebar.open{left:0}.scrim{position:fixed;inset:0;background:rgba(0,0,0,.55);border:0;z-index:15}.mobile-close{display:grid;margin-left:auto}.menu-button{display:grid}.topbar{padding:0 14px}.breadcrumb{display:none}.content{padding:20px 14px}.connection{display:none}.page-header{height:auto;min-height:62px}.last-seen{display:none}.metric-grid,.compact{grid-template-columns:1fr}.metric{min-height:115px}.server-form,.action-form{grid-template-columns:1fr}.action-form button{grid-column:auto}.server-grid{grid-template-columns:1fr}.filter{width:160px}.panel-loading{grid-template-columns:1fr}.panel-loading i:nth-child(n+2){display:none}} .log-message{display:block;min-width:260px;max-width:760px;white-space:pre-wrap;overflow-wrap:anywhere;font-family:'DM Mono',ui-monospace,monospace;color:var(--muted);line-height:1.45} +.action-form.wide{grid-template-columns:repeat(auto-fit,minmax(130px,1fr))}.action-form label{display:flex;align-items:center;gap:7px;color:var(--muted);font-size:11px}.action-form label input[type=checkbox]{width:16px;height:16px}.table-actions{display:flex;align-items:center;gap:6px} diff --git a/control-plane/frontend/src/types.ts b/control-plane/frontend/src/types.ts index da24ce7..055f23a 100644 --- a/control-plane/frontend/src/types.ts +++ b/control-plane/frontend/src/types.ts @@ -13,10 +13,15 @@ export interface SystemStatus { } export interface Interface { name: string; state: string; addresses: string[]; rx_bytes: number; tx_bytes: number } export interface SocketInfo { protocol: string; local_address: string; local_port: number; remote_address: string; remote_port: number; state: string; pid?: number; process?: string } -export interface Service { name: string; active_state: string; sub_state: string; pid: number; memory_bytes?: number } -export interface JailStatus { installed: boolean; running: boolean; version?: string; jails: string[] } +export interface Service { name: string; load_state:string; active_state: string; sub_state: string; description:string; unit_file_state:string; managed:boolean; install_available:boolean } +export interface JailDetail { jail:string; currently_failed:number; total_failed:number; currently_banned:number; total_banned:number; banned_ips:string[] } +export interface JailStatus { installed: boolean; running: boolean; version?: string; jails: string[]; jail_statuses:JailDetail[]; management_enabled:boolean; manageable_jails:string[] } export interface WireGuardInterface { name: string; public_key: string; listen_port: number; peers: Array<{public_key:string;endpoint?:string;allowed_ips:string[];latest_handshake:number;rx_bytes:number;tx_bytes:number}> } -export interface FirewallStatus { backend: string; management_enabled: boolean; managed_table: string; ruleset: unknown; warning?: string } +export interface FirewallRule { id:string; table:string; chain:string; protocol:string; source:string; destination:string; in_interface:string; out_interface:string; destination_port?:number; target:string; packets:number; bytes:number; comment:string; managed:boolean; rate_limit:boolean } +export interface FirewallStatus { backend: string; management_enabled: boolean; persistence_enabled:boolean; managed_chain: string; allowed_interfaces:string[]; allowed_sources:string[]; allowed_ports:number[]; rules:FirewallRule[]; warning?: string } export interface AuditEvent { id: number; username: string; server_id?: string; action: string; target: string; result: string; source_ip: string; created_at: string } export interface MetricSample { sampled_at:string; cpu:number; memory:number; disk:number; rx:number; tx:number; connections:number; bans:number } export interface AgentLogEntry { server_id:string; timestamp:string; unit:string; priority:number; message:string; boot_id?:string; pid?:number } +export interface ConnectionHistoryRow { protocol:string; local_address:string; local_port:number; remote_address:string; process:string; samples:number; peak:number; first_seen:string; last_seen:string } +export interface ConnectionHistory { rows:ConnectionHistoryRow[]; timeline:Array<{sampled_at:string;count:number}> } +export interface Fail2BanEvent { id:number; event_at:string; jail:string; ip:string; action:'ban'|'unban'; source:string } diff --git a/docs/architecture.md b/docs/architecture.md index a763fbd..2adc659 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -30,14 +30,18 @@ writes at 2 rps, burst 20, with 32 concurrent requests and five-second timeouts. | GET | `/v1/network/routes` | kernel routes | | GET | `/v1/network/listeners` | listening TCP/UDP sockets | | GET | `/v1/network/connections` | current TCP/UDP sockets | -| GET | `/v1/firewall/rules` | backend and read-only ruleset | +| GET/POST | `/v1/firewall/rules` | structured iptables inventory / add managed rule | +| DELETE | `/v1/firewall/rules/:id` | delete a managed rule | +| GET/POST | `/v1/rate-limits` | list / add managed L4 policies | +| DELETE | `/v1/rate-limits/:id` | delete a managed L4 policy | | GET | `/v1/fail2ban/status` | installation and jail summary | | GET | `/v1/fail2ban/jails/:jail` | validated jail detail | | POST | `/v1/fail2ban/ban` | validated IP and jail ban | | POST | `/v1/fail2ban/unban` | validated IP and jail unban | +| POST | `/v1/fail2ban/configure` | write and validate an allow-listed jail drop-in | | GET | `/v1/wireguard/status` | interface and peer dump | -| GET | `/v1/services` | allow-listed services only | -| POST | `/v1/services/:name/restart` | allow-listed restart only | +| GET | `/v1/services` | bounded inventory of all systemd services | +| POST | `/v1/services/:name/:operation` | allow-listed action or catalog installation | | GET | `/v1/logs` | cursor-paginated journald rows from allow-listed units | No generic command route exists. Child processes receive a fixed executable and @@ -53,6 +57,8 @@ fixed subcommand plus individually validated argv values. connections, bans)` with 30-day retention - `agent_log_entries(server_id, journal_cursor, event_at, unit, priority, message, boot_id, pid)` with configurable seven-day retention +- `connection_samples(...)` with current source/destination/process aggregates +- `fail2ban_events(...)` and `fail2ban_ban_state(...)` for ban history - `audit_events(actor, server, action, target, before, after, result, source_ip, created_at)`; secrets are excluded @@ -78,10 +84,8 @@ Grafana ──Prometheus/Loki read APIs──> backend ──semantic polling─ ## Privilege design -The agent has no ambient capabilities and runs as `vps-agent`. Linux usually -permits the read-only endpoints without elevation. Fail2Ban mutations and -service restarts need administrator-provided sudoers or polkit rules restricted -to each approved verb/name. The shipped service does not install such policy -automatically. Managed firewall mutation is out of v1 because giving the main -daemon `CAP_NET_ADMIN` violates least privilege; its future helper protocol must -provide prepare/apply/health/confirm/commit and persistent timed rollback. +The HTTP agent has no ambient capabilities and runs as `vps-agent`. Linux +usually permits the read-only endpoints without elevation. Mutations go over a +0600 Unix socket to a root, socket-activated helper. The helper accepts typed +JSON only, validates local allow-lists, uses fixed argv, snapshots iptables, +rolls back failures and never mutates rules outside its two reserved chains. diff --git a/docs/deployment.md b/docs/deployment.md index 0a9a49b..21d2e7f 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -7,6 +7,49 @@ WireGuard address only and allow TCP/9105 solely from the control-plane peer. Alternatively bind to loopback and expose it through an authenticated tunnel. TLS termination at the agent is supported when certificate paths are configured. +## Agent write features + +On Debian/Ubuntu install the firewall userspace and persistence provider before +enabling managed writes: + +```bash +sudo apt-get update +sudo apt-get install -y iptables iptables-persistent fail2ban +sudo systemctl enable --now netfilter-persistent vps-agent-helper.socket +``` + +Then edit `/etc/vps-agent/config.toml`. All write targets must be explicitly +allow-listed; use the real tunnel interface, management network and service +ports for the host: + +```toml +[services] +allowed = ["nginx.service", "fail2ban.service"] +inventory_limit = 512 +install_enabled = true +install_timeout_seconds = 300 +packages = { "nginx.service" = "nginx", "fail2ban.service" = "fail2ban" } + +[firewall] +management_enabled = true +persistence_enabled = true +allowed_interfaces = ["wg0"] +allowed_sources = ["192.168.50.0/24"] +allowed_ports = [22, 80, 443, 9105] +rollback_timeout_seconds = 60 +max_snapshots = 5 + +[fail2ban] +management_enabled = true +allowed_jails = ["sshd", "nginx-http-auth"] +``` + +Restart the daemon after editing. The UI shows every iptables rule but only +rules in `VPS_CONTROL_INPUT` and `VPS_CONTROL_RATE` can be deleted. Successful +changes are saved through `netfilter-persistent`; failed changes restore the +last snapshot. Keep the control-panel port and source network in the allow-list +before adding restrictive rules. + ## Control plane ```bash @@ -36,7 +79,8 @@ needs only `/etc/vps-agent/`. For upgrades, pin image tags, back up, pull/build, run `docker compose up -d`, then inspect health and audit events. Database migrations are forward-only; restore the database backup for rollback. -Metric samples are retained for 30 days and collected logs for seven days by +Metric and connection samples are retained for 30 days and collected logs and +Fail2Ban history for seven days by the backend cleanup loop. `METRICS_RETENTION` and `LOGS_RETENTION` control these windows; log retention is constrained to one hour through 90 days. Configure database-level backups independently of retention. diff --git a/docs/security.md b/docs/security.md index 5493fa3..c38bd4b 100644 --- a/docs/security.md +++ b/docs/security.md @@ -19,7 +19,7 @@ CSRF header on mutations. Passwords use Argon2id. | Request flooding | request timeouts, concurrency semaphore, token buckets, reverse-proxy limits | | Command injection | no command strings; executable and subcommands are constants; service names are allow-listed | | Privilege escalation | unprivileged user, systemd sandbox, no capabilities, write privileges opt-in and narrow | -| Accidental firewall lockout | v1 is read-only; future mutations require local, crash-safe confirm-or-rollback | +| Accidental firewall damage | only dedicated chains are mutable; every change snapshots, restores on error, and persists only after success | | Disk/log exhaustion | journald only, no metric spool, PostgreSQL retention, bounded body/audit fields | | Observability token theft | independent file secret, constant-time verification, per-source limiting, no agent credentials in Grafana | | Expensive dashboard queries | fixed metric set, restricted selectors, 31-day ranges, point/row/result caps | @@ -37,13 +37,18 @@ the file, restart the agent, then update its control-plane Docker secret and restart the backend. Keep the overlap window short; the agent intentionally accepts one token. Never pass the token on a command line. -## Firewall safety design (future helper) +## Privileged helper and firewall safety -The future root helper owns only `table inet vps_control`. It writes a bounded -snapshot (maximum five), fsyncs a pending transaction with a monotonic deadline, -applies a complete validated table, and starts an independent rollback timer. -Only an authenticated confirmation commits. On restart it rolls back any pending -transaction before accepting a new one. Unknown tables/chains remain read-only. +The HTTP daemon remains unprivileged. A socket-activated, one-request root helper +accepts only typed operations from the `vps-agent` Unix account. Firewall writes +are restricted to `VPS_CONTROL_INPUT` and `VPS_CONTROL_RATE`; external rules are +always read-only. Before a mutation the helper stores a bounded `iptables-save` +snapshot and arms an independent systemd rollback timer. The backend confirms +the transaction only after reconnecting to the agent; without confirmation the +snapshot is restored and persisted. Immediate command failures also restore it. +Interfaces, source CIDRs, ports, services, packages and Fail2Ban jails must all +match local configuration allow-lists. Service installation uses a fixed +`apt-get` argv in a time-bounded transient systemd unit. ## Operational logging diff --git a/examples/agent-config.toml b/examples/agent-config.toml index 8755105..93c5a61 100644 --- a/examples/agent-config.toml +++ b/examples/agent-config.toml @@ -16,13 +16,25 @@ burst = 20.0 command_timeout_seconds = 4 [services] -allowed = ["nginx", "fail2ban", "wg-quick@wg0"] +allowed = ["nginx.service", "fail2ban.service", "wg-quick@wg0.service"] +inventory_limit = 512 +install_enabled = false +install_timeout_seconds = 300 +packages = { "nginx.service" = "nginx", "fail2ban.service" = "fail2ban" } [firewall] management_enabled = false +persistence_enabled = true +allowed_interfaces = ["wg0"] +allowed_sources = ["192.168.50.0/24"] +allowed_ports = [22, 80, 443, 9105] rollback_timeout_seconds = 60 max_snapshots = 5 +[fail2ban] +management_enabled = false +allowed_jails = ["sshd", "nginx-http-auth"] + [logging] level = "info" diff --git a/scripts/vps-agentctl.sh b/scripts/vps-agentctl.sh index 4855043..f7f19ae 100755 --- a/scripts/vps-agentctl.sh +++ b/scripts/vps-agentctl.sh @@ -9,6 +9,8 @@ readonly CONFIG_DIR="/etc/vps-agent" readonly CREDENTIAL_DIR="${CONFIG_DIR}/credentials" readonly STATE_DIR="/var/lib/vps-agent" readonly UNIT="/etc/systemd/system/vps-agent.service" +readonly HELPER_SOCKET_UNIT="/etc/systemd/system/vps-agent-helper.socket" +readonly HELPER_SERVICE_UNIT="/etc/systemd/system/vps-agent-helper@.service" readonly DEFAULT_RELEASES="https://gitea.hyperdog.dev/dizyaka/vps-control/releases" VERSION="latest" @@ -137,6 +139,60 @@ RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK [Install] WantedBy=multi-user.target EOF + + install -o root -g root -m 0644 /dev/null "$HELPER_SOCKET_UNIT" + tee "$HELPER_SOCKET_UNIT" >/dev/null <<'EOF' +[Unit] +Description=VPS Control privileged helper socket +[Socket] +ListenStream=/run/vps-agent-helper/control.sock +Accept=yes +MaxConnections=1 +SocketUser=vps-agent +SocketGroup=vps-agent +SocketMode=0600 +DirectoryMode=0750 +RemoveOnStop=yes +[Install] +WantedBy=sockets.target +EOF + install -o root -g root -m 0644 /dev/null "$HELPER_SERVICE_UNIT" + tee "$HELPER_SERVICE_UNIT" >/dev/null <<'EOF' +[Unit] +Description=VPS Control privileged helper request +[Service] +Type=oneshot +ExecStart=/usr/local/bin/vps-agent --privileged-helper --config /etc/vps-agent/config.toml +StandardInput=socket +StandardOutput=socket +StandardError=journal +User=root +Group=root +TimeoutStartSec=330 +UMask=0077 +PrivateTmp=true +ProtectHome=true +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectKernelLogs=true +ProtectControlGroups=true +ProtectClock=true +ProtectHostname=true +RestrictSUIDSGID=true +LockPersonality=true +RestrictRealtime=true +RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK +EOF +} + +install_helper_units() { + local source_dir="$(cd "$(dirname "$0")" && pwd)/../agent/packaging" + if [[ -f "$source_dir/vps-agent-helper.socket" && -f "$source_dir/vps-agent-helper@.service" ]]; then + install -o root -g root -m 0644 "$source_dir/vps-agent-helper.socket" "$HELPER_SOCKET_UNIT" + install -o root -g root -m 0644 "$source_dir/vps-agent-helper@.service" "$HELPER_SERVICE_UNIT" + elif [[ ! -f "$HELPER_SOCKET_UNIT" || ! -f "$HELPER_SERVICE_UNIT" ]]; then + die "helper unit templates are missing; use the packaged installer or install the units manually" + fi } create_config() { @@ -158,10 +214,21 @@ burst = 20.0 command_timeout_seconds = 4 [services] allowed = [] +inventory_limit = 512 +install_enabled = false +install_timeout_seconds = 300 +packages = {} [firewall] management_enabled = false +persistence_enabled = true +allowed_interfaces = [] +allowed_sources = [] +allowed_ports = [] rollback_timeout_seconds = 60 max_snapshots = 5 +[fail2ban] +management_enabled = false +allowed_jails = ["sshd"] [logging] level = "info" [telemetry] @@ -223,8 +290,9 @@ do_install() { create_config create_token install_unit + install_helper_units systemctl daemon-reload - systemctl enable --now vps-agent.service + systemctl enable --now vps-agent-helper.socket vps-agent.service wait_healthy || die "agent failed to become healthy" systemctl status --no-pager vps-agent.service } @@ -239,6 +307,10 @@ do_update() { install -o root -g root -m 0755 "$downloaded" "$staged" install -o root -g root -m 0755 "$BINARY" "$PREVIOUS" mv -f -- "$staged" "$BINARY" + install_unit + install_helper_units + systemctl daemon-reload + systemctl enable --now vps-agent-helper.socket systemctl restart vps-agent.service if ! wait_healthy; then info "health check failed; restoring previous binary" @@ -268,8 +340,18 @@ do_remove() { read -r -p "Permanently delete $CONFIG_DIR and credentials? [y/N] " answer [[ "$answer" == "y" || "$answer" == "Y" ]] || die "purge cancelled" fi - systemctl disable --now vps-agent.service 2>/dev/null || true - rm -f -- "$UNIT" "$BINARY" "$PREVIOUS" + local pending transaction + for pending in "$STATE_DIR"/firewall/pending-*.rules; do + [[ -f "$pending" ]] || continue + transaction="${pending##*/pending-}" + transaction="${transaction%.rules}" + [[ "$transaction" =~ ^[a-fA-F0-9]{16}$ ]] || die "invalid pending firewall transaction filename" + "$BINARY" --firewall-rollback "$transaction" --config "$CONFIG_DIR/config.toml" \ + || die "could not restore pending firewall transaction $transaction" + systemctl stop "vps-agent-firewall-rollback-${transaction}.timer" 2>/dev/null || true + done + systemctl disable --now vps-agent.service vps-agent-helper.socket 2>/dev/null || true + rm -f -- "$UNIT" "$HELPER_SOCKET_UNIT" "$HELPER_SERVICE_UNIT" "$BINARY" "$PREVIOUS" rm -rf -- "$STATE_DIR" systemctl daemon-reload if [[ "$PURGE" == true ]]; then