Networking – Only Allow Certain Outbound Traffic on Specific Interfaces

iptablesnetworking

I have rather an odd issue. I have a server with two network interfaces eth0 and eth1. Each are connected to a different network. Each network has a internet gateway. The server has various outbound connections: http (some scripts on the server scrape websites), nfs client, samba client, dns client and an email fetcher to name but a few.

For reasons I won't go into, I need to split these outbound clients up so outbound http, nfs, samba and dns traffic is only requested over eth0 while everything else goes off through eth1.

I've read around a few Google searches and it looks like iptables is what I'll need but I really haven't got a clue. I'm only used to managing inbound firewall rules through ufw.

Could somebody start me off with a few example rules and tell me how to get the system to adopt these rules on boot? Ideally without locking me out of my SSH connection (I can get physical access, but I'd rather not).

Edit I can split the clients over two users if it's possible to limit all outbound traffic from an account to one interface. on paper that seems like it might be easier.

Best Answer

I would setup a separate routing table and a policy to route marked packets using that table and have iptables/netfilter mark certain packets.

Create a table: echo 1 known >> /etc/iproute2/rt_tables

Create a routing rule (the ip command is from iproute2): ip rule add from all fwmark 1 table known

We created a table called "known" and created a routing rule that says any packet with a mark equal to 1 gets routed according to the "known" table. I only called it known because it's for the list of known protocols - you can name it whatever you want. Now we setup the known table to route the proper way.

ip route add default dev eth0 table known

Create iptables rules:

iptables -t mangle -I PREROUTING -p tcp --dport 111 -j MARK --set-mark 1
iptables -t mangle -I PREROUTING -p tcp --dport 2049 -j MARK --set-mark 1

The example marks packets on the NFS ports (111, 2049) with a 1. We are adding this rule to the 'mangle' iptable. This is different from the routing tables and is not changeable; the mangle table is specifically for altering packets in any way other than NAT.

Now, to route everything else through the other interface, we add a route to the standard routing table.

ip route add default dev eth1

To really understand this, read sections 4 and 11 of the LARTC howto.

Related Question