IPtables concept and function
IPTABLES Four Tables & Five Chains
iptables has four built-in tables: Filter, NAT, Mangle, Raw.
IPTABLES packet flow
The packet first passes through PREOUTING, which determines the packet direction:
If the destination address is local, send it to INPUT, and let INPUT decide whether to receive it and send it to user space. The process is ①--->②;
If the forwarding rule on the nat table of PREROUTING is satisfied, it is sent to FORWARD, and then sent out through POSTROUTING. The process is: ①-->③-->④--> ④;
When the host sends a data packet, the flow is ④---> ④;
Where PREROUTING and POSTROUTING refer to the flow direction of packets, as shown in the figure above, POSTROUTING refers to packets sent to the public network, and PREROUTING refers to packets from the public network.
Filter table under IPtables under Linux
Filter represents the default table for iptables, so if you don't have a custom table, you'll default to the filter table, which has three built-in chains:
INPUT chain-processing data from outside;
OUTPUT chain-handles outgoing data;
FORWARD CHAIN-forwards data to other NIC devices on the machine.
NAT table under IPtables under Linux
NAT (Network Address Translation) technology is very common at ordinary times, such as when using routers to share Internet access in families, NAT technology is generally used, which can realize that many intranet IPs share a public IP Internet access.
The principle of NAT is simply that when an intranet host accesses an external network, when a packet of the intranet host wants to pass through a router, the router changes the source intranet IP address in the packet to the public network IP address on the router, and records the message of the packet;
When the external network server responds to the request or data exchange sent from the inside out, when the data packet sent by the external network server passes through the router, the public network IP address originally on the router is changed to the internal network IP by the router.
SNAT and DNAT are two important concepts related to the use of NAT rules in iptables. As shown in the figure above, if the intranet host accesses the external network and passes through the route, the source IP will change, and this change behavior is SNAT; on the contrary, when the data from the external network is sent to the intranet host through the route, the destination IP in the data packet (the public network IP on the router) will be modified to the internal network IP, and this change behavior is DNAT. NAT tables have three built-in chains:
PREROUTING Chain-processes packets that have just arrived on the machine and are before routing. It translates the destination IP address in the packet, usually used for DNAT(destination NAT).
POSTROUTING CHAIN-Process packets that are about to leave the machine. It translates the source IP address in the packet, usually used for SNAT (source NAT).
OUTPUT Chain-processes locally generated packets.