nf_tables 0.1.0

Pure Rust crate to interact with the Linux nf_tables subsystem
Documentation
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
//! Access to Linux' `nf_tables` subsystem in pure Rust.
//!
//! This crate direclty communicates with the kernel using netlink and avoids shelling out to
//! `nftables` or calling C libraries.
//!
//! In addtion to the expression based system used by `nf_tables`, this crate provides
//! [`RuleBuilder`] for simpler rule creation, similar to the `nftables` tool.
//!
//! # Basic Usage
//!
//! ```no_run
//! # use core::net::{IpAddr, Ipv4Addr};
//! #
//! # use nf_tables::*;
//! # use nf_tables::commands::*;
//! # use nf_tables::rule::*;
//! #
//! let mut conn = Connection::new().unwrap();
//!
//! // Prepare a list of commands.
//! let mut batch = Batch::new();
//!
//! // Create a new table.
//! // Equivalent to "nft add table inet MyLittleFirewall"
//! batch.push(AddTable {
//!     name: c"MyLittleFirewall".into(),
//!     proto: ProtoFamily::Inet,
//!     flags: 0,
//! });
//!
//! // Create a new chain in the table capturing packets that are being forwarded.
//! // Equivalent to "nft add chain inet MyLittleFirewall FORWARD { type filter hook forward priority 0; policy drop; }"
//! batch.push(AddChain {
//!     table: c"MyLittleFirewall".into(),
//!     proto: ProtoFamily::Inet,
//!     name: c"FORWARD".into(),
//!     hook: Some(ChainHook {
//!         hook: Hook::Forward,
//!         priority: 0,
//!         policy: Policy::Drop,
//!     }),
//! });
//!
//! // Add a new rule allowing all traffic coming from 10.0.0.0/8.
//! // Equivalent to "nft add rule inet MyLittleFirewall FORWARD ip saddr 10.0.0.0/8 accept"
//! batch.push(AddRule {
//!     table: c"MyLittleFirewall".into(),
//!     proto: ProtoFamily::Inet,
//!     chain: c"FORWARD".into(),
//!     position: None,
//!     exprs: RuleBuilder::new().with_ip_saddr_prefix(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 0)), 8).with_verdict(Verdict::Accept).build(),
//! });
//!
//! let results = conn.execute(&batch).unwrap();
//!
//! for result in results {
//!     match result.index {
//!         1 => println!("New chain has handle {:?}", result.handle),
//!         2 => println!("New rule has handle {:?}", result.handle),
//!         _ => {}
//!     }
//! }
//! ```
//!
//! Note that modifying network configuration typically requires root privileges or the
//! `CAP_NET_ADMIN` capability. If the current process does not have permission to do so, it is
//! possible that [`Connection::new`] will connect without errors, but [`Connection::execute`] will
//! always return with `EPERM`.
//!
//! # Syscalls
//!
//! Since processes accessing nftable rules typically need to run with elevated privileges,
//! this crate limits the amount of syscalls it makes, making it possible to use together
//! with [seccomp].
//!
//! This crate makes the following syscalls:
//! - `socket` when calling [`Connection::new`]
//! - `sendmsg`
//! - `recvmsg`
//! - `close` when dropping [`Connection`]
//! - Syscalls made by the global allocator
//!
//! [`RuleBuilder`]: crate::rule::RuleBuilder
//! [seccomp]: https://www.man7.org/linux/man-pages/man2/seccomp.2.html

mod constants;

pub mod commands;
pub mod rule;

use std::ffi::CString;
use std::fmt::{self, Display, Formatter};
use std::io::{self, IoSlice};

use bytes::{Buf, BufMut, Bytes};
use libc::{
    AF_NETLINK, AF_UNSPEC, NETLINK_NETFILTER, NFNL_SUBSYS_NFTABLES, NLM_F_ACK, NLM_F_APPEND,
    NLM_F_CREATE, NLM_F_ECHO, NLM_F_REQUEST, SOCK_RAW,
};
use socket2::{Domain, MaybeUninitSlice, MsgHdr, MsgHdrMut, Protocol, Socket, Type};

use crate::commands::{AddChain, AddRule, AddTable, DelChain, DelRule, DelTable};

#[derive(Debug)]
pub struct Error(ErrorImpl);

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match &self.0 {
            ErrorImpl::Io(err) => Display::fmt(err, f),
        }
    }
}

impl std::error::Error for Error {}

#[derive(Debug)]
enum ErrorImpl {
    Io(io::Error),
}

/// An opaque handle to a `nf_tables` object.
///
/// This `Handle` uniquely identifies an object for the lifetime of the object.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Handle(u64);

impl Handle {
    #[inline]
    pub const fn to_bits(self) -> u64 {
        self.0
    }

    #[inline]
    pub const fn from_bits(bits: u64) -> Self {
        Self(bits)
    }
}

/// A connection to the `nf_tables` subsystem.
#[derive(Debug)]
pub struct Connection {
    socket: Socket,
    page_size: usize,
}

impl Connection {
    /// Creates a new connection to the `nf_tables` subsystem.
    pub fn new() -> Result<Self, Error> {
        let socket = Socket::new(
            Domain::from(AF_NETLINK),
            Type::from(SOCK_RAW),
            Some(Protocol::from(NETLINK_NETFILTER)),
        )
        .map_err(|err| Error(ErrorImpl::Io(err)))?;

        let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) } as usize;

        Ok(Self { socket, page_size })
    }

    /// Submits a batch of commands.
    ///
    /// All commands in the [`Batch`] are executed atomically; if any [`Command`] fails this
    /// function returns an [`Error`] and none of the commands are applied.
    pub fn execute(&mut self, batch: &Batch<'_>) -> Result<Vec<CommandResult>, Error> {
        let mut buf = Vec::new();
        write_batch_begin(&mut buf, 1);

        let mut seq: u32 = 2;
        for cmd in &batch.cmds {
            let offset = buf.len();

            write_cmd(&mut buf, cmd.id(), cmd.proto() as u8, 0);
            cmd.encode(&mut buf);

            let len = (buf.len() - offset) as u32;
            buf[offset..offset + 4].copy_from_slice(&len.to_ne_bytes());
            buf[offset + 8..offset + 12].copy_from_slice(&seq.to_ne_bytes());

            seq += 1;
        }

        write_batch_end(&mut buf, seq);

        self.socket
            .sendmsg(&MsgHdr::new().with_buffers(&[IoSlice::new(&buf)]), 0)
            .map_err(|err| Error(ErrorImpl::Io(err)))?;

        let mut results = Vec::new();

        // 8KB is the minimum size specified by kernel docs.
        // The buffer must be at least the size of a page, we will always pad
        // to a multiple of the page size.
        // https://www.kernel.org/doc/html/next/userspace-api/netlink/intro.html
        let mut buf_size = 8_192;
        if buf_size % self.page_size != 0 {
            buf_size += self.page_size % buf_size;
        }

        let mut resp = Vec::with_capacity(buf_size);

        'outer: loop {
            resp.clear();

            let mut buffers = [MaybeUninitSlice::new(resp.spare_capacity_mut())];
            let mut hdr = MsgHdrMut::new().with_buffers(&mut buffers);
            let count = self
                .socket
                .recvmsg(&mut hdr, 0)
                .map_err(|err| Error(ErrorImpl::Io(err)))?;

            // SAFETY: The kernel has written the given number of bytes into
            // the buffer.
            unsafe {
                resp.set_len(count);
            }

            let mut resp_buf = &resp[..];

            while resp_buf.has_remaining() {
                let header = Header::decode(&mut resp_buf).unwrap();
                let len = usize::min(
                    (header.len as usize).saturating_sub(Header::SIZE),
                    resp_buf.len(),
                );
                let mut resp = &resp_buf[..len];

                match header.ty as i32 {
                    libc::NLMSG_NOOP => {}
                    libc::NLMSG_ERROR => {
                        let err = resp.get_i32_ne().abs();
                        if err != 0 {
                            let err = io::Error::from_raw_os_error(err);

                            // We should have read all messages.
                            if cfg!(debug_assertions) {
                                let err = self
                                    .socket
                                    .recvmsg(&mut MsgHdrMut::new(), libc::MSG_DONTWAIT)
                                    .unwrap_err();
                                assert_eq!(err.kind(), std::io::ErrorKind::WouldBlock);
                            }

                            return Err(Error(ErrorImpl::Io(err)));
                        }
                    }
                    libc::NLMSG_DONE => {}
                    // Echo
                    _ => {
                        resp.advance(4);

                        let index = header.seq as usize - 2;
                        match batch.cmds[index] {
                            Command::AddTable(_) => {}
                            Command::DelTable(_) => {}
                            Command::AddChain(_) => {
                                let handle = AddChain::read_handle(&mut resp).unwrap();
                                results.push(CommandResult { index, handle });
                            }
                            Command::DelChain(_) => {}
                            Command::AddRule(_) => {
                                let handle = AddRule::read_handle(&mut resp).unwrap();
                                results.push(CommandResult { index, handle });
                            }
                            Command::DelRule(_) => {}
                        }
                    }
                }

                if header.seq == seq {
                    break 'outer;
                }

                resp_buf.advance(len);
            }
        }

        // We should have read all messages.
        if cfg!(debug_assertions) {
            let err = self
                .socket
                .recvmsg(&mut MsgHdrMut::new(), libc::MSG_DONTWAIT)
                .unwrap_err();
            assert_eq!(err.kind(), std::io::ErrorKind::WouldBlock);
        }

        Ok(results)
    }
}

/// A series of [`Command`]s.
#[derive(Clone, Debug, Default)]
pub struct Batch<'a> {
    cmds: Vec<Command<'a>>,
}

impl<'a> Batch<'a> {
    /// Creates a new empty `Batch`.
    pub fn new() -> Self {
        Self { cmds: Vec::new() }
    }

    /// Adds a new [`Command`] to the end of the `Batch`.
    pub fn push<T>(&mut self, cmd: T)
    where
        T: Into<Command<'a>>,
    {
        self.cmds.push(cmd.into());
    }

    /// Removes all [`Command`]s from the `Batch`.
    pub fn clear(&mut self) {
        self.cmds.clear();
    }
}

#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Command<'a> {
    AddTable(AddTable<'a>),
    DelTable(DelTable<'a>),
    AddChain(AddChain<'a>),
    DelChain(DelChain<'a>),
    AddRule(AddRule<'a>),
    DelRule(DelRule<'a>),
}

impl Command<'_> {
    fn id(&self) -> u16 {
        match self {
            Self::AddTable(_) => AddTable::ID,
            Self::DelTable(_) => DelTable::ID,
            Self::AddChain(_) => AddChain::ID,
            Self::DelChain(_) => DelChain::ID,
            Self::AddRule(_) => AddRule::ID,
            Self::DelRule(_) => DelRule::ID,
        }
    }

    fn proto(&self) -> ProtoFamily {
        match self {
            Self::AddTable(cmd) => cmd.proto(),
            Self::DelTable(cmd) => cmd.proto(),
            Self::AddChain(cmd) => cmd.proto(),
            Self::DelChain(cmd) => cmd.proto(),
            Self::AddRule(cmd) => cmd.proto(),
            Self::DelRule(cmd) => cmd.proto(),
        }
    }
}

impl Encode for Command<'_> {
    fn encode<B>(&self, buf: B)
    where
        B: BufMut,
    {
        match self {
            Self::AddTable(cmd) => cmd.encode(buf),
            Self::DelTable(cmd) => cmd.encode(buf),
            Self::AddChain(cmd) => cmd.encode(buf),
            Self::DelChain(cmd) => cmd.encode(buf),
            Self::AddRule(cmd) => cmd.encode(buf),
            Self::DelRule(cmd) => cmd.encode(buf),
        }
    }
}

#[derive(Clone, Debug)]
pub struct CommandResult {
    pub index: usize,
    pub handle: Option<Handle>,
}

fn write_attribute<B>(mut buf: B, ty: u16, data: &[u8])
where
    B: BufMut,
{
    AttributeHeader {
        len: 4 + data.len() as u16,
        ty,
    }
    .encode(&mut buf);

    buf.put_slice(data);

    if data.len() % 4 != 0 {
        let pad = 4 - (data.len() % 4);
        for _ in 0..pad {
            buf.put_u8(0);
        }
    }
}

fn read_attribute<B>(mut buf: B) -> Result<(AttributeHeader, Bytes), Error>
where
    B: Buf,
{
    let len = buf.get_u16_le();
    let ty = buf.get_u16_le();

    let data = buf.copy_to_bytes(len.saturating_sub(4).into());

    if len % 4 != 0 {
        let pad = 4 - (len % 4);
        buf.advance(pad.into());
    }

    Ok((AttributeHeader { len, ty }, data))
}

trait Message {
    const ID: u16;

    fn proto(&self) -> ProtoFamily;

    fn read_handle<B>(_buf: B) -> Result<Option<Handle>, Error>
    where
        B: Buf,
    {
        Ok(None)
    }
}

fn write_cmd<B>(mut buf: B, cmd: u16, family: u8, seq: u32)
where
    B: BufMut,
{
    Header {
        len: 0,
        ty: ((NFNL_SUBSYS_NFTABLES as u16) << 8) | cmd,
        flags: NLM_F_REQUEST as u16
            // | NLM_F_ACK as u16
            | NLM_F_ECHO as u16
            | NLM_F_CREATE as u16
            | NLM_F_APPEND as u16, // | NLM_F_EXCL as u16,
        seq,
        pid: 0,
    }
    .encode(&mut buf);
    NfHeader {
        nfgen_family: family,
        version: NF_VERSION,
        res_id: 0,
    }
    .encode(&mut buf);
}

#[derive(Copy, Clone, Debug)]
struct Header {
    len: u32,
    ty: u16,
    flags: u16,
    seq: u32,
    pid: u32,
}

impl Header {
    const SIZE: usize = size_of::<libc::nlmsghdr>();
}

impl Encode for Header {
    fn encode<B>(&self, mut buf: B)
    where
        B: BufMut,
    {
        buf.put_u32_ne(self.len);
        buf.put_u16_ne(self.ty);
        buf.put_u16_ne(self.flags);
        buf.put_u32_ne(self.seq);
        buf.put_u32_ne(self.pid);
    }
}

impl Decode for Header {
    fn decode<B>(mut buf: B) -> Result<Self, Error>
    where
        B: Buf,
    {
        let len = buf.get_u32_ne();
        let ty = buf.get_u16_ne();
        let flags = buf.get_u16_ne();
        let seq = buf.get_u32_ne();
        let pid = buf.get_u32_ne();

        Ok(Self {
            len,
            ty,
            flags,
            seq,
            pid,
        })
    }
}

#[derive(Copy, Clone, Debug)]
struct NfHeader {
    nfgen_family: u8,
    version: u8,
    res_id: u16,
}

impl Encode for NfHeader {
    fn encode<B>(&self, mut buf: B)
    where
        B: BufMut,
    {
        buf.put_u8(self.nfgen_family);
        buf.put_u8(self.version);
        buf.put_u16_ne(self.res_id);
    }
}

impl Decode for NfHeader {
    fn decode<B>(mut buf: B) -> Result<Self, Error>
    where
        B: Buf,
    {
        let nfgen_family = buf.get_u8();
        let version = buf.get_u8();
        let res_id = buf.get_u16_ne();
        Ok(Self {
            nfgen_family,
            version,
            res_id,
        })
    }
}

const NF_VERSION: u8 = 0;

const NFT_MSG_BATCH_BEGIN: u16 = 0x10;
const NFT_MSG_BATCH_END: u16 = 0x11;

#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[repr(u16)]
pub enum ProtoFamily {
    Unspec = libc::NFPROTO_UNSPEC as u16,
    Inet = libc::NFPROTO_INET as u16,
    Ipv4 = libc::NFPROTO_IPV4 as u16,
    Arp = libc::NFPROTO_ARP as u16,
    NetDev = libc::NFPROTO_NETDEV as u16,
    Bridge = libc::NFPROTO_BRIDGE as u16,
    Ipv6 = libc::NFPROTO_IPV6 as u16,
    DecNet = libc::NFPROTO_DECNET as u16,
}

#[derive(Copy, Clone, Debug)]
struct AttributeHeader {
    len: u16,
    ty: u16,
}

impl Encode for AttributeHeader {
    fn encode<B>(&self, mut buf: B)
    where
        B: BufMut,
    {
        buf.put_u16_ne(self.len);
        buf.put_u16_ne(self.ty);
    }
}

impl Encode for CString {
    fn encode<B>(&self, mut buf: B)
    where
        B: BufMut,
    {
        buf.put_slice(self.as_bytes_with_nul());
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[repr(u32)]
pub enum Policy {
    Accept = libc::NF_ACCEPT as u32,
    Drop = libc::NF_DROP as u32,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
#[repr(u16)]
pub enum Hook {
    PreRouting = libc::NF_INET_PRE_ROUTING as u16,
    In = libc::NF_INET_LOCAL_IN as u16,
    Forward = libc::NF_INET_FORWARD as u16,
    Out = libc::NF_INET_LOCAL_OUT as u16,
    PostRouting = libc::NF_INET_POST_ROUTING as u16,
    Ingress = libc::NF_INET_INGRESS as u16,
}

trait Encode {
    fn encode<B>(&self, buf: B)
    where
        B: BufMut;
}

trait Decode: Sized {
    fn decode<B>(buf: B) -> Result<Self, Error>
    where
        B: Buf;
}

fn write_batch_begin(mut buf: &mut Vec<u8>, seq: u32) {
    Header {
        len: 20,
        ty: NFT_MSG_BATCH_BEGIN,
        // flags: NLM_F_REQUEST as u16 | NLM_F_ACK as u16 | NLM_F_ECHO as u16,
        flags: NLM_F_REQUEST as u16,
        seq,
        pid: 0,
    }
    .encode(&mut buf);
    NfHeader {
        nfgen_family: AF_UNSPEC as u8,
        version: NF_VERSION,
        res_id: (NFNL_SUBSYS_NFTABLES as u16) << 8,
    }
    .encode(&mut buf);
}

fn write_batch_end(mut buf: &mut Vec<u8>, seq: u32) {
    Header {
        len: 20,
        ty: NFT_MSG_BATCH_END,
        // flags: NLM_F_REQUEST as u16 | NLM_F_ACK as u16 | NLM_F_ECHO as u16,
        flags: NLM_F_REQUEST as u16 | NLM_F_ACK as u16,
        seq,
        pid: 0,
    }
    .encode(&mut buf);
    NfHeader {
        nfgen_family: AF_UNSPEC as u8,
        version: NF_VERSION,
        res_id: (NFNL_SUBSYS_NFTABLES as u16) << 8,
    }
    .encode(&mut buf);
}