Skip to content

About

Eight small Linux kernel steps, each tested in QEMU on six kernel releases

Topics

Resources

Stars

4 stars

Watchers

1 watching

Forks

Repository files navigation

Text console of a Linux 6.18.65 guest in QEMU. Two test lines say that an open file did not raise the module's reference count and that rmmod succeeded. Then the kernel prints: BUG: unable to handle page fault, supervisor read access in kernel mode, Oops, RIP in __x64_sys_ioctl.

Screen of the QEMU guest, Linux 6.18.65, first 15 lines of the scenario stale-file. A module was removed while another process had its device open, and the next system call on that file crashed the kernel. Captured with QEMU's screendump. How it was cut and framed is in docs/SOURCES.md.

Kernel-Linux

Eight small steps into the Linux kernel, each with a test that boots a real kernel in QEMU.

The steps start with a module that prints one line. Later ones make the kernel report a data race by itself, send one request through three struct layouts from a 32-bit and a 64-bit program, and measure where KASLR put the kernel in 32 boots. All eight build and pass on six kernel releases from 5.15 to 7.3, and on the same releases built with KASAN, lockdep and KCSAN. Four scenarios end in a kernel panic on purpose, and the test checks what the kernel says while it goes down.

The steps

Step What it builds What its test establishes
01-hello A module with an init function, an exit function and one parameter The two log lines appear, the parameter arrives, loading sets the out-of-tree taint flag
02-chardev A character device that keeps 100 bytes It behaves like a small file, a full device answers ENOSPC, rmmod is refused while it is open, a reader on a second CPU never sees a half written line
03-ioctl A device with two ioctl commands and a /dev node the kernel creates A 32-bit and a 64-bit caller compute the same command numbers and both get their value back
04-kaslr A program that prints how far KASLR moved the kernel The number equals the one the kernel prints in a panic, and a table shows who may read kernel addresses
05-lifetime A module that owns an open file and a timer What the kernel does when rmmod leaves a pointer into the module behind
06-race A counter that two CPUs update Exact with a mutex. Without it additions are lost and KCSAN names the two racing lines
07-abi A device that takes one request in three struct layouts Which layouts a 32-bit program can use, with and without a compat handler that converts them
08-layout A module that shows where three memory areas start Without KASLR every address is the documented one. With it, the spread of five addresses over 32 boots

Run it

You need an x86_64 Linux machine, and WSL2 is enough. On Debian or Ubuntu the tools are in build-essential flex bison bc libelf-dev libssl-dev cpio curl xz-utils qemu-system-x86 busybox-static.

make kernel KERNEL=6.18.65   # fetch from kernel.org, compare the SHA-256, build
make test KERNEL=6.18.65     # build the steps against it, boot QEMU, run every scenario

One kernel build took between two and four minutes on a 22 thread machine. A test run prints one line per check and ends with a count. After these two commands the count is 119, and three scenarios that need another kernel flavour are listed as NOT RUN with the command that builds it. The run below had all three flavours built, and the two extra ones are described after it.

linux-6.18.65, QEMU emulator version 10.2.1 (Debian 1:10.2.1+ds-1ubuntu3.3), accel=tcg, gcc (Ubuntu 15.2.0-16ubuntu1) 15.2.0

scenario default
  ok - 01-hello: insmod succeeds
  ok - 01-hello: the kernel log has the greeting
  [88 more checks]
  ok - host: the guest booted and started the tests
  ok - host: the guest ran to the end and powered off
  ok - host: the kernel log has no bug report

scenario kaslr-on
  ok - host: the log then says "Kernel Offset: 0xb800000 from 0xffffffff81000000"
  ok - host: the guest booted and started the tests
  ok - host: the kernel panicked before the guest finished, as this scenario intends

  [seven more scenarios]

linux-6.18.65: 309 passed, 0 failed

make matrix does both for every release in lab/versions. make survey KERNEL=6.18.65 boots that kernel 32 times for step 8. Sources, kernels, guests and logs stay under .cache/.

Two more kernel flavours let the kernel check the modules while the tests run. Once they are built, make test runs their scenarios as well.

bash lab/kernel.sh 6.18.65 debug   # KASAN and lockdep
bash lab/kernel.sh 6.18.65 kcsan   # KCSAN

Without the lab, make modules builds every step for the kernel you are running, and make modules KDIR=<kernel build tree> for another one. Both use the kernel's own build system for external modules [6].

How a run is judged

Every step has a test.sh that runs inside the guest and prints KL: ok or KL: not ok for each check. lab/run.sh boots the guest once for every line of lab/scenarios and reads the serial log.

A scenario that should finish fails if the guest does not power off, and it also fails if the kernel log holds anything that looks like a bug report, such as BUG:, WARNING: or a call trace. That second rule is what makes the KASAN, lockdep and KCSAN runs count.

A scenario that should crash prints KL-EXPECT <text> before it pulls the trigger. The host then requires that text further down in the log, and requires the panic.

One report is listed in the output instead of counted. Linux 5.15 reads a field of a mutex owner without marking the read, in mutex_spin_on_owner(), and KCSAN reports that when two CPUs want the same lock. From 6.1 on the read is marked [9]. In nine runs of the default scenario on the 5.15.226 KCSAN kernel it appeared once, and that log is kept.

Notes on each step

01-hello

hello_init() runs at insmod, hello_exit() at rmmod, and both write to the kernel log. The test also reads /proc/sys/kernel/tainted. Bit 12, value 4096, is set after the first module from outside the kernel tree is loaded [1].

02-chardev

register_chrdev() reserves a major number and creates nothing in /dev, so this step still needs mknod. The device keeps 100 bytes and follows the file position. echo text > /dev/mydev replaces the content because the shell opens with O_TRUNC, >> appends, and a write past the end fails with ENOSPC.

read() and write() share a buffer and a length, and two CPUs can be inside them at once. hammer.c runs a writer and a reader on two CPUs for two seconds. With the mutex in place no read returned a half written line.

    hammer: 1263622 reads, 0 torn

03-ioctl

class_create() and device_create() make /dev/ioctl_dev appear without mknod. The two commands carry a 32-bit integer.

The last argument of _IOW() is the type of the data, and the macro stores its size in the command number [2]. ioctl32.c is a 32-bit program without a C library that makes its system calls with int $0x80, so the build machine needs no 32-bit libc. The test runs it next to the 64-bit caller and compares the numbers both computed.

    ioctl32: pointer size 4, WR_VALUE 0x40046161, RD_VALUE 0x80046162
    ioctl32: ioctl(WR_VALUE) returned 0
    ioctl32: ioctl(RD_VALUE) returned 0, value -4321
    test_ioctl: pointer size 8, WR_VALUE 0x40046161, RD_VALUE 0x80046162

A 32-bit program on a 64-bit kernel reaches a driver through .compat_ioctl. Both commands take a pointer to a fixed size integer, so compat_ptr_ioctl() is enough [2].

04-kaslr

The kernel image is linked for one address and moved by a random offset at boot. kernel_address reads _stext from /proc/kallsyms and subtracts the link address, which it takes from a System.map or, on x86_64, from the default of 0xffffffff81000000.

The kernel prints the same offset itself when it panics [7]. The scenario kaslr-on reads the offset, forces a panic with echo c > /proc/sysrq-trigger, and the host compares the two. kaslr-off boots with nokaslr and expects 0 from the program and Kernel Offset: disabled from the kernel.

    _stext at run time:  0xffffffff8c800000 (/proc/kallsyms)
    _stext at link time: 0xffffffff81000000 (/kl/System.map)
    KASLR Offset: 0xb800000
KL-EXPECT Kernel Offset: 0xb800000 from 0xffffffff81000000
[    2.403501] Kernel Offset: 0xb800000 from 0xffffffff81000000 (relocation range: 0xffffffff80000000-0xffffffffbfffffff)

Whether a process sees real addresses in /proc/kallsyms depends on two settings. The test goes through seven combinations as root and as an unprivileged user.

Console of the guest during step 4. The program prints the run-time and link-time address of _stext and the KASLR offset. A table follows with kptr_restrict, perf_event_paranoid, user and the address of _stext each of them read from /proc/kallsyms.

Screen of the QEMU guest, Linux 6.18.65, scenario default with only step 4. With kptr_restrict=0 and perf_event_paranoid=1 the user nobody reads the real address of _stext.

With kptr_restrict at 0 an unprivileged user gets the real addresses as soon as perf_event_paranoid is 1 or lower. The code that decides this is kallsyms_show_value() [3], and the sysctl documentation describes the two settings [4].

05-lifetime

rmmod frees the code and the data of a module. This step hands the kernel two pointers into the module and has one switch for each to leave it behind.

With keep_owner=0 the file_operations have no .owner. An open file takes its reference on the module through that field [8]. Without it the file does not count as a user, rmmod succeeds, and the file keeps pointing at freed memory. The picture at the top is that scenario. Its log continues like this.

[    2.370197] Modules linked in: [last unloaded: lifetime(O)]
[    2.373026] Kernel panic - not syncing: Fatal exception

With stop_timer=0 the exit function does not stop the timer. The timer stays queued, and its timer_list lived in the module's data. A tenth of a second after rmmod the kernel comes to that timer and faults while writing to the freed structure.

[    3.369310] BUG: unable to handle page fault for address: ffffffffc03231c8
[    3.369560] #PF: supervisor write access in kernel mode
[    3.371127] RIP: 0010:__run_timers+0xd5/0x280
[    3.375838] Modules linked in: [last unloaded: lifetime(O)]
[    3.377433] Kernel panic - not syncing: Fatal exception in interrupt

With both switches at their default the test opens the device, watches the reference count go from 0 to 1, sees rmmod refused, closes the file and removes the module.

06-race

Every byte written to /dev/race adds one to a counter. Two processes write 1,048,576 bytes each at the same time. With the mutex the counter ends at 2,097,152 on every kernel in the table below.

The scenario race loads the module with locked=0 on a KCSAN kernel.

Console of the guest during the race scenario. The kernel prints BUG: KCSAN: data-race in race_write / race_write, with the call stack of a write on cpu 0 and of a read on cpu 1. The report ends with the line Reported by Kernel Concurrency Sanitizer.

Screen of the QEMU guest, Linux 6.18.65 built with KCSAN, scenario race. The numbers differ between the light and the dark picture because each is a boot of its own.

KCSAN reports the two accesses with their call stacks [5]. The count that the test prints afterwards is short of the expected one.

    without the mutex: counted 1677783 of 2097152, 419369 additions lost

07-abi

The struct that an ioctl takes is part of the interface. A 32-bit program and a 64-bit kernel must agree on its size and on where each member sits, and _IOW() builds the size into the command number. /dev/abi fills a buffer, and three commands ask for that with three structs [2].

abi_call.c is one source file built twice, as abi64 and as abi32. Each prints the size it finds for every struct, the command number that follows, and what the driver answered.

    abi64: native size 16 command 0x40106b01 result 0 filled
    abi64: padded size 16 command 0x40106b02 result 0 filled
    abi64: fixed size 16 command 0x40106b03 result 0 filled
    abi32: native size 8 command 0x40086b01 result 0 filled
    abi32: padded size 12 command 0x400c6b02 result 0 filled
    abi32: fixed size 16 command 0x40106b03 result 0 filled
    abi32, translate=0: native size 8 command 0x40086b01 result -25 untouched
    abi32, translate=0: padded size 12 command 0x400c6b02 result -25 untouched
    abi32, translate=0: fixed size 16 command 0x40106b03 result 0 filled

A pointer and a long are 16 bytes for one program and 8 for the other. A __u32 before a __u64 is 16 and 12, because i386 aligns 64-bit members to four bytes. Only the struct with every member on its natural boundary is the same for both. With translate=1 the driver's compat handler knows the two 32-bit layouts and converts them. With translate=0 it only widens the pointer, which is all compat_ptr_ioctl() does. The driver then does not know the two command numbers that the 32-bit program computed, and answers ENOTTY (-25).

08-layout

KASLR on x86-64 moves more than the kernel image. The direct mapping of physical memory, the vmalloc area and the page array each start at their own random address [11], and the first module is loaded a random number of pages into the module area [12]. layout.ko shows the three area starts in a file that only root can read.

Booted with nokaslr, all five addresses must be the ones the kernel documents for the paging mode in use [10]. make survey then boots the same kernel 32 times with KASLR. This is the table for 6.18.65.

where each area started in 32 boots
area        with nokaslr      lowest            highest           different apart by multiples of
text        ffffffff81000000  ffffffff82c00000  ffffffffb9200000  32        0x200000
module      ffffffffc0000000  ffffffffc0200000  ffffffffc0400000  2         0x200000
direct_map  ff11000000000000  ff11f0f2c0000000  ff4fcc5080000000  32        0x40000000
vmalloc     ffa0000000000000  ff18740380000000  ff8779b940000000  32        0x40000000
vmemmap     ffd4000000000000  ff52da5500000000  fff0ed5040000000  32        0x40000000

The image moved in steps of 2 MiB and the three memory areas in steps of 1 GiB. The first module started at one of two addresses. The 6.18 source rounds the block it takes module text from up to 2 MiB [12]. The same survey on 6.6.163 gives the module 32 different addresses, 4 KiB apart.

where each area started in 32 boots
area        with nokaslr      lowest            highest           different apart by multiples of
text        ffffffff81000000  ffffffff83600000  ffffffffbba00000  31        0x200000
module      ffffffffc0000000  ffffffffc0006000  ffffffffc03f6000  32        0x1000
direct_map  ff11000000000000  ff12763f00000000  ff4f266140000000  32        0x40000000
vmalloc     ffa0000000000000  ff296df500000000  ff84af4440000000  32        0x40000000
vmemmap     ffd4000000000000  ff5ccb1080000000  fffdff1380000000  32        0x40000000

On the KASAN kernels the three memory areas sit at their documented addresses even with KASLR on, and only the image and the module move. The kernel switches that part of the randomisation off when it is built with KASAN [11].

What the first version got wrong

The first version of this repository had four of these steps and no tests. Built and run as published (commit b9fb20c), it showed the following. Every row is fixed. All of them except the double unregistration, which has no visible effect on these kernels, are covered by a check.

Where What happened Evidence
Directory names Hello_world#1 does not build on 5.15.226 and 6.1.193 fixdep: error opening file: .../Hello_world: No such file or directory
Character driver, ioctl driver No .owner, so rmmod succeeded with the device open and the kernel crashed when that file was used BUG: unable to handle page fault, RIP: filp_flush+0x22 on 6.18.65
Character driver write() ignored the file position 12 bytes in three calls left ijkl, a 150 byte write left 50 bytes
Character driver No lock around the buffer hammer counted 157,135 torn reads out of 1,593,798, and KCSAN reported data-race in device_read / device_write
ioctl driver _IOW('a', 'a', int32_t *) put the size of a pointer into the number, and there was no .compat_ioctl A 32-bit caller computed 0x40046161, the driver expected 0x40086161, the call returned ENOTTY
ioctl driver class_create(name) with one argument Does not compile before 6.4. macro 'class_create' requires 2 arguments on 5.15.226 and 6.1.193
ioctl driver class_unregister() followed by class_destroy() The class is unregistered twice. No visible effect on 6.18.65, where the second call finds nothing and returns
KASLR program Printed nothing under nokaslr, and Could not find _stext symbol under kptr_restrict=2 Exit status 0 in both cases

The tests of this version were also run against those first sources, to make sure they can fail. Against the first sources 31 of 68 checks fail and three of the five boots never finish. Some of the step 3 failures are a side effect, since the new callers use the corrected command numbers and the old driver does not know them. The full output is in docs/results/first-version.txt, and the build output of the first sources on each kernel in docs/results/first-version-build.txt.

Results

Passed checks per boot. Every kernel was built from the kernel.org tarball by lab/kernel.sh, and the run was make matrix on a fresh clone.

Scenario Kernel 5.15.226 6.1.193 6.6.163 6.12.119 6.18.65 7.3.6
default plain 93 of 93 93 of 93 93 of 93 93 of 93 93 of 93 93 of 93
kaslr-on plain 3 of 3 3 of 3 3 of 3 3 of 3 3 of 3 3 of 3
kaslr-off plain 5 of 5 5 of 5 5 of 5 5 of 5 5 of 5 5 of 5
stale-file plain 6 of 6 6 of 6 6 of 6 6 of 6 6 of 6 6 of 6
stale-timer plain 4 of 4 4 of 4 4 of 4 4 of 4 4 of 4 4 of 4
layout-off plain 8 of 8 8 of 8 8 of 8 8 of 8 8 of 8 8 of 8
default debug 93 of 93 93 of 93 93 of 93 93 of 93 93 of 93 93 of 93
default kcsan 93 of 93 93 of 93 93 of 93 93 of 93 93 of 93 93 of 93
race kcsan 4 of 4 4 of 4 4 of 4 4 of 4 4 of 4 4 of 4
All 309 of 309 309 of 309 309 of 309 309 of 309 309 of 309 309 of 309

The workflow in .github/workflows/lab.yml repeats the run on GitHub's Ubuntu 26.04 runners at every push. It takes the plain kernel of each release, and the debug and kcsan kernels of the first release in lab/versions.

The summaries are in docs/results, one file per release. The serial logs of the 6.18.65 run are in docs/results/logs. Each log starts at the first line the tests print, and the boot messages before it are left out. The two survey outputs are there as well. The pictures were taken in boots of their own, so their addresses and time stamps differ from those in the logs.

What was tested and what was not

Every scenario in lab/scenarios ran on the six releases above, on kernels built from the kernel.org tarballs with gcc 15.2.0, in QEMU 10.2.1 with software emulation (TCG) and two virtual CPUs. The host was Ubuntu 26.04 under WSL2. The steps compile without warnings on all six, and sparse reports nothing for the modules on 6.18.65. The survey of step 8 ran on 6.18.65 and on 6.6.163, 32 boots each. For these runs the tools came from Ubuntu packages unpacked into a home directory.

The first run of the workflow on GitHub's Ubuntu 26.04 runner passed as well, with the tools installed by apt from the list above. It ran 119 checks on the plain kernel of each release, 93 on the debug kernel and 97 on the kcsan kernel of 6.18.65. Its output is in docs/results/github-actions-first-run.txt.

KVM, real hardware, a distribution kernel with its own headers, clang, a 32-bit kernel, module signing with Secure Boot, and releases older than 5.15 were not tested. make modules was only run with KDIR pointing at a kernel built by the lab. On arm64 kernel_address needs a System.map, and that path was read but never run. The tarballs were compared with kernel.org's SHA-256 list. The PGP signature on that list was not checked.

Project layout

01-hello to 08-layout one directory per step with its source, Makefile and test.sh
lab/kernel.sh        fetch, check and build one kernel release
lab/guest.sh         build the steps against it and pack the initramfs
lab/run.sh           boot QEMU per scenario and judge the serial log
lab/scenarios        the list of boots
lab/survey.sh        boot one kernel many times and tabulate five addresses
lab/guest/           init and test helpers that run inside the guest
lab/*.config         kernel configuration fragments (lab, debug, kcsan, screen)
docs/results/        summaries and logs of the published runs
docs/img/            the pictures above; docs/SOURCES.md says where each one comes from
.github/workflows/   the same run on GitHub's runners

Sources

The file names refer to the Linux 6.18.65 source tree.

  1. Documentation/admin-guide/tainted-kernels.rst, the table of taint flags.
  2. Documentation/driver-api/ioctl.rst, sections on command number definitions, on 32-bit compat mode and on structure layout.
  3. kernel/ksyms_common.c, function kallsyms_show_value().
  4. Documentation/admin-guide/sysctl/kernel.rst, entries kptr_restrict and perf_event_paranoid.
  5. Documentation/dev-tools/kcsan.rst.
  6. Documentation/kbuild/modules.rst, building external modules.
  7. arch/x86/kernel/setup.c, function dump_kernel_offset(), which prints the Kernel Offset line.
  8. fs/char_dev.c, function chrdev_open(), and the fops_get() macro in include/linux/fs.h, where an open takes its reference on .owner.
  9. kernel/locking/mutex.c of Linux 5.15.226, line 364, and owner_on_cpu() in include/linux/sched.h of Linux 6.1.193.
  10. Documentation/arch/x86/x86_64/mm.rst, the memory map for 4-level and for 5-level page tables. The module area of a kernel with KASLR is MODULES_VADDR to MODULES_END in arch/x86/include/asm/pgtable_64_types.h.
  11. arch/x86/mm/kaslr.c, function kernel_randomize_memory(), and kaslr_memory_enabled() in arch/x86/include/asm/setup.h.
  12. execmem_arch_setup() in arch/x86/mm/init.c and mm/execmem.c. In Linux 5.15.226 and 6.6.163 the same offset is get_module_load_offset() in arch/x86/kernel/module.c.
  13. Documentation/process/license-rules.rst, the paragraph on user space API headers, and LICENSES/exceptions/Linux-syscall-note, which LICENSES/Linux-syscall-note.txt copies unchanged.

License

Kernel-Linux, Copyright (c) 2024-2026 Ahmet Göker, comes under two licences, because part of it is loaded into the Linux kernel.

The kernel modules are licensed under the GNU General Public License, version 2. These are the seven source files that carry MODULE_LICENSE("GPL"), one in each step directory except 04-kaslr, and the two headers they share with their callers, 03-ioctl/ioctl_driver.h and 07-abi/abi.h. The kernel links a module against many of its functions only when the module declares a GPL-compatible licence. Step 3 uses four such functions, and on a kernel with lockdep every module that takes a mutex uses one more. The text is in LICENSES/GPL-2.0.txt.

The two headers also carry Linux-syscall-note, the exception the kernel puts on its own user space headers so that programs under another licence may include them [13]. That is why the callers test_ioctl.c, ioctl32.c and abi_call.c can include them and stay under CC BY-NC 4.0. Its text is in LICENSES/Linux-syscall-note.txt.

Everything else is licensed under the Creative Commons Attribution-NonCommercial 4.0 International License (CC BY-NC 4.0). That covers this README, the documents, pictures and results under docs/, the lab scripts, the test scripts and the user space programs. The full text is in LICENSE.

You may use, change and share that part for non-commercial purposes, provided you give credit. Credit means naming Ahmet Göker as the author and linking to this repository. Commercial use, such as paid training, needs written permission from the author.

Author

Ahmet Göker, CSINT Research

About

Eight small Linux kernel steps, each tested in QEMU on six kernel releases

Topics

Resources

Stars

4 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages