Get NFS client IP address in a kernel module - c

I'm working on a kernel module to track the operations performed by NFS clients on my server.
I can intercept the file operations using a hacky way (hijacking the vfs layer) but I can't retrieve the IP address of the client.
Is there any information that might be stored in the current task that I can use to obtain the IP address of the NFS client performing an operation?
I know from digging into the source code that nfsd stores a struct nfsd_net in the struct super_block's s_fs_info field, but I can only retrieve it as a struct net pointer. And in nfsd's implementation net_generic method is being used to get the struct nfsd_net pointer (using nfsd_net_id which is the pernet_operations's id).
Can I obtain this id somehow? and if yes, can I use the struct nfsd_net in my kernel module? Is it defined somewhere other than the fs/nfsd/netns.h?
Edit
I'm using this approach to hijack the open function. I'm writing this for kernel version 4.15.0. Here's the code of the kernel module:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/kobject.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/version.h>
#include <linux/proc_fs.h>
#include <linux/cred.h>
#include <linux/sched.h>
#include <linux/preempt.h>
#include <linux/uaccess.h>
#include <linux/xattr.h>
MODULE_LICENSE("GPL");
#if defined(__i386__)
#define POFF 1
#define CSIZE 6
// push address, addr, ret
char *jmp_code="\x68\x00\x00\x00\x00\xc3";
typedef unsigned int PSIZE;
#else
#define POFF 2
#define CSIZE 12
// mov address to register rax, jmp rax. for normal x64 convention
char *jmp_code="\x48\xb8\x00\x00\x00\x00\x00\x00\x00\x00\xff\xe0";
typedef unsigned long PSIZE;
#endif
DEFINE_SPINLOCK(root_open_lock);
int (*orig_root_open) (struct inode *, struct file *);
void *orig_root_open_code;
void hook(void *src_func,void *dst_addr){
barrier();
write_cr0(read_cr0() & (~0x10000));
memcpy(src_func,jmp_code,CSIZE);
*(PSIZE *)&(((unsigned char*)src_func)[POFF])=(PSIZE)dst_addr;
write_cr0(read_cr0() | 0x10000);
barrier();
}
void save_and_hook(void **p_reserve,void *src_func,void *dst_addr){
barrier();
write_cr0(read_cr0() & (~0x10000));
*p_reserve=kmalloc(CSIZE,GFP_KERNEL);
// save origin code
memcpy(*p_reserve,src_func,CSIZE);
hook(src_func,dst_addr);
write_cr0(read_cr0() | 0x10000);
barrier();
}
void fix(void **p_reserve,void *src_func){
barrier();
write_cr0(read_cr0() & (~0x10000));
memcpy(src_func,*p_reserve,CSIZE);
write_cr0(read_cr0() | 0x10000);
barrier();
}
int fake_root_open(struct inode *x, struct file *fp)
{
int ret;
printk("vfshijack: hijacked open\n"); // I need to find the client ip here.
barrier();
spin_lock(&root_open_lock);
fix(&orig_root_open_code, orig_root_open);
ret = orig_root_open(x, fp);
hook(orig_root_open, fake_root_open);
spin_unlock(&root_open_lock);
barrier();
return ret;
}
int vfs_init(void)
{
struct file *fp = filp_open("/", O_DIRECTORY|O_RDONLY, 0);
if (IS_ERR(fp))
return -1;
orig_root_open = fp->f_op->open;
if(orig_root_open)
{
save_and_hook(&orig_root_open_code, orig_root_open, fake_root_open);
}
filp_close(fp, NULL);
printk("vfshijack: vfshijack loaded\n");
return 0;
}
void vfs_exit(void)
{
if(orig_root_open)
{
fix(&orig_root_open_code, orig_root_open);
}
printk("vfshijack: vfshijack unloaded\n");
}
module_init(vfs_init);
module_exit(vfs_exit);

You can try to get needed information from linux kernel tracing tools without hooking kernel binary with some custom assembly. There are perf, ftrace, trace-cmd for most kernel versions, and stap and lttng for more custom versions. Some documentation to start: https://www.kernel.org/doc/html/v4.18/trace/index.html "Linux Tracing Technologies"
There are several tracepoints defined in nfsd:
# modprobe nfsd
# modprobe nfs
# perf list tracepoint|grep nfs
# find /sys/kernel/debug/tracing/events -type d|grep nfsd
# trace-cmd list -e nfsd:read_start -F
nfsd/read_start and nfsd/write_start tracepoints are good places to start. Both should have access to request structure rqstp with address rq_addr and fh pointer (but some eBPF or stap scripting may be useful)
https://elixir.bootlin.com/linux/v4.15/source/fs/nfsd/vfs.c#L1020
__be32 nfsd_read(struct svc_rqst *rqstp, struct svc_fh *fhp,...)
trace_read_start(rqstp, fhp, offset, vlen);
trace_read_opened(rqstp, fhp, offset, vlen);
trace_read_io_done(rqstp, fhp, offset, vlen);
trace_read_done(rqstp, fhp, offset, vlen);
I have no complete example of trace-cmd or stap usage for nfs daemon tracing.
Systemtap (stap) has some examples of nfsd statistics:
https://github.com/jav/systemtap/blob/master/testsuite/systemtap.examples/index.txt
# stap nfsd_unlink.stp -c "sleep 0.2"
The nfsdtop.stp script gathers and displays NFS lookups
https://github.com/larytet/SystemTap/blob/master/testsuite/systemtap.examples/network/nfsdtop.stp

Related

Build against newer linux headers than libc is built using

I want to write a program using the new SCHED_DEADLINE scheduling policy available since Linux 3.14.
I start out with a simple program trying to use the sched_setattr function.
#include <sched.h>
int main(void)
{
// struct sched_attr attr;
// attr.size = sizeof(struct sched_attr);
// attr.sched_policy = SCHED_DEADLINE;
sched_setattr(0, (void*)0, 0);
return 0;
}
However when compiling I get the following error:
$gcc dead.c
dead.c: In function ‘main’:
dead.c:8:2: warning: implicit declaration of function ‘sched_setattr’ [-Wimplicit-function-declaration]
sched_setattr(0, (void*)0, 0);
^~~~~~~~~~~~~
/tmp/ccGxWxZE.o: In function `main':
dead.c:(.text+0x19): undefined reference to `sched_setattr'
collect2: error: ld returned 1 exit status
My system is running Ubuntu 16.10 Yakkety, with kernel 4.8.0-59-generic. The sched.h file included is found in /usr/include/sched.h and is provided by the package libc6-dev. This headerfile does not contain the function sched_setattr and friends that I am trying to use.
However the kernel (and kernel headers) I have installed comes with a sched.h header file containing the definitions I need. It is located at /usr/src/linux-headers-4.8.0-58/include/linux/sched.h, on my system.
So I naively think lets just build against the newer linux headers instead of the libc6-dev provided headers. My program will only run on this or newer kernels, but that is just fine.
I modify the first line to be: #include <linux/sched.h> and execute:
gcc -I/usr/src/linux-headers-$(uname -r)/include -I/usr/src/linux-headers-$(unam -r)/arch/x86/include dead.c
Now I am getting page after page of errors and warning. This does not seem the way to go.
What is the correct way to build a userspace program against a newer Linux headers than those that are provided by libc?
And subsequently how do I build the program above?
sched_setattr() is a syscall and doesn't seem to have one-to-one libc wrapper. You could do the wrapper yourself, something like this:
#define _GNU_SOURCE
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <linux/sched.h>
#include <sys/syscall.h>
#include <sys/types.h>
struct sched_attr {
uint32_t size; /* Size of this structure */
uint32_t sched_policy; /* Policy (SCHED_*) */
uint64_t sched_flags; /* Flags */
int32_t sched_nice; /* Nice value (SCHED_OTHER, SCHED_BATCH) */
uint32_t sched_priority; /* Static priority (SCHED_FIFO, SCHED_RR) */
/* Remaining fields are for SCHED_DEADLINE */
uint64_t sched_runtime;
uint64_t sched_deadline;
uint64_t sched_period;
};
static int sched_setattr (pid_t pid, const struct sched_attr *attr, unsigned int flags)
{
return syscall (SYS_sched_setattr, pid, attr, flags);
}
int main (int argc, char *argv[])
{
struct sched_attr attr;
int res;
memset (&attr, 0, sizeof (struct sched_attr));
attr.size = sizeof (struct sched_attr);
res = sched_setattr (getpid (), &attr, 0);
if (res < 0) {
perror ("sched_setattr");
return 1;
}
return 0;
}
Looking at the errors reported when trying to include kernel header files required to get the definition of struct sched_attr and reading the comments found by Googling "kernel headers in user space", I really can't suggest trying to include kernel header files just for this.

Linux Kernel Module/IOCTL: inappropriate ioctl for device

I am in the process of writing a Linux Kernel Module (LKM) serving as a pseudo-driver - I am unable to figure out how to make IOCTL calls between the LKM (wait.c) and the user-level program (user.c).
The magic number for the device driver is 0xBF - the LKM does not communicate with a physical block/char device, it is simply an exercise. From what I can tell, the IOCTL call to KERN_IOCTL_CREATE_EVENT is not formatted properly & the magic number is incorrect.
The IOCTL call that I am attempting to use is:
#include <sys/ioctl.h>
#define KERN_IOCTL_CREATE_EVENT _IOWR(WAIT_DEVICE_MAGIC, 1, int)
int main(){
int ret;
int fd;
fd = open("/dev/wait", 0);
if(fd < 0){
return -1;
}
ret = ioctl(fd, KERN_IOCTL_CREATE_EVENT, 0);
Error:
[fail]: KERN_IOCTL_CREATE_EVENT: Inappropriate ioctl for device
The user-mode application can open/close a file descriptor pointing to the device: /dev/wait but the case/switch statement isn't accepting the IOCTL call. Any suggestions?
Here is the output of # uname -a
Linux vagrant-ubuntu-trusty-64 3.13.11.11+ #1 SMP Mon Dec 1 20:50:23 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux
wait.c
#include <linux/miscdevice.h>
#include <linux/moduleparam.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <asm/uaccess.h>
#include <linux/sched.h>
#include <linux/ioctl.h>
#include <linux/cdev.h>
#include <linux/init.h>
#include <linux/wait.h>
#include <linux/fs.h>
#include "wait.h"
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Tyler Fisher <tyler#tylerfisher.org>");
MODULE_DESCRIPTION("In-kernel wait queue");
static unsigned long event_table_size = 50;
module_param(event_table_size, ulong, (S_IRUSR | S_IRGRP | S_IROTH));
MODULE_PARM_DESC(event_table_size, "Size of event table (i.e. how many processes can be blocking)");
/* IOCTL function headers */
static int wait_open(struct inode *, struct file *);
static int wait_close(struct inode *, struct file *);
static long wait_ioctl(struct inode *, struct file *, unsigned int, unsigned long);
/* other function headers */
static long event_open(int event_id);
/* file operations */
static struct file_operations wait_fops = {
.owner = THIS_MODULE,
.open = wait_open,
.release = wait_close,
.llseek = noop_llseek,
.unlocked_ioctl = wait_ioctl
};
/* device handler */
static struct miscdevice wait_misc_device = {
.minor = MISC_DYNAMIC_MINOR,
.name = WAIT_DEVICE_NAME,
.fops = &wait_fops
};
/* open wait device */
static int wait_open(struct inode *inode, struct file *file){
dev_t node = iminor(inode);
if(MINOR(node) != WAIT_DEVICE_MINOR){
return -ENODEV;
}
return 0;
}
static int wait_close(struct inode *inode, struct file *file){
return 0;
}
static long wait_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long sub_cmd){
switch(cmd){
case KERN_IOCTL_CREATE_EVENT:
printk(KERN_INFO "[wait device]: create event %lu\n", sub_cmd);
return event_open(sub_cmd);
default:
return -ENOENT;
}
}
static long event_open(int id){
return 0;
}
static long __init wait_init(void){
if(misc_register(&wait_misc_device) < 0){
printk(KERN_ERR "[wait device] failed to register device\n");
return -1;
}
printk(KERN_INFO "[wait device] has been registered\n");
return 0;
}
static void __exit wait_exit(void){
misc_deregister(&wait_misc_device);
printk(KERN_INFO "[wait device] has been unregistered\n");
}
module_init(wait_init);
module_exit(wait_exit);
wait.h
#include <linux/ioctl.h>
#define WAIT_DEVICE_NAME "wait"
#define WAIT_DEVICE_MAGIC 0xBF
#define WAIT_DEVICE_MAJOR 200
#define WAIT_DEVICE_MINOR 0
#define KERN_IOCTL_CREATE_EVENT _IOWR(WAIT_DEVICE_MAGIC, 0x01, int)
#define MAX_WAITING 5
The test program for the IOCTL calls:
user.c
#include <sys/ioctl.h>
#include <fcntl.h>
#include <stdio.h>
#define WAIT_DEVICE_MAGIC 0xBF
#define KERN_IOCTL_CREATE_EVENT _IOWR(WAIT_DEVICE_MAGIC, 0x01, int)
#define KERN_IOCTL_DESTROY_EVENT _IOWR(WAIT_DEVICE_MAGIC, 0x02, int)
#define KERN_IOCTL_LOCK_EVENT _IOWR(WAIT_DEVICE_MAGIC, 0x03, int)
#define KERN_IOCTL_UNLOCK_EVENT _IOWR(WAIT_DEVICE_MAGIC, 0x04, int)
int main(){
int fd;
if(fd = open("/dev/wait", O_RDWR) < 0){
perror("failed to open /dev/wait");
return -1;
}
/* test IOCTL: event creation */
if(ioctl(fd, KERN_IOCTL_CREATE_EVENT, 0) < 0){
perror("[fail]: KERN_IOCTL_CREATE_EVENT");
return -1;
}
return 0;
}
Makefile
obj-m += wait.o
CFLAGS_wait.o += -DDEBUG
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
In order to test out the LKM - clear dmesg, compile & execute user.c w/GCC:
# dmesg -c > /dev/null 2>&1
# make
# rmmod wait.ko
# insmod wait.ko
# gcc user.c -o user && ./user
The amount of debugging errors is embarassing. I feel bad for sharing this - and realize that this may cause the issue to be closed/downvoted into oblivion.
# sh test.sh
[+] cleared dmesg
make -C /lib/modules/3.13.11.11+/build M=/home/vagrant/PROG40000-kernel-synchronization modules
make[1]: Entering directory `/home/vagrant/ubuntu-trusty'
CC [M] /home/vagrant/PROG40000-kernel-synchronization/wait.o
/home/vagrant/PROG40000-kernel-synchronization/wait.c:61:1: warning: initialization from incompatible pointer type [enabled by default]
};
^
/home/vagrant/PROG40000-kernel-synchronization/wait.c:61:1: warning: (near initialization for ‘wait_fops.unlocked_ioctl’) [enabled by default]
In file included from include/linux/moduleparam.h:4:0,
from /home/vagrant/PROG40000-kernel-synchronization/wait.c:11:
/home/vagrant/PROG40000-kernel-synchronization/wait.c: In function ‘__inittest’:
include/linux/init.h:297:4: warning: return from incompatible pointer type [enabled by default]
{ return initfn; } \
^
/home/vagrant/PROG40000-kernel-synchronization/wait.c:167:1: note: in expansion of macro ‘module_init’
module_init(wait_init);
^
Building modules, stage 2.
MODPOST 1 modules
CC /home/vagrant/PROG40000-kernel-synchronization/wait.mod.o
LD [M] /home/vagrant/PROG40000-kernel-synchronization/wait.ko
make[1]: Leaving directory `/home/vagrant/ubuntu-trusty'
[--dmesg--]
[13112.810008] [wait device] has been unregistered
[13112.819049] [wait device] has been registered
[-/dmesg--]
[+] compiled user-mode program
-----
[fail]: KERN_IOCTL_CREATE_EVENT: Inappropriate ioctl for device
[fail]: KERN_IOCTL_CREATE_EVENT: Inappropriate ioctl for device
[+] executed user-mode program
-----
[--dmesg--]
[13112.810008] [wait device] has been unregistered
[13112.819049] [wait device] has been registered
[13112.893049] SOMEONE DARE READ FROM ME!?
[13112.893057] [wait device] invalid magic number: 0:0:191
[13112.893535] [wait device] invalid magic number: 0:0:191
[-/dmesg--]
Okay. So. Here's the solution.
In Linux kernel 2.6.x the declaration for _ioctl calls changed from
static long wait_ioctl(struct inode *, struct file *, unsigned int, unsigned long);
To:
static long wait_ioctl(struct file *, unsigned int, unsigned long);
The fix is thus:
...
static long wait_ioctl(struct file *, unsigned int, unsigned long);
...
static long wait_ioctl(struct file *file, unsigned int cmd, unsigned long sub_cmd){
if(_IOC_TYPE(cmd) != WAIT_DEVICE_MAGIC){
printk(KERN_INFO "[wait device] invalid magic number: %u:%u:%u", _IOC_TYPE(cmd), cmd, WAIT_DEVICE_MAGIC);
return -ENOTTY;
}
....
.compat_ioctl
Also make sure to implement this file_operation if you are making 32-bit calls to a 64-bit kernel.
The symptom is that your ioctl handler is never run.

Cannot accessing the vm_list and mm_struct from a kernel module

I am trying to access the vm_list and the mm_struct from a kernel module, but for some reason, my output is always null, even though I have up to 3 VMs running.
In case it matters, the whole thing is running inside a VM because I don't want to mess with the real kernel.
#undef __KERNEL__
#define __KERNEL__
#undef MODULE
#define MODULE
// Linux Kernel/LKM headers: module.h is needed by all modules and kernel.h is needed for KERN_INFO.
#include <linux/module.h> // included for all kernel modules
#include <linux/kernel.h> // included for KERN_INFO
#include <linux/init.h> // included for __init and __exit macros
#include <linux/kallsyms.h>
#include <linux/string.h>
#include <linux/kvm.h>
#include <linux/kvm_host.h>
#include <linux/mm_types.h>
#include <linux/slab.h>
#include <linux/async.h>
MODULE_LICENSE("GPL");
struct list_head *vms_list;
struct mm_struct *mms_struct;
raw_spinlock_t *vm_lock;
int init_module(void)
{
struct list_head *itr;
struct kvm* kvm;
int i;
printk(KERN_INFO "Hello world!\n");
vms_list = (struct list_head*)kallsyms_lookup_name("vm_list");
mms_struct = (struct list_head*)kallsyms_lookup_name("mm_struct");
vm_lock =(raw_spinlock_t*)kallsyms_lookup_name("kvm_lock");
if(!mms_struct && !vms_list){
printk(KERN_INFO "vms_list and mms_struct are %p, %p\n", vms_list, mms_struct);
return 0; <--- This line gets executed every time.
}
printk(KERN_INFO "here 2\n");
raw_spin_lock(vm_lock);
list_for_each_entry(kvm, vms_list, vm_list)
{
printk(KERN_INFO "%p\n", kvm);
}
raw_spin_unlock(vm_lock);
itr = 0;
// printk(KERN_INFO "%p\n", itr);
return 0;
};
void cleanup_module(void)
{
printk(KERN_INFO "Goodbye world!\n");
};
References:
vm_list -> list_head
mm_struct
Answering my own question.
In short: VirtualBox (which runs the outer guest), does not support nested virtualization (see feature request).
I have found this out by simply doing a cat /proc/cpuinfo | grep vmx and getting an empty output.
Hope this will someday help someone.
Try using qemu nested virtualization on a linux host. (a dream within a dream)
--------------------
L2 | VM_1 | VM_2 | ... |
--------------------
L1 | guest hypervisor |
---------------------
L0 | host hypvevisor |
--------------------
You need to enable the VMX instructions into the guest hypervisor:
enable nested virtualization when inserting the kvm module:
modprobe kvm_intel nested=1
enable the vmx cpu flag when starting qemu in L0
qemu .... -cpu qemu64,+vmx -enable-kvm
Now when you start your VM's from L1, you should be able to see a non-null vm_list.

How to use timers in Linux kernel device drivers?

I want to implement a counter in Linux device drivers which increments after every fixed interval of time. I want to do this with the help of timers. A sample code snippet would be very useful.
Have a look at following article IBM Developerworks: Timers and Lists
There is a small example of how to use Linux kernel timers (included it here for convenience, comments are from myself, removed printk messages)
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/timer.h>
MODULE_LICENSE("GPL");
static struct timer_list my_timer;
void my_timer_callback( unsigned long data )
{
/* do your timer stuff here */
}
int init_module(void)
{
/* setup your timer to call my_timer_callback */
setup_timer(&my_timer, my_timer_callback, 0);
/* setup timer interval to 200 msecs */
mod_timer(&my_timer, jiffies + msecs_to_jiffies(200));
return 0;
}
void cleanup_module(void)
{
/* remove kernel timer when unloading module */
del_timer(&my_timer);
return;
}
Around Linux kernel 4.15 release, void setup_timer(timer, function, data); became obsolete with an intent to remove it completely.
Instead, now we have to use
void timer_setup(
struct timer_list *timer,
void (*callback)(struct timer_list *),
unsigned int flags
);
This can be found in linux/timer.h file.
Here's a full example of module_with_timer.c
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/jiffies.h>
#include <linux/timer.h>
MODULE_LICENSE("GPL");
static struct timer_list my_timer;
void my_timer_callback(struct timer_list *timer) {
printk(KERN_ALERT "This line is printed after 5 seconds.\n");
}
static int init_module_with_timer(void) {
printk(KERN_ALERT "Initializing a module with timer.\n");
/* Setup the timer for initial use. Look in linux/timer.h for this function */
timer_setup(&my_timer, my_timer_callback, 0);
mod_timer(&my_timer, jiffies + msecs_to_jiffies(5000));
return 0;
}
static void exit_module_with_timer(void) {
printk(KERN_ALERT "Goodbye, cruel world!\n");
del_timer(&my_timer);
}
module_init(init_module_with_timer);
module_exit(exit_module_with_timer);
And the Makefile is
obj-m = module_with_timer.o
# Get the current kernel version number
KVERSION = $(shell uname -r)
all:
make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean
Note: In real life programming, it is better to check the version of the kernel we are compiling for and then use an then appropriately start the timer.
References:
https://lwn.net/Articles/735887/
Depending on what you exactly want to do, you can directly use jiffies to measure time, as it has been suggested in the comments. You can also use kernel timers, and given the information in your question, they seem to be a better fit.
The kernel timers API is quite intuitive:
#include <linux/timer.h>
struct timer_list {
/* ... */
unsigned long expires;
void (*function)(unsigned long);
unsigned long data;
};
void init_timer(struct timer_list *timer);
struct timer_list TIMER_INITIALIZER(_function, _expires, _data);
void add_timer(struct timer_list * timer);
int del_timer(struct timer_list * timer);
So you would just need to define a timer function and then initialize and start the timer.
You have several sources to further learn about this topic:
Understanding the Linux Kernel. This book is a sort of bible for the kernel. It is somehow outdated in some areas, but still a really good source of information.
Linux Device Drivers. This is a very useful book when developing device drivers. There is an online version too here. The chapter dealing with time, timers, etc. is chapter 7. This book may be also a bit outdated since it is from 2005 too.
Linux Kernel Development. I have not checked this book, but the good point is that it is much newer (from 2010), so you may find some updated information compared to the previous two books.

Linux Kernel: System call hooking example

I'm trying to write some simple test code as a demonstration of hooking the system call table.
"sys_call_table" is no longer exported in 2.6, so I'm just grabbing the address from the System.map file, and I can see it is correct (Looking through the memory at the address I found, I can see the pointers to the system calls).
However, when I try to modify this table, the kernel gives an "Oops" with "unable to handle kernel paging request at virtual address c061e4f4" and the machine reboots.
This is CentOS 5.4 running 2.6.18-164.10.1.el5. Is there some sort of protection or do I just have a bug? I know it comes with SELinux, and I've tried putting it in to permissive mode, but it doesn't make a difference
Here's my code:
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/unistd.h>
void **sys_call_table;
asmlinkage int (*original_call) (const char*, int, int);
asmlinkage int our_sys_open(const char* file, int flags, int mode)
{
printk("A file was opened\n");
return original_call(file, flags, mode);
}
int init_module()
{
// sys_call_table address in System.map
sys_call_table = (void*)0xc061e4e0;
original_call = sys_call_table[__NR_open];
// Hook: Crashes here
sys_call_table[__NR_open] = our_sys_open;
}
void cleanup_module()
{
// Restore the original call
sys_call_table[__NR_open] = original_call;
}
I finally found the answer myself.
http://www.linuxforums.org/forum/linux-kernel/133982-cannot-modify-sys_call_table.html
The kernel was changed at some point so that the system call table is read only.
cypherpunk:
Even if it is late but the Solution
may interest others too: In the
entry.S file you will find: Code:
.section .rodata,"a"
#include "syscall_table_32.S"
sys_call_table -> ReadOnly You have to
compile the Kernel new if you want to
"hack" around with sys_call_table...
The link also has an example of changing the memory to be writable.
nasekomoe:
Hi everybody. Thanks for replies. I
solved the problem long ago by
modifying access to memory pages. I
have implemented two functions that do
it for my upper level code:
#include <asm/cacheflush.h>
#ifdef KERN_2_6_24
#include <asm/semaphore.h>
int set_page_rw(long unsigned int _addr)
{
struct page *pg;
pgprot_t prot;
pg = virt_to_page(_addr);
prot.pgprot = VM_READ | VM_WRITE;
return change_page_attr(pg, 1, prot);
}
int set_page_ro(long unsigned int _addr)
{
struct page *pg;
pgprot_t prot;
pg = virt_to_page(_addr);
prot.pgprot = VM_READ;
return change_page_attr(pg, 1, prot);
}
#else
#include <linux/semaphore.h>
int set_page_rw(long unsigned int _addr)
{
return set_memory_rw(_addr, 1);
}
int set_page_ro(long unsigned int _addr)
{
return set_memory_ro(_addr, 1);
}
#endif // KERN_2_6_24
Here's a modified version of the original code that works for me.
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/unistd.h>
#include <asm/semaphore.h>
#include <asm/cacheflush.h>
void **sys_call_table;
asmlinkage int (*original_call) (const char*, int, int);
asmlinkage int our_sys_open(const char* file, int flags, int mode)
{
printk("A file was opened\n");
return original_call(file, flags, mode);
}
int set_page_rw(long unsigned int _addr)
{
struct page *pg;
pgprot_t prot;
pg = virt_to_page(_addr);
prot.pgprot = VM_READ | VM_WRITE;
return change_page_attr(pg, 1, prot);
}
int init_module()
{
// sys_call_table address in System.map
sys_call_table = (void*)0xc061e4e0;
original_call = sys_call_table[__NR_open];
set_page_rw(sys_call_table);
sys_call_table[__NR_open] = our_sys_open;
}
void cleanup_module()
{
// Restore the original call
sys_call_table[__NR_open] = original_call;
}
Thanks Stephen, your research here was helpful to me. I had a few problems, though, as I was trying this on a 2.6.32 kernel, and getting WARNING: at arch/x86/mm/pageattr.c:877 change_page_attr_set_clr+0x343/0x530() (Not tainted) followed by a kernel OOPS about not being able to write to the memory address.
The comment above the mentioned line states:
// People should not be passing in unaligned addresses
The following modified code works:
int set_page_rw(long unsigned int _addr)
{
return set_memory_rw(PAGE_ALIGN(_addr) - PAGE_SIZE, 1);
}
int set_page_ro(long unsigned int _addr)
{
return set_memory_ro(PAGE_ALIGN(_addr) - PAGE_SIZE, 1);
}
Note that this still doesn't actually set the page as read/write in some situations. The static_protections() function, which is called inside of set_memory_rw(), removes the _PAGE_RW flag if:
It's in the BIOS area
The address is inside .rodata
CONFIG_DEBUG_RODATA is set and the kernel is set to read-only
I found this out after debugging why I still got "unable to handle kernel paging request" when trying to modify the address of kernel functions. I was eventually able to solve that problem by finding the page table entry for the address myself and manually setting it to writable. Thankfully, the lookup_address() function is exported in version 2.6.26+. Here is the code I wrote to do that:
void set_addr_rw(unsigned long addr) {
unsigned int level;
pte_t *pte = lookup_address(addr, &level);
if (pte->pte &~ _PAGE_RW) pte->pte |= _PAGE_RW;
}
void set_addr_ro(unsigned long addr) {
unsigned int level;
pte_t *pte = lookup_address(addr, &level);
pte->pte = pte->pte &~_PAGE_RW;
}
Finally, while Mark's answer is technically correct, it'll case problem when ran inside Xen. If you want to disable write-protect, use the read/write cr0 functions. I macro them like this:
#define GPF_DISABLE write_cr0(read_cr0() & (~ 0x10000))
#define GPF_ENABLE write_cr0(read_cr0() | 0x10000)
Hope this helps anyone else who stumbles upon this question.
Note that the following will also work instead of using change_page_attr and cannot be depreciated:
static void disable_page_protection(void) {
unsigned long value;
asm volatile("mov %%cr0,%0" : "=r" (value));
if (value & 0x00010000) {
value &= ~0x00010000;
asm volatile("mov %0,%%cr0": : "r" (value));
}
}
static void enable_page_protection(void) {
unsigned long value;
asm volatile("mov %%cr0,%0" : "=r" (value));
if (!(value & 0x00010000)) {
value |= 0x00010000;
asm volatile("mov %0,%%cr0": : "r" (value));
}
}
If you are dealing with kernel 3.4 and later (it can also work with earlier kernels, I didn't test it) I would recommend a smarter way to acquire the system callы table location.
For example
#include <linux/module.h>
#include <linux/kallsyms.h>
static unsigned long **p_sys_call_table;
/* Aquire system calls table address */
p_sys_call_table = (void *) kallsyms_lookup_name("sys_call_table");
That's it. No addresses, it works fine with every kernel I've tested.
The same way you can use a not exported Kernel function from your module:
static int (*ref_access_remote_vm)(struct mm_struct *mm, unsigned long addr,
void *buf, int len, int write);
ref_access_remote_vm = (void *)kallsyms_lookup_name("access_remote_vm");
Enjoy!
As others have hinted, the whole story is a bit different now on modern kernels. I'll be covering x86-64 here, for syscall hijacking on modern arm64 refer to this other answer of mine. Also NOTE: this is plain and simple syscall hijacking. Non-invasive hooking can be done in a much nicer way using kprobes.
Since Linux v4.17, x86 (both 64 and 32 bit) now uses syscall wrappers that take a struct pt_regs * as the only argument (see commit 1, commit 2). You can see arch/x86/include/asm/syscall.h for the definitions.
Additionally, as others have described already in different answers, the simplest way to modify sys_call_table is to temporarily disable CR0 WP (Write-Protect) bit, which could be done using read_cr0() and write_cr0(). However, since Linux v5.3, [native_]write_cr0 will check sensitive bits that should never change (like WP) and refuse to change them (commit). In order to work around this, we need to write CR0 manually using inline assembly.
Here is a working kernel module (tested on Linux 5.10 and 5.18) that does syscall hijacking on modern Linux x86-64 considering the above caveats and assuming that you already know the address of sys_call_table (if you also want to find that in the module, see Proper way of getting the address of non-exported kernel symbols in a Linux kernel module):
// SPDX-License-Identifier: (GPL-2.0 OR MIT)
/**
* Test syscall table hijacking on x86-64. This module will replace the `read`
* syscall with a simple wrapper which logs every invocation of `read` using
* printk().
*
* Tested on Linux x86-64 v5.10, v5.18.
*
* Usage:
*
* sudo cat /proc/kallsyms | grep sys_call_table # grab address
* sudo insmod syscall_hijack.ko sys_call_table_addr=0x<address_here>
*/
#include <linux/init.h> // module_{init,exit}()
#include <linux/module.h> // THIS_MODULE, MODULE_VERSION, ...
#include <linux/kernel.h> // printk(), pr_*()
#include <asm/special_insns.h> // {read,write}_cr0()
#include <asm/processor-flags.h> // X86_CR0_WP
#include <asm/unistd.h> // __NR_*
#ifdef pr_fmt
#undef pr_fmt
#endif
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
typedef long (*sys_call_ptr_t)(const struct pt_regs *);
static sys_call_ptr_t *real_sys_call_table;
static sys_call_ptr_t original_read;
static unsigned long sys_call_table_addr;
module_param(sys_call_table_addr, ulong, 0);
MODULE_PARM_DESC(sys_call_table_addr, "Address of sys_call_table");
// Since Linux v5.3 [native_]write_cr0 won't change "sensitive" CR0 bits, need
// to re-implement this ourselves.
static void write_cr0_unsafe(unsigned long val)
{
asm volatile("mov %0,%%cr0": "+r" (val) : : "memory");
}
static long myread(const struct pt_regs *regs)
{
pr_info("read(%ld, 0x%lx, %lx)\n", regs->di, regs->si, regs->dx);
return original_read(regs);
}
static int __init modinit(void)
{
unsigned long old_cr0;
real_sys_call_table = (typeof(real_sys_call_table))sys_call_table_addr;
pr_info("init\n");
// Temporarily disable CR0 WP to be able to write to read-only pages
old_cr0 = read_cr0();
write_cr0_unsafe(old_cr0 & ~(X86_CR0_WP));
// Overwrite syscall and save original to be restored later
original_read = real_sys_call_table[__NR_read];
real_sys_call_table[__NR_read] = myread;
// Restore CR0 WP
write_cr0_unsafe(old_cr0);
pr_info("init done\n");
return 0;
}
static void __exit modexit(void)
{
unsigned long old_cr0;
pr_info("exit\n");
old_cr0 = read_cr0();
write_cr0_unsafe(old_cr0 & ~(X86_CR0_WP));
// Restore original syscall
real_sys_call_table[__NR_read] = original_read;
write_cr0_unsafe(old_cr0);
pr_info("goodbye\n");
}
module_init(modinit);
module_exit(modexit);
MODULE_VERSION("0.1");
MODULE_DESCRIPTION("Test syscall table hijacking on x86-64.");
MODULE_AUTHOR("Marco Bonelli");
MODULE_LICENSE("Dual MIT/GPL");

Resources