在linux内核模块中得到fd指向的路径

最近正在完成一份简单的内核模块编码作业,功能是模拟 rootkit 隐藏进程。根据 strace ps 的观察,ps 程序通过 open /proc 打开 fd,通过 getdents <fd> 遍历目录。

sys_getdents 的函数原型如下:

// linux/syscalls.h
asmlinkage long (*sys_getdents) (unsigned int fd, struct linux_dirent __user *dirent, unsigned int count);

struct linux_dirent 的结构如下:

// linux/fs/readdir.c
struct linux_dirent {
    unsigned long   d_ino;
    unsigned long   d_off;
    unsigned short  d_reclen;
    char            d_name[1];
};

因为不想污染对其他目录的访问,所以希望在给 sys_getdents 加钩子时能判断 fd 指向的路径。

在用户态编程时,我们可以使用 readlink /proc/self/fd/<fd> 获取它,但在内核态下有什么好办法吗?望不吝赐教,谢谢!

回复
阅读 4.7k
1 个回答

思路:通过 fd -> struct file -> struct path -> 路径 获取路径

  1. fget(fd) 得到 struct file
  2. d_path(file.path) 得到路径

==== 以上是答主原文,以下是题主补充 ====

没有使用 fget,而是使用了 current->files,具体代码如下:

struct files_struct *files;
struct file *file;

int buflen = 256;
char buf[buflen];
char *path;

files = current->files;
spin_lock(&files->file_lock);
file = fcheck_files(files, fd);
path = d_path(&file->f_path, buf, buflen);
spin_unlock(&files->file_lock);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏