Routing application traffic through specific interface

Solution 1:

Have you looked at the owner module within iptables, possibly combined with a source NAT rule?

This lets you setup OUTPUT chain rules based on UID, GID, PID, SID and command name.

Solution 2:

There is support in linux for binding an application to a specific IP (used for example by Apache). If your application does not support this you are out of luck.

I am not aware of any linux kernel modules (because that is what you would need) to bind a specific application to an interface even when it tries to bind to *. Using a virtual machine is one possibility.

The closest thing I can come up with to your requirements if there is no application support is Ethernet interface bonding (http://www.cyberciti.biz/howto/question/static/linux-ethernet-bonding-driver-howto.php). But then you would only be running one instance of the application on multiple interfaces with the same ip.

Solution 3:

I believe the best option is to bind each application to a different IP, and use source-based routing to change which interface packets from that source IP go out via.

The general idea is that you can create multiple parallel routing tables ('ip route' has an optional 'table' parameter). Then you add a rule saying "if it's from IP [x.x.x.x] then use table [foo]".

So:

  • Create routing tables [foo1, foo2] in /etc/iproute2/rt_tables
  • Populate routing tables (something like "ip route add default gateway 1.2.3.4 dev eth0 table foo1" nd likewise for foo2)
  • Create rules to say which table to use based on source IP - "ip rule add from 1.2.3.2/32 table foo1", "ip rule add from 1.2.3.3/32 table foo2".

I haven't tested those examples specifically, but I've used similar in the past succesfully.