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

@@ -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");
}
}