向 Linux 添加需要 root 权限的新系统调用

Spi*_*ico 6 c linux linux-kernel

我正在尝试向需要root权限才能运行的linux内核(版本:3.10.91)添加系统调用。

您可以在下面看到我的尝试:

#include <linux/kernel.h>
#include <linux/linkage.h>
#include <linux/sched.h>
#include <asm/current.h>
#include <asm/errno.h>

asmlinkage long sys_set_casper(pid_t pid, int value)
{
    struct task_struct *process;
    
    if (!capable(CAP_SYS_ADMIN))
        return -EPERM;
    
    //valid values are 0,1,2,3
    if (value != 0 && value != 1 && value != 2 && value != 3 )
        return -EINVAL;
    
    process = find_task_by_vpid(pid);
    if (process == NULL)
        return -ESRCH;

    //modify the casper field accordingly   
    process->casper = value;
    return 0;   
}
Run Code Online (Sandbox Code Playgroud)

Casper只是我添加的一个任务描述符。基本上,我希望当 casper 值为 1 时进程被隐藏(对 ps、pstree、top 等不可见)。内核重新编译得很好(而且我还在 base.c 等中做了必要的更改)。

我尝试使用以下代码 test.c 测试我的系统调用:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define NR_set_casper 351

int main(int argc, char **argv)
{
    long y;
    printf("PID of current process: %d\n\n", getpid());
    
    printf("Call set_casper system call to set flag 1\n");
    y = syscall(NR_set_casper, getpid(), 0);
    printf("Return value of set_casper system call: %ld\n", y);
    if (y < 0)
    {
        printf("set_casper system call failed. Run with sudo\n");
        return EXIT_FAILURE;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我编译并运行如下:

海湾合作委员会测试.c

须藤./a.out

输出是:

PID of current process: 3852

Call set_casper system call to set flag 1
Return value of set_casper system call: -1
set_casper system call failed. Run with sudo
Run Code Online (Sandbox Code Playgroud)

奇怪的是,即使删除了 sudo 控制行:

 if (!capable(CAP_SYS_ADMIN))
        return -EPERM;
Run Code Online (Sandbox Code Playgroud)

并重新编译内核,我仍然遇到同样的错误。

基本上,为什么我的 sys_set_casper 函数返回 -1 ?

编辑

我添加了这个: 351 i386 set_casper sys_set_casper to arch/x86/syscalls$ gedit syscall_32.tbl

不过我的系统是64位的。这可能是问题所在吗?

Spi*_*ico 2

正如其他人在评论中所说,问题是我根本没有调用系统调用。我只是将我的调用添加到 64 位系统调用表中,然后再次尝试一切,它成功了。