We are going to create a simple kernel module that adds a new system call.
Steps:
- Check the kernel version and architecture (we assume x86_64 for simplicity, but we'll try to be generic where possible).
- We note that in modern kernels (since 3.8), adding a system call involves:
- Adding an entry in the syscall table (arch/x86/entry/syscalls/syscall_64.tbl for x86_64).
- Providing a function that implements the system call.
- However, note that in recent kernels, it is discouraged to add new system calls and instead use existing ones or other interfaces.
- But for educational purposes, we'll proceed.
However, note that directly modifying the kernel source and recompiling is one way, but we want a module that does this at runtime?
Actually, a module cannot modify the syscall table in a clean way because the syscall table is in read-only memory (on x86_64, it's in the .rodata section).
We would have to change the page permissions to write, then change the entry, then restore permissions. This is highly architecture-specific and dangerous.
Alternatively, we can use a technique that involves hooking the syscall table by overwriting the read-only memory. But note that this is not safe and may break with kernel updates.
Since the problem says "Develop a kernel module in C that adds a new system call", and given the constraints, we have two options:
Option 1: Modify the kernel source and recompile (not a module, but a kernel change).
Option 2: Write a module that patches the syscall table at runtime (using techniques like writing to the syscall table after making the page writable).
However, note that the kernel may have protection mechanisms (like KPROBES, or the syscall table being in read-only memory) that prevent this.
Let me clarify: the typical way to add a system call without modifying the kernel source and recompiling is to use a kernel module that:
a) Finds the address of the syscall table (usually by looking at the symbol sys_call_table).
b) Changes the page permissions of that memory to writable.
c) Writes the address of our new system call function into the appropriate entry in the table.
But note: in recent kernels, the sys_call_table symbol is not exported (it's hidden). So we cannot simply use it from a module.
Alternatively, we can use kallsyms to get the address (if kallsyms is enabled and we have permission). But again, in production kernels, kallsyms might not be accessible.
Given the complexity and the fact that it's highly dependent on the kernel version and configuration, and that it's generally considered bad practice, we will do the following:
We will write a module that tries to:
- Locate the sys_call_table (by searching for the sys_close system call address in the kernel memory? or by using kallsyms if available).
- Change the write protection of the page containing the syscall table entry we want to modify.
- Replace the old function pointer with our function.
- Restore the write protection.
But note: the syscall table is an array of function pointers, and we are going to replace one of them.
However, the problem says "adds a new system call", which implies we need to assign a new syscall number. But the syscall table is fixed in size and the numbers are fixed by the kernel.
So what we can do is replace an existing system call (like a dummy one) or use an unused slot. But finding an unused slot is difficult because the table is full.
Alternatively, we can try to extend the table? That would require moving the table and updating the NR_syscalls constant, which is not feasible without recompiling the kernel.
Therefore, the practical way to "add" a system call via a module is to replace an existing one (and hope the original one is not used). This is called "hooking".
But the problem says "add", so let's assume we are allowed to replace an existing one (for example, we replace a system call that we know is not used, or we replace one that we are going to use and then restore it on module unload).
However, note that the system call number is fixed. We cannot add a new number without changing the kernel's syscall table size and the NR_syscalls macro.
So let's change the plan: we will replace an existing system call (say, sys_getpid) with our function, and then in our function we can do what we want and then optionally call the original if needed.
But note: the problem says "add", meaning we want a new system call number? Or just a new function that can be called via a system call?
Since we cannot add a new number without recompiling, we'll have to use an existing number. So we are really "replacing" an existing system call.
However, the problem might be interpreted as: we are going to create a new system call and assign it a number that is currently unused? But the kernel does not have unused numbers in the table.
Wait: the syscall table for x86_64 has 448 entries (as of kernel 5.x) and the maximum is defined by __NR_syscalls. There might be unused numbers at the end? Let's check:
In arch/x86/entry/syscalls/syscall_64.tbl, the last entry is 448? Actually, the last entry is 448 and the numbers are consecutive? Not necessarily, but in practice they are.
But even if there is an unused number, the kernel's syscall table is an array of size __NR_syscalls, and if we try to call a system call with a number beyond __NR_syscalls, the kernel will return -ENOSYS.
So we must have the number within the table. Therefore, we cannot add a new number without changing the __NR_syscalls and the table.
Given the complexity, we will do the following:
We will assume that we are going to replace an existing system call (for example, sys_getpid) with our own function, and we will do so by:
- Finding the address of the sys_call_table.
- Changing the write permission of the page that contains the entry for the system call we want to replace.
- Overwriting the function pointer in the table with our function.
- On module unload, we restore the original function pointer and the page permissions.
But note: the sys_call_table is an array of unsigned long (or function pointers) and each entry is 8 bytes on x86_64.
However, the kernel may have changed the type of the syscall table. In recent kernels, it's const sys_call_ptr_t * (which is a function pointer type). But in memory, it's just an array of addresses.
Steps for the module:
a. We need to get the address of sys_call_table. We can use kallsyms if available and if we have CAP_SYS_ADMIN, or we can search for the sys_close address and then calculate the offset.
b. We need to change the page protection. We can use write_cr0 to toggle the WP bit? Or use set_memory_rw and set_memory_ro from <linux/mm.h>. But note: these functions are exported? They are in newer kernels.
c. We must be cautious about the CPU we are running on (only one CPU at a time?).
d. We must disable preemption when changing the syscall table? The kernel does that when it updates the table.
e. We must also consider that the syscall table might be in a read-only section and we are going to change it.
Given the above, let's write a module that hooks the getpid system call (sys_getpid) and replaces it with our own.
Steps:
-
Define our new system call function (with the same signature as the original).
-
Find the address of the sys_call_table.
-
Find the address of the original sys_getpid (by reading the sys_call_table at the index of __NR_getpid).
-
Change the page permissions of the page containing the sys_call_table[NR_getpid] to writable.
-
Replace sys_call_table[NR_getpid] with our function.
-
Restore the page permissions.
-
On module exit, do the reverse: make the page writable, restore the original function, and then make it read-only.
However, note that the sys_call_table might be spread across multiple pages? We assume one page, but it's 8*448=3584 bytes, which is 3.5 pages (4KB pages). So it might span multiple pages.
We must change the permissions of every page that contains the entry we are modifying.
But note: the sys_call_table is contiguous? Yes, it's an array. So we need to change the permissions for each page that contains the entry we are modifying.
Alternatively, we can change the entire table to be writable? But that's more risky.
Let's do:
- Calculate the start and end of the memory region that contains the entry we want to modify (aligned to page boundaries).
- Change each page to RW, then change the entry, then change back to RO.
However, note that the table might be in a section that is shared with other read-only data? We must be cautious.
Alternatively, we can use set_memory_rw and set_memory_ro for the entire range of the sys_call_table? But we don't know the size of the table.
We can get the size by NR_syscalls * sizeof(void *). But we don't know the exact NR_syscalls at runtime? We can get it from the syscall table? Actually, the table is of size NR_syscalls.
But note: the table is defined as sys_call_ptr_t sys_call_table[__NR_syscalls] and __NR_syscalls is a constant.
We can get the NR_syscalls from the kernel's NR_syscalls symbol? It's not exported. So we have to know the size for our kernel version.
For x86_64, as of kernel 5.4, __NR_syscalls is 448.
But it's better to get it from the kernel's syscall_table_size? Actually, there is no such symbol.
Alternatively, we can calculate the size by:
size = (unsigned long)sys_call_table_end - (unsigned long)sys_call_table;
But sys_call_table_end is not exported either.
So we have to hardcode the number of syscalls for our kernel version? That's not portable.
Given the complexity, let's assume we are going to change only the page that contains the entry we are interested in.
Steps:
- Get the address of the sys_call_table (via kallsyms or by searching for sys_close).
- Get the index of the system call we want to replace (__NR_getpid).
- Calculate the address of the entry: entry_addr = (unsigned long *)((unsigned long)sys_call_table + (__NR_getpid * sizeof(void *)));
- Change the page permissions of the page containing entry_addr to RW.
- Write our function pointer to entry_addr.
- Change the page permissions back to RO.
But note: the sys_call_table might be in a section that is mapped as read-only, and we are changing only the page that contains the entry. This might be safe if the entry is the only thing we change on that page.
However, the table is an array and consecutive entries are on the same page until we cross a page boundary.
Since we are only changing one entry, we only need to change the page that contains that entry.
But what if the entry is at the boundary of two pages? Then we must change two pages.
Let's do:
start_page = entry_addr & PAGE_MASK;
end_page = (entry_addr + sizeof(void *) - 1) & PAGE_MASK;
Then iterate from start_page to end_page by PAGE_SIZE.
How to change the page permissions?
We can use:
#include <linux/mm.h>
set_memory_rw(start_page, 1);
set_memory_ro(start_page, 1);
But note: set_memory_rw and set_memory_ro are exported in newer kernels (since 4.11?).
If we are on an older kernel, we might have to change the page table entries directly (using write_cr0 and __flush_tlb_one).
However, for simplicity, we assume a recent kernel (>=4.11) and that set_memory_rw and set_memory_ro are available.
Steps for the module:
-
Include necessary headers.
-
Define our new system call function.
-
In module init:
a. Find sys_call_table.
b. Save the original function pointer at the index we want to replace.
c. Change the page permissions of the page(s) containing the entry to RW.
d. Write our function pointer.
e. Change the page permissions back to RO.
-
In module exit: do the reverse (change to RW, restore original, change to RO).
But note: the sys_call_table might be in use by other CPUs? We should disable preemption and maybe use smp_mb()? The kernel does:
preempt_disable();
write_cr0(read_cr0() & ~X86_CR0_WP);
// modify the table
write_cr0(read_cr0() | X86_CR0_WP);
preempt_enable();
However, using set_memory_rw and set_memory_ro might be safer because they handle multiple pages and also handle the TLB flush.
But note: set_memory_rw and set_memory_ro might allocate memory? And they might sleep? We are in kernel module context, and we cannot sleep in atomic context? Actually, these functions might sleep.
So we must be in a process context (not interrupt). Our module init and exit are in process context, so it's okay.
However, if we are replacing a system call that might be called from interrupt context? Our function must be safe for that? The original system call signature is the same, so we must follow the same rules.
Let's write our function:
asmlinkage long (*original_getpid)(void);
asmlinkage long our_getpid(void) {
printk(KERN_INFO "Our getpid called\n");
return original_getpid();
}
But note: the original system call might have a different signature? For getpid, it's asmlinkage long sys_getpid(void).
We must use the same calling convention (asmlinkage) and the same arguments.
However, the problem says "add a new system call", so we might want a different function. Let's make a simple one that returns a constant.
asmlinkage long our_syscall(void) {
return 1234;
}
And we will replace, say, sys_getpid with our_syscall.
But note: the system call number for getpid is 39 (on x86_64). So when a user program calls getpid, it will get 1234.
This is just an example.
Steps:
Let's code accordingly.
However, we must be cautious: the kernel might have multiple syscall tables (for 32-bit and 64-bit). We are on 64-bit, so we use the 64-bit table.
Also, note that the kernel might have a different syscall table for IA32 emulation? We are not touching that.
Let's code for x86_64.
Steps for finding sys_call_table:
We can use kallsyms:
sys_call_table = (void **)kallsyms_lookup_name("sys_call_table");
But kallsyms_lookup_name is not exported by default. We can use:
#include <linux/kallsyms.h>
unsigned long kallsyms_lookup_name(const char *name);
But it's not exported. We can try to get it via:
static unsigned long (*kallsyms_lookup_name_ptr)(const char *name) = NULL;
kallsyms_lookup_name_ptr = (void *)kallsyms_lookup_name; // but we need to get the address of the function?
Alternatively, we can use the kallsyms on the running kernel by reading /proc/kallsyms? But we are in a module.
Another method: search for the sys_close address and then calculate the offset? Because we know the index of sys_close is 2 (on x86_64, but check?).
Actually, the index of sys_close is 2? Let's check: in syscall_64.tbl, the first few are:
0 common read sys_read
1 common write sys_write
2 common open sys_open
So sys_close is at index 3? Actually, the table is indexed by the syscall number, and the first entry (index 0) is for syscall number 0.
But note: the table is an array of size __NR_syscalls, and the index is the syscall number.
So if we want to replace sys_getpid, we need the index for __NR_getpid, which is 39.
How about we get the address of sys_call_table by:
We know the address of the sys_close function (we can get it by kallsyms if we can, or we can search for the function in memory?).
But we don't know the offset of sys_close in the table? Actually, the table is an array of function pointers, and the index of sys_close is 3.
So if we get the address of sys_close (say, `sys_close_addr`), then:
sys_call_table = (void **)(sys_close_addr - 3 * sizeof(void *));
But we must get the address of sys_close. We can use:
sys_close_addr = (void *)kallsyms_lookup_name("sys_close");
But again, kallsyms_lookup_name is not exported.
So we have to use a trick: we can use the syscall function from user space to get the address of the kernel function? No.
Alternatively, we can parse /proc/kallsyms from the module? That's not safe and might be disabled.
Given the difficulty, we assume that the kernel is configured with CONFIG_KALLSYMS and that we can get the address of sys_call_table by:
extern void *sys_call_table;
But that symbol is not exported.
So we have to use a method that searches for the pattern of the sys_call_table? That's too hacky.
Given the constraints, we might have to modify the kernel source and recompile? But the problem says kernel module.
Alternatively, we can use a feature of the kernel that allows us to get the sys_call_table via a module parameter? No.
Since this is a common problem, there are known methods:
Method 1: Use the kallsyms_lookup_name function by resolving it from the kernel's kallsyms (if available). We can try to get the address of kallsyms_lookup_name by:
We know that kallsyms_lookup_name is a function in the kernel, and we can get its address by:
kallsyms_lookup_name_ptr = (void *)get_kallsyms_lookup_name();
But we have to implement get_kallsyms_lookup_name by searching for the function? Not trivial.
Method 2: Use the sys_call_table symbol from the kernel's symbol table if it's exported. It's not.
Method 3: Use a hack: we can get the address of the syscall table by looking at the idt table? Because the syscall instruction uses the MSR_IA32_LSTAR, which points to the entry function (entry_SYSCALL_64), and then from there we can find the syscall table? That's very architecture-specific and complex.
Given the time, we will assume that the kernel has the sys_call_table symbol exported (which it doesn't by default) or that we have a way to get it.
Actually, in some kernels, you can export the symbol by adding:
EXPORT_SYMBOL_GPL(sys_call_table);
in the source and recompiling. But that's not the case for a module that we load without recompiling the kernel.
So we are stuck.
Let's change the approach: we will write a module that does not require modifying the syscall table, but instead uses a different mechanism? But the problem says "add a new system call".
Alternatively, we can use a system call that is not implemented (like a high number) and then handle it in a custom way? But the kernel will return -ENOSYS for that number.
We cannot change that without changing the syscall table.
Given the complexity and the fact that the assignment might be expecting a simple module that registers a system call by modifying the table, and assuming we have a kernel that exports sys_call_table (or we are allowed to modify the kernel to export it), we proceed.
But note: the problem says "Develop a kernel module", so we are writing a module. We cannot rely on modified kernel.
So we have to use a method that works on a standard kernel.
After research, a common method is:
unsigned long **sys_call_table;
Then we get the address by:
sys_call_table = (unsigned long *)kallsyms_lookup_name("sys_call_table");
But kallsyms_lookup_name is not exported.
We can use:
#include <linux/kallsyms.h>
and then:
sys_call_table = (unsigned long *)kallsyms_lookup_name("sys_call_table");
But we get an error because the symbol is not exported.
So we have to use a different method.
Another method: search for the pattern of the sys_call_table in memory? We can look for the address of sys_close and then calculate backwards? But we don't have the address of sys_close.
We can get the address of the current system call by using the syscall instruction from assembly? That's not easy.
Given the time, I will write the module assuming we have the address of sys_call_table. We can get it by:
We know that the kernel loads the sys_call_table at a fixed address? No.
Alternatively, we can use the syscall instruction and then read the MSR_IA32_LSTAR to get the entry function, and then from the entry function we can find the syscall table? That's too complex.
Given the constraints of the problem, I think we are allowed to assume that we have the address of sys_call_table (maybe by modifying the kernel to export it). But that's not a module.
So perhaps the problem expects us to write a module that, when loaded, modifies the sys_call_table by first making it writable, and we assume we have the address of sys_call_table via a symbol that we define in the module? That doesn't work.
Alternatively, we can define a new system call by adding a new entry to the syscall table and then recompiling the kernel? That's not a module.
I think the problem is misstated. Adding a new system call typically requires recompiling the kernel.
But let's read: "Develop a kernel module in C that adds a new system call to Linux."
So we are writing a module that, when loaded, adds a new system call. That means we are going to modify the syscall table at runtime.
So we must find the syscall table.
Given the above, I will write the module with the following assumptions:
- We are running on x86_64.
- The kernel has the
sys_call_table symbol available (maybe because we recompiled the kernel with CONFIG_KALLSYMS and EXPORT_SYMBOL_GPL(sys_call_table)). But that's not standard.
Alternatively, we can use a tool like kprobes to get the address? No.
Given the time, I will write the code that works if we have the address of sys_call_table. We can get it by:
sys_call_table = (unsigned long *)0xffffffff81d00000; // example address, but it changes per kernel version.
So we cannot hardcode.
We can use the kallsyms to get the address of sys_call_table if the kernel has kallsyms and we have permission.
But note: the function kallsyms_lookup_name is not exported, but we can use the kallsyms on the system? Actually, we can open /proc/kallsyms and read it? But that's from user space.
In kernel space, we can use:
#include <linux/kallsyms.h>
unsigned long kallsyms_lookup_name(const char *name);
But it's not exported.
We can try to get it by:
static unsigned long (*__kallsyms_lookup_name)(const char *name) = NULL;
__kallsyms_lookup_name = (void *)kallsyms_lookup_name;
But that will fail because the symbol is not exported.
So we have to use a different method.
After some research, a common method is to search for the sys_close function and then calculate the sys_call_table address by:
sys_close_addr = (void *)kallsyms_lookup_name("sys_close");
sys_call_table = (unsigned long **)(sys_close_addr - (__NR_close * sizeof(void *)));
But again, we need kallsyms_lookup_name.
We can get the address of kallsyms_lookup_name by:
We know that the kernel's kallsyms_lookup_name is at a fixed offset from the `sys_call_table`? Not necessarily.
Given the complexity, I will assume that we have a function that can get the address of sys_call_table by some means.
For the purpose of this example, I will write:
static unsigned long **sys_call_table;
And then in the module init, we will assign it by:
sys_call_table = (unsigned long **)0xffffffff81d00000; // This is just an example, and will not work on most kernels.
So the module will only work if we adjust the address for the specific kernel.
This is not portable.
Given the above, I think the problem is expecting a theoretical answer or a simple module that does the hooking if we have the address.
So I will write the code that does the hooking, but the address of sys_call_table must be found by some other means (like by looking at the kernel's System.map file and then hardcoding).
Steps:
Let's write the module:
We'll replace the getpid system call (sys_getpid) with our own.
We'll define:
asmlinkage long (*original_getpid)(void);
asmlinkage long our_getpid(void) {
printk(KERN_INFO "Our getpid called\n");
return original_getpid();
}
But note: the original_getpid might be called from user space, and we are changing the system call table. We must save the original function pointer.
Code:
Note: We are on x86_64, so the system call table is an array of function pointers of type sys_call_ptr_t which is asmlinkage (*)(...) but in the table it's stored as void *.
We'll use unsigned long for the table entries.
Let's code accordingly.
However, note that the system call table might be of type const sys_call_ptr_t * and we are removing the const? We are casting away the const.
We'll do:
unsigned long *sys_call_table;
And then we will cast the original and our function to unsigned long.
But the function signatures must match.
Steps:
Let's write the module.
We assume the kernel version is 5.x and the syscall table for x86_64 has 448 entries.
We assume we have the address of sys_call_table.
We'll use:
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/kallsyms.h> // for kallsyms_lookup_name, but not exported so we might not use it.
#include <linux/delay.h>
#include <linux/mm.h> // for set_memory_rw, set_memory_ro
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/syscalls.h>
But note: set_memory_rw and set_memory_ro are in <asm/pgtable.h>? Actually, they are in <linux/mm.h> and are exported.
Let's code:
We'll define:
static unsigned long **sys_call_table;
asmlinkage long (*original_getpid)(void);
asmlinkage long our_getpid(void) {
printk(KERN_INFO "Our getpid called\n");
return original_getpid();
}
In the module init:
// Get the address of sys_call_table (we assume we have it)
sys_call_table = (unsigned long **)0xffffffff81d00000; // This is an example, find the correct one for your kernel.
// Save the original
original_getpid = (void *)sys_call_table[__NR_getpid];
// Change the page permissions of the page containing sys_call_table[__NR_getpid] to RW
unsigned long page = (unsigned long)sys_call_table[__NR_getpid] & PAGE_MASK;
set_memory_rw(page, 1);
// Replace the function pointer
sys_call_table[__NR_getpid] = (unsigned long)our_getpid;
// Change the page back to RO
set_memory_ro(page, 1);
But wait: what if the entry spans two pages? We must change both pages.
Let's do:
unsigned long start = (unsigned long)sys_call_table[__NR_getpid];
unsigned long end = start + sizeof(void *);
unsigned long page_start = start & PAGE_MASK;
unsigned long page_end = (end - 1) & PAGE_MASK;
for (; page_start <= page_end; page_start += PAGE_SIZE) {
set_memory_rw(page_start, 1);
}
// Now change the entry
sys_call_table[__NR_getpid] = (unsigned long)our_getpid;
for (page_start = (unsigned long)sys_call_table[__NR_getpid] & PAGE_MASK; page_start <= page_end; page_start += PAGE_SIZE) {
set_memory_ro(page_start, 1);
}
But note: the page_end is computed from the original start? We should compute page_end again after writing? Because the address of the entry is the same.
Actually, the entry address doesn't change, so we can compute page_end once.
However, we are changing the content of the page, but the address of the entry is the same, so the page boundaries are the same.
So we can compute:
unsigned long entry_addr = (unsigned long)sys_call_table[__NR_getpid];
unsigned long start_page = entry_addr & PAGE_MASK;
unsigned long end_page = (entry_addr + sizeof(void *) - 1) & PAGE_MASK;
for (addr = start_page; addr <= end_page; addr += PAGE_SIZE) {
set_memory_rw(addr, 1);
}
sys_call_table[__NR_getpid] = (unsigned long)our_getpid;
for (addr = start_page; addr <= end_page; addr += PAGE_SIZE) {
set_memory_ro(addr, 1);
}
But note: set_memory_rw and set_memory_ro take the virtual address and the number of pages. We are doing one page at a time.
Alternatively, we can do:
set_memory_rw(start_page, 1);
if (start_page != end_page) {
set_memory_rw(end_page, 1);
}
But what if the entry spans more than two pages? It's one pointer, so it's at most two pages.
Actually, the pointer is 8 bytes, so it will span two pages only if it's at the last 8 bytes of a page? Yes.
So we can do:
if (start_page == end_page) {
set_memory_rw(start_page, 1);
} else {
set_memory_rw(start_page, 1);
set_memory_rw(end_page, 1);
}
Then after writing, we do the same for ro.
However, the set_memory functions might change the memory attributes for the entire page, and we might be changing other entries? That's okay because we are only changing one entry, but we are making the entire page writable. That might be a security risk? But we are only changing one entry and then setting it back to RO.
But what if the page contains other syscall table entries? We are making them writable too? Yes, but we are not changing them. But while the page is writable, another CPU might change them? We are disabling preemption? Actually, the module init is in process context and we are not preemptible? We are in a module init function, which is not preemptible? Actually, it can be preempted? We should disable preemption.
We do:
preempt_disable();
// change page permissions and modify the table
preempt_enable();
But the set_memory functions might sleep? They do, because they might need to allocate memory for the new page tables? Actually, they might. So we cannot disable preemption across them.
Alternatively, we can do:
// Disable preemption? Not needed because set_memory_rw might sleep.
But we are in a module init, which can sleep.
However, we must be cautious about the syscall table being used by other CPUs. We should use a lock? The kernel doesn't lock the syscall table when modifying? Actually, the kernel uses a lock when modifying the syscall table (like when applying seccomp filters). But we are not using that.
We can use write_cr0 to toggle the WP bit without using set_memory? That might be faster and doesn't sleep.
But then we have to handle multiple pages ourselves.
Let's use the write_cr0 method:
unsigned long cr0 = read_cr0();
write_cr0(cr0 & ~X86_CR0_WP);
// modify the table
write_cr0(cr0);
But note: the table might be in a page that is not present? It should be present.
And we must do:
preempt_disable();
write_cr0(cr0 & ~X86_CR0_WP);
// modify the table
write_cr0(cr0);
preempt_enable();
But we are toggling the WP bit for the entire CPU, and we are only modifying one entry. This is safe because we are disabling preemption and interrupts? Actually, write_cr0 affects the current CPU and we are in a non-preemptible section? But preempt_disable() doesn't disable interrupts. However, the syscall table is per-CPU? No, it's global.
So we must ensure that no other CPU is using the table while we modify it? Actually, the table is read-only and we are making it writable. Other CPUs might be reading it? They might read the old value or the new value? We must ensure that the modification is atomic? We are writing one pointer, which is atomic on x86_64.
But the issue is that we are changing the page permissions. We must do it with preemption disabled and with interrupts disabled? Because an interrupt might come and try to use the syscall table? The syscall table is used by the syscall instruction, which is an interrupt? Actually, the syscall instruction is a fast system call and doesn't use the interrupt descriptor table. It uses the MSR_IA32_LSTAR. And the MSR points to the entry function, which then does:
swapgs
movq %rsp, %gs:rsp
... and then calls the system call function from the table.
So during the modification, if we are on the same CPU, we are safe because we are in the kernel and we are not preemptible? But what about other CPUs? They might be executing the syscall instruction and reading the table? They would read the old or new value? We are only changing one entry, and the read is atomic? Yes, but the table is read-only, so they might get a page fault if we haven't made the page writable? Actually, we are making the page writable, so they can read it without fault.
But the issue is that we are changing the page permissions and then the entry. We must do:
Step 1: Make the page writable.
Step 2: Change the entry.
Step 3: Make the page read-only.
If another CPU reads the entry while the page is writable, it will get the old value until we change it? Then it will get the new value. But what if it reads the entry while we are in the middle of writing? The write of a pointer is atomic, so it will read either the old or new.
But what about the page permissions? If we make the page writable, then another CPU might write to it? But we are the only one writing? We are not locking, so another CPU might also try to modify the table? That would be bad.
So we must have a lock? The kernel doesn't provide a lock for the syscall table. So we must be the only one modifying it.
In our module, we are the only one modifying the table. So we must ensure that we don't have concurrent modifications.
But what about the kernel itself? The kernel might modify the table (for seccomp, or for other reasons). We are not using those, so it might be safe.
Given the above, we'll use the write_cr0 method and disable preemption.
Code for module init:
unsigned long cr0;
unsigned long *entry;
// Find the sys_call_table (we assume we have it)
// Save the original
original_getpid = (void *)sys_call_table[__NR_getpid];
// Calculate the page(s) we need to change
entry = (unsigned long *)sys_call_table[__NR_getpid];
start_page = (unsigned long)entry & PAGE_MASK;
end_page = ((unsigned long)entry + sizeof(void *) - 1) & PAGE_MASK;
preempt_disable();
cr0 = read_cr0();
write_cr0(cr0 & ~X86_CR0_WP);
// Change the pages to writable? Actually, we are just disabling write protection, so the pages are already present and we can write to them.
// But note: the pages might be read-only at the page table level? We are only disabling the WP bit in CR0, which is a protection for the current page tables.
// So we don't need to change the page table attributes? Actually, if the page is marked as read-only in the page table, then even with WP disabled we cannot write? We are in kernel mode and we have the page tables. The WP bit is an additional protection.
// So we assume the page is present and writable by the kernel? Actually, the syscall table is in the .rodata section, so it's read-only. But the kernel can write to it by disabling WP.
// So we just disable WP and then write.
sys_call_table[__NR_getpid] = (unsigned long)our_getpid;
write_cr0(cr0);
preempt_enable();
But note: we are not changing the page table attributes, just the WP bit. This is the common method.
However, if the page is not writable at the page table level (i.e., the PTEs are read-only), then we must change the PTE to writable? Actually, the kernel maps the .rodata section as read-only, but the kernel can write to it by disabling WP? I think the PTEs are read-only and WP is an additional check. So if we disable WP, we can write even if the PTE is read-only? Actually, no. The PTE must be writable. But the kernel sets the PTEs for .rodata as read-only? Then we cannot write even with WP disabled.
So we must change the PTE to be writable? That's what set_memory_rw does: it changes the PTE to be writable.
Therefore, we must use set_memory_rw and set_memory_ro to change the page attributes.
So we go back to the set_memory method.
But set_memory_rw might sleep, so we cannot disable preemption across it.
We'll do:
// Disable preemption? We don't need to because set_memory_rw might sleep, and we are in process context.
// But we must ensure that the syscall table is not being used by another CPU? We can use a lock? But the kernel doesn't lock the syscall table.
// We'll assume that we are the only one modifying the table.
// Change the page(s) to RW
for (addr = start_page; addr <= end_page; addr += PAGE_SIZE) {
set_memory_rw(addr, 1);
}
// Now write the new pointer
sys_call_table[__NR_getpid] = (unsigned long)our_getpid;
// Change the page(s) back to RO
for (addr = start_page; addr <= end_page; addr += PAGE_SIZE) {
set_memory_ro(addr, 1);
}
But note: set_memory_rw and set_memory_ro might fail? They return 0 on success.
We should check the return value.
Let's code accordingly.
Now, the problem: how to get the address of sys_call_table?
We can use the following trick if the kernel has kallsyms and we have the address of kallsyms_lookup_name:
We can get the address of kallsyms_lookup_name by:
We know that the kernel's kallsyms_lookup_name is in the kernel text, and we can get the address of the function `kallsyms_lookup_name` by:
We can use the `sys_call_table` symbol? No.
Alternatively, we can use the `__symbol_get`? But that's for modules.
Given the complexity, I will leave it as a hardcoded address for the example.
So the module will only work on a specific kernel version and configuration.
We can try to get the address of sys_call_table by:
We know that the sys_call_table is in the .rodata section, and we can get the address of the __start_rodata and then search? Not reliable.
So for the purpose of this example, we assume the address is known.
Let's write the code accordingly.
We'll also handle the module exit by restoring the original.
Code:
Note: We must include the necessary headers and use the correct calling convention for system calls (asmlinkage).
Let's write the complete module.
We assume the kernel is 5.4 and the syscall table for x86_64 is at 0xffffffff81d00000 (this is just an example, you must find the correct one for your kernel by looking at /boot/System.map or /proc/kallsyms).
Steps to find the address:
$ grep sys_call_table /boot/System.map-$(uname -r)
Or:
$ sudo cat /proc/kallsyms | grep sys_call_table
Then use that address.
But note: the address might be different for each boot because of KASLR? Then we cannot hardcode.
So we must find it dynamically.
Given the above, I think the problem is too complex for a simple module.
But let's try to write a module that works without hardcoding by using kallsyms_lookup_name, but we have to get that function.
We can get kallsyms_lookup_name by:
We can use the fact that the kernel exports the `kallsyms_lookup_name` function if we are running a kernel that has `CONFIG_KALLSYMS` and we have the necessary permissions? Actually, it's not exported.
But we can use the `kallsyms` on the running kernel by reading /proc/kallsyms from kernel space? We can open /proc/kallsyms and read it? But that's from user space.
We can use the `sys_open` and `sys_read` to read /proc/kallsyms? But we are in the kernel and we are going to replace sys_open? That's dangerous.
Alternatively, we can use the kprobe to get the address? Not really.
Given the time, I will write the module with a hardcoded address and note that it must be adjusted.
Code:
Note: This code is for educational purposes only and may not work on your kernel.
Let's code:
Creating a kernel module that adds a new system call involves patching the kernel's syscall table at runtime since modern Linux kernels do not support dynamically adding system calls via modules. This approach is highly version/architecture-specific, risky, and generally discouraged for production systems. Below is a conceptual example for x86_64 Linux (kernel 5.x+) that replaces an existing system call (e.g., getpid) with a custom one. Use only for educational/testing in a VM.
1. Important Warnings
- Kernel panics likely if done incorrectly.
- Security risks: Disables W^P (Write-Protect) protection.
- Not portable: Works only on specific kernel versions/architectures.
- Violates kernel stable ABI: May break after updates.
- Alternatives: Use
ioctl, procfs, or netlink instead.
2. Module Code: hook_syscall.c
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/kallsyms.h>
#include <linux/delay.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/syscalls.h>
#include <linux/sched.h>
#include <linux/version.h>
#include <asm/pgtable.h>
#include <asm/cacheflush.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Example");
MODULE_DESCRIPTION("Hook a syscall (replace getpid)");
// ========== Configuration ==========
#define TARGET_SYSCALL_NR __NR_getpid // Replace getpid (adjust as needed)
// ===================================
static unsigned long **sys_call_table;
static unsigned long original_syscall_ptr;
// Custom syscall function (replace getpid)
asmlinkage long (*original_getpid)(void);
asmlinkage long custom_getpid(void) {
printk(KERN_INFO "custom_syscall: getpid() hooked! Returning 1234\n");
return 1234; // Return fake PID (or call original_getpid())
}
// Locate sys_call_table using kallsyms (if available)
static unsigned long **find_sys_call_table(void) {
unsigned long **sct;
unsigned long addr = kallsyms_lookup_name("sys_call_table");
if (!addr) {
pr_err("Cannot find sys_call_table\n");
return NULL;
}
sct = (unsigned long **)addr;
pr_info("sys_call_table found at %p\n", sct);
return sct;
}
// Make memory region writable (x86_64)
static void make_rw(unsigned long addr) {
unsigned long cr0 = read_cr0();
write_cr0(cr0 & ~X86_CR0_WP); // Disable write-protect
// Optional: flush TLB if needed
__flush_tlb_one(addr);
}
// Restore write-protect
static void make_ro(unsigned long addr) {
unsigned long cr0 = read_cr0();
write_cr0(cr0 | X86_CR0_WP); // Enable write-protect
__flush_tlb_one(addr);
}
static int __init hook_syscall_init(void) {
unsigned long *entry;
struct page *page;
unsigned long page_addr;
pr_info("Loading hook_syscall module...\n");
// 1. Find sys_call_table
sys_call_table = find_sys_call_table();
if (!sys_call_table)
return -EFAULT;
// 2. Save original syscall pointer
original_syscall_ptr = sys_call_table[TARGET_SYSCALL_NR];
pr_info("Original syscall[%d] = %pS\n", TARGET_SYSCALL_NR,
(void *)original_syscall_ptr);
// 3. Make page writable (handle multi-page if needed)
entry = (unsigned long *)&sys_call_table[TARGET_SYSCALL_NR];
page_addr = (unsigned long)entry & PAGE_MASK;
// Disable preemption (optional but safer)
preempt_disable();
make_rw(page_addr);
// 4. Replace syscall
sys_call_table[TARGET_SYSCALL_NR] = (unsigned long)custom_getpid;
pr_info("Hooked syscall[%d] -> custom_getpid (%pS)\n",
TARGET_SYSCALL_NR, custom_getpid);
// 5. Restore write-protect
make_ro(page_addr);
preempt_enable();
return 0;
}
static void __exit hook_syscall_exit(void) {
unsigned long *entry;
unsigned long page_addr;
if (!sys_call_table)
return;
pr_info("Unloading hook_syscall module...\n");
entry = (unsigned long *)&sys_call_table[TARGET_SYSCALL_NR];
page_addr = (unsigned long)entry & PAGE_MASK;
preempt_disable();
make_rw(page_addr);
sys_call_table[TARGET_SYSCALL_NR] = original_syscall_ptr;
make_ro(page_addr);
preempt_enable();
pr_info("Restored original syscall[%d]\n", TARGET_SYSCALL_NR);
}
module_init(hook_syscall_init);
module_exit(hook_syscall_exit);
3. Makefile
obj-m += hook_syscall.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
4. How to Use
-
Get sys_call_table address (adjust for your kernel):
grep sys_call_table /boot/System.map-$(uname -r)
# or
sudo cat /proc/kallsyms | grep sys_call_table
Example output: ffffffff81d00200 D sys_call_table
Replace the find_sys_call_table() function with:
sys_call_table = (unsigned long **)0xffffffff81d00200ULL;
-
Compile & load:
make
sudo insmod hook_syscall.ko
-
Test:
strace -e getpid /bin/true # Should see return value 1234
dmesg | tail # Should see log messages
-
Unload:
sudo rmmod hook_syscall
5. Key Considerations
- Kernel Version:
__NR_getpid may differ (check arch/x86/entry/syscalls/syscall_64.tbl).
- SMP: No locking; unsafe on multi-CPU during modification.
- Alternatives: Use
kprobes or ftrace for safer hooking.
- Modern Kernels:
sys_call_table is often const and hidden; may require patching kernel source instead.
6. Safer Alternative: Use kprobes
#include <linux/kprobes.h>
static struct kprobe kp = {
.symbol_name = "sys_getpid",
};
static int handler_pre(struct kprobe *p, struct pt_regs *regs) {
pr_info("kprobe: getpid hooked!\n");
// Modify regs->rax to return custom value
regs->ax = 1234;
return 1; // Skip original function
}
static int __init kprobe_init(void) {
int ret = register_kprobe(&kp);
if (ret < 0) {
pr_err("register_kprobe failed, %d\n", ret);
return ret;
}
kp.pre_handler = handler_pre;
return 0;
}
Note: kprobes still requires kernel debugging symbols (CONFIG_KPROBES).
Conclusion
This module replaces an existing syscall (not adds a new one). Truly adding a new syscall requires recompiling the kernel:
- Add entry to
arch/x86/entry/syscalls/syscall_64.tbl.
- Implement
SYSCALL_DEFINE0(new_call) in kernel source.
- Rebuild kernel.
For user-space needs, prefer ioctl/procfs/netlink over syscalls. This example is strictly for kernel education/research.