aboutsummaryrefslogtreecommitdiff
path: root/src/expr/mod.rs
blob: b0d9d51e4f7436275d3e3c696d811650097f71fa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
//! A module with all the nftables expressions that can be added to [`Rule`]s to build up how
//! they match against packets.
//!
//! [`Rule`]: struct.Rule.html

use std::fmt::Debug;

use rustables_macros::nfnetlink_struct;

use crate::error::DecodeError;
use crate::nlmsg::{NfNetlinkAttribute, NfNetlinkDeserializable};
use crate::parser_impls::NfNetlinkList;
use crate::sys::{self, NFTA_EXPR_DATA, NFTA_EXPR_NAME};

mod bitwise;
pub use self::bitwise::*;

mod cmp;
pub use self::cmp::*;

mod counter;
pub use self::counter::*;

pub mod ct;
pub use self::ct::*;

pub mod exthdr;
pub use self::exthdr::*;

mod immediate;
pub use self::immediate::*;

mod log;
pub use self::log::*;

mod lookup;
pub use self::lookup::*;

mod masquerade;
pub use self::masquerade::*;

mod meta;
pub use self::meta::*;

mod nat;
pub use self::nat::*;

mod payload;
pub use self::payload::*;

mod reject;
pub use self::reject::{IcmpCode, Reject, RejectType};

mod register;
pub use self::register::Register;

mod verdict;
pub use self::verdict::*;

pub trait Expression {
    fn get_name() -> &'static str;
}

#[derive(Clone, PartialEq, Eq, Default, Debug)]
#[nfnetlink_struct(nested = true, derive_decoder = false)]
pub struct RawExpression {
    #[field(NFTA_EXPR_NAME)]
    name: String,
    #[field(NFTA_EXPR_DATA)]
    data: ExpressionVariant,
}

impl<T> From<T> for RawExpression
where
    T: Expression,
    ExpressionVariant: From<T>,
{
    fn from(val: T) -> Self {
        RawExpression::default()
            .with_name(T::get_name())
            .with_data(ExpressionVariant::from(val))
    }
}

macro_rules! create_expr_variant {
    ($enum:ident $(, [$name:ident, $type:ty])+) => {
        #[derive(Debug, Clone, PartialEq, Eq)]
        pub enum $enum {
            $(
                $name($type),
            )+
        }

        impl $crate::nlmsg::NfNetlinkAttribute for $enum {
            fn is_nested(&self) -> bool {
                true
            }

            fn get_size(&self) -> usize {
                match self {
                    $(
                        $enum::$name(val) => val.get_size(),
                    )+
                }
            }

            fn write_payload(&self, addr: &mut [u8]) {
                match self {
                    $(
                        $enum::$name(val) => val.write_payload(addr),
                    )+
                }
            }
        }

        $(
            impl From<$type> for $enum {
                fn from(val: $type) -> Self {
                    $enum::$name(val)
                }
            }
        )+

        impl $crate::nlmsg::AttributeDecoder for RawExpression {
            fn decode_attribute(
                &mut self,
                attr_type: u16,
                buf: &[u8],
            ) -> Result<(), $crate::error::DecodeError> {
                debug!("Decoding attribute {} in an expression", attr_type);
                match attr_type {
                    x if x == sys::NFTA_EXPR_NAME => {
                        debug!("Calling {}::deserialize()", std::any::type_name::<String>());
                        let (val, remaining) = String::deserialize(buf)?;
                        if remaining.len() != 0 {
                            return Err($crate::error::DecodeError::InvalidDataSize);
                        }
                        self.name = Some(val);
                        Ok(())
                    },
                    x if x == sys::NFTA_EXPR_DATA => {
                        // we can assume we have already the name parsed, as that's how we identify the
                        // type of expression
                        let name = self.name.as_ref()
                            .ok_or($crate::error::DecodeError::MissingExpressionName)?;
                        match name {
                            $(
                                x if x == <$type>::get_name() => {
                                    debug!("Calling {}::deserialize()", std::any::type_name::<$type>());
                                    let (res, remaining) =  <$type>::deserialize(buf)?;
                                    if remaining.len() != 0 {
                                            return Err($crate::error::DecodeError::InvalidDataSize);
                                    }
                                    self.data = Some(ExpressionVariant::from(res));
                                    Ok(())
                                },
                            )+
                            name => {
                                info!("Unrecognized expression '{}', generating an ExpressionRaw", name);
                                self.data = Some(ExpressionVariant::ExpressionRaw(ExpressionRaw::deserialize(buf)?.0));
                                Ok(())
                            }
                        }
                    },
                    _ => Err(DecodeError::UnsupportedAttributeType(attr_type)),
                }
            }
        }
    };
}

create_expr_variant!(
    ExpressionVariant,
    [Bitwise, Bitwise],
    [Cmp, Cmp],
    [Conntrack, Conntrack],
    [Counter, Counter],
    [ExpressionRaw, ExpressionRaw],
    [Immediate, Immediate],
    [Log, Log],
    [Lookup, Lookup],
    [Masquerade, Masquerade],
    [Meta, Meta],
    [Nat, Nat],
    [Payload, Payload],
    [Reject, Reject]
);

pub type ExpressionList = NfNetlinkList<RawExpression>;

// default type for expressions that we do not handle yet
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExpressionRaw(Vec<u8>);

impl NfNetlinkAttribute for ExpressionRaw {
    fn get_size(&self) -> usize {
        self.0.get_size()
    }

    fn write_payload(&self, addr: &mut [u8]) {
        self.0.write_payload(addr);
    }
}

impl NfNetlinkDeserializable for ExpressionRaw {
    fn deserialize(buf: &[u8]) -> Result<(Self, &[u8]), DecodeError> {
        Ok((ExpressionRaw(buf.to_vec()), &[]))
    }
}

// Because we loose the name of the expression when parsing, this is the only expression
// where deserializing a message and then reserializing it is invalid
impl Expression for ExpressionRaw {
    fn get_name() -> &'static str {
        "unknown_expression"
    }
}