Linux Kernel Module Security: Signing, Address Leak Prevention & Hardening

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →
Linux Kernel Module Security: Signing, Address Leaks & Hardening | EmbeddedPathashala

Linux Kernel Module Security
Cryptographic Signing, Address Leak Prevention & Module Hardening — Free Linux Kernel Development Course
Level
Intermediate
Kernel
Linux 6.x
Course
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 %pK and %px printk 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_disabled sysctl
  • What tainted kernels mean and how to interpret them
Prerequisites: Basic understanding of Linux kernel modules, familiarity with 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.

How a Kernel Address Leak Defeats KASLR
📚
Address Leak
printk prints raw pointer or /proc leaks address
→
🧐
KASLR Bypassed
Attacker calculates kernel base address
→
📄
ROP Chain Built
Known gadget offsets now usable for exploit
→
🔒
Kernel Exploited
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 ValueBehavior of %pKRecommended For
0Prints the real address to any userDevelopment only, never production
1Shows real address only to processes with CAP_SYSLOGDefault on most distros
2Always hides the real address from everyoneHigh 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
✅ Tip: After editing /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);
⚠ Warning: Using %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.
Printk Address Specifier Comparison
🔒
%p
Hashed address
Safe for production
No real addr exposed
✅ USE IN PRODUCTION
🔐
%pK
Privilege-sensitive
Controlled by kptr_restrict
Conditional exposure
⚠ USE WITH CARE
🔓
%px
Always real address
Debug only
Bypasses all controls
❌ DEBUG ONLY

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

Kernel Module Signing and Verification Flow
✍ BUILD TIME
1. Compile mydriver.ko
↓
2. Sign with private key
scripts/sign-file
↓
3. Signature appended to .ko file tail
→
📋 LOAD TIME (insmod)
4. Kernel reads .ko file
↓
5. Extracts signature from tail
↓
6. Verifies against public key in kernel keyring
→
✅ / ❌ RESULT
Valid sig → Module loads
No/bad sig + FORCE=y → Load fails
No sig + FORCE=n → Loads but kernel tainted

Kernel 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 OptionTypeWhat It Does
CONFIG_MODULE_SIGBooleanEnables the module signature verification subsystem. Must be set to use any signing feature.
CONFIG_MODULE_SIG_FORCEBooleanWhen 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_ALLBooleanAutomatically signs all built-in modules during make modules_install.
CONFIG_MODULE_SIG_HASHStringSpecifies 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
ℹ Note about Linux 6.x: Starting from Linux 6.3, the kernel introduced improved keyring handling that makes it easier to add custom signing keys via 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
⚠ Important: Once a module is signed, you must not strip it or modify it in any way. Stripping debug symbols after signing will invalidate the signature. Always sign as the very last step in your build pipeline.

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
⚠ This is a one-way operation! Once you write 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.

Recommended Production Kernel Lockdown Sequence
1. Kernel Boots
↓
2. Load All Required Signed Modules
(network drivers, storage, sensors, etc.)
↓
3. Set kptr_restrict=2
Prevent address leaks from proc/sysfs
↓
4. Set modules_disabled=1
No new modules can load for this session
↓
5. System Enters Operational State
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 LetterMeaning
0 (1)PProprietary module loaded
9 (512)EUnsigned module was loaded
11 (2048)OOut-of-tree (externally built) module loaded
12 (4096)FModule 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

✖ Mistake 1: Forgetting to Remove %px from Production Code

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/
✖ Mistake 2: Stripping the Module After Signing

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.

✖ Mistake 3: Setting modules_disabled Too Early

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.

✖ Mistake 4: Using Different Keys for Signing vs Kernel Keyring

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

✅
Always use %p in production

Default hashing protects real addresses while still providing a stable reference for debugging within a session.

✅
Enable module signing in production kernels

Set CONFIG_MODULE_SIG=y and CONFIG_MODULE_SIG_FORCE=y in your production kernel config. Use SHA-512 as the hash algorithm.

✅
Set kptr_restrict=2 on embedded systems

Completely hide kernel addresses from all users including root. Add to /etc/sysctl.conf for persistence.

✅
Lock down module loading post-boot

On fixed-function devices, set modules_disabled=1 after loading all required modules during system initialization.

✅
Review taint flags after loading

Check /proc/sys/kernel/tainted and dmesg after loading your module during development. A tainted kernel in CI is a warning sign.

✅
Use Secure Boot with UEFI

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, %pK with care, and %px only during debugging.
  • Control kptr_restrict via sysctl. Value 2 is 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_SIG enables signing; CONFIG_MODULE_SIG_FORCE=y makes 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/tainted to 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

Q1: Does enabling CONFIG_MODULE_SIG_FORCE break all existing out-of-tree drivers?
Yes, on a kernel with 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.
Q2: Can I add a signing key to a running kernel without rebooting?
Yes, in limited ways. You can use the 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.
Q3: What is the difference between a tainted and a corrupted kernel?
A tainted kernel is still running correctly but has done something that kernel developers prefer not to officially support (like loading a proprietary or unsigned module). It is not broken or corrupt. A corrupted kernel would have memory errors, bad data structures, or be in a crash state. Taint is just a flag for “we know something unusual happened here.”
Q4: How do I disable module signing checks during development without disabling it permanently?
The cleanest approach is to use a development kernel config with 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.
Q5: Is there a way to check whether a .ko file is signed before loading it?
Yes. Use 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.
Q6: Does kptr_restrict affect kernel module authors, or only system administrators?
It affects both. As a module author, you should choose the right format specifier (%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.
Q7: What happens to modules_disabled after a reboot?
The 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.
Q8: How does module signing relate to Secure Boot on embedded ARM systems?
On ARM-based embedded systems with UEFI firmware (increasingly common in modern SoCs), you can chain Secure Boot → signed kernel → signed modules. The firmware verifies the bootloader, the bootloader verifies the kernel, and the kernel verifies the modules. This creates a complete hardware-rooted chain of trust. Module signing is the kernel’s part of that chain.

Official References and Further Reading

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
💬 Need help or career guidance? Ask us!Contact Us →

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →