🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Intermediate
Linux 6.x
Free
Linux Kernel Module Security: Signing, Address Leaks, and Hardening
Security in the Linux kernel is not an afterthought — it is built into the very way the kernel loads and manages modules. If you are learning Linux kernel module programming or working through a free Linux kernel development course, understanding how to secure kernel modules is just as important as writing them. A poorly secured system can allow attackers to inject malicious kernel code, even if they somehow get root access.
This tutorial covers three important security topics you will encounter in any serious Linux device driver development or kernel programming journey: preventing kernel address leaks through printk, cryptographically signing kernel modules, and completely disabling module loading when required.
🎓 What You Will Learn
- Why leaking kernel addresses is a serious security risk
- How
%pKand%pxprintk format specifiers differ and when to use each - How cryptographic module signing works in Linux 6.x
- The role of
CONFIG_MODULE_SIG,CONFIG_MODULE_SIG_FORCE, and related Kconfig options - How to check if your kernel enforces module signing
- How to disable module loading entirely using
modules_disabledsysctl - What tainted kernels mean and how to interpret them
insmod / modprobe, and basic comfort with the Linux command line. It is helpful to have completed earlier lectures on module parameters and printk logging.
Why Kernel Address Security Matters
Every time your kernel module calls printk() to print a pointer address, you are potentially giving an attacker a gift. Kernel virtual addresses are extremely valuable to an attacker because they can be used to bypass modern exploit mitigations like Kernel Address Space Layout Randomization (KASLR).
KASLR randomizes where the kernel image, modules, and data structures are loaded in memory each time the system boots. If an attacker can read a kernel address from a log message, a /proc file, or a /sys entry, they can calculate the base address of the kernel and completely defeat KASLR. This is called a kernel address leak.
printk prints raw pointer or /proc leaks address
Attacker calculates kernel base address
Known gadget offsets now usable for exploit
Privilege escalation or code execution achieved
Printk Format Specifiers for Kernel Addresses
When printing pointer values inside kernel modules, you have three main format specifiers available. Each behaves differently depending on the security context.
The %p Specifier (Hashed by Default)
The plain %p specifier looks harmless, but since around Linux 4.15 it no longer prints the actual address. Instead, the kernel prints a cryptographically hashed representation of the pointer. This prevents address leaks in most scenarios. The hash is stable during a single boot but changes across reboots, so it is not useful to an attacker.
/* In your kernel module - this is SAFE for production */
pr_info("Device structure address: %p\n", dev);
/* Output: something like: Device structure address: 00000000a3b7c291
(hashed, not the real address) */
The %pK Specifier (Privilege-Sensitive)
The %pK specifier was designed to conditionally show real addresses based on user privilege. Its behavior is controlled by the /proc/sys/kernel/kptr_restrict sysctl tunable, which takes three values:
| kptr_restrict Value | Behavior of %pK | Recommended For |
|---|---|---|
0 | Prints the real address to any user | Development only, never production |
1 | Shows real address only to processes with CAP_SYSLOG | Default on most distros |
2 | Always hides the real address from everyone | High security / production embedded systems |
To check the current value on your system:
$ cat /proc/sys/kernel/kptr_restrict
1
To temporarily set it to the most restrictive mode (will reset after reboot):
$ sudo sysctl -w kernel.kptr_restrict=2
To make it permanent, add the following to /etc/sysctl.conf:
# /etc/sysctl.conf - make kptr_restrict permanent
kernel.kptr_restrict = 2
/etc/sysctl.conf, apply the changes immediately with sudo sysctl -p without needing a reboot.
The %px Specifier (Always Shows Real Address)
The %px specifier bypasses all security protections and always prints the actual kernel virtual address, regardless of kptr_restrict or user privilege. This is intentional — it exists for kernel developers who genuinely need to see raw addresses during debugging, with the understanding that these print statements will be removed before the code reaches production.
/* DEBUGGING ONLY - NEVER leave this in production code */
pr_debug("Real pointer for debugging: %px\n", ptr);
%px in production kernel code is a serious security mistake. Any user who can read kernel logs (/dev/kmsg or dmesg) will see the actual address. Always remove %px prints before shipping.
Safe for production
No real addr exposed
Controlled by kptr_restrict
Conditional exposure
Debug only
Bypasses all controls
Cryptographic Signing of Linux Kernel Modules
One of the most powerful security features in modern Linux is the ability to require that kernel modules are cryptographically signed before they can be loaded. If an attacker somehow gains root access, they cannot simply write a malicious .ko file and load it — the kernel will reject any module whose signature cannot be verified against a key in the kernel’s trusted keyring.
This is especially critical for IoT devices and embedded systems where a compromised device could affect thousands of deployed units. Any serious free Linux device drivers course must cover this topic because all drivers you write will eventually need to comply with signing requirements in production environments.
How Module Signing Works
mydriver.koscripts/sign-file.ko file tail.ko fileKernel Configuration Options for Module Signing
Module signing behaviour is entirely controlled by Kconfig options set when compiling the kernel. Here are the key ones you need to know:
| Kconfig Option | Type | What It Does |
|---|---|---|
CONFIG_MODULE_SIG | Boolean | Enables the module signature verification subsystem. Must be set to use any signing feature. |
CONFIG_MODULE_SIG_FORCE | Boolean | When set to y, modules without a valid signature are rejected at load time. When n, unsigned modules still load but mark the kernel tainted. |
CONFIG_MODULE_SIG_ALL | Boolean | Automatically signs all built-in modules during make modules_install. |
CONFIG_MODULE_SIG_HASH | String | Specifies the hash algorithm (e.g., sha256, sha512) used in signing. SHA-512 is preferred for new deployments. |
Checking Module Signing Status on Your System
On any Linux system, you can check whether module signing is enabled and how strictly it is enforced by inspecting the running kernel’s config:
$ grep MODULE_SIG /boot/config-$(uname -r)
CONFIG_MODULE_SIG_FORMAT=y
CONFIG_MODULE_SIG=y
# CONFIG_MODULE_SIG_FORCE is not set
CONFIG_MODULE_SIG_ALL=y
CONFIG_MODULE_SIG_SHA512=y
CONFIG_MODULE_SIG_HASH="sha512"
The line # CONFIG_MODULE_SIG_FORCE is not set tells us that unsigned modules will still load on this system, but they will mark the kernel as tainted. You can verify the taint state at any time:
$ cat /proc/sys/kernel/tainted
512
A non-zero value means the kernel is tainted. Each bit in this number corresponds to a specific reason. Bit 9 (value 512) means an unsigned module was loaded. You can decode all taint flags with:
$ dmesg | grep -i taint
[ 12.345678] mymodule: loading out-of-tree module taints kernel.
[ 12.345689] mymodule: module verification failed: signature and/or
required key missing - tainting kernel
CONFIG_SYSTEM_EXTRA_CERTIFICATE without recompiling the full kernel. This is very useful for embedded product deployments where you maintain your own signing infrastructure.
How to Sign a Kernel Module Manually (Linux 6.x)
The kernel build system provides a script called sign-file for signing individual modules. After building your module, you can sign it as follows:
# Syntax:
# scripts/sign-file <hash_algo> <private_key> <certificate> <module.ko>
# Example: Sign mydriver.ko with SHA-512 using your own key pair
$ /usr/src/linux-$(uname -r)/scripts/sign-file sha512 \
my_signing_key.pem \
my_signing_cert.pem \
mydriver.ko
To generate a signing key pair for development and testing (do not use this for production systems — get a proper key from your PKI infrastructure):
# Generate a private key and self-signed certificate for development
$ openssl req -newkey rsa:4096 -nodes -keyout my_signing_key.pem \
-x509 -days 365 -out my_signing_cert.pem \
-subj "/CN=MyDriver Signing Key/O=EmbeddedPathashala/C=IN"
# Check that your module is signed
$ modinfo mydriver.ko | grep signer
signer: MyDriver Signing Key
Disabling Kernel Module Loading Entirely
For extremely security-sensitive systems — think of an ATM, a medical device, or a satellite controller — even signed module loading might be considered a risk. In these cases, Linux provides two ways to completely shut the door on module loading after the initial boot sequence.
Method 1: Build the Kernel Without Module Support
The most radical approach is to compile the kernel with CONFIG_MODULES set to n. This completely removes the module loading infrastructure from the kernel. All required drivers must be compiled as built-in (y) in the kernel image itself. Once done, insmod and modprobe simply have nothing to do — there is no module loader in the kernel at all.
This is appropriate for deeply embedded systems with a fixed hardware configuration. However, it requires you to know exactly what hardware your system will ever use, and kernel upgrades require a full rebuild.
Method 2: Dynamically Disable Module Loading at Runtime
If your kernel is compiled with CONFIG_MODULES=y but you want to prevent any further module loading after the system has finished booting, you can use the modules_disabled sysctl tunable:
# Check current state (0 = module loading allowed)
$ cat /proc/sys/kernel/modules_disabled
0
# Disable module loading permanently for this boot session
$ sudo sysctl -w kernel.modules_disabled=1
# Verify
$ cat /proc/sys/kernel/modules_disabled
1
1 to modules_disabled, you cannot set it back to 0 without rebooting. The kernel enforces this to prevent an attacker from re-enabling module loading after you have locked it down. Any attempt to run insmod after this will fail with an error.
# After disabling, attempting to load a module fails:
$ sudo insmod mydriver.ko
insmod: ERROR: could not insert module mydriver.ko: Operation not permitted
A common production pattern is to load all required modules in an rc.local script or systemd service during boot, then set modules_disabled=1 as a final security step before the system enters its operational state.
(network drivers, storage, sensors, etc.)
Prevent address leaks from proc/sysfs
No new modules can load for this session
Attacker cannot load kernel code even with root
Understanding Tainted Kernels
A tainted kernel is one where something happened that the kernel developers consider outside the normal supported state. Loading an unsigned or out-of-tree module is the most common cause in embedded development. Understanding kernel taint is important when debugging because kernel maintainers may ask about it when you file a bug report.
The taint value is a bitmask. Here are the most relevant bits for kernel module developers:
| Bit (Value) | Flag Letter | Meaning |
|---|---|---|
| 0 (1) | P | Proprietary module loaded |
| 9 (512) | E | Unsigned module was loaded |
| 11 (2048) | O | Out-of-tree (externally built) module loaded |
| 12 (4096) | F | Module was force-loaded despite warnings |
# Decode taint flags easily on Linux 6.x
$ cat /proc/sys/kernel/tainted
2560
# 2560 = 512 (unsigned module) + 2048 (out-of-tree module)
# This means an out-of-tree unsigned module was loaded
# Alternatively, read the human-readable taint string from dmesg
$ dmesg | grep "Tainted:"
[ 0.000000] Tainted: OE
Common Mistakes and Troubleshooting
Many developers use %px during debugging and forget to remove it. Always audit your module for %px before any production build. A quick check:
$ grep -rn "%px" your_driver_directory/
If your build system strips debug symbols (strip) after you have signed the module, the signature becomes invalid. Always sign as the very final build step, after all stripping is complete.
If you set modules_disabled=1 before all required modules are loaded during boot, your system may fail to function correctly (network might not come up, storage drivers missing, etc.). Verify your full module dependency chain before locking down.
The public key used to verify a module must be embedded in the kernel at build time (via CONFIG_SYSTEM_TRUSTED_KEYS) or added to the keyring at runtime (using the Integrity Measurement Architecture). If there is a key mismatch, the module will not load even if it appears correctly signed.
Security Best Practices for Kernel Module Development
Default hashing protects real addresses while still providing a stable reference for debugging within a session.
Set CONFIG_MODULE_SIG=y and CONFIG_MODULE_SIG_FORCE=y in your production kernel config. Use SHA-512 as the hash algorithm.
Completely hide kernel addresses from all users including root. Add to /etc/sysctl.conf for persistence.
On fixed-function devices, set modules_disabled=1 after loading all required modules during system initialization.
Check /proc/sys/kernel/tainted and dmesg after loading your module during development. A tainted kernel in CI is a warning sign.
On x86 systems, combine kernel module signing with UEFI Secure Boot for a complete chain of trust from firmware to module.
Summary and Key Takeaways
- Kernel address leaks can defeat KASLR. Use
%p(hashed) by default,%pKwith care, and%pxonly during debugging. - Control
kptr_restrictvia sysctl. Value2is the most restrictive and is recommended for production embedded systems. - Cryptographic module signing (enabled since kernel 3.7) prevents loading of untrusted kernel modules even by root.
CONFIG_MODULE_SIGenables signing;CONFIG_MODULE_SIG_FORCE=ymakes it mandatory — unsigned modules will be rejected.- A tainted kernel indicates that something non-standard happened (unsigned module, out-of-tree module, etc.). Check
/proc/sys/kernel/taintedto decode. - You can completely disable module loading at runtime with
sysctl -w kernel.modules_disabled=1. This is a one-way operation per boot session. - Always sign your module as the very last build step, after all stripping is done.
Frequently Asked Questions
CONFIG_MODULE_SIG_FORCE=y, any module that is not signed with a key trusted by the kernel will fail to load. You must sign all your out-of-tree drivers using your own signing key pair, and enrol that key into the kernel’s trusted keyring during build time.keyctl tool or IMA (Integrity Measurement Architecture) to add keys to the session keyring. However, adding keys to the system trusted keyring requires kernel configuration at build time. The runtime approach is suitable for development but not for enforced production security.CONFIG_MODULE_SIG_FORCE=n. Unsigned modules will still load but taint the kernel. Alternatively, you can use CONFIG_MODULE_SIG=n in your development kernel — just never use that kernel config in production.modinfo to inspect the module: modinfo mydriver.ko | grep -E "signer|sig_key|sig_hashalgo". If the signer field is present, the module has been signed. If not, the module is unsigned.%p vs %pK vs %px) in your code. As a system administrator, you set the kptr_restrict value to control what your %pK calls actually reveal at runtime.modules_disabled sysctl resets to 0 (module loading allowed) on every reboot. It is an in-memory setting that is not persistent. If you want it set on every boot, you must add it to your system initialization scripts or a systemd service that runs after all required modules are loaded.Official References and Further Reading
- Linux Kernel Module Signing Documentation (kernel.org)
- Printk Format Specifiers Reference (kernel.org)
- Linux Kernel Sysctl Parameters (kernel.org)
- Linux Kernel Key Management (kernel.org)
Continue Your Free Linux Kernel Development Journey
EmbeddedPathashala offers a completely free Linux kernel programming course covering everything from writing your first module to advanced device driver security. Join thousands of students preparing for embedded systems careers.
Explore Free Courses