[pve-devel] [PATCH proxmox-firewall 28/37] firewall: add config loader

Stefan Hanreich s.hanreich at proxmox.com
Tue Apr 2 19:16:20 CEST 2024


We load the firewall configuration from the default paths, as well as
only the guest configurations that are local to the node itself. In
the future we could change this to use pmxcfs directly instead.

We also load information from nftables directly about dynamically
created chains (mostly chains for the guest firewall).

Co-authored-by: Wolfgang Bumiller <w.bumiller at proxmox.com>
Signed-off-by: Stefan Hanreich <s.hanreich at proxmox.com>
---
 proxmox-firewall/Cargo.toml    |   2 +
 proxmox-firewall/src/config.rs | 163 +++++++++++++++++++++++++++++++++
 proxmox-firewall/src/main.rs   |   3 +
 3 files changed, 168 insertions(+)
 create mode 100644 proxmox-firewall/src/config.rs

diff --git a/proxmox-firewall/Cargo.toml b/proxmox-firewall/Cargo.toml
index b59d973..431e71a 100644
--- a/proxmox-firewall/Cargo.toml
+++ b/proxmox-firewall/Cargo.toml
@@ -11,6 +11,8 @@ description = "Proxmox VE nftables firewall implementation"
 license = "AGPL-3"
 
 [dependencies]
+log = "0.4"
+env_logger = "0.10"
 anyhow = "1"
 
 proxmox-nftables = { path = "../proxmox-nftables", features = ["config-ext"] }
diff --git a/proxmox-firewall/src/config.rs b/proxmox-firewall/src/config.rs
new file mode 100644
index 0000000..212d650
--- /dev/null
+++ b/proxmox-firewall/src/config.rs
@@ -0,0 +1,163 @@
+use std::collections::HashMap;
+use std::default::Default;
+use std::io;
+
+use anyhow::{anyhow, format_err, Error};
+
+use proxmox_ve_config::firewall::cluster::Config as ClusterConfig;
+use proxmox_ve_config::firewall::guest::Config as GuestConfig;
+use proxmox_ve_config::firewall::host::Config as HostConfig;
+use proxmox_ve_config::firewall::types::alias::{Alias, AliasName, AliasScope};
+
+use proxmox_ve_config::guest::types::Vmid;
+use proxmox_ve_config::guest::GuestMap;
+
+use proxmox_nftables::command::{Commands, List, ListOutput};
+use proxmox_nftables::types::ListChain;
+use proxmox_nftables::NftCtx;
+
+#[derive(Debug, Default)]
+pub struct NftConfig {
+    pub(crate) chains: HashMap<String, ListChain>,
+}
+
+impl NftConfig {
+    pub fn load() -> Result<Self, Error> {
+        let mut nft = NftCtx::new()?;
+
+        let commands = Commands::new(vec![List::chains()]);
+        let output = nft
+            .run_commands(&commands)?
+            .ok_or_else(|| format_err!("got no response from nft"))?;
+
+        let mut chains = HashMap::new();
+
+        for element in output.nftables {
+            if let ListOutput::Chain(chain) = element {
+                chains.insert(chain.name().to_owned(), chain);
+            }
+        }
+
+        Ok(Self { chains })
+    }
+}
+
+const CLUSTER_CONFIG_PATH: &str = "/etc/pve/firewall/cluster.fw";
+const HOST_CONFIG_PATH: &str = "/etc/pve/local/host.fw";
+
+#[derive(Debug)]
+pub struct FirewallConfig {
+    cluster: ClusterConfig,
+    guests: HashMap<Vmid, GuestConfig>,
+    host: HostConfig,
+    nft: NftConfig,
+}
+
+fn read_config_file(path: &str) -> Result<Option<Vec<u8>>, Error> {
+    match std::fs::read(path) {
+        Ok(data) => Ok(Some(data)),
+        Err(err) if err.kind() == io::ErrorKind::NotFound => {
+            log::debug!("config file not found: {path}");
+            Ok(None)
+        }
+        Err(err) => Err(anyhow!(err)),
+    }
+}
+
+impl FirewallConfig {
+    pub fn load() -> Result<Self, Error> {
+        log::debug!("loading cluster config");
+        let cluster_config = read_config_file(CLUSTER_CONFIG_PATH)?;
+
+        let cluster = match cluster_config {
+            Some(data) => ClusterConfig::parse(data.as_slice())?,
+            None => ClusterConfig::default(),
+        };
+
+        log::debug!("loading host config");
+        let host_config = read_config_file(HOST_CONFIG_PATH)?;
+
+        let host = match host_config {
+            Some(data) => HostConfig::parse(data.as_slice())?,
+            None => HostConfig::default(),
+        };
+
+        let guest_map = GuestMap::load()?;
+        let mut guests = HashMap::new();
+
+        for (vmid, guest) in guest_map.iter() {
+            if !guest.is_local() {
+                log::trace!("#{vmid} is not a local VM - skipping");
+                continue;
+            }
+
+            log::debug!("loading guest #{vmid} config");
+            let firewall_config = read_config_file(&guest_map.firewall_config_path(vmid))?;
+
+            if let Some(data) = firewall_config {
+                let config_path = guest_map
+                    .config_path_local(vmid)
+                    .ok_or_else(|| format_err!("could not find config for guest #{vmid}"))?;
+
+                let guest_config = std::fs::read(config_path)?;
+                let config = GuestConfig::parse(
+                    vmid,
+                    guest.ty().iface_prefix(),
+                    data.as_slice(),
+                    guest_config.as_slice(),
+                )?;
+
+                guests.insert(*vmid, config);
+            };
+        }
+
+        log::debug!("loading nft config");
+        let nft = NftConfig::load()?;
+
+        Ok(Self {
+            cluster,
+            guests,
+            host,
+            nft,
+        })
+    }
+
+    pub fn cluster(&self) -> &ClusterConfig {
+        &self.cluster
+    }
+
+    pub fn host(&self) -> &HostConfig {
+        &self.host
+    }
+
+    pub fn guests(&self) -> &HashMap<Vmid, GuestConfig> {
+        &self.guests
+    }
+
+    pub fn nft(&self) -> &NftConfig {
+        &self.nft
+    }
+
+    pub fn is_enabled(&self) -> bool {
+        self.cluster.is_enabled() && self.host.nftables()
+    }
+
+    pub fn alias(&self, name: &AliasName, vmid: Option<Vmid>) -> Option<&Alias> {
+        log::trace!("getting alias {name:?}");
+
+        match name.scope() {
+            AliasScope::Datacenter => self.cluster.alias(name.name()),
+            AliasScope::Guest => {
+                if let Some(vmid) = vmid {
+                    if let Some(entry) = self.guests.get(&vmid) {
+                        return entry.alias(name);
+                    }
+
+                    log::warn!("trying to get alias {name} for non-existing guest: #{vmid}");
+                }
+
+                None
+            }
+        }
+    }
+}
diff --git a/proxmox-firewall/src/main.rs b/proxmox-firewall/src/main.rs
index 248ac39..656ac15 100644
--- a/proxmox-firewall/src/main.rs
+++ b/proxmox-firewall/src/main.rs
@@ -1,5 +1,8 @@
 use anyhow::Error;
 
+mod config;
+
 fn main() -> Result<(), Error> {
+    env_logger::init();
     Ok(())
 }
-- 
2.39.2




More information about the pve-devel mailing list