iptables规则根据本地用户ID设置源IP

我有两个用户,alpha(uid 500)和beta(uid 501),以及两个分配为eth0和eth0:1的IP地址。 我希望所有由用户alpha启动的进程发出的数据包都标记为eth0的源IP地址,而来自用户beta进程的所有数据包都将标记为eth0:1的源IP地址。

从search这个论坛和其他地方的可用答案,我发现我应该这样做:

# mark packets with 11 or 12 depending which user they came from: iptables -A OUTPUT -m owner --uid-owner 500 -j MARK --set-mark 11 iptables -A OUTPUT -m owner --uid-owner 501 -j MARK --set-mark 12 # now, for a packet having mark 11 (or 12), set source IP to 192.168.1.1 (or .2) iptables -t nat -I POSTROUTING -m connmark --mark 11 -j SNAT --to-source 192.168.1.1 iptables -t nat -I POSTROUTING -m connmark --mark 12 -j SNAT --to-source 192.168.1.2 

上述工作? 有一个更简单的(一步,而不是两步)设置? 我怎样才能使用tcpdump来validation它的工作,的确如此?

不幸的是,由于netfilter工作方式,你不能做一个“一步”的设置。

  • 数据包所有者只能在OUTPUT链中检测到,但是
  • SNAT只能在POSTROUTING链中执行

这就是说,我不推荐使用SNAT,而是推荐使用netfilteriproute2的组合,例如:

对于netfilter

 iptables -A OUTPUT -m owner --uid-owner 500 -j MARK --set-mark 500 iptables -A OUTPUT -m owner --uid-owner 501 -j MARK --set-mark 501 

对于iproute2

 ip rule add fwmark 500 table 500 ip rule add fwmark 501 table 501 ip route add default via $gateway dev eth0 src $ip_eth0 table 500 ip route add default via $gateway dev eth0 src $ip_eth0_1 table 501