forked from one-d-wide/netlink-bindings
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnftables-api.rs
More file actions
253 lines (203 loc) · 6.96 KB
/
nftables-api.rs
File metadata and controls
253 lines (203 loc) · 6.96 KB
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
//! This example demonstrates a small high-level wrapper for nftables built on
//! top of netlink-bindings.
//!
//! Run with: `cargo run --example nftables-api --features=nftables`
use std::{io, net::Ipv4Addr};
use netlink_bindings::{
nftables::{
self, CmpOps, PayloadBase, PushExprListAttrs, PushNfgenmsg, PushOpNewruleDoRequest,
Registers, VerdictCode,
},
utils,
};
use netlink_socket2::{NetlinkSocket, ReplyError};
#[cfg_attr(not(feature = "async"), maybe_async::maybe_async)]
#[cfg_attr(feature = "tokio", tokio::main(flavor = "current_thread"))]
#[cfg_attr(feature = "smol", macro_rules_attribute::apply(smol_macros::main))]
async fn main() {
let mut sock = netlink_socket2::NetlinkSocket::new();
let chain = "example-api-chain";
println!();
println!("Appending new rule to {chain:?} chain");
// Same as
// iptables -N example-api-chain
// iptables -A example-api-chain --src 1.2.3.4 -j ACCEPT
let mut rules = Transaction::new(&mut sock).await.unwrap();
rules.create_chain(chain);
rules
.append_rule_ipv4(chain)
.has_source_ipv4("1.2.3.4".parse().unwrap())
.accept();
rules.send(&mut sock).await.unwrap();
println!();
println!("Running iptables -L to verify");
print_chain(chain);
println!();
println!("Deleting {chain:?} chain");
// Same as
// iptables -D example-api-chain
let mut rules = Transaction::new(&mut sock).await.unwrap();
rules.delete_chain(chain);
rules.send(&mut sock).await.unwrap();
println!();
println!("Running iptables -L again");
print_chain(chain);
}
fn print_chain(chain: &str) {
std::process::Command::new("iptables")
.arg("-n")
.arg("-L")
.arg(chain)
.spawn()
.unwrap()
.wait()
.unwrap();
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct GenerationId(u32);
impl GenerationId {
#[cfg_attr(not(feature = "async"), maybe_async::maybe_async)]
async fn new_latest(sock: &mut NetlinkSocket) -> Result<Self, ReplyError> {
let request = nftables::Request::new().op_getgen_do_request(&PushNfgenmsg::new());
let mut iter = sock.request(&request).await?;
let (_, attrs) = iter.recv_one().await?;
Ok(GenerationId(attrs.get_id()?))
}
}
const FILTER_TABLE: &str = "filter";
struct Transaction {
inner: nftables::Chained<'static>,
}
impl Transaction {
#[cfg_attr(not(feature = "async"), maybe_async::maybe_async)]
async fn new(sock: &mut NetlinkSocket) -> Result<Self, ReplyError> {
let seq = sock.reserve_seq(256);
let genid = GenerationId::new_latest(sock).await?;
Ok(Self::new_with_genid(seq, genid))
}
fn new_with_genid(seq: u32, genid: GenerationId) -> Self {
let mut inner = nftables::Chained::new(seq);
let mut h = nftables::PushNfgenmsg::new();
h.set_res_id(10);
inner
.request()
.op_batch_begin_do_request(&h)
.encode()
.push_genid(genid.0);
Self { inner }
}
fn create_chain(&mut self, chain: &str) {
let mut h = nftables::PushNfgenmsg::new();
h.set_nfgen_family(libc::AF_INET as u8);
// Create a separate table to not interfere with actual traffic
self.inner
.request()
.op_newchain_do_request(&h)
.encode()
.push_table_bytes(FILTER_TABLE.as_bytes())
.push_name_bytes(chain.as_bytes());
}
fn delete_chain(&mut self, chain: &str) {
let mut h = nftables::PushNfgenmsg::new();
h.set_nfgen_family(libc::AF_INET as u8);
self.inner
.request()
.op_delchain_do_request(&h)
.encode()
.push_table_bytes(FILTER_TABLE.as_bytes())
.push_name_bytes(chain.as_bytes());
}
fn append_rule_ipv4(&mut self, chain: &str) -> NewRuleExprs<'_> {
self.rule_ipv4(chain, true)
}
fn rule_ipv4(&mut self, chain: &str, append: bool) -> NewRuleExprs<'_> {
let mut h = nftables::PushNfgenmsg::new();
h.set_nfgen_family(libc::AF_INET as u8); // aka ipv4
let mut inner = self.inner.request();
if append {
inner = inner.set_append();
}
let inner = inner
.set_create()
.op_newrule_do_request(&h)
.into_encoder()
.push_table_bytes(FILTER_TABLE.as_bytes())
.push_chain_bytes(chain.as_bytes())
.nested_expressions();
NewRuleExprs { inner }
}
#[cfg_attr(not(feature = "async"), maybe_async::maybe_async)]
async fn send(mut self, sock: &mut NetlinkSocket) -> Result<(), ReplyError> {
let mut h = nftables::PushNfgenmsg::new();
h.set_res_id(10);
self.inner.request().op_batch_end_do_request(&h);
let c = self.inner.finalize();
let res = sock.request_chained(&c).await?.recv_all().await;
if let Err(err) = &res {
if let Some(err) = err.as_io_error().raw_os_error() {
if err == libc::ERESTART {
return Err(io::Error::other("Generation id is too old").into());
}
}
}
res
}
}
type PushExprs<'a> = PushExprListAttrs<PushOpNewruleDoRequest<utils::RequestBuf<'a>>>;
struct NewRuleExprs<'a> {
inner: PushExprs<'a>,
}
// Pretty stuff
impl<'a> NewRuleExprs<'a> {
fn has_source_ipv4(self, ipv4: Ipv4Addr) -> Self {
self.contains_bytes(
&ipv4.to_bits().to_be_bytes(),
PayloadBase::NetworkHeader,
12, // source ipv4 offset
)
}
fn accept(self) -> PushExprs<'a> {
self.verdict(VerdictCode::Accept)
}
// ...
}
// Not so pretty stuff
impl<'a> NewRuleExprs<'a> {
fn contains_bytes(mut self, bytes: &[u8], base: PayloadBase, offset: u32) -> Self {
self.inner = self
.inner
// Save source ip addr bytes to register 1
.nested_elem()
.nested_data_payload()
.push_dreg(Registers::Reg1 as u32)
.push_base(base as u32)
.push_offset(offset) // ipv4 source addr
.push_len(bytes.len() as u32)
.end_nested()
.end_nested()
// If bytes in register 1 equal to the expected ip addr
.nested_elem()
.nested_data_cmp()
.push_sreg(Registers::Reg1 as u32)
.push_op(CmpOps::Eq as u32)
.nested_data()
.push_value(bytes)
.end_nested()
.end_nested()
.end_nested();
self
}
fn verdict(self, code: VerdictCode) -> PushExprs<'a> {
self.inner
.nested_elem()
.nested_data_immediate()
.push_dreg(Registers::RegVerdict as u32)
.nested_data()
.nested_verdict()
.push_code(code as u32)
.end_nested()
.end_nested()
.end_nested()
.end_nested()
}
}