Make application use specific network interface

Posted on

Problem :

I have an openvpn connection and I need it to work only for one application, this app uses an specific local port. I used route-nopull on my openvpn config file and then:

ip route add default via {P-t-P-IP} dev tun0 table 10;
ip rule add from {tun0-inet addres} table 10;

Using curl to test I tried.

curl --interface tun0;

The first one gives my normal ip, the second one the openvpn connection ip, so that seems to work well.

Now I am having problems making a specific app use the tun0 interface. The app uses the local port 1033 to make some web requests. I tried these iptables rules (one at a time) i found googling:

iptables -A OUTPUT -o eth0 -p tcp -m tcp --sport 1033 -j DROP
iptables -A OUTPUT -o tun0 -p tcp -m tcp --sport 1033 -j ACCEPT

iptables -A PREROUTING -p tcp --sport 1033 -i tun0

iptables -A PREROUTING -i tun0 -p tcp -m tcp --sport 1033

iptables -A PREROUTING -i tun0 -t mangle -p tcp --sport 1033 -j MARK --set-mark 1

Then I ran this test:

curl --local-port 1033

But I get my normal eth0 ip, not the openvpn connection ip.

If I try these rules (have also set ipv4_forward to 1):

iptables -t nat -A POSTROUTING -p tcp --sport 1033 -j SNAT --to-source;
iptables -t nat -A POSTROUTING -p udp --sport 1033 -j SNAT --to-source; is my tun0 interface ip (the one openvpn uses), then the curl command times out.

How can I make all traffic that from local port 1033 go through the tun0 interface?

Solution :

You can use linux network namespace for that
I think you can add tun interface to a different namespace and run your app in that namespace.
here is some example how to use this.

Leave a Reply

Your email address will not be published. Required fields are marked *