11

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?
jetboy
  • 912
  • 2
  • 11
  • 25

1 Answers1

23
   PC ----- Ubuntu 10 Server ----- Slashdot 
(1.2.3.4)      (5.6.7.8)        (216.34.181.45)
  1. 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
    
  2. No.

  3. 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 user@216.34.181.45

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.

quanta
  • 51,413
  • 19
  • 159
  • 217
  • Fantastic. The iptables version works like a charm. I was missing the POSTROUTING rule, and was getting nowhere. If anyone's trying to do this with a saved .conf file, this is what you're after: `*nat -A PREROUTING -p tcp -m tcp -i eth0 --dport 8080 -j DNAT --to-destination 216.34.181.45:80 -A POSTROUTING -o eth0 -j SNAT --to-source 5.6.7.8 COMMIT` – jetboy Nov 01 '11 at 13:25
  • Follow-up question here: http://serverfault.com/questions/326837/iptables-nat-port-fowarding-and-apache-log-ips – jetboy Nov 01 '11 at 22:16
  • Perfect! Just a quick question. When the response packet comes back to the ubuntu server with a destination address of 5.6.7.8, what is the module responsible for modifying the packet and returning it back to 1.2.3.4? Is it the "connection tracking" module? – Keeto Aug 11 '17 at 22:42