0

I have setup an ubuntu box as a router manually , using iptables + NAT.

But I was wondering, how does the "middle-router" know if the packet is meant for it or to be forwarded?

I tested this scenario:

                SYN                                       SYN
                src:192.168.3.3.8080                      src:12.12.12.12:8080
+--------------+dst:5.5.5.5:443       +-----------------+ dst:5.5.5.5:443
|              |                      |   Linux Router  |
|   Client     +--------------------->|                 +------------------>
|              |                      |LAN: 192.168.3.1 |
| 192.168.3.3  |                      |                 |
|              |<---------------------+WAN: 12.12.12.12 |<------------------
+--------------+SYN-ACK               +-----------------+ SYN-ACK
                src:5.5.5.5:443                           src:5.5.5.5:443
                dst:192.168.3.3:8080      (HOW???)        dst:12.12.12.12:8080

                                      Webserver listening
                                      on 0.0.0.0:8080

And it works as expected on the client. But when the router receives the packet with DST 12.12.12.12:8080 (on which it is listening) , how does it know to forward it? I tried this manually with UDP as well (so no TCP states) and it seems to work.

Why is there no port conflict when its the same port?

My iptables NAT rule on the router:

-A POSTROUTING -o enp6s0 -j MASQUERADE
4
  • Why are you inferring the originating port to be 8080? On the outbound connection, the originating OS will use a high port as a source port, something in the 32768–60999 range.
    – Marco Zink
    Aug 18, 2022 at 4:40
  • 1
    What's the problem you experience? Questions just "out of curiosty" are better asked on SuperUser. That said, the answer to this one is simple, see the the packet flow diagram. For first packet in the connection, nat table is consulted and installs a record into conntrack table. For reply packets, the destination address change happens in conntrack handler, earlier than routing decision happens, so even if packet was mapped to the source port 8080 by the MASQERADE, the reply will reach original destination. Aug 18, 2022 at 5:12
  • @MarcoZink I was able to set the originating port via netcat / curl and confirmed it via tcpdump
    – poiasd
    Aug 18, 2022 at 6:16
  • @NikitaKipriyanov thanks, that is quite useful information. My apologies for asking on the wrong forum
    – poiasd
    Aug 18, 2022 at 6:17

0

You must log in to answer this question.

Browse other questions tagged .