netfilter/iptables (iptables for short) constitute the packet filtering firewall under Linux platform
The iptables component is a tool, also known as user space, that makes it easy to insert, modify, and remove rules from the packet filter table
netfilter component, also known as kernel space, is a part of the kernel. It is composed of some packet filtering tables, which contain the rule set used by the kernel to control packet filtering processing
Install: Yum - y install iptables iptables services
Restart: systemctl restart iptables
Save: service iptables save
1. iptables Foundation
Iptables is not exactly a firewall. The real firewall is netfilter running in the system kernel, and iptables is only the spokesman of netfilter. Its main function is to interact with users, obtain users' requirements and convert them into information that netfilter can receive. It mainly works at the network layer for IP packets. It is reflected in the processing of IP address, port and other information in the packet
netfilter belongs to the firewall function system of "Kernel Space" (also known as Kernel Space).
It is a part of the kernel and consists of some packet filtering tables. These tables contain the rule set used by the kernel to control packet filtering processing.
iptables belongs to the firewall management system of "User Space" (also known as User Space).
Is a command program used to manage the Linux firewall. It makes it easy to insert, modify and delete the rules in the packet filtering table. It is usually located in the / sbin/iptables directory.
netfilter/iptables is later referred to as iptables.
iptables is a kernel based firewall, which has built-in four rule tables: raw, mangle, nat and filter. After all the rules in the table are configured, they will take effect immediately without restarting the service
Implementation mechanism of firewall
The core processing mechanism of firewall is filtering. When it comes to filtering, it must have two key elements of "condition & action". In iptables, these two elements are called "rule & target" respectively, which can be understood as that the traffic conforming to the rule will go to the target.
Elements matching rules
The processing object of firewall is network traffic. For network traffic, the most important information identifying traffic is five tuples, including S_IP, S_PORT, D_IP, DI_PORT, TCP/UDP and iptables are also commonly used to filter according to one or some elements in the quintuple
Take a chestnut
The main function of the firewall is filtering, so we might as well regard the firewall as a community wastewater treatment plant, which is responsible for collecting the community's domestic wastewater and returning it to the community after multiple processes of treatment.
- Chain: since we want to treat wastewater, we should first set up a "treatment chain" for centralized treatment on individual key links of wastewater treatment, and place various filter screens, membranes and chemical formulas in the "treatment chain".
- Table: even in different treatment chains, some of the same treatment technologies may be used, such as coarse filtration membrane and fine filtration membrane. In order to facilitate the reuse of these technologies, the wastewater treatment plant encapsulates the treatment technologies with similar functions into a collection, which can be used more conveniently
2. Four tables and five chains
Chain is the key link of computer processing messages from message entry to message departure
Just like the sewage treatment plant, the sewage must be treated before entering, precipitated after entering, and some treatment must be carried out when returning. Then these three nodes are the key links
- INPUT: process inbound packets and match the packets whose target IP is local.
- OUTPUT: Processing outbound packets. Generally, it is not configured on this chain.
- FORWARD: process and FORWARD packets and match the packets flowing through the machine.
- Preouting chain: process packets before routing, which is used to modify the destination address and make DNAT. It is equivalent to mapping port 80 in the intranet to the router's extranet port.
- POSTROUTING chain: processing packets after routing, which is used to modify the source address and make SNAT. It is equivalent to that the intranet host accesses the Internet through a public IP address through the NAT conversion function of the router.
Matching order of chains
- Inbound data (packets from the outside, and the destination address is local to the firewall)
Preouting -- > Input -- > native application
- Outbound data (packets sent from firewall native to external address)
Native application -- > output -- > postrouting
- Inbound data (packets from the outside, and the destination address is local to the firewall)
- Forward data (packets that need to be forwarded through the firewall)
PREROUTING --> FORWARD --> POSTROUTING
- Forward data (packets that need to be forwarded through the firewall)
Matching order within the rule chain
- Check in order from top to bottom, and stop when you find the matching rule (LOG policy exception, which means recording relevant logs)
- If no matching rule is found in the chain, it will be handled according to the default policy of the chain (if it is not modified, the default policy is allowed)
There are a pile of rules on each chain, but some rules are similar. Then we can easily complete reuse by putting together some rules that realize the same function.
For example, in a sewage treatment plant, coarse filtration and fine filtration are basically used in many key links. Why not directly package the coarse filter screen and fine filter screen into one pipe. When it needs to be used, directly connect the whole pipe to realize two functions at one time? Isn't it convenient?
- raw table: determines whether to track the status of the packet. It contains two rule chains, OUTPUT and preouting.
- mangle table: modify the content of the data packet, use it for traffic shaping, and set a flag for the data packet. It contains five rule chains: INPUT, OUTPUT, FORWARD, preouting and POSTROUTING.
- nat table: it is responsible for network address translation and is used to modify the source, destination IP address or port in the packet. It contains three rule chains: OUTPUT, preouting and POSTROUTING.
- filter table: it is responsible for filtering the data packet and determining whether to release the data packet (filtering). It contains three rule chains: INPUT, FORWARD and OUTPUT.
- Among the four rule tables of iptables, the application of mangle table and raw table is relatively reduced.
3. Concept of rules
Rules mainly include two parts, namely "condition & action"
(1) Matching conditions
iptables is mainly matched through five tuples (one or some) of network traffic, including:
- S_IP: source IP
- S_PORT: source port
- D_IP: destination IP
- D_PORT: destination port
- TCP/UDP: four layer protocol
(2) Processing action
iptables is called target
- ACCEPT: allow packets to pass.
- DROP: DROP packets directly. Do not respond to any information. The client will respond only after the link times out.
- REJECT: REJECT the packet. Will send a response message to the client.
- SNAT: source NAT, which solves the problem of private network users accessing the Internet with the same public network IP.
- MASQUERADE: it is a special form of SNAT, which is applicable to dynamic and temporarily changeable IP.
- DNAT: the purpose of NAT is to solve the problem of private network server receiving public network requests.
- REDIRECT: do port mapping on the machine.
- LOG: leave a record in / etc/log/messages, but do not perform any operation on the packet.
1. Common parameters
Usage: iptables + -t table name + rule / chain management parameters + matching parameters + action type parameters
# Select table -t # Operate on the specified table (it must be one of raw, nat, filter and mangle. If it is not specified, it will be the filter table by default) # Rule management -A # Adds a new rule at the end of the specified rule chain -I # Add a new rule at the head of the specified rule chain (added on the first line by default) -D # Delete a rule in the specified chain (it can be deleted by rule sequence number and content) -R # Modify and replace a rule in the specified chain (it can be replaced according to the rule sequence number and content) # Chain management -P # Sets the default policy for the specified chain -N # Create a user-defined rule chain -X # Delete the user-defined rule chain in the specified table -E # Rename a user-defined chain (without changing the chain itself) -Z # Clear the byte and packet counters of all chains of all tables # Rule chain INPUT # Processing inbound packets OUTPUT # Processing outbound packets FORWARD # Process forwarded packets PREROUTING # Handling inbound routing rules POSTROUTING # Processing outbound routing rules # Match (except that the exclamation mark "!" indicates this target (a space should be added after the exclamation mark, followed by a matching item)) -s # Match source address IP/MASK -d # Match destination address -i # Network card name (matching the data flowing in from this network card) -o # Network card name (matching the data flowing out of this network card) -m # Using extension modules -p # Matching protocol (e.g. tcp, udp, icmp) tcp # Extension options: - source port (extension options can be viewed with iptables -p tcp -h) udp # Extension options: - source port (extension options can be viewed with iptables -p icmp -h) icmp # Available Extensions: - ICMP type (available extensions can be viewed with iptables -p icmp -h) --dport 80 # Match target port 80 --sport 81 # Match source port 81 # Specify action type -j # Specify action type Action type: ACCEPT # Allow packets to pass REJECT # Reject packet passing (send response message if necessary) DROP # Discard directly (no response) QUEUE # Interrupt the filter program, put the packet into the queue and hand it over to other programs for processing RETURN # Stop the subsequent rules in the current chain and return to the calling chain REDIRECT # Port mapping on the local machine DNAT # Change the destination address of the packet SNAT # Change the source address of the packet MASQUERADE # A special form of SNAT, which is applicable to dynamic and temporarily changeable IP (only the POSTROUTING chain of user nat table) LOG # Record the log information in the / var/log/messages file, and then pass the packet to the next rule # View / empty rules -L # Lists all rules in the specified chain -n # The IP address and port are printed as a number -v # Detailed output -F # Empty rule chain
2. Expansion module
Usage: iptables + -m + extension module name
Available extension options: iptables + -m + extension + - h view
Limit (rate limit)
# Five icmp packets are allowed per minute (the default is 3 / hour, second: / sec, minute: / hour, day: / day) iptables -A INPUT -p icmp -m limit --limit 5/minute -j ACCEPT # No more than 5 icmp packets per minute iptables -A INPUT -p icmp -m limit --limit 5/minute --limit-burst 10 -j ACCEPT
Multiport (multiport matching)
# Up to 22 ports can be specified iptables -A INPUT -p tcp -m multiport --dport 22,80 -j ACCEPT iprange(Match addresses within the specified range)# # Matches addresses within the specified range iptables -A INPUT -p tcp -m iprange --src-range 192.168.1.0-192.168.1.111 --dport 22 -j ACCEPT
String (string matching)
# When the data message returned by the server detects the keyword "test", the message will be discarded (the string in the message application layer can be detected. Note: this rule needs to be added to the OUTPUT chain) iptables -A OUTPUT -p tcp --dport 80 -m string --algo kmp --string "test" -j DROP
# Limit up to 10 simultaneous http connections to the same IP iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 10 -j REJECT # Limit each group of class C IP to 10 http connections at the same time iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 10 --connlimit-mask 24 -j DROP # Limit the IP of the specified network segment to 10 http connections at the same time iptables -A INPUT -s 192.168.1.0/24 -p tcp --syn --dport 80 -m connlimit --connlimit-above 10 -j REJECT
recent (time limit)
--name # Set list name --resource # source address --redest # Destination address --seconds # Within the specified time (in seconds) --hitcount # Matching times --set # Add the address to the list and update the information (including the timestamp of the address) --rcheck # Source address in the match list (time is calculated based on the first match) --update # Similar to rcheck (calculate the time with the last match) --remove # Delete the corresponding address in the list (followed by the list name and address) # Record the accessed host in the test list and release it iptables -A INPUT -p tcp --dport 80 --syn -m recent --name test --set -j ACCEPT # If the accessed host has a record in the test list, it is limited to 80 ports. Each IP can only initiate 20 new connections within 60 seconds. If it exceeds the limit, the log will be recorded (the log prefix is DDOS:) iptables -A INPUT -p tcp --dport 80 --syn -m recent --name test --rcheck --seconds 60 --hitcount 20 -j LOG --log-prefix 'DDOS:' --log-ip-options # If the accessed host is recorded in the test list, it is limited to 80 ports, and each IP can only initiate 20 new connections within 60 seconds. If it exceeds the limit, packets will be lost iptables -A INPUT -p tcp --dport 80 --syn -m recent --name test --rcheck --seconds 60 --hitcount 20 -j DROP
state (status check)
NEW: Create a new session ESTABLISHED: Established connection RELATED: Associated connections INVALID: Unrecognized connection # Release the first connection status of ssh iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT # Release the associated connection and the established connection iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
3. Rule table and rule chain
(1) Rule tables
The rule table provides specific functions (4 built-in tables), similar to user groups. Each group has different functions and has corresponding users (rule chain)
filter # Responsible for filtering function (kernel module: iptables_filter) nat # Responsible for network address translation function (kernel module: iptable_nat) mangle # Disassembly, modification and encapsulation message (kernel module; iptable_mangle) raw # Determine whether the packet is processed by the state tracking mechanism (kernel module: iptable_raw)
Rule table priority (from left to right): raw < --- mangle < --- NAT < --- filter
Rule chain corresponding to rule table:
raw Table: PREOUTING,OUTPUT mangle Table: PREROUTING,INPUT,FORWARD,OUTPUT,POSTROUTING nat Table: PREROUTING,INPUT,OUTPUT,POSTROUTING filter Table: INTPUT,FORWARD,OUTPUT
(2) Rule chains
A rule chain is a collection of rules. Set corresponding rules for specific packets (read the rule chain from top to bottom)
INPUT # Processing inbound packets OUTPUT # Processing outbound packets FORWARD # Processing forwarded packets PREROUTING # Before the packet enters the routing table POSTROUTING # After the packet enters the routing table
Inbound sequence (from left to right): preouting < --- input
Outbound sequence (from left to right): output < --- postrouting
Forwarding order (from left to right): forwarding < --- forward < --- postrouting
View / delete rules
iptables -L # List all rules iptables -L -nv # View details (IP and port will be displayed in digital form) iptables -t nat -L # Lists all rules in the nat table iptables -t nat -L -nv # View details (IP and port will be displayed in digital form) iptables -F # Clear all rules (if no table is specified, the default table is filter) iptables -t nat -D INPUT 1 # Delete the first rule under the INPUT chain of nat table
Create a new rule in the specified table (if not specified, the default is the filter table)
# Open port 80 in nat table iptables -t nat -A INPUT -p tcp --dport 80 -j ACCEPT
Set white list
# Allow host access of 192.168.1.0/24 network segment iptables -A INPUT -p all -s 192.168.1.0/24 -j ACCEPT # Allow hosts in the 192.168.2.0/24 network segment to access port 80 of this machine iptables -A INPUT -p all -s 192.168.2.0/24 --dport 80 -j ACCEPT
# Specify IP range iptables -t nat -A POSTROUTING -s 192.168.0.0/24 -o eth0 -j MASQUERADE # Specify port range iptables -t nat -A INPUT -p tcp --dport 90:100 -j ACCEPT
# When another host accesses the local port 80, it will be redirected to port 8080 iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080
# Ban Ping iptables -A INPUT -p icmp -j DROP # Ban Ping iptables -I INPUT -p icmp --icmp-type Echo-Request -j DROP # Access to the host with MAC address 00:11:22:33:44:55 is prohibited iptables -A INPUT -m mac --mac-source 00:11:22:33:44:55 -j DROP # It is forbidden to forward the data of the host whose MAC address is 00:11:22:33:44:55 iptables -A FORWARD -m mac --mac-source 00:11:22:33:44:55 -j DROP
Simple understanding of iptables