I would like to route traffic to some specific addresses through VPN. Easy enough, one can simply add a route:
ip route add <destination ip> dev tun0 scope link
Here comes the catch: I do not want to route all traffic through the VPN, just some. Ideally, I would like to "map" an IP (e.g. a 10.x.x.x address) which would "point" to the real destination IP, but routed through the VPN. As far as I understand, this amounts to adding a route (like above), and then carrying out the equivalent of DNAT in a POSTROUTING chain.
Essentially, I would like to do a Dirty NAT trick in reverse (i.e. on the client instead of the server).
(I would like to create a simple HTTP proxy that routes traffic through the VPN only if the URL matches a given pattern. The ultimate solution would be to influence the routing of a given connection directly from a user-space program, but I think that's impossible.)
Let's say I would like to direct some traffic to, say,
tun0, but I still want some traffic to
18.104.22.168 go through
eth0. For example, image
22.214.171.124 hosted multiple sites and I want to tunnel traffic going to only some sites.
I would like to set up a "fake" address, say,
10.1.2.3. Any traffic directed from my computer to
10.1.2.3 would go to
126.96.36.199, but get routed through
tun0 instead of the main routing table.
I partially managed to set up: first I picked to an IP range, say
10.1.0.0/16. Than I mark packages in the OUTPUT chain goind to that range with, say,
sudo iptables -A OUTPUT -t mangle --dst 10.1.0.0/16 -j MARK --set-mark 64
Next, I add DNAT rules to map the "fake" IPs from that range to the real destination. This could be probably automated:
sudo iptables -A OUTPUT -t nat --dst 10.1.2.3 -j DNAT --to 188.8.131.52
Based on the mark, I route the packages by a different routing table:
sudo ip rule add fwmark 64 lookup vpn sudo ip route add default dev tun0 scope global proto static table vpn
Unfortunately, I still cannot ping
10.1.2.3. If I remove the MARK rule, I do get response, so the DNAT part works as expected.