Skip to content

Commit 0f883de

Browse files
authored
Merge pull request #733 from wedsonaf/netfilter-sample
samples/rust: add netfilter sample
2 parents 54c2639 + 2876c75 commit 0f883de

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

samples/rust/Kconfig

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,16 @@ config SAMPLE_RUST_PLATFORM
120120

121121
If unsure, say N.
122122

123+
config SAMPLE_RUST_NETFILTER
124+
tristate "Network filter module"
125+
help
126+
This option builds the Rust netfilter module sample.
127+
128+
To compile this as a module, choose M here:
129+
the module will be called rust_netfilter.
130+
131+
If unsure, say N.
132+
123133
config SAMPLE_RUST_HOSTPROGS
124134
bool "Host programs"
125135
help

samples/rust/Makefile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,5 +11,6 @@ obj-$(CONFIG_SAMPLE_RUST_SEMAPHORE) += rust_semaphore.o
1111
obj-$(CONFIG_SAMPLE_RUST_SEMAPHORE_C) += rust_semaphore_c.o
1212
obj-$(CONFIG_SAMPLE_RUST_RANDOM) += rust_random.o
1313
obj-$(CONFIG_SAMPLE_RUST_PLATFORM) += rust_platform.o
14+
obj-$(CONFIG_SAMPLE_RUST_NETFILTER) += rust_netfilter.o
1415

1516
subdir-$(CONFIG_SAMPLE_RUST_HOSTPROGS) += hostprogs

samples/rust/rust_netfilter.rs

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! Rust netfilter sample.
4+
5+
use kernel::net;
6+
use kernel::net::filter::{self as netfilter, inet, Disposition, Family};
7+
use kernel::prelude::*;
8+
9+
module! {
10+
type: RustNetfilter,
11+
name: b"rust_netfilter",
12+
author: b"Rust for Linux Contributors",
13+
description: b"Rust netfilter sample",
14+
license: b"GPL v2",
15+
}
16+
17+
struct RustNetfilter {
18+
_in: Pin<Box<netfilter::Registration<Self>>>,
19+
_out: Pin<Box<netfilter::Registration<Self>>>,
20+
}
21+
22+
impl netfilter::Filter for RustNetfilter {
23+
fn filter(_: (), skb: &net::SkBuff) -> Disposition {
24+
let data = skb.head_data();
25+
pr_info!(
26+
"packet headlen={}, len={}, first bytes={:02x?}\n",
27+
data.len(),
28+
skb.len(),
29+
&data[..core::cmp::min(10, data.len())]
30+
);
31+
Disposition::Accept
32+
}
33+
}
34+
35+
impl kernel::Module for RustNetfilter {
36+
fn init(_name: &'static CStr, _module: &'static ThisModule) -> Result<Self> {
37+
Ok(Self {
38+
_in: netfilter::Registration::new_pinned(
39+
Family::INet(inet::Hook::PreRouting),
40+
0,
41+
net::init_ns().into(),
42+
None,
43+
(),
44+
)?,
45+
_out: netfilter::Registration::new_pinned(
46+
Family::INet(inet::Hook::PostRouting),
47+
0,
48+
net::init_ns().into(),
49+
None,
50+
(),
51+
)?,
52+
})
53+
}
54+
}

0 commit comments

Comments
 (0)