如何在编写Linux内核模块时获取userID

时间:2012-12-31 04:21:20

标签: c linux-kernel

这是我的内核模块中的函数,我在insmod之后使用make命令在后期插入。我正在研究goldfish (2.6.29)

asmlinkage long our_sys_read(unsigned int fd, char  *buf, size_t count)
{
      printk("------->> our_sys_read getuid() ---------- %d\n", getuid());

      return original_call_read(fd,buf,count);
}

我想捕获系统调用并找出哪些用户进行了这些系统调用。但是当我运行'make'时,它会抛出我的错误。

/home/mohsin/LKM/trapcall.c:245: error: implicit declaration of function 'getuid'

任何建议都将不胜感激。

4 个答案:

答案 0 :(得分:6)

你也许可以用这个:

 #include <include/linux/cred.h>

 static int getuid()
 {
     return current_uid();
 }

cred代表“凭据”,此宏返回当前活动凭据的用户ID。但请记住,“当前用户ID”在Linux中可能意味着多种用途。

[dan3显然没有像我一样挖掘相同数量的代码 - 或者他在我面前开始!]

答案 1 :(得分:5)

你需要调用在linux / cred.h中定义的current_uid()(从2.6开始,以前是当前的&gt; uid)。请参阅kernel doc about credentials

当前是macro,BTW。

答案 2 :(得分:5)

花了两天之后,我终于想出了如何获得进行系统调用的进程。我将提供我在不同链接上找到的所有建议,以便如果我的解决方案不起作用,其他一个可能会有效。

1)告诉我Mats,

#include <include/linux/cred.h>

 static int getuid()
 {
     return current_uid();
 }

你调用此函数来获取uid,但它给了我一些负数,如-943124788等。

2)

uid_t credd_uid ;
const struct cred *cred = current_cred();
credd_uid = current->cred->uid; 

相同的输出,如大负数。

3)

uid_t struct_uid;
struct user_struct *u = current_user();

struct_uid = get_uid(u);

4)工作解决方案

实际上给了here

i)在顶部声明函数原型,如

asmlinkage int (*getuid_call)();

ii)将以下行添加到init_module()函数

/ *获取getuid * /

的系统调用
  getuid_call = sys_call_table[__NR_getuid];

iii)调用被困系统调用函数中的函数以获得类似

的uid
uid_t uid = getuid_call();

答案 3 :(得分:0)

在不使用getuid系统调用挂钩的情况下获取UID:

#include "linux/cred.h"

static inline uid_t get_uid(void) {
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 5, 0)
#include "linux/uidgid.h"
    // current_uid() returns struct in newer kernels
    return __kuid_val(current_uid());
#else
    return 0 == current_uid();
#endif
}

您还应该通过linux/uidgid.h查看定义ROOT uid / gid的有用宏以及内联比较函数,以避免直接调用__kuid_val()

例如,常见的用途是检查用户是否为root:

static inline bool is_root_uid(void) {
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 5, 0)
#include "linux/uidgid.h"
    // current_uid() returns struct in newer kernels
    return uid_eq(current_uid(), GLOBAL_ROOT_UID);
#else
    return 0 == current_uid();
#endif
}
相关问题