Search code examples
iptablesportforwarding

Wrapping one's head around port forwarding with iptables


Honestly, I get part of what's going on. Like I need to enter rules, to forward with specific filters. But do I need one rule, two, three? Why do some people do FORWARD and others also OUT and yet some others even IN. Do I need separate rules for SYN, ESTABLISHED, RELATED? Is conntrack a separate package? Why does one guide do -t nat and all the others don't?

It's really painful, since everybody delivers almost copy&pastable guides, but not enough explanation of what they are actually providing as a solution, or how to get help if the reader's setup (oh surprise) is not 100% the same.

What I basically want to achieve is:

  • accept connections from everybody on *:443
  • send all the requests to 1.2.3.4:443 (nobody but me can reach 1.2.3.4)
  • enable requesters to receive the response from 1.2.3.4 as well
  • see in dmesg whether or not stuff works, but not more if not necessary

Please explain why you are doing or not doing something. I really want to grasp this stuff. Thanks!


Solution

  • The best explanation I found is in archwiki, even with further references to more in depth descriptions and diagrams. One real in depth guide I found through archwiki is this iptables tutorial.

    For instance, here (Simple stateful firewall) is a detailed example with explanation of all the decisions.

    Because I'm a visual learner I also found this youtube video very helpful that shows and explains a running example with two VMs that pretty much anybody can reproduce at home.

    Now I feel I'm at a level that I mostly just need to reference the following diagram, which shows how a package walks through the tables and chains:

    enter image description here

    Furhter reading:

    Side notes:

    • I always got confused why some guides contain ESTABLISHED,RELATED rules and others don't. Whether or not these rules are there decides if already existing network traffic is cut or not. For instance if you are using an ssh session to connect to the machine, it would be nice if your ssh session wouldn't get killed by adding iptables rules, thus having a rule that allows your ESTABLISHED connection is nice. RELATED packages are for instances responses to ping or network information packages (ICMP).
    • The Simple stateful firewall example also explains the differences between different nmap tests.
    • Also a good overview