The user wants a Linux kernel module written in C that adds a new system call.
1. Initial Assessment & Feasibility:
* Can a kernel module add a system call? Technically, yes, but it's highly discouraged and hacky in modern Linux kernels (x86_64 specifically). The system call table is generally read-only (CONFIG_DEBUG_RODATA and friends).
* Why is it hard? The kernel protects the system call table to prevent rootkits. To modify it, you need to disable write protection (CR0 register bit) temporarily.
* Is there a better way? For actual functionality, one would usually write a character device driver (ioctl), a filesystem, or use Netlink sockets. However, the prompt explicitly asks for a system call.
* Context: This is likely an academic exercise or a deep dive into kernel internals. I need to provide a solution that works but also warn heavily about the "right way" to do things in production.
2. Key Technical Components Needed:
* Headers: module.h, kernel.h, init.h, unistd.h, syscalls.h, asm/unistd.h (arch specific).
* Finding the Syscall Table: The symbol sys_call_table is not exported in newer kernels. We need to find its address.
* Method 1 (kallsyms): Use kallsyms_lookup_name. But kallsyms_lookup_name itself stopped being exported in 5.7+!
* Method 2 (kprobes): This is the modern standard way to find unexported symbols. It's a bit complex for a beginner tutorial but necessary for recent kernels (5.7+).
* Method 3 (Manual grep/Boot param): Hardcoding addresses or passing them as parameters. (Brittle).
* Decision: I will use the kprobes method because it's the most robust for modern kernels, but I'll also mention the simpler (older) method or just stick to the modern robust one to avoid code that doesn't compile. Actually, for simplicity in a tutorial, often people assume an older kernel or a kernel where kallsyms_lookup_name is available.
* Refined Decision: I will provide the kprobes technique to find kallsyms_lookup_name, which then finds sys_call_table. This handles the 5.7+ restriction.
* **Disabling Write Protection:**
* Need to access the CR0 register.
* Function `write_cr0(read_cr0() & (~0x10000));` to enable writing.
* Function `write_cr0(read_cr0() | 0x10000);` to disable writing.
* **The System Call Implementation:**
* Standard `asmlinkage long sys_mycall(...)`.
* Use `printk` to prove it ran.
* **Replacing the Entry:**
* Save the original syscall pointer (usually intercepting an existing unused one or an existing one like `sys_getuid` - strictly for demonstration).
* Overwrite the table entry.
* **Restoration:**
* On module exit, put the original pointer back.
3. Structuring the Code:
* *Headers*
* *Global variables:* `sys_call_table` address, original syscall pointer, target syscall number.
* *Helper function:* `kprobes` to get `kallsyms_lookup_name`.
* *CR0 control functions:* `enable_page_rw`, `disable_page_rw`.
* *The new syscall:* `sys_hello_world`.
* *Init function:* Find table, disable protection, swap pointer, enable protection.
* *Exit function:* Disable protection, restore pointer, enable protection.
* *Module Macros:* `module_init`, `module_exit`, `MODULE_LICENSE`.
4. Refining the Specifics (Addressing the "Unused Syscall" vs "Overwrite" issue):
* Adding a brand new syscall number requires recompiling the kernel headers/user-space headers to know about the number.
* The standard "module adds syscall" exercise usually involves hijacking an existing syscall (like mkdir or an unused slot if available).
* Better approach for the user: Hijack an existing, non-critical syscall (e.g., sys_getuid or sys_mkdir) or simply provide a number they can call via syscall().
* Let's choose to hook sys_getuid. It's easy to test. Or, to be less destructive, maybe look for __NR_getuid.
* Actually, finding a free slot is hard because the table is contiguous.
* Safest approach: I will instruct the user to pick a syscall number to override. I will default to __NR_getuid in the example but warn them.
5. Writing the Code (Mental Draft):
```c
#include <linux/module.h>
#include <linux/kprobes.h> // For kallsyms_lookup_name
// Kprobe technique to find kallsyms
static unsigned long (*kallsyms_lookup_name_ptr)(const char *name) = NULL;
// CR0 manipulation
static inline void write_cr0_forced(unsigned long val) {
unsigned long __force_order;
asm volatile("mov %0, %%cr0" : "+r"(val), "+m"(__force_order));
}
static void enable_write_protection(void) { write_cr0_forced(read_cr0() | 0x10000); }
static void disable_write_protection(void) { write_cr0_forced(read_cr0() & ~0x10000); }
// The hook function
asmlinkage long my_syscall(void) {
printk("I am the new syscall!\n");
return 0;
}
// init:
// 1. register kprobe to get kallsyms_lookup_name
// 2. lookup sys_call_table
// 3. disable WP
// 4. swap entry
// 5. enable WP
```
6. The User-Space Test Program:
* The user needs to know how to trigger it.
* syscall(SYS_getuid, ...);
7. Constraints & Safety Warnings:
* This is dangerous.
* This is architecture specific (x86_64 only code provided).
* Kernel version dependency (Code might break on 6.x or very old 2.x).
* Mention that ioctl is the "real" way.
8. Drafting the Response:
* Introduction: Acknowledge this is a hack, not production code. Mention the read-only memory protection.
* The Kernel Module Code:
* Use the kprobes trick to get kallsyms_lookup_name (crucial for Kernel 5.7+).
* Use inline assembly to toggle CR0 WP bit.
* Hook sys_getuid as the example target.
* The Makefile: Standard kernel module Makefile.
* Testing: C program using syscall().
* Dmesg: Check output.
Self-Correction/Refinement during drafting:
* Problem: Modifying CR0 directly is often blocked by secure boot or kernel patches (CONFIG_STRICT_KERNEL_RWX).
* Correction: I can't fix Secure Boot in a code snippet. I will assume the user is running a standard environment (like a VM) where they have root and standard kernel.
* Problem: kallsyms_lookup_name is tricky.
* Simplification: Should I just ask the user to grep /proc/kallsyms and hardcode the address? No, that's terrible practice and breaks on reboot. I will stick to the kprobes method. It's cleaner and educational.
* One Catch: CONFIG_KPROBES might not be enabled in the user's kernel. I should mention that.
Final Code Structure Plan:
1. Struct for Kprobe: Define a dummy kprobe to extract kallsyms_lookup_name.
2. CR0 Ops: Functions to disable/enable write protection.
3. Syscall: The new function logic.
4. Init:
* Register kprobe -> get kallsyms_lookup_name.
* Get sys_call_table address.
* Save original syscall (e.g., __x64_sys_getuid or sys_getuid).
* Disable WP -> Replace pointer -> Enable WP.
5. Exit:
* Disable WP -> Restore original -> Enable WP.
Let's refine the "Target Syscall". Overwriting sys_mkdir is a classic. Overwriting sys_getuid is safer for the system (doesn't break filesystem structure if something goes wrong). Let's use sys_getuid (specifically looking for __x64_sys_getuid or the generic wrapper depending on kernel config, actually sys_call_table usually points to the entry point, often __x64_... on modern x86).
Wait, strictly speaking, system call implementations are often named __x64_sys_name. However, sys_call_table entries might point to sys_name or __x64_sys_name depending on how the kernel was compiled (pti, etc). To be safe, I'll just cast the pointer.
Disclaimer: Emphasize that doing this on a production machine is a recipe for a kernel panic.
Let's go.
Adding a system call via a kernel module is a common educational exercise, but it is important to note that modern Linux kernels (x86_64) have strict memory protection. The system call table is located in read-only memory, so simply writing to it will cause a crash (Kernel Oops).
To make this work, we must:
- Disable CPU write protection (CR0 register) temporarily.
- Find the address of the
sys_call_table (which is no longer exported).
- Replace the function pointer.
Warning: This code involves patching active kernel memory. It can destabilize your system. Use a Virtual Machine for testing.
The Kernel Module (syscall_hook.c)
We will "hijack" an existing, less-critical system call. In this example, we will override sys_getuid. This allows us to test it easily from a C user-space program.
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/syscalls.h>
#include <linux/kprobes.h>
#include <asm/unistd.h>
#include <asm/special_insns.h>
// The license must be GPL to use certain kernel functions (like kallsyms_lookup)
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Assistant");
MODULE_DESCRIPTION("A simple example of adding a syscall via module");
MODULE_VERSION("0.1");
// 1. Define the system call number to hijack.
// We use __NR_getuid. You can check available numbers in /usr/include/asm/unistd_64.h
#define SYSCALL_TO_HOOK __NR_getuid
// Pointer to the original system call function
static asmlinkage long (*original_sys_call)(const struct pt_regs *);
// Pointer to the system call table
static unsigned long *sys_call_table;
// 2. The new system call implementation
// Note: modern x86_64 syscalls use pt_regs for arguments.
// arg0 -> di, arg1 -> si, arg2 -> dx, etc.
static asmlinkage long my_syscall(const struct pt_regs *regs)
{
printk(KERN_INFO "my_syscall: Intercepted call to getuid!\n");
// We can return a dummy value to prove we are here.
// Normally, we would forward to the original function:
// return original_sys_call(regs);
return 1337;
}
// 3. Helper to find the system call table address
// Since sys_call_table is not exported, we use kprobes to find it.
static unsigned long *find_syscall_table(void) {
struct kprobe kp = {
.symbol_name = "sys_call_table",
};
if (register_kprobe(&kp) < 0) {
return NULL;
}
unregister_kprobe(&kp);
return (unsigned long *)kp.addr;
}
// 4. Function to disable/enable write protection
static inline void write_cr0_forced(unsigned long val) {
unsigned long __force_order;
asm volatile(
"mov %0, %%cr0"
: "+r"(val), "+m"(__force_order));
}
static void enable_write_protection(void) {
write_cr0_forced(read_cr0() | (1 << 16));
}
static void disable_write_protection(void) {
write_cr0_forced(read_cr0() & ~(1 << 16));
}
// Module initialization
static int __init my_module_init(void) {
printk(KERN_INFO "Syscall Module: Loading...\n");
// Find the table
sys_call_table = find_syscall_table();
if (!sys_call_table) {
printk(KERN_ERR "Syscall Module: Failed to find sys_call_table.\n");
return -1;
}
printk(KERN_INFO "Syscall Module: Found sys_call_table at %p\n", sys_call_table);
// Save the original pointer
original_sys_call = (void *)sys_call_table[SYSCALL_TO_HOOK];
// Disable write protection to modify the table
disable_write_protection();
// Replace the system call
sys_call_table[SYSCALL_TO_HOOK] = (unsigned long)my_syscall;
// Re-enable write protection
enable_write_protection();
printk(KERN_INFO "Syscall Module: Hooked syscall %d\n", SYSCALL_TO_HOOK);
return 0;
}
// Module cleanup
static void __exit my_module_exit(void) {
printk(KERN_INFO "Syscall Module: Unloading...\n");
if (!sys_call_table || !original_sys_call) {
return;
}
// Disable write protection
disable_write_protection();
// Restore the original system call
sys_call_table[SYSCALL_TO_HOOK] = (unsigned long)original_sys_call;
// Re-enable write protection
enable_write_protection();
printk(KERN_INFO "Syscall Module: Restored original syscall.\n");
}
module_init(my_module_init);
module_exit(my_module_exit);
The Makefile
Save this as Makefile in the same directory (case sensitive).
obj-m += syscall_hook.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
The User-Space Test Program (test.c)
This program will trigger our new logic by calling getuid().
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
int main() {
printf("Attempting to call getuid() (which we hooked)...\n");
// This calls the standard C library wrapper,
// which eventually executes the syscall instruction.
uid_t uid = getuid();
printf("Return value received: %d\n", uid);
// If we received 1337, the kernel module worked!
if (uid == 1337) {
printf("Success! The kernel module intercepted the call.\n");
} else {
printf("Failure. Original syscall was executed.\n");
}
return 0;
}
How to Run It
- Compile the Kernel Module:
make
- Compile the Test Program:
gcc test.c -o test
- Load the Module:
(You must be root)
sudo insmod syscall_hook.ko
Check dmesg to see if it loaded successfully and found the table.
- Run the Test:
./test
You should see the return value 1337.
- Check Kernel Logs:
sudo dmesg | tail
You should see "my_syscall: Intercepted call to getuid!".
- Unload the Module:
sudo rmmod syscall_hook
Technical Explanation
- Memory Protection (CR0): The
sys_call_table resides in write-protected memory. If we try to write to it without changing the CR0 register, the CPU will trigger a page fault. We use write_cr0_forced to flip the 16th bit (Write Protect) of the CR0 register off, perform the write, and turn it back on immediately.
- Locating the Table: Newer kernels do not export the symbol
sys_call_table for modules to use directly. We use a kprobe (Kernel Probe) trick. We register a dummy probe looking for the symbol name "sys_call_table"; the kernel looks it up for us and puts the address in kp.addr.
- Argument Passing: On modern x86_64 Linux, system calls do not pass arguments on the stack. They are passed in registers (
rdi, rsi, rdx, etc). The kernel wraps these into a struct pt_regs pointer. That is why our function signature looks different than standard C functions.