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 0790390C2E
 for <pve-devel@lists.proxmox.com>; Tue,  2 Apr 2024 19:17:33 +0200 (CEST)
Received: from firstgate.proxmox.com (localhost [127.0.0.1])
 by firstgate.proxmox.com (Proxmox) with ESMTP id CC60CA827
 for <pve-devel@lists.proxmox.com>; Tue,  2 Apr 2024 19:16:43 +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:16:41 +0200 (CEST)
Received: by lana.proxmox.com (Postfix, from userid 10043)
 id CD5FC2C3A92; 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:22 +0200
Message-Id: <20240402171629.536804-31-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.320 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
Subject: [pve-devel] [PATCH proxmox-firewall 30/37] firewall: add object
 generation logic
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:17:33 -0000

ToNftObjects is basically a conversion trait that converts firewall
config structs into nftables objects. It returns a list of commands
that create the respective nftables objects.

Co-authored-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Stefan Hanreich <s.hanreich@proxmox.com>
---
 proxmox-firewall/src/main.rs   |   1 +
 proxmox-firewall/src/object.rs | 139 +++++++++++++++++++++++++++++++++
 2 files changed, 140 insertions(+)
 create mode 100644 proxmox-firewall/src/object.rs

diff --git a/proxmox-firewall/src/main.rs b/proxmox-firewall/src/main.rs
index ae832e3..a4979a7 100644
--- a/proxmox-firewall/src/main.rs
+++ b/proxmox-firewall/src/main.rs
@@ -1,6 +1,7 @@
 use anyhow::Error;
 
 mod config;
+mod object;
 mod rule;
 
 fn main() -> Result<(), Error> {
diff --git a/proxmox-firewall/src/object.rs b/proxmox-firewall/src/object.rs
new file mode 100644
index 0000000..ec0c0b1
--- /dev/null
+++ b/proxmox-firewall/src/object.rs
@@ -0,0 +1,139 @@
+use anyhow::{format_err, Error};
+use proxmox_nftables::{
+    command::{Add, Flush},
+    expression::Prefix,
+    types::{
+        AddCtHelper, AddElement, CtHelperProtocol, ElementType, L3Protocol, SetConfig, SetFlag,
+        SetName, TablePart,
+    },
+    Command, Expression,
+};
+use proxmox_ve_config::{
+    firewall::{
+        ct_helper::CtHelperMacro,
+        types::{address::Family, alias::AliasName, ipset::IpsetAddress, Alias, Ipset},
+    },
+    guest::types::Vmid,
+};
+
+use crate::config::FirewallConfig;
+
+pub(crate) struct NftObjectEnv<'a, 'b> {
+    pub(crate) table: &'a TablePart,
+    pub(crate) firewall_config: &'b FirewallConfig,
+    pub(crate) vmid: Option<Vmid>,
+}
+
+impl NftObjectEnv<'_, '_> {
+    pub(crate) fn alias(&self, name: &AliasName) -> Option<&Alias> {
+        self.firewall_config.alias(name, self.vmid)
+    }
+}
+
+pub(crate) trait ToNftObjects {
+    fn to_nft_objects(&self, env: &NftObjectEnv) -> Result<Vec<Command>, Error>;
+}
+
+impl ToNftObjects for CtHelperMacro {
+    fn to_nft_objects(&self, env: &NftObjectEnv) -> Result<Vec<Command>, Error> {
+        let mut commands = Vec::new();
+
+        if let Some(_protocol) = self.tcp() {
+            commands.push(Add::ct_helper(AddCtHelper {
+                table: env.table.clone(),
+                name: self.tcp_helper_name(),
+                ty: self.name().to_string(),
+                protocol: CtHelperProtocol::TCP,
+                l3proto: self.family().map(L3Protocol::from),
+            }));
+        }
+
+        if let Some(_protocol) = self.udp() {
+            commands.push(Add::ct_helper(AddCtHelper {
+                table: env.table.clone(),
+                name: self.udp_helper_name(),
+                ty: self.name().to_string(),
+                protocol: CtHelperProtocol::UDP,
+                l3proto: self.family().map(L3Protocol::from),
+            }));
+        }
+
+        Ok(commands)
+    }
+}
+
+impl ToNftObjects for Ipset {
+    fn to_nft_objects(&self, env: &NftObjectEnv) -> Result<Vec<Command>, Error> {
+        let mut commands = Vec::new();
+
+        for family in env.table.family().families() {
+            let mut elements = Vec::new();
+            let mut nomatch_elements = Vec::new();
+
+            for element in self.iter() {
+                let cidr = match &element.address {
+                    IpsetAddress::Cidr(cidr) => cidr,
+                    IpsetAddress::Alias(alias) => env
+                        .alias(alias)
+                        .ok_or(format_err!("could not find alias {alias} in environment"))?
+                        .address(),
+                };
+
+                if family != cidr.family() {
+                    continue;
+                }
+
+                let expression = Expression::from(Prefix::from(cidr));
+
+                if element.nomatch {
+                    nomatch_elements.push(expression);
+                } else {
+                    elements.push(expression);
+                }
+            }
+
+            let element_type = match family {
+                Family::V4 => ElementType::Ipv4Addr,
+                Family::V6 => ElementType::Ipv6Addr,
+            };
+
+            let set_name = SetName::new(
+                env.table.clone(),
+                SetName::ipset_name(family, self.name(), false),
+            );
+
+            let set_config =
+                SetConfig::new(set_name.clone(), vec![element_type]).with_flag(SetFlag::Interval);
+
+            let nomatch_name = SetName::new(
+                env.table.clone(),
+                SetName::ipset_name(family, self.name(), true),
+            );
+
+            let nomatch_config = SetConfig::new(nomatch_name.clone(), vec![element_type])
+                .with_flag(SetFlag::Interval);
+
+            commands.append(&mut vec![
+                Add::set(set_config),
+                Flush::set(set_name.clone()),
+                Add::set(nomatch_config),
+                Flush::set(nomatch_name.clone()),
+            ]);
+
+            if !elements.is_empty() {
+                commands.push(Add::element(AddElement::set_from_expressions(
+                    set_name, elements,
+                )));
+            }
+
+            if !nomatch_elements.is_empty() {
+                commands.push(Add::element(AddElement::set_from_expressions(
+                    nomatch_name,
+                    nomatch_elements,
+                )));
+            }
+        }
+
+        Ok(commands)
+    }
+}
-- 
2.39.2