在内核模块中为根用户提供权限

Providing permissions for a root user in a kernel module

Linux Kernel 5.0.0-37

我正在编写一个函数来管理权限,作为指向 struct inode_operations 的函数指针提供。这是一个简化的存根实现:

#include <linux/cred.h>

int pfsw_permission(struct inode *ino, int op){
    if(uid_eq(INIT_USER->uid, get_current_user()->uid)){
        printk(KERN_INFO "Current user is root\n");
    } else {
        printk(KERN_INFO "Current user is not root\n");
    }
    if(op & (MAY_READ | MAY_WRITE)){
        return 0;
    }

    return -EACCES;
}

编译包含此函数的内核模块并尝试加载它时 dmesg 显示以下错误:

Unknown symbol root_user (err -2)

我认为这是由于 INIT_USER 来自 include/linux/sched/user.h 的宏定义为

extern struct user_struct root_user;
#define INIT_USER (&root_user)

问题: 为什么符号 root_user 已声明,但未定义?如何正确使用INIT_USER

root_user 不被 linux 内核 seem to be exported using EXPORT_SYMBOL;因此您不能从模块中使用它。

查看 its definition 我们可以看到 uid 值设置为 GLOBAL_ROOT_UID。这是在 include/linux/uidgid.h 中定义的宏,基本上只是 0 到 kuid_t 的类型转换,因此如果您只需要 UID,就可以使用该宏。

所以...

Why is the symbol root_user declared, but not defined?

符号已定义。虽然它没有导出,所以您不能从模块中使用它。

How to use INIT_USER correctly?

"Not"。你不能使用它。