Linux Kernel Module Security and Prevention of Information Leaks

🚀 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: dmesg_restrict, kptr_restrict and Preventing Info Leaks – Free Linux Kernel Course | EmbeddedPathashala

FREE LINUX KERNEL DEVELOPMENT COURSE — EmbeddedPathashala

Linux Kernel Module Security: Preventing Info Leaks with dmesg_restrict, kptr_restrict, and %pK

Learn how kernel address exposure leads to privilege escalation attacks and how to write kernel modules that are secure by design — updated for Linux 6.x

Level
Intermediate
Kernel
Linux 6.x
Topic
Kernel Security

Linux Kernel Module Security — dmesg_restrict, kptr_restrict, and Stopping Information Leaks

Security in the Linux kernel is not just the job of the security team. As a kernel module developer, every line of code you write runs with full kernel privileges. A careless printk() call that prints a kernel address could give an attacker the information they need to compromise the entire system. This lecture in our free Linux kernel development course explains the modern Linux kernel security model around information leaks, how the dmesg_restrict and kptr_restrict tunables work, and what you must do in your kernel modules to keep kernel addresses private.

What You Will Learn

  • Why kernel-space attacks are increasing even as user-space security improves
  • What an information leak (info-leak) is in the Linux kernel context
  • How exposing a single kernel address enables privilege escalation attacks
  • What dmesg_restrict does and how to configure it
  • What kptr_restrict does and the three levels of protection it provides
  • Why you must never use %p or %px to print kernel addresses in production modules
  • How to use %pK safely in your kernel module’s printk statements
  • POSIX capabilities relevant to kernel log access (CAP_SYSLOG)
  • A complete secure-by-default checklist for kernel module developers

Prerequisites

  • Understanding of Linux kernel modules (init/exit, printk)
  • Familiarity with basic Linux security concepts (root, users, permissions)
  • Basic knowledge of virtual memory — what a kernel virtual address is
  • The previous lecture on module autoloading is helpful but not required

Why Kernel Security Has Become the Attacker’s Preferred Target

Over the past two decades, an enormous amount of engineering effort went into securing user-space programs. Techniques like Address Space Layout Randomization (ASLR), stack canaries, non-executable memory (NX/XD), and various compiler hardening flags made it dramatically harder to exploit user-space programs through classical techniques like buffer overflows.

The irony is that this success in user-space security pushed attackers toward the kernel instead. Kernel-space attacks have risen sharply because the kernel runs with full privileges — a single successful exploit gives an attacker complete control over the entire machine. There is no privilege boundary to escape from once you are in the kernel.

The Shift: From User-Space Exploits to Kernel-Space Attacks
PAST (Pre-2010)
🎯 Main Target
User-space programs
Common Attacks
Stack buffer overflows, heap exploits, format string bugs
User-space is now well defended
ASLR + NX + Stack canaries + compiler hardening
→
NOW (Modern Linux)
🎯 New Target
Kernel space — drivers, modules, syscalls
Why?
Successful exploit = root access + no privilege boundary to escape
Key enabler: Info Leaks
A single kernel address leak can defeat KASLR entirely

What Is KASLR and Why Does It Matter?

KASLR stands for Kernel Address Space Layout Randomization. Just like ASLR randomizes where user-space programs are loaded in memory, KASLR randomizes where the kernel itself is loaded in physical and virtual memory at every boot. An attacker who wants to exploit a kernel vulnerability must first know the address of specific kernel functions and data structures. KASLR defeats this by making those addresses unpredictable.

The critical point is this: KASLR is only effective if kernel addresses are never leaked to unprivileged users. If your kernel module prints a kernel address in a log message that an unprivileged user can read, KASLR’s protection collapses entirely. The attacker reads the leaked address, computes the kernel’s base load address, and can now target any other kernel structure with precision.

🔴 Critical Security Rule: Never print a kernel virtual address where an unprivileged user can see it. A single leaked address is all an attacker needs to defeat KASLR and enable a full privilege escalation attack.

What Is a Kernel Information Leak?

A kernel information leak (commonly shortened to “info-leak”) happens when kernel-private data — especially kernel virtual addresses — becomes visible to users who should not have access to it. The most common channel for these leaks in kernel modules is the kernel log, which is accessible via the dmesg command and through /proc/kmsg.

When a kernel module uses printk() to print a variable’s address for debugging purposes, that address goes into the kernel ring buffer. By default on many Linux systems, any user can read the kernel ring buffer using dmesg. This means that a debug printk you added to your driver — even something completely innocent-looking — can expose kernel addresses to any user on the system.

How a Kernel Address Leak Enables Privilege Escalation
/* Innocent-looking debug printk in your module: */
printk(KERN_INFO “buffer at %p\n”, buf);
⬇ Kernel ring buffer stores the address
[ 1234.567890] buffer at 0xffff888012345678
Attacker reads dmesg (no root required by default)
$ dmesg | grep buffer
Attacker computes kernel base address
kernel_base = leaked_addr − known_offset
💥 KASLR Defeated → Privilege Escalation Attack Possible

Understanding dmesg_restrict — Controlling Who Can Read the Kernel Log

The dmesg_restrict tunable is a kernel security setting that controls which users are allowed to read the kernel ring buffer (the log that dmesg reads from). It lives at:

/proc/sys/kernel/dmesg_restrict

This file accepts two values:

ValueMeaningSecurity Level
0 (default on many distros) Any user can read the kernel log via dmesg ❌ Insecure — permits info leaks
1 Only users with CAP_SYSLOG capability (typically root) can read the kernel log ✅ Secure — required for production
# Check current value
cat /proc/sys/kernel/dmesg_restrict

# Set it to restricted (secure) — immediately, without reboot
sudo sysctl -w kernel.dmesg_restrict=1

# Make it permanent across reboots
echo "kernel.dmesg_restrict=1" | sudo tee -a /etc/sysctl.d/99-kernel-security.conf
sudo sysctl -p /etc/sysctl.d/99-kernel-security.conf

The CAP_SYSLOG Capability

Linux uses the POSIX capabilities model to grant specific privileges to processes without giving them full root access. When dmesg_restrict=1, reading the kernel log requires the CAP_SYSLOG capability. A process with CAP_SYSLOG can read and clear the kernel ring buffer and perform other privileged log operations. Traditional root processes have all capabilities by default, including CAP_SYSLOG.

The broader CAP_SYS_ADMIN capability is a catch-all for system administration operations and effectively grants nearly root-level access. On a hardened production system, running processes with the minimum required capabilities — rather than full root — follows the principle of least privilege.

📌 Note: On Ubuntu 24.04 and recent Fedora versions, the default value of dmesg_restrict may vary depending on the distribution’s security profile. On high-security configurations like those derived from CIS benchmarks, it is typically set to 1. Always verify with cat /proc/sys/kernel/dmesg_restrict on your target system.

Understanding kptr_restrict — Hiding Kernel Addresses in printk Output

Even with dmesg_restrict=1, root users can still read the kernel log. If your module prints kernel addresses, those addresses are visible to root. While root access is already trusted, there are security scenarios where you want to limit address exposure even from privileged logs — for example, when debugging output ends up in crash dumps that might be sent to vendors.

More importantly, kptr_restrict protects against cases where kernel addresses are exposed through /proc files and sysfs files — not just dmesg. The tunable is at:

/proc/sys/kernel/kptr_restrict

It has three possible values:

ValueBehaviour for %pKUse Case
0 %pK behaves exactly like %p — prints the real address always Development only — not for production
1 (default on modern distros) Prints real address only for processes with CAP_SYSLOG; others see 0x0000000000000000 ✅ Good default for most production systems
2 Always prints 0x0000000000000000 — even for root — for any address printed with %pK Maximum security — for highly sensitive deployments
# Check current value
cat /proc/sys/kernel/kptr_restrict

# Set to level 1 (recommended for most systems)
sudo sysctl -w kernel.kptr_restrict=1

# Set to maximum security level 2
sudo sysctl -w kernel.kptr_restrict=2

# Make permanent
echo "kernel.kptr_restrict=2" | sudo tee -a /etc/sysctl.d/99-kernel-security.conf

The Correct Way to Print Kernel Addresses: %pK, %p, and %px

This is where your responsibility as a kernel module developer begins. The kptr_restrict tunable is only effective if you use the right format specifier in your printk() calls. The kernel provides three relevant format specifiers for printing pointer values:

Kernel Address Format Specifiers — Which One to Use?
%p
❌ DO NOT USE in modules
  • In Linux 4.15+, deliberately prints a hashed pointer value, not the real address
  • Hash is consistent within one boot but not the real address
  • Useless for debugging, still confusing
  • Never rely on this for meaningful output
%px
⚠️ Development use only
  • Always prints the real kernel address
  • Bypasses kptr_restrict entirely
  • Useful during development and debugging
  • Must be removed or replaced with %pK before production
%pK
✅ Always use in production modules
  • Respects the kptr_restrict sysctl tunable
  • Automatically hides address from unprivileged users
  • Prints real address only to users with CAP_SYSLOG
  • The correct choice for any permanent kernel address logging

Practical Code: Using %pK in Your Kernel Module

The change required in your module code is minimal. Here is a comparison of insecure versus secure kernel address printing:

/* ========================================================
 * INSECURE — Do NOT use this in a production kernel module
 * %p in Linux 4.15+ prints a hashed value (not the real address)
 * %px always prints the real address, bypassing kptr_restrict
 * ======================================================== */
static int __init mydriver_init(void)
{
    void *my_buffer;

    my_buffer = kmalloc(256, GFP_KERNEL);
    if (!my_buffer)
        return -ENOMEM;

    /* ❌ WRONG: %p prints hash, %px leaks real address */
    pr_info("Buffer allocated at: %p\n", my_buffer);   /* hashed, useless */
    pr_info("Buffer allocated at: %px\n", my_buffer);  /* real addr, leaks! */

    return 0;
}
/* ========================================================
 * SECURE — Use %pK for printing kernel addresses
 * kptr_restrict controls who sees the real address
 * ======================================================== */
static int __init mydriver_init(void)
{
    void *my_buffer;

    my_buffer = kmalloc(256, GFP_KERNEL);
    if (!my_buffer)
        return -ENOMEM;

    /* ✅ CORRECT: %pK respects kptr_restrict sysctl */
    pr_info("Buffer allocated at: %pK\n", my_buffer);
    /*
     * With kptr_restrict=0: prints real address (dev use)
     * With kptr_restrict=1: prints real addr only for CAP_SYSLOG holders
     * With kptr_restrict=2: always prints 0x0000000000000000
     */

    return 0;
}
📌 Linux 4.15+ Change — %p Now Hashes Addresses: Starting from Linux kernel 4.15, using plain %p in printk() for a pointer no longer prints the actual kernel address. Instead, the kernel prints a hash of the address that is consistent within one boot session but different across reboots. This was an important security improvement that prevents accidental address leaks via %p. If you need the real address (for debugging), use %px temporarily, then switch to %pK for production.

Other Secure Pointer Format Specifiers in Linux 6.x

The kernel’s printk format subsystem provides several other security-aware pointer format specifiers beyond %pK:

SpecifierOutputUse Case
%pKAddress, restricted by kptr_restrictGeneral kernel addresses in printk
%pSSymbol name + offset (e.g., myfunction+0x14/0x40)Printing function pointers with symbol resolution
%pBSymbol name with best-effort backtracingStack traces
%pxAlways prints real address (bypasses restrictions)Development/debugging only — remove before production
%pHashed address (not the real address, since Linux 4.15)Not useful — avoid

The Two Key Security Tunables: A Combined View

Together, dmesg_restrict and kptr_restrict form a two-layer defence against kernel address exposure. Understanding how they interact is important when configuring a production Linux system or evaluating the security posture of an embedded product.

Two-Layer Kernel Address Leak Prevention
LAYER 1 — dmesg_restrict: Who can read the kernel log at all?
= 0 (default, insecure)
Any user can run dmesg and see all kernel log output including any addresses logged by modules
= 1 (secure)
Only users with CAP_SYSLOG can read kernel log. Unprivileged users cannot access dmesg at all
LAYER 2 — kptr_restrict: What does an authorized reader see?
= 0 (insecure)
%pK prints real address for everyone
= 1 (recommended)
%pK prints real addr only to CAP_SYSLOG holders
= 2 (maximum)
%pK always shows 0x0 — even to root

User-Space Security Hardening vs Kernel Security — What Has Changed

It is worth understanding why kernel security is now the harder problem. The following table summarises the major user-space hardening techniques that are now standard, and why they have driven attackers toward the kernel.

User-Space Hardening TechniqueWhat It PreventsKernel Equivalent
ASLR (Address Space Layout Randomization)Stack/heap address predictionKASLR (defeated by info-leaks)
NX / XD (Non-Executable Memory)Code injection into data regionsSMEP / SMAP prevent userspace code execution in kernel mode
Stack canaries (-fstack-protector)Stack buffer overflow exploitationKernel stack protector (CONFIG_STACKPROTECTOR)
RELRO (Relocation Read-Only)GOT/PLT overwrite attacksKernel read-only data sections
FORTIFY_SOURCEBuffer overflow in C stdlib functionsKernel hardened usercopy (CONFIG_HARDENED_USERCOPY)
Compiler sanitizers (ASAN, UBSAN)Memory bugs during testingKASAN, KUBSAN, KMSAN for kernel
Static analysis (clang-tidy, sparse)Code-level bugs before runtimesparse, coccinelle, smatch for kernel code

The kernel has equivalents for most user-space hardening mechanisms. But these kernel mechanisms are only effective when developers use them — and when they do not accidentally undermine them through careless coding, such as printing kernel addresses with %px in production code.

Kernel Module Security Best Practices Checklist

✅ 1. Use %pK for Every Kernel Address in printk

Replace every occurrence of %p or %px with %pK when printing kernel addresses. Audit your module for any printk or pr_* calls that print pointer values before releasing to production.

✅ 2. Set dmesg_restrict=1 on Production Systems

Configure /proc/sys/kernel/dmesg_restrict = 1 via sysctl.d on all production and embedded systems. This ensures unprivileged users cannot read the kernel log even if a module accidentally prints an address with the wrong format specifier.

✅ 3. Set kptr_restrict=1 (or 2) on Production Systems

Configure /proc/sys/kernel/kptr_restrict = 1 at minimum on all production systems. For maximum security in sensitive deployments, set it to 2. Add both sysctl settings to a file in /etc/sysctl.d/ to make them persistent.

✅ 4. Remove or Conditionalize All Debug Printks Before Production

Debug printk statements that print addresses should either be removed or wrapped in a #ifdef DEBUG block. Consider using the kernel’s dynamic debug facility (pr_debug() with CONFIG_DYNAMIC_DEBUG) instead of unconditional pr_info() for address printing during debugging phases.

✅ 5. Use the Kernel’s Static Analysis Tools During Development

Build your module with sparse (make C=1 or make C=2) to catch type-safety issues, potential info-leaks through incorrect pointer handling, and other common kernel coding mistakes. The kernel’s “better Makefile” approach includes static analysis targets as part of the standard build.

✅ 6. Never Expose Kernel Addresses in sysfs or proc Files

If your module creates /proc or /sys entries that display information, never output raw kernel addresses in those files. Use %pK if you must output an address, or better yet, output only the information the userspace consumer actually needs (e.g., a device ID or size) without exposing any kernel memory addresses at all.

⚠️ Real-World Example: Many historical Linux kernel CVEs (Common Vulnerabilities and Exposures) involved kernel address leaks through /proc files, sysfs attributes, or kernel log messages. Bugs like these have been used in privilege escalation exploits on Android devices, desktop Linux systems, and embedded products. Your module is part of the kernel’s security boundary — treat it accordingly.

Common Mistakes and How to Avoid Them

❌ “I only use %p so it is safe”

Not quite. In Linux 4.15+, %p prints a hashed value rather than the real address, which is better than %px, but it is still not the right choice. The hash is deterministic within a single boot, which can still give an attacker useful correlation information in some scenarios. Always use %pK which properly respects the kptr_restrict policy.

❌ “kptr_restrict is set to 1, so my module is automatically safe”

kptr_restrict only protects addresses printed with %pK. If your code uses %px, the restriction is completely bypassed and the real address is always printed. The sysctl setting and the format specifier must both be correct for protection to work.

❌ “My module only runs on an embedded device with no external access, so security does not matter”

Local privilege escalation is a real concern even on embedded devices. Many embedded products have multiple user accounts with different privilege levels, or run untrusted code in constrained user-space environments. A privilege escalation exploit can allow an attacker with limited access to gain full control of the device — breaking product security guarantees and potentially enabling firmware manipulation.

Key Takeaways

  • Info-Leak Exposing even a single kernel virtual address to an unprivileged user can defeat KASLR and enable privilege escalation attacks.
  • dmesg_restrict Controls whether unprivileged users can read the kernel log. Set to 1 on all production systems.
  • kptr_restrict Controls what kernel addresses look like when printed. Set to 1 or 2 on production systems. Only effective when modules use %pK.
  • %pK The correct format specifier for printing kernel addresses in any permanent kernel module code. Respects kptr_restrict policy automatically.
  • %px Always prints the real address — bypasses all restrictions. Development use only. Must never appear in production kernel module code.
  • The Linux 4.15 change made %p print a hashed value instead of the real address — this is better than before, but %pK is still the correct choice.
  • As a kernel module developer, you are part of the system’s security boundary. Security is your responsibility, not just the security team’s.

Frequently Asked Questions

Q1: What is the difference between dmesg_restrict and kptr_restrict in Linux?

dmesg_restrict controls which users can read the kernel ring buffer (the output of the dmesg command). Setting it to 1 restricts kernel log access to users with the CAP_SYSLOG capability. kptr_restrict controls how kernel addresses are displayed when a module uses the %pK format specifier in printk(). Both work together: dmesg_restrict restricts who can read the log at all, while kptr_restrict controls what addresses look like in that log for authorized readers.

Q2: Why is printing a kernel address with %p dangerous in Linux?

Linux uses KASLR (Kernel Address Space Layout Randomization) to load the kernel at a random address in memory at each boot, making it harder for attackers to exploit kernel vulnerabilities because they cannot predict where key kernel structures are located. If a kernel address is leaked to an unprivileged user — for example through a dmesg output — the attacker can compute the kernel’s base load address and defeat KASLR entirely, enabling precision attacks on kernel data structures.

Q3: What does %pK do differently compared to %p and %px in kernel printk?

%p in Linux 4.15+ prints a hashed value that is not the real address. %px always prints the real kernel address, bypassing all security restrictions — it should only be used during development. %pK respects the kptr_restrict sysctl: at level 0 it behaves like %px; at level 1 it prints the real address only to users with CAP_SYSLOG and zeros for others; at level 2 it always prints all zeros. Always use %pK in production kernel module code.

Q4: How do I make kptr_restrict persistent across reboots?

Create a file in /etc/sysctl.d/, for example /etc/sysctl.d/99-kernel-security.conf, and add the line kernel.kptr_restrict = 1 (or 2 for maximum security). Then run sudo sysctl -p /etc/sysctl.d/99-kernel-security.conf to apply immediately. On the next boot, systemd’s sysctl service will apply the setting automatically from this file.

Q5: What is the CAP_SYSLOG capability and who has it?

CAP_SYSLOG is a POSIX capability in the Linux capabilities model that grants a process the right to perform privileged kernel log operations, including reading the ring buffer when dmesg_restrict=1. By default, the root user and processes running with full root privileges have all capabilities including CAP_SYSLOG. Non-root users do not have this capability unless it is explicitly granted to them via tools like capsh or setcap.

Q6: If I set kptr_restrict=2, will my kernel module still work correctly?

Yes, kptr_restrict=2 only affects how kernel addresses are displayed in printk output. It has no effect on the actual kernel address values in memory or on your module’s operation. Your module allocates memory and uses pointers exactly as normal — the restriction only applies to the string representation when you use pr_info("addr: %pK\n", ptr). With level 2, that output will show 0x0000000000000000 instead of the real address, but ptr itself holds the correct value in your code.

Q7: Does kptr_restrict protect addresses in /proc and /sys files too?

Yes. The kptr_restrict protection applies whenever the %pK format specifier is used in kernel code — whether that is in a printk() call, in a /proc file’s read handler using seq_printf(), or in a sysfs attribute’s show() function. As long as kernel developers use %pK consistently, kptr_restrict protects all these output paths uniformly.

Q8: What is SMEP and SMAP and how do they relate to kernel module security?

SMEP (Supervisor Mode Execution Prevention) and SMAP (Supervisor Mode Access Prevention) are hardware-level CPU features that add important boundaries between user space and kernel space. SMEP prevents the kernel from executing code located in user-space memory pages — stopping attacks where an attacker places shellcode in user space and tricks the kernel into running it. SMAP prevents the kernel from accessing user-space memory at all without explicitly enabling it first, closing another class of privilege escalation attacks. These are hardware enforced on modern x86 and ARM64 CPUs and are enabled by default in the Linux kernel on supported hardware.

Conclusion

Kernel module security is not an optional add-on — it is a fundamental responsibility that every developer must take seriously. The two security tunables covered in this lecture, dmesg_restrict and kptr_restrict, give system administrators powerful controls over kernel address visibility. But these controls are only as strong as the kernel code that uses them. If your module bypasses them with careless use of %px, or exports kernel addresses through proc files without restriction, no system-level tuning can protect against the resulting information leak.

The discipline of using %pK instead of %p or %px, removing debug printks before production, and configuring the correct sysctl values on deployment targets is a small price to pay compared to the damage that a successful kernel privilege escalation can cause — especially in an embedded product shipped to millions of devices.

In your future kernel module development career, treat every printk() involving a pointer as a potential security decision, and choose the right format specifier for the right context.

Build Your Linux Kernel Skills — Completely Free

EmbeddedPathashala provides free, industry-aligned courses on Linux kernel module development, Linux device drivers, Bluetooth/BLE stack programming, and embedded systems for engineers and students.

Visit EmbeddedPathashala
💬 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 →