Linux Port Forwarding Using iptables

Posted on In Linux

Linux port forwarding is simple to do with iptables which may probably already being used as the firewall or part of the setting up a Linux gateway. In the Linux kernel, port forwarding is achieved by packet filter rules in iptables.

Port forwarding

Port forwarding also called “port mapping” commonly refers to the network address translator gateway changing the destination address and/or port of the packet to reach a host within a masqueraded, typically private, network.

Port forwarding can be used to allow remote computers (e.g., public machines on the Internet) to connect to a specific computer within a private network such as local area network (LAN), sothat xternal hosts can communicate with services provided by hosts within a LAN. For example, running a public HTTP server (port 80) on a host within a private LAN, or permitting secure shell ssh (port 22) access to hosts within the private LAN from the Internet.

In Unix/Linux box where port numbers below 1024 can only be listened by software running as root, port forwarding is also used to redirect incoming traffic from a low numbered port to software listening on a higher port. This software can be running as a normal user, which avoids the security risk caused by running as the root user.

iptables in Linux

iptables is a generic table structure for the definition of rulesets for network filtering framework by netfilter in Linux kernel.

In Linux box, iptables is implemented in Linux kernel as some kernel modules. Each rule within an IP table consists of a number of classifiers (iptables matches) and one connected action (iptables target). Users can build very powerfull firewall based on iptables which handles packets based on the type of packet activity and enqueues the packet in one of its builtin ‘tables’.

There are three important tables: mangle, filter and nat. The mangle table is responsible for the alteration of service bits in the TCP header. The filter queue is responsible for packet filtering. The nat table performs Network Address Translation (NAT). Each tables may have some built-in chains in which firewall policy rules can be placed.

The filter table has three built-in chains:

  • Forward chain: Filters packets destined for networks protected by the firewall.
  • Input chain: Filters packets destined for the firewall.
  • Output chain: Filters packets originating from the firewall.

The nat table has the following built-in chains:

  • Pre-routing chain: NATs packets when the destination address of the packet needs to be changed.
  • Post-routing chain: NATs packets when the source address of the packet needs to be changed.
  • Output chain: NATs packets originating from the firewall.

Below is a brief view of how packets are processed by the chains:

PACKET IN
    |
PREROUTING--[routing]-->--FORWARD-->--POSTROUTING-->--OUT
 - nat (dst)   |           - filter      - nat (src)
               |                            |
               |                            |
              INPUT                       OUTPUT
              - filter                    - nat (dst)
               |                          - filter
               |                            |
               `----->-----[app]----->------'

Note: if the packet is from the firewall, it will not go through the PREROUTING chain.

We only look into the packets that requires port forwarding which is the topic of this post.

The packet entering the firewall is inspected by the rules in the nat table’s PREROUTING chain to see whether it requires destination modification (DNAT). The packet is then routed by Linux router after leaving the PREROUTING chain. The packet which is destined for a “protected” network is filtered by the rules in the FORWARD chain of the filter table. The it will go through the packet undergoes SNAT in the POSTROUTING chain before arriving at the “protected” network. When the destination server decides to reply, the packet undergoes the same sequence of steps.

Port forwarding using iptables

This section assumes you have already set up the the Linux host as the gateway and configured the POSTROUTING rules as shown in Setting Up Gateway Using iptables and route on Linux for SNAT.

A port-forwarded packet will pass the PREROUTING chain in nat table, FORWARD chain in filter table, POSTROUTING chain in nat table and other chains. We need to add rules to these chains.

Let’s use a senario to introduce how to configure iptables to do port forwarding. Suppose our gateway can connect to both the Internet (0.0.0.0/0) and the LAN (192.168.1.0/24). The gateway’s eth0 interface has a public IP 7.8.9.10 while the eth1 has a LAN IP 192.168.1.1. Now, suppose that we have set up a HTTP server on 192.168.1.2:8080 and we want to provides service to the Internet through the public IP. We need to configure iptables to forward packets coming to port 80 of 7.8.9.10 to 8080 of 192.168.1.2 in LAN.

Below is the network topology:

Internet---------[router/firewall]-------------LAN
0.0.0.0/0      7.8.9.10    192.168.1.1    192.168.1.0/24

Normally we deny all incoming connections to a gateway machine by default because opening up all services and ports could be a security risk. We will only open the ports for the services that we will use. In this example, we will open port 80 for HTTP service.

First make sure that the IP forwarding is enabled on Linux following the “Enable Linux IP forwarding” Section in Setting Up Gateway Using iptables and route on Linux.

This is the rules to forward connections on port 80 of the gateway to the internal machine:

# iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j DNAT --to 192.168.1.2:8080
# iptables -A FORWARD -p tcp -d 192.168.1.2 --dport 8080 -j ACCEPT

These two rules are straight forward. The first one specifies that all incoming tcp connections to port 80 should be sent to port 8080 of the internal machine 192.168.1.2. This rule alone doesn’t complete the job as described above that we deny all incoming connections by default. Then we accept the incoming connection to port 80 from eth0 which connect to the Internet with the publich IP by the second rule. From the process path in the “iptables” part, the packet will also pass the FORWARD chains. We add the second rule in FORWARD chain to allow forwarding the packets to port 8080 of 192.168.1.2.

By now, we have set up the the iptables rules for forwarding the 80 port. For other service, the method is similiar with the HTTP service.

The conntrack entries

The “nf_conntrack_*” kernel modules enables iptables to examine the status of connections by caching the related information for these connections. A cat of /proc/net/nf_conntrack (in some old Linux kernels, the file is /proc/net/ip_conntrack) will give a list of all the current entries in the conntrack database.

A conntrack entry looks like this:

ipv4     2 tcp      6 431581 ESTABLISHED
src=7.8.9.20 dst=7.8.9.10 sport=53867 dport=80 packets=22 bytes=13861
src=192.168.1.2 dst=7.8.9.20 sport=8080 dport=53867 packets=14 bytes=3535
[ASSURED] mark=0 secmark=0 use=2

This entry contains all the information that the conntrack module maintains to know the state of a specific connection. We can find the version of ip protocal version and the decimal coding, the protocol and the normal decimal coding. After this, we get how long this conntrack entry should live. Next is the actual state that this entry is in at this present point of time. Then, we get the source IP address, destination IP address, source port and destination port. After that, we get the IPs and ports of both source and destination we expect of return packets.

In this entry we can find that the arriving connection is:

7.8.9.20:53867 --> 7.8.9.10:80

while the returning connection is:

192.168.1.2:8080 --> 7.8.9.20:53867

which reflects the port forwarding which we have set.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

78 comments

  1. Pingback: Port Forwarding
  2. This is the most precise and working document i have found for IPTABLES in a long time ….THANKS

  3. Thank you very much for this diagram of packet flow!! Before that I could understand iptables partially, but some things were still not clear to me. Once I saw this diagram everything became clearly understandable at one moment. This is the thing which most of the manuals really lack.

  4. Is it possible to forward the port on the same machine? for instance, suppose your server is your firewall and you want to login to ssh. But, you don’t want to expose port 22 to the web and can’t change the port in the ssh server. Can you forward, say port 2222 to port 22, on the same server box?

    1. Frankly I do not know how to do this.

      But what about creating an internal IP besides the public IP for the server and forwarding the packet to that internal IP?

      1. The computer has 2 nics, 1 with a public ip and one with a local ip (192.168.12.2). I tried but could not get it to work. But, that does not mean I did it right. how would you do it?

        1. Hi Scott!
          Did you manage to forward the port on the same machine? I’m facing the same situatuion.

          Thanks a lot if you could help me.

  5. I have a trouble to map to web server with this network topology:

    Internet———[router]——-[Linux firewall]
    0.0.0.0/0 7.8.9.10 192.168.1.1 eth0
    |
    eth2 | eth1
    192.168.3.1 —-|— 192.168.1.1
    | |
    | |
    LAN2 (Web/Mail Server) LAN1
    192.168.3.0/24 192.168.1.0/24

    I did ACCEPT rules and MSQ to LAN1 for home PCs but can’t do work the webserver or mail server for http://www.mybloqdomain.com.

    I tryed with those rules for LAN2 but nothing happen:

    # iptables -A PREROUTING -t nat -i eth0 -p tcp –dport 80 -j DNAT –to 192.168.3.1:80
    # iptables -A FORWARD -p tcp -d 192.168.3.1 –dport 80 -j ACCEPT

    Must does POSTROUTING and FORWARD from LAN2 to Internet TOO?

    any help please?

    1. The rules look good at my first glance. The Web/Mail server should be able to connect to the Internet through the Linux firewall and the router so that the client on the Internet can communicate with it.

  6. Helo ppl !!

    I have an issue with Debian Proxmox x2.3 with 2 bridged NICS, vmbr0 (public IP) and vmbr1 (10.10.11.0/24).

    There are 4 VMs going outside through NAT without any problem. All network is visible, all computers see all, etc. ‘Till here all fine ! !

    Now I want to forward some ports from the internet to internal VMs, but this is not working, and I’m not expert in this !

    I tried a lot of things without any success:

    iptables -t nat -A PREROUTING -i eth0 -p udp –dport 3389 -j DNAT –to-destination 10.10.11.3:3389
    iptables -t nat -A PREROUTING -i vmbr0 -p udp –dport 3389 -j DNAT –to-destination 10.10.11.3:3389
    iptables -t nat -A PREROUTING -i eth0 -p tcp –dport 3389 -j DNAT –to-destination 10.10.11.3:3389

    iptables -A PREROUTING -t nat -i eth0 -p tcp –source 212.212.212.85 –dport 25 -j DNAT –to 10.10.11.2:25

    This is my interfaces file:

    # network interface settings
    auto lo
    iface lo inet loopback

    iface eth0 inet manual

    auto vmbr1
    iface vmbr1 inet static
    address 10.10.11.1
    netmask 255.255.255.0
    bridge_ports none
    bridge_stp off
    bridge_fd 0
    post-up echo 1 > /proc/sys/net/ipv4/ip_forward
    post-up iptables -t nat -A POSTROUTING -s ‘10.10.11.0/24’ -o vmbr0 -j MASQUERADE
    post-down iptables -t nat -D POSTROUTING -s ‘10.10.11.0/24’ -o vmbr0 -j MASQUERADE

    auto vmbr0
    iface vmbr0 inet static
    address 212.212.212.85
    netmask 255.255.255.0
    gateway 212.121.212.254
    broadcast 212.212.212.255
    bridge_ports eth0
    bridge_stp off
    bridge_fd 0
    network 212.212.212.0

    any tip ?

    1. What about this one?

      iptables -A PREROUTING -t nat -i vmbr0 -p tcp –source 212.212.212.85 –dport 25 -j DNAT –to 10.10.11.2:25

        1. Oops:

          iptables -t nat -A PREROUTING -d 212.212.212.85/32 -p tcp -m tcp –dport 25 -j DNAT –to-destination 10.10.11.2:25

          1. Now worked, but same, nothing ….

            Could this work?

            iptables -t nat -A PREROUTING -d 212.212.212.85/32 -p udp -m udp –dport 3389 -j DNAT –to-destination 10.10.11.3:3389

            1. If you are using the UDP protocol, you should change the tcp to udp in the rule.

              And remember to set the rule in FORWARD chain. It may also block you connection. one example:


              iptables -A FORWARD -p tcp -d 192.168.1.2 --dport 8080 -j ACCEPT

                1. You may also check whether the ports are blocked by other devices (e.g. the network gateway).

                  And also note that these rules only works for external IPs (not from the host or the VMs).

                  1. My friend, there’s nothing between the proxmox node and the VMs.

                    From the node, I can ping and see all internal LAN, from the VMs I see internet. And yes, I know this is only to pass the NAT from outside using the public proxmox node (vmbr0). Rest is OK and working without any issue.

                    This is a fresh Debian with latest proxmox.

                    Anyway, thanks for your help !

                    1. I see. By now, I can not figure out what’s the problem without working on your node. But I am curious to know how you fix it. Please share with us if possible.

      1. Ahh, sorry, I forgot the —

        But same problem, not working, and I don’t get any error entering the IPTABLES command :-?

  7. I struggled with this for many hours. Would have been nice to mention in this post that ip_forward option must be enabled.

    echo 1 > /proc/sys/net/ipv4/ip_forward

  8. Could you show us the content of iptables file. I just can’t make this work without POSTROUTING that you don’t mention and it would be nice to compare files .

    Regards,

  9. May i ask you to help me on this ?

    All UDP-packets going out should be changed to TCP-packets at the
    same port.

    1. TCP and UDP are different protocols. Simply changing from UDP to TCP may confuse the applications unless they are aware of the protocol changing. Even the applications are aware of the protocol changing, iptables may not be suitable for your purpose. You may need a “proxy” application that knows that application semantics.

  10. Hello.

    I have an issue with a linux distribution (Busybox) It is not possible to add a prerouting rule using UDP, isnt’ it ? because it says there is nothing related with the port, Example:

    iptables -A PREROUTING -i usb0 -p udp -m udp –dport 137 -j DNAT –to-destination 192.168.0.10

    and

    iptables -A FORWARD -i usb0 -p udp -m udp –dport 137 -j ACCEPT

    TCP NAT works OK.

    1. Hi Ivan,

      That seems caused by your iptables command rather than udp.

      PREROUTING is in the nat table and you need to specify it in the iptables command:

      iptables -t nat -A PREROUTING -i usb0 -p udp -m udp --dport 137 -j DNAT --to-destination 192.168.0.10
      
  11. Hi Eric,

    I tried to do some NAT and its working fine until i enable the firewall. I got 2 servers. Server A connected to the internet and 1 internal NIC. Server B is connected to Server A with an internal ip. I turned on NAT on Server A: iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE (internet facing) and ip forwarding: sysctl net.ipv4.ip_forward=1

    Everything works ok. I can use DNS (8.8.8.8) on the backend server to resolve names. But when I turn on the firewall on server A I cannot resolve names anymore. ping http://www.google.nl gives me “unknown host”. When I turn off the firewall on server A it works ok. With the firewall turned on I CAN ping 8.8.8.8 or any other external addresses. But somehow DNS traffic (and maybe more traffic) is blocked by the firewall on server A.

    I added many rules but nothing seems to be working. Both servers are running Centos 7. Any ideas?

    Thanks!

      1. I must admit I just started out working with Centos and Linux commands :)

        The output for iptables -S:

        -P INPUT ACCEPT
        -P FORWARD ACCEPT
        -P OUTPUT ACCEPT
        -N FORWARD_IN_ZONES
        -N FORWARD_IN_ZONES_SOURCE
        -N FORWARD_OUT_ZONES
        -N FORWARD_OUT_ZONES_SOURCE
        -N FORWARD_direct
        -N FWDI_public
        -N FWDI_public_allow
        -N FWDI_public_deny
        -N FWDI_public_log
        -N FWDO_public
        -N FWDO_public_allow
        -N FWDO_public_deny
        -N FWDO_public_log
        -N INPUT_ZONES
        -N INPUT_ZONES_SOURCE
        -N INPUT_direct
        -N IN_public
        -N IN_public_allow
        -N IN_public_deny
        -N IN_public_log
        -N OUTPUT_direct
        -A INPUT -m conntrack –ctstate RELATED,ESTABLISHED -j ACCEPT
        -A INPUT -i lo -j ACCEPT
        -A INPUT -j INPUT_direct
        -A INPUT -j INPUT_ZONES_SOURCE
        -A INPUT -j INPUT_ZONES
        -A INPUT -p icmp -j ACCEPT
        -A INPUT -j REJECT –reject-with icmp-host-prohibited
        -A FORWARD -m conntrack –ctstate RELATED,ESTABLISHED -j ACCEPT
        -A FORWARD -i lo -j ACCEPT
        -A FORWARD -j FORWARD_direct
        -A FORWARD -j FORWARD_IN_ZONES_SOURCE
        -A FORWARD -j FORWARD_IN_ZONES
        -A FORWARD -j FORWARD_OUT_ZONES_SOURCE
        -A FORWARD -j FORWARD_OUT_ZONES
        -A FORWARD -p icmp -j ACCEPT
        -A FORWARD -j REJECT –reject-with icmp-host-prohibited
        -A OUTPUT -j OUTPUT_direct
        -A FORWARD_IN_ZONES -g FWDI_public
        -A FORWARD_OUT_ZONES -g FWDO_public
        -A FWDI_public -j FWDI_public_log
        -A FWDI_public -j FWDI_public_deny
        -A FWDI_public -j FWDI_public_allow
        -A FWDO_public -j FWDO_public_log
        -A FWDO_public -j FWDO_public_deny
        -A FWDO_public -j FWDO_public_allow
        -A INPUT_ZONES -g IN_public
        -A IN_public -j IN_public_log
        -A IN_public -j IN_public_deny
        -A IN_public -j IN_public_allow
        -A IN_public_allow -s 195.240.177.39/32 -p tcp -m tcp –dport 3306 -m conntrack –ctstate NEW -j ACCEPT
        -A IN_public_allow -s 31.3.96.72/32 -p tcp -m tcp –dport 3306 -m conntrack –ctstate NEW -j ACCEPT
        -A IN_public_allow -s 217.21.193.235/32 -p tcp -m tcp –dport 3306 -m conntrack –ctstate NEW -j ACCEPT
        -A IN_public_allow -p tcp -m tcp –dport 80 -m conntrack –ctstate NEW -j ACCEPT
        -A IN_public_allow -p tcp -m tcp –dport 25 -m conntrack –ctstate NEW -j ACCEPT
        -A IN_public_allow -p tcp -m tcp –dport 22 -m conntrack –ctstate NEW -j ACCEPT
        -A IN_public_allow -p tcp -m tcp –dport 443 -m conntrack –ctstate NEW -j ACCEPT
        -A IN_public_allow -p tcp -m tcp –dport 993 -m conntrack –ctstate NEW -j ACCEPT
        -A IN_public_allow -p tcp -m tcp –dport 3306 -m conntrack –ctstate NEW -j ACCEPT

        I cannot use the command iptables -t nat -S. It gives me the error that the nat table does not exist. Maybe that is the problem?

        Altough i can NAT. I can ping external servers from Server B

        Thanks!

        1. I just fixed the problem by adding:

          iptables -I FORWARD -i eth0 -o eth1 -m state –state RELATED,ESTABLISHED -j ACCEPT
          iptables -I FORWARD -i eth1 -o eth0 -j ACCEPT

          I already did this a couple of times but with iptables -A. This will append the rules instead of inserting them above any reject rules. Been stuck on this for at least 2 weeks…

          1. Ok I guess I was to fast giving an reply..

            I can ping external adresses by name. So the DNS resolving works. Now i encounter a problem when using wget “website”

            On server A I get the index.html file but on server B i get the warning: 301 moved permanently. I can only get the index.html when using the –no-check-certificate flag.

            The reason i need this to work is because i’m using a backup script which contains http and https urls. Alhough i fixed the DNS problem somehow this traffic is still not working.

        2. The MASQUERADE rule is in nat table. It is strange that the nat table does not exit.

          Note that the firewall and the forwarding/gateway rules are all in the iptables.

          You may do it in this orders: load the firewall -> apply your own rules.

  12. @biggy:

    About your `wget` problem: it is not related to your iptables/firewall configurations if you can get the index.html. It is likely `wget` or your systems certificate configurations’ problem.

    Your web site’s certificate may not be recognized by your Linux server.

    On quick tip/try may be updating the packages on your server B.

    1. Hi Eric,

      In my case server B is a copy of server A. So besides some firewall rules everything is the same. Also on server B I cannot do wget https://“website” it gives me unknown host. That seems to be due iptables on server A. Its not just one website, I get this error with every https website.

      Could it be that port 443 and/or 80 somehow are still blocked?

      1. I changes some things last night to allow 443. It didn’t work. I just tried again and now it suddenly works. I deleted some entrys in the /etc/hosts file though. All seems to be working now :)

        Thanks for the help!

        1. If you can get some content (event the wrong one) from wget, the iptables rules are likely working.

          It sounds like your /etc/hosts file pointed your domain name to some non-correct IPs on your server.

          Glad to know you figured it out.

  13. Hi Eric,

    Nice to see your gr8 responses to queries, have same basic issue i am facing.

    I have static iP 122.166.205.56 provided by internet service provider on which i can access the internet.
    There is wifi modem which spawns internal IP ( 192.168.1.103 etc… ), I have an application server running on the linux machine on port 8080.
    I am able to access my application server default page using internal ip 192.168.1.103:8080 within my LAN network, however when I try to access same default page using static ip 122.168.205.56:8080 outside the LAN it does not work.

    I have added the port forwarding configuration in the modem admin console.
    However it did not help.

    NAPT List
    Enable Description Remote_Host Protocol External_Port Internal_Port Internal_Client
    Yes maa 122.166.205.56 tcp 8080-8080 8080 192.168.1.103

    Also logged into static ip machine 122.166.205.56 and added record into the FORWARD chain

    ACCEPT tcp — anywhere 192.168.1.103 tcp dpt:8080
    ACCEPT tcp — anywhere abts-kk-dynamic-056.205.166.122.airtelbroadband.in tcp dpt:8080

    but no use.

    Any help on the same will be gr8

    1. Hi adfuser,

      Is the 192.168.1.103’s gateway the box 122.166.205.56 (its internal IP)? This is a common problem I usually find. The incoming packets arrive at the internal node (192.168.1.103 here) through the box to internet while the reply packages can not be delivered back.

      Another possible problem is whether the 192.168.1.103’s firewall/iptables block the traffic from Internet. A quick testing method is to flush the iptables by `iptables -F` temporarily to test.

      If you still have the problem, you may print out the full iptables (iptables -S; iptables -t nat -S) on the box with internet access and the network configuration info (iptables -S; ip route) on the internal box here or at http://ask.systutorials.com/ to be checked.

  14. Hello,

    I am newbie , so i need a help :) …

    I need to configure the iptables and NAT to Setup a proxy server on centos 5.5 to provide internet access to lan users… i installed webmin and squid but problem is i did’nt know how to setup the Iptables and NAT..
    I also searched and visit different forums to check and apply the commands but in the end nothing happend expect confusion lots of ..

    so Could u please help me ,, to provide me iptables command.

    CentOS5.5 iptables and NAT config

    eth0 = Is ISP Network which i droped on server
    eth1 = Private lan

    eth0 : IP: 192.168.2.171 Gateway : 192.168.2.53 Subnet mask :255.255.252.0
    eth1 : IP: 192.168.3.172

    looking forward for a prompt response.

    1. I do not quite understand your question.

      If you just want to let lan users have Internet access to the Internet, making the CentOS node as gateway may be easier: http://www.systutorials.com/1372/setting-up-gateway-using-iptables-and-route-on-linux/

      If you still have the problem, you may print out the full iptables (iptables -S; iptables -t nat -S) on the box with internet access and the network configuration info (iptables -S; ip route) on the internal box here or at http://ask.systutorials.com/ to be checked.

  15. Just to let you know that I just did this on Android Lollipop on a Samsung Galaxy S5 SM-G900M. I just forwarded a port from my phone’s wifi to my computer using USB tethering without using the Google Play apps that already exist for this purpose (they are incompatible with Android 5.0).

    I will post the full step-by-step solution here with complete commands just in case a newbie stumbles upon this example:

    1: Root your phone.
    2: Install the iptables app from Google Play: https://play.google.com/store/apps/details?id=com.mgranja.iptables
    3: Install the terminal emulator app: https://play.google.com/store/apps/details?id=jackpal.androidterm
    4: Find out your computer’s IP address. On Windows, open cmd.exe and type “ipconfig”; on Linux, open the system terminal and type “sudo ipconfig” then enter your user’s password.
    5: Open the terminal emulator, type “su” then Enter, approve the superuser permission request, then type this:

    iptables -A PREROUTING -t nat -i wlan0 -p tcp –dport -j DNAT –to :
    iptables -A FORWARD -p tcp -d –dport -j ACCEPT

    1. Whoops, the blog software ate my placeholders on the terminal commands. Here they go again:

      iptables -A PREROUTING -t nat -i wlan0 -p tcp –dport (port to open on phone) -j DNAT –to (computer’s IP address):(target port on computer)
      iptables -A FORWARD -p tcp -d (computer’s IP address) –dport (target port on computer) -j ACCEPT

  16. i have configured mail server on two machine , machine-1 installed squirrelmail GUI and machine-2 is my server( postfix ,dovecot..etc) ,machine-1 is on public ip but machine-2 is on private ip because machine-2 have all user and mailbox to recive mail for security purpose, i am able to send mail but not receive mail, but if i am using only one machine then I’m successfully send and Receive mail , but my task is to setup mail server on 2 machine, so where is problem please reply me soon?

    1. Please give more details:

      “machine-2 is on private ip” -> can its outgoing request to Internet go out?
      “send mail but not receive mail” -> send to where and receive from where?
      “only one machine” -> which machine?

      What’s the gateway of machine-2? What’s the network topology?

      If you still have the problem, you may print out the full iptables (iptables -S; iptables -t nat -S) and the network configuration info (iptables -S; ip route) on these 2 machines here or at http://ask.systutorials.com/ to be checked.

  17. Is there a way to redirect only allowed traffic and drop the rest of the traffic coming on 22.

    1. You can add an iptables rule to allow only certain IP YOUR_ALLOWED_IP to issue TCP connection to port 22 on the router like (assume you are forwarding 80 of router to your Linux’s 22)

      iptables -A PREROUTING -t nat -p tcp --dport 80 ! -s YOUR_ALLOWED_IP -j DROP
      

      Or, on the Linux host itself:

      iptables -A INPUT -p tcp --dport 22 ! -s YOUR_ALLOWED_IP -j DROP
      
  18. I would like to redirect traffic from my LAN going to port 80 to the web server on the internet to be redirected to another port. Is it possible to do it ?

    #iptables -t nat -A PREROUTING -s 192.168.10.0/24 -p tcp –destination-port 80 Redirect –to-port 10000

    As the server on internet listens to port 80 or 443, after altering the port number will it change the packet header to port 10000, if so server will not be able to respond for the port number it receives.

    Does port forwarding alters the header or it just has locally importance on the firewall.??

    I am confused please help.

    1. I am not sure I understand you situation. But you can certainly forward one port on your gateway’s private IP to an Internet IP’s port.

      For example, assume my gateway IP is 192.168.1.1. I can forward 192.168.1.1:8088 to 198.35.26.96:80. 192.35.26.96 is an IP on the Internet (outside of the private network).

      The rule added to the gateway (192.168.1.1) will be:

      # iptables -t nat -A PREROUTING -s 192.168.1.0/24 -d 192.168.1.1/32 -p tcp -m tcp --dport 8088 -j DNAT --to-destination 198.35.26.96:80
      
  19. Wow this is the best iptables port forwarding tutorial I’ve seen. If you don’t do a lot of forwarding this article has a lot of the “gotchas” to have almost all scenarios covered.

    Cheers

    Areeb

  20. Hello Eric, thanks for the great article. Im trying to access IP cameras connected directly to an NVR. I was wondering if this guide would work assuming i get root on the NVR? Thanks.

  21. Hello guys,

    I have KVM VM running on bare metal server. That guest VM running service on port 80 with IP address 192.168.122.177.
    I want to access this service from host machine’s public IP address. I have public ip address on interface eth3
    I added Iptables rules as below:
    iptables -I FORWARD -i virbr0 -d 192.168.122.177 -j ACCEPT
    iptables -I FORWARD -o virbr0 -d 192.168.122.177 -j ACCEPT
    iptables -t nat -I POSTROUTING -o eth3 -j MASQUERADE
    iptables -t nat -A PREROUTING -i eth3 -p tcp –dport 80 -j DNAT –to 192.168.122.177:80

    Am I missing any other iptable rule. I am not able to access service running on guest with public IP of host machine.

  22. Superb Blog Eric!

    Just 1 question. In your port forwarding example above, you say that we have to make sure that the FORWARD chain also allows the DNAT’ed packet to pass through which is why this is neccessary

    iptables -A FORWARD -p tcp -d 192.168.1.2 –dport 8080 -j ACCEPT

    If that is indeed the case, won’t we need to have such a rule at the POSTROUTING chain as well since the same packet will also hit the POSTROUTING chain?

    If not, perhaps I am missing something. Keen to hear

  23. Hi
    I want to connect my local pc via centos open vpn server. what command should i use? I want to open 3389 port.
    Cenos openvpn vps ip : 1.2.3.4
    local pc vpn client ip : 10.8.0.19

      1. Thanks. I open this port.
        openvz vps centos > pfsense > lan pc.
        I successfully open 3 tcp port but stuck with udp port 5060, 10000:20000.
        My nmap tools show that all of udp open or filter. Clint pc’s os Scientific Linux and iptables off.
        -A INPUT -p udp -m state –state NEW -m udp –dport 5060 -j ACCEPT
        -A FORWARD -d 10.8.0.2/32 -p udp -m udp –dport 5060 -j ACCEPT
        -A FORWARD -i venet0 -o tun0 -j ACCEPT
        -A FORWARD -i tun0 -o venet0 -j ACCEPT

  24. How can we get the network usage of the forwarded port ?
    In this tutorial, port 80 is forwarded and I want to get the network usage of this port.
    I try this command but it doesn’t work:
    sudo iptables -A FORWARD -p tcp –dport 80 -j DROP
    sudo iptables -A FORWARD -p tcp –dport 80 -m quota –quota 10000000 -j ACCEPT

    1. Hi amin, iptables does not (though it did) report the remaining quota left any more after this change https://www.systutorials.com/linux-kernel-xt_quota-report-initial-quota-value-instead-of-current-value-to-userspace/ . This may be related to your question.

      If what you want is to get the network usage of a port, as an alternative way, you may create a chain, and check the statistics for that chain.

      # iptables -N web
      # iptables -A FORWARD -p tcp --dport 80 -j web

      Then, check statitiscs

      # iptables -vnL
  25. After research about PREROUTING and FORWARD chain in iptables,This is what I realized:
    FORWARD chain is after PREROUTING chain.
    Ports are translated to the destination port, in PREROUTING chain by NAT, therefore In FORWARD chain there is no traffic with the port(80) and all traffic translated to port(8080).
    I can see consumed traffic on port(8080) in FORWARD chain.
    But I can not see the consumed traffic on port(80) in FORWARD chain,because there is no more traffic with port 80 in FORWARD chain

  26. Amazing description if you wrote an advance config book I would buy it. Thanks for the free schooling

Leave a Reply

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