r/kernel 2h ago

Optimizing eBPF Policies for Speed and Space (Not AI Gen)

Thumbnail
1 Upvotes

r/kernel 3h ago

LSM + eBPF to supervise an untrusted userspace agent (PID tree, path default-deny, create-before-inode)

1 Upvotes

I am using BPF LSM as the actual security boundary for a coding agent (Claude Code, etc.). The process still runs as the invoking user. The IDE harness is not a kernel boundary. One binary loads policy, tracks the agent TGID, and starts the agent as SUDO_USER.

PID set. Map keys are pid-namespace TGIDs (bpf_get_ns_current_pid_tgid), not init-ns, so it works in Docker. Launch: PTRACE_TRACEME, wait stop, insert into tracked_pids, detach. sched_process_fork copies the set. Insert-after-Start() races the first open/connect.

Policy in the kernel (YAML → maps):

Hook Job
file_open Suffix deny (.envid_rsa, kubeconfig) + workspace prefix default-deny
path_unlinkpath_renamepath_mkdirpath_rmdirpath_symlinkpath_link Parent dir must be workspace or an allow prefix
path_mknod Create before the inode exists
bprm_check_security Basename suffix: rm / dd / rmdir
socket_* Unproxied/raw denied; allow-listed 443 via an authenticated userspace proxy

Workspace: confine: true, root = EvalSymlinks(cwd). Allow /usr/tmp~/.claude, … Refuse //home, exact $HOME/proc is a known hole (d_path rewrites /proc/self).

Create vs file_opentouch ~/x + lsm/file_open → -EPERM on open, 0-byte file remains. vfs_create already committed. path_mknod is the hook that runs first.

path_unlink/path_rename/path_mkdir can use bpf_d_path (sleepable). path_mknod cannot: helper call is not allowed in probesleepable_lsm_hooks lists those path hooks and omits path_mknod. Same helper, different attach BTF id.

Inode-walk + userspace stat() (ino, s_dev) fail-closed and never matched CO-RE reads — every create died, including in-tree. Working path: bpf_path_d_path kfunc on the trusted dir from path_mknod, then the same prefix matcher as file_open. Outside create: -EPERM, no leftover inode. In-tree open(O_CREAT) works.

path_link: a stack {mnt, dentry} into bpf_d_path is R1 type=fp expected=ptr_. We only confine new_dir (hardlink-into-/tmp still open).

Closing the loop (userspace). Ringbuf violation → session JSON with the YAML reason string. Agent PostToolUseFailure hook injects that text so the model sees policy, not a bare EPERM. Empty workspace reasons are not written (they overwrote credential/network IPC). Telemetry denies skip IPC.

Not a VM, not a user ns, not seccomp. Same UID, LSM on that tree. Apache-2.0: https://github.com/AgentGuard-hq/AgentGuard (enforcer.bpf.c).

Questions for people who own these hooks: is path_mknod non-sleepable on purpose (which caller)? Is bpf_path_d_path the supported replace for non-sleepable path LSMs? Better pattern than “trusted dir + kfunc” for create-before-inode?


r/kernel 4h ago

Replacing iptables with eBPF: How I built a zero-downtime, identity-aware kernel firewall engine in Go & C

0 Upvotes

Over the past few weeks, I’ve been working on an open-source project: Identity-

Aware eBPF Firewall](https://github.com/AboEl3iz/Identity-Aware-eBPF-Firewall) — a

high-performance in-kernel packet filtering engine written in C (eBPF bytecode)

with a Go control plane .

Traditional `iptables`/`netfilter` setups suffer from sequential O(N) rule

scanning, mandatory kernel `sk_buff` memory allocations per packet (which chokes under

volumetric floods), blocking monolithic reloads, and IP-only granularity. I wanted to

build a modern system that addresses these limitations using native eBPF primitives

and container identity.

---

### Key Technical Highlights

  1. Stateless XDP Volumetric Fast-Path (`SEC("xdp")`)

- Drops malicious floods directly inside interface driver RX queues before

`sk_buff` allocation.

- Subnet filtering uses kernel-native Longest Prefix Match Tries

(`BPF_MAP_TYPE_LPM_TRIE`) for $O(\text{prefix_len})$ lookups instead of linear rules.

  1. TC Stateful Connection Tracking (`SEC("tc")`)

- Enforces TCP 3-way handshakes and state machine transitions using an LRU flow

map (`BPF_MAP_TYPE_LRU_HASH`).

- Automatically drops untracked non-SYN packets (e.g. out-of-order ACK/PSH flood

attacks) before reaching the Linux networking stack.

  1. Cgroup v2 Workload Identity Resolution

- Binds network rules directly to container workloads using 64-bit Linux cgroup

v2 inode numbers (`syscall.Stat`) mapped to `bpf_get_current_cgroup_id()`.

- Allows fine-grained container microsegmentation on single hosts without needing

full Kubernetes stack dependencies.

  1. Double-Buffered Zero-Drop Atomic Policy Reloads

- Updates policies without dropping continuous packet streams.

- Compiles AST policies into generation-indexed BPF maps and performs a single-

operation atomic switch via `active_generation_map[0] = next_gen`. If staging fails,

it safely rolls back automatically.

  1. Security Hardening & Control Plane RBAC

- Capability Bounding : Drops full root permissions down to the minimal set

(`CAP_BPF`, `CAP_NET_ADMIN`, `CAP_SYS_RESOURCE`).

- IPC Security : Unix domain socket control plane authenticates caller process

credentials using Linux `SO_PEERCRED` (`unix.GetsockoptUcred`) and enforces 3-tier

RBAC (`Admin`, `Operator`, `Viewer`).

  1. Real-Time Observability & Interactive TUI

- Built an interactive 4-pane Bubbletea Terminal UI (`firewall-tui`) driven by

zero-copy BPF ring buffer streams (`BPF_MAP_TYPE_RINGBUF`) with real-time sparkline

metrics, conntrack flow tables, and explainable audit streams (`[PASS]` / `[DROP]`).


r/kernel 9h ago

How to Build a Custom Linux Kernel from Source (Arch Linux + Hyprland Guide)

Thumbnail youtu.be
0 Upvotes

Ever wanted to compile your own custom Linux kernel from scratch? In this step-by-step tutorial, I walk you through the entire process of building a custom kernel directly from source on Arch Linux. We cover everything from fetching the bleeding-edge code from Linus Torvalds' Git repository to cloning your current system configuration for guaranteed hardware compatibility.

To make things interesting, we even dive into the kernel's C source code to modify the motherboard PC speaker driver, proving our custom build works perfectly on reboot! Whether you want to optimize your system, strip out unnecessary bloated modules, or just learn how the core of your operating system functions, this complete guide takes you from `make menuconfig` all the way to updating your GRUB bootloader.


r/kernel 1d ago

Looking for feedback on a Go/eBPF TCP failure-recovery prototype

Thumbnail
2 Upvotes

r/kernel 2d ago

Most efficient way to port a small AMD driver patch from kernel 7.2 to 7.3

4 Upvotes

I have a small patch (78 kB) that patches a few files in the AMD driver for my specific hardware. Going from 7.0, 7.1, 7.2 was easy, but I can see that there quite a few changes in 7.3 that break it. Some of the code I tack on to has even shifted to different files.

What is the quickest way to port to 7.3? Happy to use AI assistance but it isn't very good at keeping track of line numbers or generating diffs.

Note: my patch doesn't really change the core functionality of the driver, so my expectation is that I need to move my additions to new places rather than modify anything new in 7.3.


r/kernel 4d ago

Best way to build i686-elf toolchain on modern Arch Linux (GCC 15) for a first OS project?

1 Upvotes

Hi everyone! I'm starting my first OS development project for x86 (32-bit), following the standard OSDev Wiki approach (using a minimal setup with boot.s, kernel.c, and a custom linker.ld script)


r/kernel 4d ago

Understanding Linux source

0 Upvotes

It is possible for a single person have read about processor programming and some hardware topics to understand the full Linux source code and how to read and understand the whole source code.


r/kernel 5d ago

BPF Token Delegation

Thumbnail
0 Upvotes

r/kernel 6d ago

What do kernel developers do in the companies when the whole kernel is free-source?

86 Upvotes

I am very new to this domain. My question may sound too simple or trivial. Pls excuse my ignorance. I don't know much about linux kernel, and I wish to know a little of it. I am not afraid to ask simple questions.

The whole linux kernel is available for free. Why do companies hire kernel engineers? Sure, you need someone who understands and it can help you modify and compile as per your requirement, but why would you need a full time engineer for that?

What do these kernel engineers do?


r/kernel 5d ago

My journey into kernel development as a beginner

12 Upvotes

My journey into kernel development as a beginner

Hey everyone 👋

I'm a beginner in kernel development and recently decided to seriously start learning how operating systems work under the hood.

I've done normal application/backend development before, but kernel development feels completely different. 😅

Right now I'm trying to understand things like:

CPU architecture and registers

Boot process

How the kernel actually gets loaded

Kernel entry

GDT / IDT

Interrupts

Paging and virtual memory

Physical memory management

Heap allocation

Scheduling

Processes and system calls

Drivers and filesystems

My long-term goal is to eventually build my own small kernel from scratch, rather than just following tutorials and copying code.

At the moment, pointers, memory, assembly, and low-level concepts are definitely making my brain work overtime 😂

I'm planning to learn slowly and understand why things work instead of just getting something to boot.

For people who have experience with OS/kernel development:

What would you recommend a beginner focus on first?

And what are some mistakes you wish you had avoided when you started learning kernel development?

Would love to hear your advice! 🚀


r/kernel 5d ago

¿Alguien sabe como aprender a hacer un kernel/sistema Monolitico?

Thumbnail
0 Upvotes

r/kernel 5d ago

After installing Kali net hunter, I encountered an issue saying protocol driver not attached while installing required packages for Bluetooth Arsenal.

Post image
0 Upvotes

I don't know what I did wrong, but I faced this issue even before switching to Lineage 23.2. I am using a Redmi Note 8 (Ginkgo), and I tried installing Kali NetHunter GinkgoA16 on it.


r/kernel 5d ago

How do you transition from "writing C for MCU-based electronic products" to linux kernel development?

1 Upvotes

Hello everyone,
My professional background: around 4 years of experience in writing driver and application layer code (C) for consumer electronic products. I can write peripheral drivers for a variety of microcontrollers and external sensors. With my experience and some help from AI, I am very confident in my abilities for the mentioned kind of work. I can also write application layer code in C. Most of the work I have done is in bare-metal environment. I have some experience with RTOS environment too, but not too much.

My motivation:
My reason(s) for getting into this domain is:

  1. The community. I see that the kernel is supported by the community of developers. The fact that at least SOME people are doing it because they want to build efficient and reliable code for everyone to use is really good. I am sure I will meet people with very high ethics if I join this community.
  2. Global Impact: So the code I write CAN impact a large group of people is very satisfying.
  3. Fully remote work is possible: This is highly subjective (depends on projects and what not), but it is possible to work from anywhere in the world.
  4. Good salaries (if you are good at it): Once again a selfish reason. I see that companies need engineers who understand the kernel well and make important contributions to it. If I am marginally better than an average kernel developer, I will have very good technical and financial growth.

Question:
Now that I have laid out my background, how do I get into it? Apologies for the question. I know this question must have been asked many times here.

Then another question is, how do I get a job? People need you to have n years of experience before they consider your profile. I think if I learn things well and start contributing, it should give me an edge. I have a long way to go (and I am excited about it) and I would appreciate some help from this wonderful community.

EDIT: I would like to connect with people who had a similar background as me and transitioned to kernel development. Any suggestions on project-based learning is deeply appreciated. I learn by doing.

Thanks for reading!


r/kernel 6d ago

[Stupid Question] How do I start contributing ?

10 Upvotes

What I know:
1. How TLB's work and ways of handling TLB misses
2. Paging and faults and demands
3. Swap
4. NICs and how ether buffers are loaded into kernel.
So, How do I find what do I work on. I am fairly good at C and Rust.
Do I look at syzbot and pick some easy issues from there ? Also I am particularly interested in the memory management subsystem, because alot of commits I see are from people working in arm etc working on their hardware integrations.

I do have set the email and the git workflow.

Thank You. And sorry if this question has been asked multiple times(which I know it probably is).


r/kernel 8d ago

Block-layer error injection

Thumbnail lwn.net
4 Upvotes

r/kernel 9d ago

Linux 7.3 Better Protects Against Buggy EFI Firmware Taking Down The Rest Of User-Space

Thumbnail phoronix.com
28 Upvotes

r/kernel 12d ago

Hcitool in blueZ linux bt stack

Thumbnail
3 Upvotes

r/kernel 12d ago

Having trouble getting started with HID-BPF

7 Upvotes

I've got a USB device that is announcing itself as a gamepad when it isn't one. I understand the basics of HID, and I've successfully decoded the HID report descriptor. I see what byte I need to change.

I've read through https://docs.kernel.org/hid/hidintro.html and https://docs.kernel.org/hid/hid-bpf.html several times. I've got code that I think ought to do the job.

One problem: I'm missing some critical header, or some parameter to gcc, because I just can't get it to build!

Here's what I've got:

#include <linux/types.h>
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include <bpf/libbpf.h>

char _license[] SEC("license") = "GPL";

struct hid_bpf_ctx {
struct hid_device *hid;
__u32 allocated_size;
union {
__s32 retval;
__s32 size;
};
};

SEC("struct_ops/hid_rdesc_fixup")
int BPF_PROG(filter_switch, struct hid_bpf_ctx *hid_ctx)
{
__u8 *data = hid_bpf_get_data(hctx, 0 /* offset */, 4096 /* size */);

if (!data)
return 0;

data[3] = 0x07; /*0x07: keypad*/

return 0;
}

SEC(".struct_ops.link")
struct hid_bpf_ops surface_dial = {
.hid_rdesc_fixup = (void *)hid_rdesc_fixup,
};

(yes, I'm probably going to need something to filter to the correct USB id, but anyway)

Here's how I'm building it, and the build errors:

gcc -I /usr/include -fpermissive -c ./fixup.c -o ~/Projects/MfdFix/build/fixup.o
./fixup.c:18:28: error: expected ‘)’ before ‘struct’
   18 | int BPF_PROG(filter_switch, struct hid_bpf_ctx *hid_ctx)
      |                            ^~~~~~~
      |                            )
./fixup.c:31:8: error: variable ‘surface_dial’ has initializer but incomplete type
   31 | struct hid_bpf_ops surface_dial = {
      |        ^~~~~~~~~~~
./fixup.c:32:10: error: ‘struct hid_bpf_ops’ has no member named ‘hid_rdesc_fixup’
   32 |         .hid_rdesc_fixup = (void *)hid_rdesc_fixup,
      |          ^~~~~~~~~~~~~~~
./fixup.c:32:36: error: ‘hid_rdesc_fixup’ undeclared here (not in a function)
   32 |         .hid_rdesc_fixup = (void *)hid_rdesc_fixup,
      |                                    ^~~~~~~~~~~~~~~
./fixup.c:32:28: warning: excess elements in struct initializer
   32 |         .hid_rdesc_fixup = (void *)hid_rdesc_fixup,
      |                            ^
./fixup.c:32:28: note: (near initialization for ‘surface_dial’)
./fixup.c:31:20: error: storage size of ‘surface_dial’ isn’t known
   31 | struct hid_bpf_ops surface_dial = {
      |                    ^~~~~~~~~~~~

What am I missing? I've searched and searched for hid_bpf_ctx and similar, and all I find is documentation for the specific structures in https://docs.ebpf.io/, none of which list which damn header to include! I got a suggestion to grep the kernel source; that comes up with the struct, but including it gets me A: a warning message in the compiler output NOT to include the source directly, and B: more compiler errors.

There's obviously a library or header I'm missing, or some arg to gcc I ought to be passing that I'm not. What is it? I couldn't even get it to build without -fpermissive, and if I pass any version flag to gcc it errors out due to multiple declarations of enums and structs (I thought that was perfectly legal in C, as long as they're identical? Not like it's my own code, anyway!...)

Like, I'm pretty sure I know how to solve the actual problem I'm trying to solve with HID-BPF. I can even see what I need to write to load the compiled .o into memory and have it take effect. I'm just getting nowhere trying to actually build it!...


r/kernel 11d ago

How many ioctls can you do?

0 Upvotes

I can do 8.

Observe.

One ioctl.

Two ioctl.

Three ioctl.

Four ioctl.

Five ioctl.

Six ioctl.

Seven ioctl.

Eight ioctl.


r/kernel 12d ago

Building my own Kernel problem whitps2 driver keyborad can't write on shell

Thumbnail
1 Upvotes

r/kernel 12d ago

NSD: LKML RFC - Kernel readahead learning prefetcher

1 Upvotes

Posting benchmark results from the ongoing LKML RFC discussion.

The patchset adds a learning prefetcher to the page cache that

observes access patterns and issues prefetch only when the kernel's

own window is insufficient.

Test methodology: interleaved ON/OFF, drop_caches before each run,

3 passes, 4 workloads, 5 read_ahead_kb values.

seq64 (8 GB sequential, 64k requests, n=131K/run):

| kb | OFF avg | ON avg | diff | p50 OFF->ON | p99 OFF->ON | overhead |

|-------|---------|---------|--------|-------------|--------------|----------|

| 128 | 22.02s | 17.11s | -22% | 50->23 us | 812->805 us | 5.94->4.33s |

| 256 | 17.08s | 17.22s | +1% | 20->15 us | 824->1129 us | 4.07->4.13s |

| 512 | 16.81s | 16.96s | +1% | 16->14 us | 1092->1903 us| 4.24->3.60s |

| 1024 | 17.25s | 17.03s | -1% | 15->16 us | 1903->1883 us| 3.67->3.74s |

SQLite full-table scan (6.2 GB):

| kb | OFF avg | ON avg | diff | overhead |

|-------|---------|---------|--------|----------|

| 128 | 24.51s | 20.48s | -16% | +0.95s |

| 256 | 20.05s | 16.60s | -17% | +1.26s |

| 512 | 15.31s | 12.18s | -20% | +1.06s |

| 1024 | 12.22s | 12.09s | -1% | +0.26s |

Key takeaways:

- 128K: seq64 -22%, SQLite -16%

- 512K: NSD reaches the same throughput as kernel+1M (12.18s vs 12.22s)

- 1M: NSD is completely silent, no regression

- random4k: neutral

- random_repeat: slight improvement

- Disk I/O is byte-identical between ON and OFF in all 96 runs


r/kernel 12d ago

Linux Kernel Update

Post image
1 Upvotes

r/kernel 13d ago

How to initialize Qualcomm SCMI Bluetooth (/dev/scmi_bluetooth) to get hci0 in a virtualized Yocto Linux PVM?

Thumbnail
2 Upvotes

r/kernel 14d ago

Debian in Termux... Android in Debian through chroot or QEMU...

Thumbnail
2 Upvotes