#233 Conntrack: High-Performance Connection Tracking and NAT Implementation

Preface

In the previous two articles, we thoroughly understood Netfilter’s HOOK mechanism (Article 231) and iptables’ rule table-chain system (Article 232). However, there’s one system hiding between them, omnipresent yet not yet detailed — Connection Tracking (conntrack).

Conntrack is the cornerstone of Linux stateful firewalls. It’s because of conntrack that iptables can determine whether a packet is a “new connection” or a “continuation of an existing connection.” It’s because of conntrack that NAT knows how to restore the original IP:Port for return traffic.

Without understanding conntrack, you cannot truly understand how Linux network firewalls work. This article dives deep into conntrack’s architecture design, state machine, protocol handling, memory management, with practical demos and Windows WFP comparison.


1. Why is Connection Tracking Needed?

Stateless vs Stateful

Stateless firewall makes decisions based solely on single packet info (source IP, destination IP, protocol, port). It can’t distinguish “actively initiated new connections” from “responses to existing connections.”

Stateful firewall maintains a “connection state table” via the connection tracking system, recording each flow’s lifecycle and attributes. When evaluating a packet, it considers not just the packet itself but whether it belongs to a tracked connection.

Bash

        Stateless Firewall vs Stateful Firewall Comparison

  Scenario: Internal 192.168.1.10:80 ←→ External 8.8.8.8:12345

  Stateless Firewall: checks single packets only
    Inbound packet: src=8.8.8.8:12345, dst=192.168.1.10:80
     → Match: Allow external access to internal port 80? (YES/NO)
     → Conclusion: But it doesn't know if this is a response
                    to a request initiated by 192.168.1.10

    Outbound packet: src=192.168.1.10:80, dst=8.8.8.8:12345
     → Match: Allow internal port 80 to access any external port? (YES/NO)
     → Conclusion: Can't determine if this is active outbound
                    or a response to an external request

  Stateful Firewall (conntrack): maintains connection state table
    Tracks connection state: NEW, ESTABLISHED, RELATED, INVALID
    Makes decisions based on connection context
Last modified: 2024年12月16日

Author

Comments

Write a Reply or Comment

Your email address will not be published.