Understanding how dnat works in iptables

1

I'm running 3 virtual machines with Fedora 19. The machine B is set up with two networks adapters and provides que channel between machine A and machine C.

The machine A IP is set to 192.168.1.3 and machine C IP is set to 172.16.1.1. On machine B I have one adapter with IP 192.168.1.254 and another adapter with IP 172.16.1.254.

I have to create a rule on machine B in the NAT table that allows an SSH connection to machine A but using the IP external address of machine B.

I've created this rule (don't know if this is correct or not):

iptables -t nat -A PREROUTING -i p8p1 -s 172.16.1.1 -d 172.16.1.254 -p tcp --dport 22 -j DNAT --to-destination 192.168.1.3

If I only do this, if I use netcat I can't connect to machine A. Now, if i insert this rule:

iptables -A FORWARD -i p8p1 -o p7p1 -s 172.16.1.1 -d 192.168.1.3 -p tcp --dport 22 -j ACCEPT

I can make the connection.

My question is this:

Inserting the second rule doesn't make the first rule unnecessary?

Favolas

Posted 2013-10-19T14:45:40.680

Reputation: 167

Answers

2

The first rule tells the kernel to nat packets coming from 172.16.1.1 for 172.16.1.254 on port 22 to 192.168.1.3.

The second rules tells it to allow packets coming from 172.16.1.1 going to 192.168.1.3 on port 22. This rule is applied after the first has nated the packet, so both are necessary if your default policy is to reject forwarded packets.

ASCII art diagram describing the process:

                      Packet (src -> dst)

          +-----------------------+--------------------+
machine C |            172.16.1.1 -> 172.16.1.254      |
          +-----------------------+--------------------+
                                  |
                                  v
          +---------------------p8p1-------------------+
          |                       |                    |
          |PREROUTING: 172.16.1.1 -> 192.168.1.3 (DNAT)|
machine B |                       |                    |
          |FORWARD:            ACCEPT                  |
          |                       |                    |
          +---------------------p7p1-------------------+
                                  v
                                  |
          +-----------------------+--------------------+
machine A |           172.16.1.1 -> 192.168.1.3        |
          +--------------------------------------------+

user2313067

Posted 2013-10-19T14:45:40.680

Reputation: 2 160

Yes. My default policy is to reject packets. Many thanks for your explanation – Favolas – 2013-10-19T18:06:09.137