iptables rule to set source IP depending on local userid
Solution 1:
Now (iptables v1.4.21) it's works in one step:
iptables -t nat -A POSTROUTING ! -o lo -m owner --uid-owner 1030 -j SNAT --to-source 10.0.0.85
And the user with uid 1030 will be originating all connections from the 10.0.0.85 (if the ip is on the outgoing interface).
Solution 2:
Unfortunately, due to the way netfilter
works, you can't do a 'one-step' setup.
- Packet owners can only be detected in the OUTPUT chain, but
- SNAT can only be performed in the POSTROUTING chain
That said, instead of using SNAT, I recommend using a combination of netfilter
and iproute2
, e.g.:
For 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
For 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