Skip to content

samples/rust: add netfilter sample #733

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions samples/rust/Kconfig
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,16 @@ config SAMPLE_RUST_PLATFORM

If unsure, say N.

config SAMPLE_RUST_NETFILTER
tristate "Network filter module"
help
This option builds the Rust netfilter module sample.

To compile this as a module, choose M here:
the module will be called rust_netfilter.

If unsure, say N.

config SAMPLE_RUST_HOSTPROGS
bool "Host programs"
help
Expand Down
1 change: 1 addition & 0 deletions samples/rust/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ obj-$(CONFIG_SAMPLE_RUST_SEMAPHORE) += rust_semaphore.o
obj-$(CONFIG_SAMPLE_RUST_SEMAPHORE_C) += rust_semaphore_c.o
obj-$(CONFIG_SAMPLE_RUST_RANDOM) += rust_random.o
obj-$(CONFIG_SAMPLE_RUST_PLATFORM) += rust_platform.o
obj-$(CONFIG_SAMPLE_RUST_NETFILTER) += rust_netfilter.o

subdir-$(CONFIG_SAMPLE_RUST_HOSTPROGS) += hostprogs
54 changes: 54 additions & 0 deletions samples/rust/rust_netfilter.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// SPDX-License-Identifier: GPL-2.0

//! Rust netfilter sample.

use kernel::net;
use kernel::net::filter::{self as netfilter, inet, Disposition, Family};
use kernel::prelude::*;

module! {
type: RustNetfilter,
name: b"rust_netfilter",
author: b"Rust for Linux Contributors",
description: b"Rust netfilter sample",
license: b"GPL v2",
}

struct RustNetfilter {
_in: Pin<Box<netfilter::Registration<Self>>>,
_out: Pin<Box<netfilter::Registration<Self>>>,
}

impl netfilter::Filter for RustNetfilter {
fn filter(_: (), skb: &net::SkBuff) -> Disposition {
let data = skb.head_data();
pr_info!(
"packet headlen={}, len={}, first bytes={:02x?}\n",
data.len(),
skb.len(),
&data[..core::cmp::min(10, data.len())]
);
Disposition::Accept
}
}

impl kernel::Module for RustNetfilter {
fn init(_name: &'static CStr, _module: &'static ThisModule) -> Result<Self> {
Ok(Self {
_in: netfilter::Registration::new_pinned(
Family::INet(inet::Hook::PreRouting),
0,
net::init_ns().into(),
None,
(),
)?,
_out: netfilter::Registration::new_pinned(
Family::INet(inet::Hook::PostRouting),
0,
net::init_ns().into(),
None,
(),
)?,
})
}
}