Adding your own syscall in linux kernel

0x00:

主要是一个记录,搞kernel exploit可能会需要。给自己的linux增加一个自定义的系统调用,开始找的资料比较老3.x的内核,然而4.x的源码和3.x源码结构不太一样,所以过程也不太一样,多多参考一些比较官方的文档

环境准备

  • ubuntu 14.04 LTS x86 (4.2.0-42-generic)

0x01:过程

1.获取源码

apt-get source linux-image-$(uname -r)

2.编辑源码

首先创建一个目录放新增系统调用的定义
mkdir helloworld && cd helloworld
然后进去

1
2
3
# muhe @ ubuntu in ~/linux_kernel_study/linux-lts-wily-4.2.0/helloworld [6:48:05] 
$ ls
helloworld.c Makefile
1
2
3
4
5
6
#include <linux/kernel.h>
asmlinkage long sys_helloworld(void){

printk("Hello world\n");
return 0;
}
1
2
Makefile
obj-y=helloworld.o

然后修改源码目录下的Makefile,把刚才新建的helloworld目录加进去
如图所示

修改include/linux/syscalls.h文件,把helloworld原型加进去

1
2
3
4
5
6
7
8
...
asmlinkage long sys_bpf(int cmd, union bpf_attr *attr, unsigned int size);

asmlinkage long sys_execveat(int dfd, const char __user *filename,
const char __user *const __user *argv,
const char __user *const __user *envp, int flags);
asmlinkage long sys_helloworld(void);
#endif

然后修改arch/x86/entry/syscalls下的syscall_32.tbl文件 添加这个调用的信息

1
2
3
4
5
6
...
355 i386 getrandom sys_getrandom
356 i386 memfd_create sys_memfd_create
357 i386 bpf sys_bpf
358 i386 execveat sys_execveat stub32_execveat
359 i386 helloworld sys_helloworld
3.编译新内核

先安装一些需要的工具

1
2
3
sudo apt-get build-dep linux-image-$(uname -r)
sudo apt-get update
sudo apt-get install curses-dev

然后是配置

1
2
3
4
chmod a+x debian/scripts/*
chmod a+x debian/scripts/misc/*
fakeroot debian/rules clean
fakeroot debian/rules editconfigs

编译

1
2
fakeroot debian/rules clean
fakeroot debian/rules binary-headers binary-generic -j 2

4.安装

因为这样编译出来的是deb,所以直接dpkg安装就行了。

安装结束后直接重启就好了。

0x02:测试

编写测试程序

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#include <linux/kernel.h>
#include <sys/syscall.h>
#include <unistd.h>
int main()
{
printf("Invoking 'helloworld' system call");

long int ret = syscall(359); // 359 is the syscall number

return 0;
}

编译后运行,然后使用dmesg查看打印的消息。


可以看到打印了helloworld的信息,即这个syscall添加成功。

0x03:参考与引用

Implementing a system call in Linux Kernel 4.7.1
[UBUNTU 14.04] BUILDING LINUX KERNEL
Linux/Documentation/adding-syscalls.txt
Adding hello world system call to Linux