Bài gốc: A Brief Introduction to Conntrack — tác giả BaconYao, lấy qua Notion public API.

What Is Connection Tracking?

Conntrack, short for connection tracking, is a core feature of the Linux kernel’s Netfilter subsystem.It records and manages the state of every network connection and data flow, enabling the kernel to understand whether a packet belongs to a new, established, or related connection. This mechanism is fundamental for implementing stateful firewalls and Network Address Translation (NAT) , forming the backbone of many higher-level networking systems such as container networking and Kubernetes Services.

Connection Tracking Table

A table maintained by the Linux kernel that records the state and NAT mappings of each flow based on the five-tuple (src IP, dst IP, src port, dst port, protocol). Each record in this table is called an entry . Conntrack continuously maintains this table and uses it to determine which existing connection each packet belongs to.
  • Common connection states (ctstate):
    • NEW: The first packet of a flow (no existing entry).
    • ESTABLISHED: A bidirectional connection that has been fully established.
    • RELATED: A connection related to an existing one (e.g., an FTP data channel or an ICMP error response).
    • INVALID: A packet that cannot be logically associated with any existing connection (possibly malformed or tampered).
  • NAT (SNAT / DNAT / MASQUERADE) relies on conntrack to create and maintain address and port mappings, ensuring that return packets can be correctly translated back.
  • Stateful firewalls (filter tables) use conntrack’s connection states to determine whether packets should be allowed or dropped.

Why Do We Need Conntrack?

When Using Only iptables to Filter Packets

In previous sections (Demystifying Container Networking ), we examined iptables rules extensively to understand which packets are forwarded, accepted by the host, or dropped. However, if we rely only on iptables rules (for example, a simple rule like iptables -A INPUT -p tcp --dport 22 -j ACCEPT), each packet is evaluated independently — iptables has no memory of past packets. This means the kernel cannot determine whether a packet is part of an existing connection or simply a new incoming request. As a result, it becomes difficult to distinguish between new packets and response packets.

With the Help of Conntrack

  • The kernel can identify packets that belong to an ESTABLISHED connection.
  • It can recognize NEW connections.
  • And it can also track packets that are RELATED to existing connections (for example, responses or auxiliary connections).
With this information, firewall rules can be written in a simpler and safer way like below.

Deep Dive into ctstate

ctstate is the packet state label exposed by the conntrack module in iptables / nftables. It allows you to match packets based on the state of a conntrack entry (connection state), which can be used to determine whether to accept, drop, or modify the packet. These states are not the TCP-level SYN/ACK/FIN flags, but rather the overall connection state observed by Netfilter.

Common ctstate Types and Their Meanings

Understanding the ctstate Logical Flow (TCP Example)

ctstate for UDP

UDP is connectionless, but conntrack still tracks it using timeouts. Therefore, UDP packets also go through similar states:

How Conntrack Works

1. Packet Enters Netfilter

When a packet enters the Linux kernel network stack (for example, passing through Netfilter hooks like PREROUTING, OUTPUT, or FORWARD), the nf_conntrack module intercepts it and checks whether it belongs to an existing connection.

2. Lookup or Create a Conntrack Entry

  • If the packet does not belong to any existing connection: Conntrack creates a new connection tracking entry based on the packet’s five-tuple (src IP, dst IP, src port, dst port, protocol) and marks it with the NEW state.
  • If it belongs to an existing connection: Conntrack updates the entry’s state (for example, from SYN_SENT → ESTABLISHED) and resets the timeout.
  • If the connection is idle for a long time: The entry is removed according to protocol-defined timeouts (e.g., TCP, UDP).
You can view all currently tracked connections using command sudo conntrack -L

3. NAT and Firewalls Handle Packets Based on Connection State

This is the core mechanism behind stateful firewalls and NAT.
  • NAT modules attach address/port translation information to conntrack entries (e.g., SNAT, DNAT) and record the mapping between the original and translated addresses, ensuring that return packets are correctly reverse-translated.
  • Firewall rules (using m state or m conntrack) can allow or drop packets based on their connection state (e.g., NEW, ESTABLISHED, RELATED, INVALID).

4. State Maintenance When Packets Exit

When packets are processed and leave the network interface (or enter user space):
  • Conntrack updates NAT mappings accordingly.
  • If the connection is closing (e.g., TCP FIN/ACK), the entry is marked as TIME_WAIT and is eventually removed when the timeout expires.

Real Case Study

Environment Setup

This environment uses the Docker Server provided by iximiuz Labs, which offers a fast and convenient online practice environment.Reference: https://labs.iximiuz.com/playgrounds/docker

Installing Packages

After accessing a machine with Docker pre-installed, use the following commands to install the packages required for the upcoming exercises.

Inspecting IP Addresses and Conntrack Entries

IP address

Analyzing Conntrack Connections

The above information reveals that the current conntrack table contains 4 stable TCP connections:
  • 1 local SSH connection
  • 1 external SSH connection
  • 2 application-layer service connections (ports 40059 and 40060)

Analysis of Each Connection

Experiment 1: Accessing google.com from Within a Container

In this experiment, we will use the curl command from a Docker container to access google.com, while observing system behavior using tcpdump and conntrack.

1. Start a Container

We can use the existing environment and start a container named client using the following command.

2. Observing Traffic While Accessing google.com with curl

  • Step 1: Enter the client container.
  • Step 2: On the host, use tcpdump to monitor the docker0 bridge.
  • Step 3: On the host, list all current conntrack entries.
  • Step 4: On the host, use the E option to monitor changes in conntrack.
  • Step 5: Inside the client container, run curl google.com to fetch information.

3. Packet Flow Analysis

3.1 Environment Overview

Using the tcpdump and conntrack logs from our experiment, we can identify the IP addresses of the key components:

3.2 High-Level Process Flow

Outbound: container → Internet
Inbound: Internet → container
When we run the curl google.com command inside the container, the container’s source IP is 172.17.0.2, and it sends packets out via the docker0 bridge.The docker0 bridge, following the Linux bridge mechanism, forwards the packets to the host network stack, where they pass through iptables/nftables NAT rules.In the tcpdump logs, we observe:
This indicates that the container is sending DNS query packets (UDP/53) outward, and the original source IP captured via docker0 is still 172.17.0.2.
When Docker starts, it sets up a set of iptables NAT rules, for example:
This rule means:
Any packet originating from the Docker subnet (172.17.0.0/16) that is not leaving through docker0 will be SNATed, changing the source IP to the host’s external IP.
As a result, packets sent from the container undergo the following changes:In other words, from the perspective of the external network, the request appears to come from the host at 172.16.0.2.This also explains why conntrack shows the following mapping:
  • The first line represents the original internal connection (original direction).
  • The second line represents the reply direction after NAT.
→ This shows that conntrack tracks both the container-to-host mapping and the NAT translation.
The external DNS server responds with:
We see this packet in tcpdump because it is captured on docker0.Meanwhile, the host’s conntrack table performs DNAT, changing the destination of the reply packet from the host IP (172.16.0.2) back to the container IP (172.17.0.2).DNAT Restoration Process:
  • 3.2.4.1
    • The curl command initiates a TCP connection:
      This is the SYN packet from the container to Google. The host performs SNAT, translating it to:
  • 3.2.4.2
    • The external Google server responds:
      When the host receives it, DNAT translates the destination back to the container:
We can observe the complete TCP flow as:
From the conntrack log, we can observe:
This represents:
  1. Container sends SYN → new connection created (NEW)
  2. SYN/ACK received from the server → enters SYN_RECV
  3. Handshake completed → ESTABLISHED
  4. curl finishes → FIN_WAIT → LAST_ACK
  5. Both sides close the connection → TIME_WAIT → entry will eventually expire and be removed
Each TTL update (e.g., 432000 seconds) indicates the connection’s state and timeout countdown.
conntrack is the core mechanism for tracking connection states after NAT. In this example, both DNS queries and HTTP connections rely on it. Without conntrack, NATed responses would not be correctly mapped back to the container.

4. Observing Changes in the iptables NAT Table

Next, let’s observe the packet counts in the iptables NAT table.
Question:We notice that before and after running the curl command, the docker0 bridge shows only 2 additional packets in the MASQUERADE rule. However, tcpdump clearly shows a large number of packets passing through the docker0 bridge. Why does this MASQUERADE rule only count two packets?
Only packets that are actually leaving the external interface pass through the MASQUERADE rule.The two new packets are most likely the initial outbound packets:Because conntrack handles NAT caching, after the first packet creates a NAT mapping, subsequent packets in the same connection no longer hit this rule.
  • The first packet matches j MASQUERADE → iptables calls conntrack to create a NAT entry, e.g.:
  • Subsequent packets (in the same connection) bypass the rule and are translated via conntrack fast-path NAT.
  • Therefore, the iptables counter only increments on the first NAT trigger.

Experiment 2 – How SNAT Port Range Affects TCP/UDP Connections

In this section, we limit the range of available port numbers for SNAT in the iptables NAT table. We then run curl google.com from a container to observe the impact on connection stability.

1. Adjusting NAT Rules in iptables

We modify the SNAT rule in the POSTROUTING chain (shown in the left figure) to limit the range of ports available for SNAT.
  • Step 1: Remove the existing SNAT rule.
  • Step 2: Add two new SNAT rules that only allow TCP and UDP packets from docker0 to be SNATed, and restrict them to ports 4999 and 5000.
With this configuration, at most two simultaneous SNAT mappings can exist.

2. Repeated Connections and curl Stalling Analysis

After configuring the iptables NAT rules, we will run multiple curl commands and observe the entries in conntrack.
  • Step 1: First, run a curl google.com command inside the container.
  • Step 2: Check the contents of conntrack. You will see that two connections are established: one UDP and one TCP.
  • Step 3: Run curl multiple times. You will notice that it hangs and fails to retrieve data.
  • Step 4: Check conntrack again. We observe that the TCP and UDP connections have already used the destination ports 4999 and 5000. Since we previously limited the range of ports available for SNAT, the reply packets from the external server can only be mapped to these two SNAT ports.
When a third connection is attempted, conntrack tries to create a third SNAT entry but cannot find an available port (because the NAT table keys are already occupied), resulting in:
  • The new connection fails to establish (no SNAT entry is created).
  • The TCP SYN packet is sent but cannot match any reply.
  • curl hangs until it times out.
Eventually, curl’s own timeout mechanism terminates with an error. After a while, due to conntrack’s timeout mechanism, all connection entries are released. At this point, running curl again works normally.

Conclusion

Previously, we learned that packets entering and leaving a container rely on SNAT and DNAT to be transmitted correctly. Conntrack further provides a cache-like mechanism: by matching connection entries, it can determine whether a packet is new or part of an existing connection, thereby reducing the number of times iptables rules need to be evaluated. Additionally, conntrack offers firewall functionalities, helping protect the container. From Experiment 2, we also learned that the conntrack table can become full or be limited by available port numbers, which may prevent new connection entries from being created and cause packets to fail to operate properly.

Reference