[pve-devel] [PATCH proxmox-firewall v3 32/39] firewall: add proxmox-firewall binary and move existing code into lib

Stefan Hanreich s.hanreich at proxmox.com
Thu Apr 18 18:14:27 CEST 2024


Reviewed-by: Lukas Wagner <l.wagner at proxmox.com>
Reviewed-by: Max Carrara <m.carrara at proxmox.com>
Co-authored-by: Wolfgang Bumiller <w.bumiller at proxmox.com>
Signed-off-by: Stefan Hanreich <s.hanreich at proxmox.com>
---
 proxmox-firewall/src/bin/proxmox-firewall.rs | 96 ++++++++++++++++++++
 proxmox-firewall/src/lib.rs                  |  4 +
 proxmox-firewall/src/main.rs                 | 11 ---
 3 files changed, 100 insertions(+), 11 deletions(-)
 create mode 100644 proxmox-firewall/src/bin/proxmox-firewall.rs
 create mode 100644 proxmox-firewall/src/lib.rs
 delete mode 100644 proxmox-firewall/src/main.rs

diff --git a/proxmox-firewall/src/bin/proxmox-firewall.rs b/proxmox-firewall/src/bin/proxmox-firewall.rs
new file mode 100644
index 0000000..2f4875f
--- /dev/null
+++ b/proxmox-firewall/src/bin/proxmox-firewall.rs
@@ -0,0 +1,96 @@
+use std::io::Write;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use anyhow::{Context, Error};
+
+use proxmox_firewall::firewall::Firewall;
+use proxmox_nftables::{client::NftError, NftClient};
+
+const RULE_BASE: &str = include_str!("../../resources/proxmox-firewall.nft");
+
+fn remove_firewall() -> Result<(), std::io::Error> {
+    log::info!("removing existing firewall rules");
+    let commands = Firewall::remove_commands();
+
+    // can ignore other errors, since it fails when tables do not exist
+    if let Err(NftError::Io(err)) = NftClient::run_json_commands(&commands) {
+        return Err(err);
+    }
+
+    Ok(())
+}
+
+fn handle_firewall() -> Result<(), Error> {
+    let firewall = Firewall::new();
+
+    if !firewall.is_enabled() {
+        return remove_firewall().with_context(|| "could not remove firewall tables".to_string());
+    }
+
+    log::info!("creating the firewall skeleton");
+    NftClient::run_commands(RULE_BASE)?;
+
+    let commands = firewall.full_host_fw()?;
+
+    log::info!("Running proxmox-firewall commands");
+    for (idx, c) in commands.iter().enumerate() {
+        log::debug!("cmd #{idx} {}", serde_json::to_string(&c)?);
+    }
+
+    let response = NftClient::run_json_commands(&commands)?;
+
+    if let Some(output) = response {
+        log::debug!("got response from nftables: {output:?}");
+    }
+
+    Ok(())
+}
+
+fn init_logger() {
+    match std::env::var("RUST_LOG_STYLE") {
+        Ok(s) if s == "SYSTEMD" => env_logger::builder()
+            .format(|buf, record| {
+                writeln!(
+                    buf,
+                    "<{}>{}: {}",
+                    match record.level() {
+                        log::Level::Error => 3,
+                        log::Level::Warn => 4,
+                        log::Level::Info => 6,
+                        log::Level::Debug => 7,
+                        log::Level::Trace => 7,
+                    },
+                    record.target(),
+                    record.args()
+                )
+            })
+            .init(),
+        _ => env_logger::init(),
+    };
+}
+
+fn main() -> Result<(), std::io::Error> {
+    init_logger();
+
+    let term = Arc::new(AtomicBool::new(false));
+
+    signal_hook::flag::register(signal_hook::consts::SIGTERM, Arc::clone(&term))?;
+    signal_hook::flag::register(signal_hook::consts::SIGINT, Arc::clone(&term))?;
+
+    while !term.load(Ordering::Relaxed) {
+        let start = Instant::now();
+
+        if let Err(error) = handle_firewall() {
+            log::error!("error creating firewall rules: {error}");
+        }
+
+        let duration = start.elapsed();
+        log::info!("firewall update time: {}ms", duration.as_millis());
+
+        std::thread::sleep(Duration::from_secs(5));
+    }
+
+    remove_firewall()
+}
diff --git a/proxmox-firewall/src/lib.rs b/proxmox-firewall/src/lib.rs
new file mode 100644
index 0000000..c4b037a
--- /dev/null
+++ b/proxmox-firewall/src/lib.rs
@@ -0,0 +1,4 @@
+pub mod config;
+pub mod firewall;
+pub mod object;
+pub mod rule;
diff --git a/proxmox-firewall/src/main.rs b/proxmox-firewall/src/main.rs
deleted file mode 100644
index 53c1289..0000000
--- a/proxmox-firewall/src/main.rs
+++ /dev/null
@@ -1,11 +0,0 @@
-use anyhow::Error;
-
-mod config;
-mod firewall;
-mod object;
-mod rule;
-
-fn main() -> Result<(), Error> {
-    env_logger::init();
-    Ok(())
-}
-- 
2.39.2




More information about the pve-devel mailing list