haitam lazaar / lazaarsec
←Back to all research & writeups
·36 min read

Three Mistakes I Found Reviewing My Own Kernel Firewall

Revisiting a 20,000-line full-stack firewall I wrote at 18: dissecting multi-core hook races, atomic context memory traps, and silent memory corruption on fragmented sk_buffs.

Topics:#Linux Kernel#Netfilter#C#Systems Programming#Systems Security#Memory Safety

A kernel module is a program loaded into the Linux kernel itself. Unlike Firefox or Chrome, which run in user space behind a memory protection boundary, a module runs in kernel space — same address space as the scheduler, the network stack, and every driver on the machine.

That buys you performance and access. It also means a mistake that would earn a user-space program a polite segfault will instead take down the entire system:

[ 1.076702] Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0)
[ 1.077718] CPU: 0 PID: 1 Comm: swapper/0 Not tainted 3.10.0-327.el7.x86_64 #1
[ 1.082311] Call Trace:
[ 1.082616]  [<ffffffff816351f1>] dump_stack+0x19/0x1b
[ 1.083005]  [<ffffffff8162ea6c>] panic+0xd8/0x1e7
A real Linux kernel panic screen on Ubuntu: ASCII Tux penguin and KERNEL PANIC! Fatal exception in interrupt with no prompt to return to.
What “it takes down the whole system” actually looks like: a Fatal exception in interrupt halts the machine instantly.

I built the original firewall in 2022 — roughly 20,000 lines across a C kernel module, a C user-space bridge daemon, and a PHP/JS management interface.

The ZeroTrust web interface: a left-hand nav with Overview, Map, Rules, Alerts, Raw Logs, Monitoring, Infra, Components and Users, and a world map whose countries are shaded by traffic volume, above a total interaction counter reading 527,624.
The management UI, shaded by traffic per country. Every rule set here travelled the path in the next diagram to reach the kernel.

The control path looked like this:

Web UI (POST)
  → C user-space daemon (receives signal)
  → Netlink message into kernel
  → LKM applies the rule inside the packet-processing function
user space kernel space Web UI PHP · HTML · JS fw-daemon C, user space rule table country · port · verdict fw_hook_fn() NF_INET_FORWARD POST /rules netlink socket lookup packet (sk_buff) NF_ACCEPT NF_DROP
The control plane descends once per rule change; the data plane crosses the hook once per packet. The Netlink socket is the only place the two address spaces touch.

Reviewing that module years later surfaced three structural mistakes — not exotic bugs, but the specific pitfalls every new kernel developer may make, ordered by severity.

Let’s start with how packets reach your code at all.

Netfilter in one page

Netfilter is the framework built into the kernel that lets you intercept, inspect, modify, accept, or drop network packets. It exposes a set of hooks — points in the network stack where your callback gets handed each packet.

Which hook you register with decides which traffic you see:

  • NF_INET_PRE_ROUTING — immediately after a packet arrives from the interface, before any routing decision is made.
  • NF_INET_LOCAL_IN — packets destined for this machine.
  • NF_INET_FORWARD — packets routed through this machine; the routing decision has already happened. This is the one you want if you’re building a router or a transparent gateway.
  • NF_INET_LOCAL_OUT — packets generated locally, on their way out.
  • NF_INET_POST_ROUTING — just before a packet leaves the interface, for both forwarded and locally generated traffic.
packet from the NIC PRE_ROUTING routing decision for this host LOCAL_IN LOCAL_OUT local process socket, daemon, app inbound outbound through this host FORWARD every rule I wrote lived here POST_ROUTING to the wire
Which hook you register with decides which traffic you ever see. A firewall router lives in FORWARD, so it never observes traffic addressed to the box itself. Locally generated packets also pass a routing decision before POST_ROUTING, omitted here.

Since I was building a firewall router, everything happened in NF_INET_FORWARD.

Here is a complete, minimal module that drops every UDP packet it forwards:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/ip.h>
#include <linux/skbuff.h>

static struct nf_hook_ops fw_hook_ops;

/* The callback. Netfilter hands us one packet per invocation. */
static unsigned int fw_hook_fn(void *priv, struct sk_buff *skb,
                               const struct nf_hook_state *state)
{
    /* Safe check: if malformed packet, reading iph->protocol causes OOB read/panic */
    if (!skb || skb->len < sizeof(struct iphdr))
        return NF_ACCEPT;
    
    struct iphdr *iph = ip_hdr(skb);

    if (iph->protocol == IPPROTO_UDP)
        return NF_DROP;

    return NF_ACCEPT;
}

static int __init fw_init(void)
{
    int ret;

    fw_hook_ops.hook     = fw_hook_fn;
    fw_hook_ops.pf       = PF_INET;             /* IPv4 only */
    fw_hook_ops.hooknum  = NF_INET_FORWARD;
    fw_hook_ops.priority = NF_IP_PRI_FIRST;     /* see the packet before anyone else */

    ret = nf_register_net_hook(&init_net, &fw_hook_ops);
    if (ret < 0) {
        pr_err("lazaarsec_fw: hook registration failed: %d\n", ret);
        return ret;                             /* always check this */
    }

    pr_info("lazaarsec_fw: module loaded\n");
    return 0;
}

static void __exit fw_exit(void)
{
    /* Clean up after yourself, or the next packet calls a function
       that no longer exists. */
    nf_unregister_net_hook(&init_net, &fw_hook_ops);
    pr_info("lazaarsec_fw: module unloaded\n");
}

module_init(fw_init);
module_exit(fw_exit);

MODULE_LICENSE("GPL");          /* non-GPL modules can't use most of the network API */
MODULE_AUTHOR("Haitam Lazaar");
MODULE_DESCRIPTION("Minimal Netfilter forward-hook example");

Load it with insmod, watch dmesg, and your callback starts receiving packets. That’s the easy part.

Terminal showing make, insmod udp_drop.ko, network namespace tests dropping UDP packets, and dmesg logging packet drops.
Watching the module in action: ping passes across namespaces while UDP packets to port 9999 are caught and dropped in dmesg.

Mistake 1: assuming your hook runs one packet at a time

Your hook callback does not run once per packet in a tidy queue. It runs concurrently on every CPU core, once per packet, with no locking that you didn’t write yourself.

Which means any state living outside the callback is shared between invocations that are running right now, on different cores, on different packets.

Here’s the shape of the bug, and it’s embarrassingly easy to write:

/* BROKEN: one pointer, every core writing to it */
static struct udphdr *udp_header;

static unsigned int fw_hook_fn(void *priv, struct sk_buff *skb,
                               const struct nf_hook_state *state)
{
    struct iphdr *iph = ip_hdr(skb);

    if (iph->protocol == IPPROTO_UDP) {
        udp_header = udp_hdr(skb);                  /* core 0 stores its packet... */

        if (ntohs(udp_header->dest) == 80)          /* ...core 1 reads core 0's packet */
            return NF_DROP;
    }

    return NF_ACCEPT;
}

How things panic in practice:

  1. Core 0 assigns udp_header to its packet.
  2. At the exact same microsecond, Core 1 executes the hook for a different packet and overwrites udp_header with its buffer address.
  3. Core 0 resumes, dereferencing a pointer that now points to Core 1’s packet — or worse, to memory whose processing already finished and was freed back to the slab.

Now, looking at this isolated snippet, you might think: “Why would anyone declare udp_header as a global variable?”

In a 20-line snippet, the flaw stands out immediately. Inside a larger codebase with stateful connection tables, CIDR lists, and multi-protocol parsers, file-scope pointers creep in to avoid threading state through dozens of helpers.

And here is the most frustrating part of this bug: the sheer randomness.

In user space, a concurrency bug usually gives you a reproducible crash or deadlock. In kernel space, it’s a ghost. You can sit staring at your code for ten straight hours, run manual ping tests, and everything looks completely innocent. Then you push heavy traffic through the interface, two CPU cores race, and your entire operating system freezes without leaving a trace.

1 2 3 CPU 0 has packet A CPU 1 has packet B one static udp_header udp_header = A then preempted udp_header = B overwrites it udp_header->dest reads packet B NULL packet A packet B time
Nothing here is preempted unfairly or scheduled badly — this is the normal case. Two cores running the same hook on different packets, and one variable that only one of them can own.

The fix for this particular case is trivial: move the declaration inside the callback, so each invocation gets its own copy on its own stack.

static unsigned int fw_hook_fn(void *priv, struct sk_buff *skb,
                               const struct nf_hook_state *state)
{
    struct iphdr  *iph = ip_hdr(skb);
    struct udphdr *udp_header;                      /* one per invocation, on the stack */

    if (iph->protocol == IPPROTO_UDP) {
        udp_header = udp_hdr(skb);

        if (ntohs(udp_header->dest) == 80)
            return NF_DROP;
    }

    return NF_ACCEPT;
}

(Note: In production, rather than calling udp_hdr() directly, robust firewalls often use skb_header_pointer() to safeguard against uninitialized transport headers or fragmented packets—a trap we will explore in Mistake 3. But for concurrency, the core fix is simple: declaring the pointer locally so each CPU core gets its own independent copy on the stack.)

Written out like that it looks obvious.

It stops looking obvious once the module has multiple netfilter hooks, rule tables, per-IP counters, GeoIP ranges, port-knock sequence trackers and connection state — which is exactly what mine had. The declarations drift upward over time, one at a time, each for a defensible local reason.

And moving declarations only solves half the problem. Genuinely shared state — a rule list, a conntrack table, a counter — still has to be shared. For such cases, we need real synchronization: a spinlock (spin_lock_bh() in softirq context), RCU for read-mostly structures like a rule set, or per-CPU variables for counters.

“Make it local” is the fix for accidental sharing. For deliberately shared data structures, you need to pick a locking strategy and apply it consistently.

What makes this class of bug genuinely nasty is the failure mode. It doesn’t crash on your test packet. It crashes under load, randomly, on a machine that’s been up for hours, with a stack trace that points at the memcpy and tells you nothing about who corrupted what.

Kernel crash dump showing register dump, softirq context, and CR2 register faulting at 00000000deadbeef.
The real crash dump: the CPU halts with CR2 at 00000000deadbeef in softirq context, giving no hint of which concurrent core corrupted the pointer.

I’ve since talked to other engineers who develop kernel modules, and every single one shares collective trauma over these silent multi-core race conditions.

Which brings us directly to my biggest nightmare during those early kernel days: memory allocation flags.

Mistake 2: GFP_KERNEL inside a hook

When you ask the kernel for memory with kmalloc(), the second argument tells it how hard it’s allowed to try:

  • GFP_KERNEL — “I can wait.” The kernel may put your thread to sleep while it reclaims pages, flushes caches, or swaps something out.
  • GFP_ATOMIC — “I cannot sleep.” The allocation either succeeds immediately, possibly dipping into an emergency reserve, or fails.
process context softirq context a user process there is a task to put to sleep a packet from the NIC no process behind it at all write() syscall hardware IRQ, then softirq my_driver_write() fw_hook_fn() kmalloc(len, GFP_KERNEL) kmalloc(len, GFP_KERNEL) no free pages, so: the task is put to sleep while the kernel reclaims memory no free pages, so: it tries to sleep, and there is no task here to put to sleep GFP_KERNEL is correct the write() just takes longer BUG: scheduling while atomic GFP_ATOMIC is the only option
The middle line is identical in both columns. Everything that differs is above it — who, if anyone, is on the CPU when your allocation needs to wait.

To understand why this distinction is life-or-death, look at who is actually executing on the CPU:

1. Process Context: The Character Driver (my_driver_write)

Imagine a standard Linux device driver — like a character driver exposing /dev/my_device. When a user-space application writes data to it via the write() system call, the kernel executes my_driver_write() directly on behalf of that specific user process.

Because this code runs in process context:

  • It is attached to a real process descriptor (the kernel’s current pointer to the executing task_struct, which tracks the running program’s state and identity).
  • If the system is low on RAM during kmalloc(..., GFP_KERNEL), the kernel’s scheduler can pause this thread and put it to sleep.
  • While the user thread is sleeping, the kernel reclaims memory pages, flushes dirty filesystem caches, or swaps out inactive anonymous memory. Once physical pages become available, the thread wakes up and resumes its allocation.
  • To user space, the write() call simply took a few extra milliseconds. Sleeping is completely legitimate and safe here:
/* Process context: a user-space program called write(). Sleeping is allowed. */
ssize_t my_driver_write(struct file *filp, const char __user *buf,
                        size_t count, loff_t *f_pos)
{
    struct my_device_data *data;

    /* SAFE: Running on behalf of a user process. If RAM is tight, 
     * the kernel puts our thread to sleep until memory pages are freed. */
    data = kmalloc(sizeof(*data), GFP_KERNEL);
    if (!data)
        return -ENOMEM;                  /* always check. always. */

    data->buffer = kmalloc(count, GFP_KERNEL);
    if (!data->buffer) {
        kfree(data);
        return -ENOMEM;
    }

    /* ... copy buffer from user space, interact with device hardware ... */

    kfree(data->buffer);
    kfree(data);
    return count;
}

2. Interrupt Context: The Netfilter Hook (fw_hook_fn)

Now consider our firewall callback fw_hook_fn().

When an Ethernet frame hits your network interface card (NIC), the card raises a hardware interrupt (top half), which schedules a SoftIRQ / software interrupt (bottom half) to process the network stack.

Our Netfilter hook executes directly inside this SoftIRQ:

  • There is no user process attached. The CPU is not executing code on behalf of an application; it is servicing an asynchronous hardware-triggered network event in bottom-half context.
  • If you request memory with GFP_KERNEL and RAM is tight, the allocator tries to put the current execution thread to sleep.
  • But there is no task to put to sleep. You cannot pause an interrupt handler — if you put an interrupt to sleep, there is no scheduler context to ever wake it back up!

The kernel catches this immediately, flags a fatal violation of the execution model, and throws:

BUG: scheduling while atomic: swapper/0/0/0x00000100
Kernel call trace showing msleep inside fw_hook_fn triggering a scheduling while atomic / RCU context switch warning in softirq context.
Sleeping in atomic context, caught in the act: invoking a sleeping call inside fw_hook_fn triggers an immediate RCU / softirq kernel splat.

followed by a stack trace, and depending on what you corrupted on the way down, possibly a full panic. It is not always an instant kernel panic — which is worse, because it means the bug can sit in your module looking fine.

So inside a hook, always GFP_ATOMIC:

buf = kmalloc(len, GFP_ATOMIC);
if (!buf)
    return NF_DROP;     /* no memory, no packet. decide this deliberately. */

Two things worth knowing. First, build with CONFIG_DEBUG_ATOMIC_SLEEP enabled during development — it catches “might sleep in atomic context” at the moment it happens instead of three hours later. Second, NF_INET_LOCAL_OUT can run in process context, so the rule isn’t quite “hooks are always atomic” — but writing hooks as if they always are is the safe habit.

A story about allocation failure

There’s a talk I heard that stuck with me, from the work replacing how Linux tracks Virtual Memory Areas.

Before kernel 6.1, the VMA subsystem used a red-black tree plus a linked list — two structures to maintain, and a design from an era when multi-threading and concurrent access weren’t the dominant workload. It serialized access in ways that had become a bottleneck.

Liam Howlett at Oracle proposed replacing it with a Maple Tree: an RCU-safe B-tree variant that allows concurrent readers while a writer is modifying the structure, and finds unallocated gaps in the virtual address space faster. It merged in 6.1.

before 6.1 6.1 onward red-black tree doubly linked list one set of VMAs, two structures to keep in sync · a writer blocks readers range range range reader reader writer readers traverse while the writer modifies RCU-safe · no reader lock one structure · each node holds several ranges
The reason the talk dwelt on allocation failure: a structure this central has to keep working when there is no memory to grow it with.

The line from that conference that stuck with me ever since was this:

“If you are allocating memory inside the kernel, you have to expect it to eventually fail.”

In user space, if malloc() fails, the operating system gives you virtual pages anyway, or worst case your process exits with an out-of-memory error. In the kernel, memory allocations fail regularly under pressure, and you must explicitly define what happens.

Now, you might ask: what on earth are we supposed to do if the kernel can’t allocate memory in atomic context?

As unglamorous as it sounds: we either dip into an emergency memory pool reserved for critical SoftIRQs, or we simply fail the operation and drop the packet. It might feel painful to drop traffic, but dropping a packet is infinitely better than panic-locking the whole machine.

Mistake 3: assuming the packet is one contiguous buffer

This one isn’t from the firewall. It’s from a later project in prépa — a kernel module that encrypted IP payloads in flight between two gateways.

The cipher was meant to be proprietary — a custom stream cipher inspired by historical point-to-point secure telephone links. Because it wasn’t a standard algorithm like AES or ChaCha20, I couldn’t use the kernel’s built-in crypto subsystem.

(And as a friendly reminder: if you ever need real encryption in the kernel, please use the built-in crypto subsystem! It is battle-tested, hardware-accelerated, and audited.)

Not being able to use the standard APIs meant I had the “privilege” of doing manual pointer arithmetic directly inside raw packet memory.

LAN A gateway A encrypt · append MAC gateway B check MAC · then decrypt LAN B untrusted network IP hdr payload IP hdr ciphertext MAC IP hdr payload leaving LAN A in flight delivered on LAN B +8 bytes, appended by hand
Gateway B checks the MAC before decrypting, so a forged packet is dropped without the cipher ever touching attacker-chosen bytes. Those eight appended bytes are the whole subject of this section.

The encryption itself was fine. The trouble started when I wanted to append an 8-byte MAC — a message authentication code — to each packet, so the receiving gateway could verify it came from the real encryptor before attempting decryption rather than decrypting attacker-chosen ciphertext.

Which brings us to the million-dollar question: where do we put our 8 bytes?

What an sk_buff actually looks like

An sk_buff (“socket buffer”, skb) is the kernel’s representation of a packet as it moves through the network stack. It carries pointers into the buffer that holds the packet data:

headroom IP header UDP header payload tailroom (free) skb->head skb->data skb->tail skb->end skb->len the live packet spare room, reserved so IPsec, WireGuard or a MAC can be appended in place
The shape everyone draws, and the shape the next diagram breaks.

skb->data points at the start of the live packet, skb->tail at the end of it, and the gap between tail and end is tailroom — spare space the stack deliberately reserves so that layers like IPsec, WireGuard and OpenVPN can append their own trailers without reallocating.

So, back to the question: where do those 8 bytes go?

Looking at the diagram, the intuitive answer seems obvious: slap them right into that free tailroom at the end of the packet payload. Calculate where the packet ends, do a quick memcpy, increment the packet length, and send it out into the world.

So appending 8 bytes looks like it should be this:

/* WRONG. This will panic on a non-linear packet. */
unsigned char *dst = skb_tail_pointer(skb);
memcpy(dst, my_mac, MAC_SIZE);
skb->len  += MAC_SIZE;
skb->tail += MAC_SIZE;

Why that panics

In reality, that diagram represents only the simplest layout an sk_buff can take.

For performance, the Linux kernel doesn’t waste CPU copying network data into a single continuous block of RAM. Instead, a packet is often non-linear: the network headers (IP, UDP) live in a small initial buffer, while the actual data payload lives in separate memory pages linked together under skb_shinfo(skb)->frags. You run into this constantly whenever handling large transfers, streaming downloads, or when the network card bundles multiple incoming packets together to save CPU (a standard kernel optimization known as Generic Receive Offload, or GRO).

headroom IP header UDP header tailroom (tiny) your 8 bytes land here skb->head skb->data skb->tail skb->end skb_tail_pointer() + memcpy skb_shinfo frags[0] page · payload frags[1] page · payload frags[2] page · payload the packet really ends down here
Same packet, same skb, same accessors — and skb->tail now marks the end of the headers, not the end of the data. The eight bytes go past skb->end, into memory that belongs to something else.

When the packet is non-linear, skb->tail doesn’t mean what the textbooks told you. If you blindly write at skb_tail_pointer(), two things happen:

  1. Kernel panic / page fault: You write into a memory page that doesn’t belong to the packet, and the CPU halts immediately with a fatal exception. If your box is acting as the network router, congratulations — you just knocked down internet access for everyone on the floor.
  2. Silent corruption: Even worse. The machine doesn’t crash right away. Instead, you silently overwrite adjacent kernel structures or memory belonging to another process, and the disaster surfaces three hours later somewhere completely unrelated.
This is ME! Working on the hardware testbench and testing packet interception across the laptops and routers in the lab.
This is ME ! Working on the physical lab setup — testing real-time packet interception, custom routing, and module stability across the machines.

The fix: linearize, expand, then re-fetch

To touch packet bytes safely you need three guarantees: the data is contiguous, there is room for what you’re adding, and the buffer isn’t cloned (shared with another part of the stack that would see your modifications).

#define MAC_SIZE 8

static unsigned int fw_append_mac(void *priv, struct sk_buff *skb,
                                  const struct nf_hook_state *state)
{
    struct iphdr  *iph;
    unsigned char *tail;
    u8 mac[MAC_SIZE];

    /* 1. Collapse fragments into one contiguous buffer. */
    if (skb_is_nonlinear(skb) && skb_linearize(skb) != 0)
        return NF_DROP;          /* allocation failed — drop, don't guess */

    /* 2. Guarantee tailroom, and a buffer nobody else is holding. */
    if (skb_tailroom(skb) < MAC_SIZE || skb_cloned(skb)) {
        if (pskb_expand_head(skb, 0, MAC_SIZE, GFP_ATOMIC))
            return NF_DROP;      /* GFP_ATOMIC: we are in softirq context */
    }

    /* 3. CRUCIAL: re-fetch your headers.
     *    Steps 1 and 2 may have reallocated and moved the whole buffer.
     *    Any iphdr/udphdr pointer taken before this line is now dangling. */
    iph = ip_hdr(skb);

    /* 4. Append. skb_put() advances skb->len and skb->tail correctly. */
    compute_mac(skb, mac);
    tail = skb_put(skb, MAC_SIZE);
    memcpy(tail, mac, MAC_SIZE);

    /* 5. The packet grew: fix the L3 length, then recompute the L3 checksum. */
    iph->tot_len = htons(ntohs(iph->tot_len) + MAC_SIZE);
    ip_send_check(iph);

    return NF_ACCEPT;
}

Step 3 is the one that cost me the most time. pskb_expand_head() can allocate an entirely new buffer and copy the packet into it. Every pointer you derived before that call — iph, udph, a cached payload pointer — points into memory that may now be freed. The code looks correct, because the pointer was valid when you took it.

before pskb_expand_head() after pskb_expand_head() IP header payload no tailroom left buffer A skb->data iph both point into buffer A IP header payload buffer A freed copied buffer B (larger) IP header payload tailroom (+8 B) iph skb->data iph still points into memory that is gone
The kernel updates the pointers it owns. The ones you derived are yours to fix — which is why every header pointer has to be taken after the last call that can reallocate.

Two more things that example glosses over, and which bit me:

  • Layer 4 also has to be fixed up. Appending bytes after the payload means the UDP length field (udph->len) and the L4 checksum no longer describe the packet. For a gateway-to-gateway design the peer strips the MAC before delivery, so the two ends have to agree on exactly where that accounting happens. Decide it explicitly; don’t let it emerge.
  • Encrypting the payload invalidates both checksums. L3 via ip_send_check(), and L4 by recomputation — and if the NIC is doing checksum offload, the value sitting in the header may be a placeholder rather than a real checksum. That interaction is its own debugging afternoon.

Architectural Takeaways

The three mistakes escalate neatly: a race condition you can’t reproduce, an allocation flag that violates the rules of the context you’re in, and pointer arithmetic on memory that isn’t shaped the way the diagram promised.

Kernel code operates without a safety net, and subtle mismatches between developer assumptions and subsystem contracts translate directly into system halts or memory corruption. Writing reliably in ring 0 comes down to designing around those invariants from the start: lockless synchronization (RCU) across hooks, strict respect for atomic contexts, and explicit handling of non-linear packet buffers.

The useful habits are small:

  • Treat every hook invocation as if it’s racing with every other one, because it is.
  • Assume every allocation can fail, and write down what happens when it does.
  • Re-fetch every pointer after anything that might reallocate.

Pair those habits with kernel debug instrumentation (CONFIG_DEBUG_ATOMIC_SLEEP, Lockdep, and KASAN) so contract violations surface immediately on the test bench rather than in production.

Corrections and feedback from fellow kernel engineers are always welcome.