问题
I'm writing a kernel module that uses a netfilter hook to filter TCP packets and need to find out the path to the executable that is sending the packets. So far I have used the following approach but it prints names that are seemingly unrelated to the executables used (/usr/lib/firefox/firefox, usr/bin/telnet.netkit and /usr/bin/wget).
pid_t pid = current->pid;
struct path path;
char buff[BUFF_LEN];
snprintf (buff, BUFF_LEN, "/proc/%d/exe", pid);
if(!kern_path(buff, LOOKUP_FOLLOW, &path)) {
struct dentry* procEntry = path.dentry;
printk("Process: %s\n", procEntry->d_name.name);
printk("Parent: %s\n", procEntry->d_parent->d_name.name);
}
Kernel log output:
回答1:
This reads like a poor quality college assignment and I have a distinct impression something of the sort already appeared here.
Your code most likely executes from an interrupt context, i.e. a random thread got interrupted to do packet processing and 'current' is a pointer to said random thread. This should be easy to verify e.g. by obtaining a backtrace -- doable with WARN_ONCE and the like.
Looking for executable name of current by going through procfs is weirdly bad. procfs has to do more work and ends up accessing what's effectively current anyway. To make matters worse, you fail to put the found path thus you leak resources. If this code indeed executes from an interrupt handler, the result is not only nonsensical but can't be safely obtained with this method due to sleep potential.
Even if you were to obtain the "right" executable name, the entire assignment is crap. There are many ways in which one process can alter execution of another. thus effectively bypassing whatever filter you have in place. Interestingly there is a way to just change your process name to something else without execing anything, once more invalidating the concept.
The best you can do is filter by credentials, but they are not process-specific. In principle you can add selinux labels to files and filter by that, but once more that's weak.
In short, the assignment is bullshit.
来源:https://stackoverflow.com/questions/47634064/finding-name-of-executable-sending-packet-in-a-netfilter-hook