clinux-kernelhookftrace

How to get the process ID of the program that called a system function


I am writing a small kernel driver that has the job to act as a honeypot and monitor actions taken on a specific file on the system. To start things off, I used the code in this repository, which I then slightly modified for simplicity reasons so that it works only for one system call: sys_open.

Now I need to gather information for the process and the user that run that system call to open this file, but I could not find any way to do it. I thought that I could use the file descriptor to identify which process has it, but after a discussion with my university professor, he told me that file descriptors are NOT unique system-wide, but only process-wide.

To conclude, is there a way that could give me the PID of the process that implicitly called sys_open?


Solution

  • When running in kernel code, information about the currently running process is stored in the current global variable (it's actually a platform specific macro rather than a global variable, to be precise), which is a struct task_struct. If you are inside a syscall handler (or a hook to one), then current will be the process which started the syscall, and you can just check current->pid to get its PID.

    To get the current process' UID, GID, EUID, EGID (and so on) you can use the set of macros defined in linux/cred.h. From the relative kernel documentation page:

    There are convenience wrappers for retrieving specific aspects of a task’s credentials (the value is simply returned in each case):

    uid_t current_uid(void)     // Current's real UID
    gid_t current_gid(void)     // Current's real GID
    uid_t current_euid(void)    // Current's effective UID
    gid_t current_egid(void)    // Current's effective GID
    /* ... */