Ip_conntrack is built into the Netfilter framework of the Linux protocol stack. Its implementation is complicated, but its logic is quite simple. Ip_conntrack tracks every stream. A stream is defined by a quintuple. The basic term of the quintuple network is not explained. Therefore, ip_conntrack is bound to be able to make a judgment on "where is the beginning of a stream". Although such judgment is not always accurate, see ip_conntrack easily obfuscated issues in linux.
Ip_conntrack binds a stream for each incoming package. If no stream can be bound according to the 5-tuple, it is considered as a stream header, then a new stream is created based on the 5-tuple information carried by the package. The entire scenario can be shown in the following flowchart:
With a basic understanding, you can use the knowledge you know to solve problems. For example, in iptables and Policy Routing to intercept the streams of interest in VPN, to intercept a specific stream, however, due to the complicated topology, it also supports intercommunication between any point and any point, it is difficult to tell where a two-way data stream is initiated based on the information of the IP layer. Therefore, ip_conntrack must be used. Ip_conntrack has a match, that is, ctdir, which can identify the direction information, but how does it do it? We can see that ip_conntrack stores a hash table, and the table item content is a quintuple. However, the quintuple information in both directions is stored separately, this facilitates searching based on individual quintuple groups. Although they are stored separately, two bidirectional quintuple belonging to the same stream are in the same nf_conn structure (Different kernel versions may have different names) unified. In this way, it is easy to identify the direction. Shows the mangle rules for traffic interception:
The following are rule routing rules:
The above method of traffic interception is to use the ip_conntrack mechanism to add a direction feature for IP datagram, and then you can easily distinguish different traffic based on the Direction information, finally, a policy route is used to direct data packets to a specific destination.
Although ip_conntrack is powerful, it still brings about a lot of controversy. Fortunately, there are solutions to the bad aspects of these disputes.