Basic iptables NAT port forwarding
I have three machines: A local PC (public IP 1.2.3.4), an Ubuntu 10 Server box in a datacentre (eth0 on 5.6.7.8 public IP), and a third-party server hosting a website outside of my network (let's say Slashdot on 216.34.181.45).
- Using iptables, how do I access Slashdot from my local machine using 5.6.7.8:8080 ?
- Would this process differ if Slashdot was on the same LAN as my Ubuntu box?
- Can this be done with just NAT PREROUTING/POSTROUTING, or do I need MASQUERADE?
Solution 1:
PC ----- Ubuntu 10 Server ----- Slashdot
(1.2.3.4) (5.6.7.8) (216.34.181.45)
-
Enable the IP forwarding on Ubuntu:
echo 1 > /proc/sys/net/ipv4/ip_forward
and add the following rules:
iptables -t nat -A PREROUTING -i eth0 -p tcp -m tcp --dport 8080 -j DNAT \ --to-destination 216.34.181.45:80 iptables -t nat -A POSTROUTING -o eth0 -j SNAT --to-source 5.6.7.8
No.
-
You should use MASQUERADE if the Ubuntu has a dynamic IP:
iptables -t nat -A POSTROUTING -j MASQUERADE
You can also use SSH local port forwarding in this case by executing the below command on the Ubuntu:
$ ssh -L 5.6.7.8:8080:216.34.181.45:80 -N [email protected]
There's still another (or more) way to do this. Take a look at the rinetd:
Name : rinetd
Arch : i386
Version : 0.62
Release : 6.el5.art
Size : 41 k
Repo : installed
Summary : TCP redirection server
URL : http://www.boutell.com/rinetd
License : GPL
Description: rinetd is a daemon which redirects TCP connections from one IP address
: and port to another IP address and port. This daemon is often used to
: access services behind a firewall.
The configuration is very simple. Add the belows line into /etc/rinetd.conf
:
5.6.7.8 8080 216.34.181.45 80
and start:
# /etc/init.d/rinetd start
Starting rinetd: [ OK ]
It will do everything for you.