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 ECB1790CA6
 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 B20C6B3C2
 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 628432C3609; 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:11 +0200
Message-Id: <20240402171629.536804-20-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.309 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. [lib.rs, types.rs, expression.rs]
Subject: [pve-devel] [PATCH proxmox-firewall 19/37] nftables: expression:
 add types
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:19 -0000

Adds an enum containing most of the expressions defined in the
nftables-json schema [1].

[1] https://manpages.debian.org/bookworm/libnftables1/libnftables-json.5.en.html#EXPRESSIONS

Co-authored-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
Signed-off-by: Stefan Hanreich <s.hanreich@proxmox.com>
---
 proxmox-nftables/Cargo.toml        |   2 +-
 proxmox-nftables/src/expression.rs | 268 +++++++++++++++++++++++++++++
 proxmox-nftables/src/lib.rs        |   4 +
 proxmox-nftables/src/types.rs      |  53 ++++++
 4 files changed, 326 insertions(+), 1 deletion(-)
 create mode 100644 proxmox-nftables/src/expression.rs
 create mode 100644 proxmox-nftables/src/types.rs

diff --git a/proxmox-nftables/Cargo.toml b/proxmox-nftables/Cargo.toml
index ebece9d..909869b 100644
--- a/proxmox-nftables/Cargo.toml
+++ b/proxmox-nftables/Cargo.toml
@@ -17,4 +17,4 @@ serde = { version = "1", features = [ "derive" ] }
 serde_json = "1"
 serde_plain = "1"
 
-proxmox-ve-config = { path = "../proxmox-ve-config", optional = true }
+proxmox-ve-config = { path = "../proxmox-ve-config" }
diff --git a/proxmox-nftables/src/expression.rs b/proxmox-nftables/src/expression.rs
new file mode 100644
index 0000000..da6e40f
--- /dev/null
+++ b/proxmox-nftables/src/expression.rs
@@ -0,0 +1,268 @@
+use crate::types::{ElemConfig, Verdict};
+use serde::{Deserialize, Serialize};
+use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
+
+use crate::helper::NfVec;
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Expression {
+    Concat(NfVec<Expression>),
+    Set(NfVec<Expression>),
+    Range(Box<(Expression, Expression)>),
+    Map(Box<Map>),
+    Prefix(Prefix),
+    Payload(Payload),
+    Meta(Meta),
+    Ct(Ct),
+    Elem(Box<Element>),
+
+    #[serde(rename = "|")]
+    Or(Box<(Expression, Expression)>),
+    #[serde(rename = "&")]
+    And(Box<(Expression, Expression)>),
+    #[serde(rename = "^")]
+    Xor(Box<(Expression, Expression)>),
+    #[serde(rename = "<<")]
+    ShiftLeft(Box<(Expression, Expression)>),
+    #[serde(rename = ">>")]
+    ShiftRight(Box<(Expression, Expression)>),
+
+    #[serde(untagged)]
+    List(Vec<Expression>),
+
+    #[serde(untagged)]
+    Verdict(Verdict),
+
+    #[serde(untagged)]
+    Bool(bool),
+    #[serde(untagged)]
+    Number(i64),
+    #[serde(untagged)]
+    String(String),
+}
+
+impl Expression {
+    pub fn set(expressions: impl IntoIterator<Item = Expression>) -> Self {
+        Expression::Set(NfVec::from_iter(expressions))
+    }
+
+    pub fn concat(expressions: impl IntoIterator<Item = Expression>) -> Self {
+        Expression::Concat(NfVec::from_iter(expressions))
+    }
+}
+
+impl From<bool> for Expression {
+    #[inline]
+    fn from(v: bool) -> Self {
+        Expression::Bool(v)
+    }
+}
+
+impl From<i64> for Expression {
+    #[inline]
+    fn from(v: i64) -> Self {
+        Expression::Number(v)
+    }
+}
+
+impl From<u16> for Expression {
+    #[inline]
+    fn from(v: u16) -> Self {
+        Expression::Number(v.into())
+    }
+}
+
+impl From<u8> for Expression {
+    #[inline]
+    fn from(v: u8) -> Self {
+        Expression::Number(v.into())
+    }
+}
+
+impl From<&str> for Expression {
+    #[inline]
+    fn from(v: &str) -> Self {
+        Expression::String(v.to_string())
+    }
+}
+
+impl From<String> for Expression {
+    #[inline]
+    fn from(v: String) -> Self {
+        Expression::String(v)
+    }
+}
+
+impl From<Meta> for Expression {
+    #[inline]
+    fn from(meta: Meta) -> Self {
+        Expression::Meta(meta)
+    }
+}
+
+impl From<Ct> for Expression {
+    #[inline]
+    fn from(ct: Ct) -> Self {
+        Expression::Ct(ct)
+    }
+}
+
+impl From<Payload> for Expression {
+    #[inline]
+    fn from(payload: Payload) -> Self {
+        Expression::Payload(payload)
+    }
+}
+
+impl From<Prefix> for Expression {
+    #[inline]
+    fn from(prefix: Prefix) -> Self {
+        Expression::Prefix(prefix)
+    }
+}
+
+impl From<Verdict> for Expression {
+    #[inline]
+    fn from(value: Verdict) -> Self {
+        Expression::Verdict(value)
+    }
+}
+
+impl From<&IpAddr> for Expression {
+    fn from(value: &IpAddr) -> Self {
+        Expression::String(value.to_string())
+    }
+}
+
+impl From<&Ipv6Addr> for Expression {
+    fn from(address: &Ipv6Addr) -> Self {
+        Expression::String(address.to_string())
+    }
+}
+
+impl From<&Ipv4Addr> for Expression {
+    fn from(address: &Ipv4Addr) -> Self {
+        Expression::String(address.to_string())
+    }
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum IpFamily {
+    Ip,
+    Ip6,
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct Meta {
+    key: String,
+}
+
+impl Meta {
+    pub fn new(key: impl Into<String>) -> Self {
+        Self { key: key.into() }
+    }
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct Map {
+    key: Expression,
+    data: Expression,
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct Ct {
+    key: String,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    family: Option<IpFamily>,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    dir: Option<CtDirection>,
+}
+
+impl Ct {
+    pub fn new(key: impl Into<String>, family: impl Into<Option<IpFamily>>) -> Self {
+        Self {
+            key: key.into(),
+            family: family.into(),
+            dir: None,
+        }
+    }
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum CtDirection {
+    Original,
+    Reply,
+}
+serde_plain::derive_display_from_serialize!(CtDirection);
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(untagged)]
+pub enum Payload {
+    Raw(PayloadRaw),
+    Field(PayloadField),
+}
+
+impl Payload {
+    pub fn field(protocol: impl Into<String>, field: impl Into<String>) -> Self {
+        Self::Field(PayloadField {
+            protocol: protocol.into(),
+            field: field.into(),
+        })
+    }
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub enum PayloadBase {
+    #[serde(rename = "ll")]
+    Link,
+    #[serde(rename = "nh")]
+    Network,
+    #[serde(rename = "th")]
+    Transport,
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct PayloadRaw {
+    base: PayloadBase,
+    offset: i64,
+    len: i64,
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct PayloadField {
+    protocol: String,
+    field: String,
+}
+
+impl PayloadField {
+    pub fn protocol_for_ip_family(family: IpFamily) -> String {
+        match family {
+            IpFamily::Ip => "ip".to_string(),
+            IpFamily::Ip6 => "ip6".to_string(),
+        }
+    }
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct Prefix {
+    addr: Box<Expression>,
+    len: u8,
+}
+
+impl Prefix {
+    pub fn new(addr: impl Into<Expression>, len: u8) -> Self {
+        Self {
+            addr: Box::new(addr.into()),
+            len,
+        }
+    }
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct Element {
+    #[serde(flatten)]
+    config: ElemConfig,
+    val: Expression,
+}
diff --git a/proxmox-nftables/src/lib.rs b/proxmox-nftables/src/lib.rs
index 485bb81..712858b 100644
--- a/proxmox-nftables/src/lib.rs
+++ b/proxmox-nftables/src/lib.rs
@@ -1 +1,5 @@
+pub mod expression;
 pub mod helper;
+pub mod types;
+
+pub use expression::Expression;
diff --git a/proxmox-nftables/src/types.rs b/proxmox-nftables/src/types.rs
new file mode 100644
index 0000000..942c866
--- /dev/null
+++ b/proxmox-nftables/src/types.rs
@@ -0,0 +1,53 @@
+use std::fmt::Display;
+
+use serde::{Deserialize, Serialize};
+
+use crate::helper::Null;
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Verdict {
+    Accept(Null),
+    Drop(Null),
+    Continue(Null),
+    Return(Null),
+    Goto { target: String },
+    Jump { target: String },
+}
+
+impl Display for Verdict {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        let output = match self {
+            Verdict::Accept(_) => "ACCEPT",
+            Verdict::Drop(_) => "DROP",
+            Verdict::Continue(_) => "CONTINUE",
+            Verdict::Return(_) => "RETURN",
+            Verdict::Jump { .. } => "JUMP",
+            Verdict::Goto { .. } => "GOTO",
+        };
+
+        f.write_str(output)
+    }
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct ElemConfig {
+    timeout: Option<i64>,
+    expires: Option<i64>,
+    comment: Option<String>,
+}
+
+impl ElemConfig {
+    pub fn new(
+        timeout: impl Into<Option<i64>>,
+        expires: impl Into<Option<i64>>,
+        comment: impl Into<Option<String>>,
+    ) -> Self {
+        Self {
+            timeout: timeout.into(),
+            expires: expires.into(),
+            comment: comment.into(),
+        }
+    }
+}
+
-- 
2.39.2