From mboxrd@z Thu Jan  1 00:00:00 1970
Return-Path: <shanreich@lana.proxmox.com>
Received: from firstgate.proxmox.com (firstgate.proxmox.com [212.224.123.68])
 (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits)
 key-exchange X25519 server-signature RSA-PSS (2048 bits))
 (No client certificate requested)
 by lists.proxmox.com (Postfix) with ESMTPS id 71C8090CA1
 for <pve-devel@lists.proxmox.com>; Tue,  2 Apr 2024 19:26:18 +0200 (CEST)
Received: from firstgate.proxmox.com (localhost [127.0.0.1])
 by firstgate.proxmox.com (Proxmox) with ESMTP id 535A9B3C0
 for <pve-devel@lists.proxmox.com>; Tue,  2 Apr 2024 19:25:48 +0200 (CEST)
Received: from lana.proxmox.com (unknown [94.136.29.99])
 by firstgate.proxmox.com (Proxmox) with ESMTP
 for <pve-devel@lists.proxmox.com>; Tue,  2 Apr 2024 19:25:46 +0200 (CEST)
Received: by lana.proxmox.com (Postfix, from userid 10043)
 id B95602C3A8B; Tue,  2 Apr 2024 19:16:31 +0200 (CEST)
From: Stefan Hanreich <s.hanreich@proxmox.com>
To: pve-devel@lists.proxmox.com
Cc: Stefan Hanreich <s.hanreich@proxmox.com>,
 Wolfgang Bumiller <w.bumiller@proxmox.com>
Date: Tue,  2 Apr 2024 19:16:20 +0200
Message-Id: <20240402171629.536804-29-s.hanreich@proxmox.com>
X-Mailer: git-send-email 2.39.2
In-Reply-To: <20240402171629.536804-1-s.hanreich@proxmox.com>
References: <20240402171629.536804-1-s.hanreich@proxmox.com>
MIME-Version: 1.0
Content-Transfer-Encoding: 8bit
X-SPAM-LEVEL: Spam detection results:  0
 AWL -0.311 Adjusted score from AWL reputation of From: address
 BAYES_00                 -1.9 Bayes spam probability is 0 to 1%
 DMARC_MISSING             0.1 Missing DMARC policy
 KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment
 KAM_LAZY_DOMAIN_SECURITY 1 Sending domain does not have any anti-forgery
 methods
 RDNS_NONE 0.793 Delivered to internal network by a host with no rDNS
 SPF_HELO_NONE           0.001 SPF: HELO does not publish an SPF Record
 SPF_NONE                0.001 SPF: sender does not publish an SPF Record
 URIBL_BLOCKED 0.001 ADMINISTRATOR NOTICE: The query to URIBL was blocked. See
 http://wiki.apache.org/spamassassin/DnsBlocklists#dnsbl-block for more
 information. [config.rs, main.rs, self.host]
Subject: [pve-devel] [PATCH proxmox-firewall 28/37] firewall: add config
 loader
X-BeenThere: pve-devel@lists.proxmox.com
X-Mailman-Version: 2.1.29
Precedence: list
List-Id: Proxmox VE development discussion <pve-devel.lists.proxmox.com>
List-Unsubscribe: <https://lists.proxmox.com/cgi-bin/mailman/options/pve-devel>, 
 <mailto:pve-devel-request@lists.proxmox.com?subject=unsubscribe>
List-Archive: <http://lists.proxmox.com/pipermail/pve-devel/>
List-Post: <mailto:pve-devel@lists.proxmox.com>
List-Help: <mailto:pve-devel-request@lists.proxmox.com?subject=help>
List-Subscribe: <https://lists.proxmox.com/cgi-bin/mailman/listinfo/pve-devel>, 
 <mailto:pve-devel-request@lists.proxmox.com?subject=subscribe>
X-List-Received-Date: Tue, 02 Apr 2024 17:26:18 -0000

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@proxmox.com>
Signed-off-by: Stefan Hanreich <s.hanreich@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