23

是否可以使用 iptables 来允许由“进程”发起的流量,即使用进程名称?例如,我想允许由 ping 命令启动的所有内容。

4

5 回答 5

27

看起来所有者iptables 模块就是您想要的。首先,检查它是否在您的系统中可用:

iptables -m owner --help

你可以在这里阅读更多:http ://www.frozentux.net/iptables-tutorial/iptables-tutorial.html#OWNERMATCH

于 2010-11-30T13:52:53.203 回答
10
-m owner --pid-owner PID

请参阅http://linuxpoison.blogspot.com/2010/11/how-to-limit-network-access-by-user.htmlhttp://linux.die.net/man/8/iptables

请注意,您需要 ipt_owner 模块,因为 xt_owner 不支持 --pid-owner。

例如(这只是一个近似值)

#!/bin/bash
$@ &
iptables -m owner --pid-owner %1 -j REJECT

但实际上,最好使用--uid-owner 和--gid-owner。首先,--pid-owner 标准仅匹配确切的 pid,这意味着您的程序可以轻松生成不会被此规则阻止的子进程。(至少我没有阅读其他内容。)其次,iptables(8) 警告 --pid-owner 在 SMP 系统上已损坏(这可能适用于您,也可能不适用于您,但在任何一种情况下都会限制可移植性)。第三,上面的脚本中有一个竞态条件,因为进程在被阻塞之前就已经启动了。(如果有办法在进程启动之前获取进程的 pid,那么我从未听说过。)

于 2015-01-21T18:48:13.117 回答
4

如果有办法在进程启动之前获取进程的 pid,那么我从未听说过它。

您可以编写一个首先分叉的包装器,然后添加规则并执行进程(假设您正在运行的程序不会再次分叉),因为 exec(3) 调用不会更改 PID。

/* NOTE this contains zero error checking */
int main(int argc, char **argv) {
    /* Eat argv[0] the name of the wrapper script */
    argv++;
    argc--;

    pid_t my_pid = getpid();

    char *iptables_cmd = NULL;
    asprintf(&iptables_cmd, "/sbin/iptables -A INPUT -m owner --pid_owner %d -j ACCEPT", my_pid);

    system(iptables_cmd);

    execv(argv[0], argv);
}
于 2016-12-13T19:48:33.577 回答
3

基于@Bgs 的回答,我会这样做:

  1. 添加一个新的系统组,例如。snitch
sudo addgroup --system snitch
  1. Add yourself to that group, so that you won't be asked for a password to run processes with the primary group set to it:
sudo adduser $USER snitch
  1. Add IPv4 and IPv6 rules to log and reject any packets generated by processes belonging to that group:
sudo iptables  -A OUTPUT -m owner --gid-owner snitch -j LOG --log-prefix 'Snitch: '
sudo ip6tables -A OUTPUT -m owner --gid-owner snitch -j LOG --log-prefix 'Snitch: '
sudo iptables  -A OUTPUT -m owner --gid-owner snitch -j REJECT
sudo ip6tables -A OUTPUT -m owner --gid-owner snitch -j REJECT
  1. Open a tail watch on kernel messages:
dmesg -w
  1. Launch your target process using sg or any other similar means:
sg snitch 'your target program'
于 2020-10-11T19:59:52.333 回答
0

关于 iptables 的法语维基百科页面https://fr.wikipedia.org/wiki/Iptables指出从内核 2.6.14 开始删除了使用 --pid-owner 或 --cmd-owner 进行过滤的可能性......和链接到内核​​更改日志,我无法检查这个断言,因为我不是内核内部结构的专家!

英文的等效页面没有详细说明。

使用 UID/GID 过滤仍然有效。

于 2020-08-15T06:48:47.503 回答