This commit is contained in:
2026-09-22 23:37:05 +03:00
parent cf1c31eb2a
commit 0fc35589e6
25 changed files with 2616 additions and 245 deletions

View File

@@ -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<AppState>) -> 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<Arc<AppState>>) -> Json<firewall::FirewallStatus> {
Json(firewall::status(command_timeout(&state)).await)
Json(firewall::status(&state.config, command_timeout(&state)).await)
}
async fn firewall_add(
State(state): State<Arc<AppState>>,
Json(request): Json<firewall::AddRuleRequest>,
) -> Result<Json<Value>, 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<Arc<AppState>>,
Path(id): Path<String>,
) -> Result<Json<Value>, 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<Arc<AppState>>) -> Json<Vec<firewall::FirewallRule>> {
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<Arc<AppState>>,
Json(request): Json<firewall::RateLimitRequest>,
) -> Result<Json<Value>, 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<Arc<AppState>>,
Path(id): Path<String>,
) -> Result<Json<Value>, 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<Arc<AppState>>,
Path(id): Path<String>,
) -> Result<Json<Value>, 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<Arc<AppState>>) -> Json<fail2ban::Status> {
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::<std::net::IpAddr>()
.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<Arc<AppState>>,
Json(request): Json<fail2ban::ConfigureRequest>,
) -> Result<Json<Value>, 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<Arc<AppState>>,
) -> Result<Json<Vec<wireguard::Interface>>, ApiError> {
@@ -344,33 +425,34 @@ async fn wireguard_status(
}
async fn service_list(State(state): State<Arc<AppState>>) -> Json<Vec<services::ServiceStatus>> {
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<Arc<AppState>>,
Path(name): Path<String>,
Path((name, operation)): Path<(String, String)>,
) -> Result<Json<Value>, 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"})))
}

View File

@@ -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<String>,
pub inventory_limit: usize,
pub install_enabled: bool,
pub install_timeout_seconds: u64,
pub packages: HashMap<String, String>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Firewall {
pub management_enabled: bool,
pub persistence_enabled: bool,
pub allowed_interfaces: Vec<String>,
pub allowed_sources: Vec<String>,
pub allowed_ports: Vec<u16>,
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<String>,
}
#[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::<std::net::IpAddr>().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::<std::net::IpAddr>() else {
return false;
};
let Ok(prefix) = prefix.parse::<u8>() 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"));
}
}

View File

@@ -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<String>,
pub jails: Vec<String>,
pub jail_statuses: Vec<JailStatus>,
pub management_enabled: bool,
pub manageable_jails: Vec<String>,
}
#[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<JailStatus> {
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?;

View File

@@ -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<String>,
pub allowed_sources: Vec<String>,
pub allowed_ports: Vec<u16>,
pub rules: Vec<FirewallRule>,
pub warning: Option<String>,
}
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<u16>,
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<String> {
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<String> {
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<String> {
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<String> {
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<String> {
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<FirewallRule> {
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<String> {
tokens
.iter()
.position(|token| token == name)
.and_then(|index| tokens.get(index + 1))
.cloned()
}
fn split_arguments(line: &str) -> Vec<String> {
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");
}
}

View File

@@ -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<PathBuf> {
struct Arguments {
config_path: PathBuf,
privileged_helper: bool,
firewall_rollback: Option<String>,
}
fn parse_args() -> Result<Arguments> {
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<PathBuf> {
.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<PathBuf> {
_ => anyhow::bail!("unknown argument: {argument}"),
}
}
Ok(config)
Ok(Arguments {
config_path: config,
privileged_helper,
firewall_rollback,
})
}
async fn wait_for_shutdown() {

915
agent/src/privileged.rs Normal file
View File

@@ -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<String>,
pub data: Option<Value>,
}
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<String>) -> Self {
Self {
ok: false,
changed: false,
error: Some(error.into()),
data: None,
}
}
}
pub async fn call(request: &Request, timeout_duration: Duration) -> Result<Response> {
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<Request> {
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<Response> {
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<Response> {
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<Response> {
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<bool> {
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<Response> {
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<bool> {
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<Response> {
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<bool> {
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<Vec<String>> = 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<Response> {
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<Response> {
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<Response> {
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<Response> {
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<Response>,
transaction: &str,
snapshot: &Path,
config: &Config,
) -> Result<Response> {
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<String> {
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<String> {
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<Response> {
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<PathBuf> {
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::<Request>(payload).is_err());
}
#[test]
fn helper_request_is_typed() {
let payload = br#"{"action":"service_install","service":"nginx.service"}"#;
assert!(matches!(
serde_json::from_slice::<Request>(payload).unwrap(),
Request::ServiceInstall { .. }
));
}
}

View File

@@ -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<u64>,
pub active_since_monotonic_us: Option<u64>,
pub description: String,
pub unit_file_state: String,
pub managed: bool,
pub install_available: bool,
}
pub async fn list(allowed: &[String], timeout: Duration) -> Vec<ServiceStatus> {
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<ServiceStatus> {
if !valid_service_name(name) {
bail!("invalid service name")
}
let output = command::run(
pub async fn list(config: &Services, timeout: Duration) -> Vec<ServiceStatus> {
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<ServiceStatus> {
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::<Vec<_>>().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<String, String> {
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");
}
}