Forward (redirect/nat) traffic with iptables

From vpsget wiki
Revision as of 19:00, 17 July 2013 by Ndi (talk | contribs)
Jump to: navigation, search

If you want to redirect/nat some traffic to IP 2.2.2.2 via IP 1.1.1.1, it simply can be done with iptables on IP 1.1.1.1.
You can also redirect/nat traffic to specific port by specifying a port instead of range.

It's useful for example if you would like to configure "double openvpn": in this case you connect to 1st ip address which forward you to your open vpn server and you "exit under second ip".


First of all enable IP forwarding in /etc/sysctl.conf on 1.1.1.1 host:

net.ipv4.ip_forward=1

Execute following for the changes to take effect:

sysctl -p

iptables rules example to forward&nat with another ip all tcp/udp traffic with port ranges 1000-65500

iptables -A FORWARD -d 2.2.2.2 -i eth0 -p tcp -m tcp --dport 1000:65500 -j ACCEPT #forward tcp port range
iptables -A FORWARD -d 2.2.2.2 -i eth0 -p udp -m udp --dport 1000:65500 -j ACCEPT #forward udp port range
iptables -t nat -A PREROUTING -d 1.1.1.1 -p tcp -m tcp --dport 1000:65500 -j DNAT --to-destination 2.2.2.2  #tcp port range
iptables -t nat -A PREROUTING -d 1.1.1.1 -p udp -m udp --dport 1000:65500 -j DNAT --to-destination 2.2.2.2  #udp port range
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE

Example for single tcp port:

iptables -A FORWARD -d 2.2.2.2 -i eth0 -p tcp -m tcp --dport 3389 -j ACCEPT 
iptables -t nat -A PREROUTING -d 1.1.1.1 -p tcp -m tcp --dport 3389 -j DNAT --to-destination 2.2.2.2
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE


Save and restart

iptables-save >/etc/sysconfig/iptables
service iptables restart

NOTE if you trying to forward openvpn traffic (for make smthng like double vpn) you should also add rule for internal ovpn network like this:

iptables -A POSTROUTING -s 10.17.0.0/255.255.255.0 -o eth0 -j SNAT --to-source 1.1.1.1

where 10.17.0.0 is the ypour openvpn internal network

Here is an example of working iptables:

# Generated by iptables-save v1.4.7 on Tue Apr  9 14:27:04 2013
*filter
:FORWARD ACCEPT [0:0]
-A FORWARD -d 2.2.2.2 -i eth0 -p tcp -m tcp --dport 23:65500 -j ACCEPT
-A FORWARD -d 2.2.2.2 -i eth0 -p udp -m udp --dport 23:65500 -j ACCEPT
COMMIT
# Completed on Tue Apr  9 14:27:04 2013
# Generated by iptables-save v1.4.7 on Tue Apr  9 14:27:04 2013
*nat
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A PREROUTING -d 1.1.1.1 -p tcp -m tcp --dport 23:65500 -j DNAT --to-destination 2.2.2.2
-A PREROUTING -d 1.1.1.1 -p udp -m udp --dport 23:65500 -j DNAT --to-destination 2.2.2.2
-A POSTROUTING -o eth0 -j MASQUERADE
COMMIT
# Completed on Tue Apr  9 14:27:04 2013

Warning: Make sure your ssh port is out of range 23:65500, otherwise you will lose ssh access to 1.1.1.1. ""