This is the 11th day of my participation in the More text Challenge. For more details, see more text Challenge


A lifelong learner, practitioner, and sharer committed to the path of technology, an original blogger who is busy and sometimes lazy, and a teenager who is occasionally boring and sometimes humorous.

Wechat search [Jack’s IT journey] pay attention to this teenager who has a little bit of something.

Iptables Firewall (1) – Four-table/five-chain, packet matching process, writing iptables rules

First, Linux firewall foundation

Linux firewall mainly works in the network layer, the implementation of TCP/IP packet filtering and restrictions, the typical packet filtering firewall, based on kernel coding implementation, has very stable performance and high efficiency.

  • Iptables: a command program used to manage Linux firewalls. It is located in /sbin/iptables directory and belongs to the firewall management system in user space.

  • Netfilter: an internal structure of the packet filtering firewall in the Linux kernel. Generally, it does not exist in the form of programs or files. It is a firewall management system in the kernel space.

Iptables provides rules for the implementation of the packet filtering mechanism. The different rules tell NetFilter how to process packets from certain sources, destined for certain purposes, or with certain protocol characteristics.

Iptables table chain structure

Each rule table, it is equivalent to a kernel space of the container, according to the different purposes of the rule set is divided into four tables by default, in the chain of each rule contains different rules in the table, processing packets is divided into five kinds of different timing chain, decided to whether packet filtering or processing of a variety of rules and in accordance with the order in each rule in the chain.

  • Function of rules: Filter or process data packets;

  • The role of the chain: to accommodate multiple firewall rules;

Rule table

Iptables manages four different rule tables, each implemented by a separate kernel module.

  • The filter table is used to filter packets. The specific rules determine how to process a packet.

    The corresponding kernel module is ipTable_filter, which contains three chains: input, forward, and output.

  • NAT table: FULL NAME of NAT: Network Address Translation Network address translation, which is used to modify IP addresses and port numbers of data packets.

    The corresponding kernel module is iptable_NAT, which contains three chains: PRERouting, POstrouting, and output.

  • Mangle table: Used to modify the service type and lifetime of data packets, set tags for data packets, and implement traffic shaping and policy-based routing.

    The corresponding kernel module is iptable_mangle, and its table contains five chains: PRERouting, POstrouting, INPUT, output, and forward.

  • Raw table: Used to determine whether to track the status of packets.

    The corresponding kernel module is iptable_RAW, and its table contains two chains: Output and PRERouting;

Rules of the chain

  • Input chain: Rules in this chain are applied when packets accessing the local address of the firewall are received.

  • Output chain: Rules in this chain are applied when packets are sent out by the local firewall.

  • Forward chain: When receiving packets that need to be forwarded to other addresses through fire prevention, rules in this chain are applied.

  • Prerouting chain: Rules in this chain are applied before packet routing is made;

  • Postrouting chain: Rules in this chain are applied after routing packets;

Input chain and output chain are mainly used in the main model firewall, is for the protection of the server firewall;

The forward chain, PRERouting chain, and Postrouting chain are mainly used on network firewalls to control the security between the Intranet and the Internet.

3. Matching process of packet filtering

Order between rule tables

When the packets arrive at the firewall, if there are rules in the corresponding chain, they will go from the RAW table to the Mangle table to the NAT table to the Filter table in sequence.

Order between chains of rules

  • Incoming data flow: If the packets from outside arrive at the firewall, they must pass the PRERouting chain: After routing the packet, the rules in the chain will be applied, and then the route will be selected to confirm whether the target address of the packet is the local firewall. The packet will be sent to the input chain for processing in combination with the kernel. After passing the confirmation, it can be handed over to the server for response.

  • Forwarding data flow: If the packet from the outside reaches the firewall, it needs to be processed through the PRERouting chain and then route selection. If the destination address of the packet is any other address, it will be passed through the kernel to the forward for processing. Whether it needs to be passed or discarded directly. Finally, it’s over to the Postrouting chain to see if any packet information needs to be modified for processing.

  • Outgoing data flow direction: The outgoing traffic refers to the packets sent by the local firewall to the external address. The packets are processed by the output chain first, then the route is selected, and then the postrouting chain is used to check whether the packet information is modified for processing.

The sequence of firewall rules within a rule chain

When a packet passes through each rule chain, it will follow the first rule, the second rule… The sequence is matched and processed.

In-chain filtering principles

  • If a matching rule is found, other subsequent rules in the chain will not be executed.

  • If no matching rule can be found in the whole chain, the default policy of the rule chain is followed.

Four, write firewall rules

Basic syntax command format of iptables

Iptables [-t table name] Management options [chain name] [matching condition] [-j control type]Copy the code
  • Table name and chain name: Specifies the tables and chains operated by the iptables command. If no table name is specified, the filter table is used by default.

  • Management options: Indicates the operation modes of iptables rules, such as inserting, adding, deleting, and viewing.

  • Matching condition: Specifies the characteristics of the packets to be processed. Packets that do not meet the specified conditions are not processed.

  • Control type: indicates the processing mode of packets, such as permit, deny, and discard.

Iptables Most commonly used control types of firewalls

  • Accept: Allows packets;

  • Drop: the data packet is dropped without any response message.

  • Reject: Reject the packet and send a response message to the sender if necessary.

  • Log: log messages in the /var/log/messages file and then pass the packet to the next address;

Most common basic operations of the iptables firewall

-d: deletes A rule in the specified chain. The sequence number or specific contents can be deleted. -I: Inserts A new rule in the specified chain. -l: Lists all the rules in the specified chain. If the chain name is not specified, all the chains in the table are listed. -f: deletes all the rules in the specified chain. -p: sets the default policy for the specified chain. -n: Displays the output result in numbers. -V: displays the detailed information when viewing the rule listCopy the code

Adding a new rule

When adding new firewall rules, you can use the management option -a: to add rules. -l: to insert rules.

Add a rule at the end of the INPUT chain of the filter table. The -p protocol name can be used as the matching condition.

# iptables -t filter -A INPUT -p tcp -j ACCEPT
Copy the code

The -i option allows you to specify the sequence number of the rule to be added. If the sequence number is not specified, the rule is used as the first rule by default.

Add two rules to the first and second filter table, and the default filter table will be used.

# iptables -I INPUT -p udp -j ACCEPT
# iptables -I INPUT 2 -p icmp -j ACCEPT
Copy the code

Viewing the Rule List

When viewing firewall rules, use the -l management option and the –line-numbers option to display the sequence number of each rule in the chain.

View all rules in the INPUT chain of the Filter table and display the rule number;

# iptables -L INPUT --line-numbers
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination         
1    ACCEPT     udp  --  anywhere             anywhere            
2    ACCEPT     icmp --  anywhere             anywhere            
3    ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED 
4    ACCEPT     icmp --  anywhere             anywhere            
5    ACCEPT     all  --  anywhere             anywhere            
6    ACCEPT     tcp  --  anywhere             anywhere            state NEW tcp dpt:ssh 
7    REJECT     all  --  anywhere             anywhere            reject-with icmp-host-prohibited 
8    ACCEPT     tcp  --  anywhere             anywhere
Copy the code

If there are many firewall rules, the address and port information can be displayed in digital format, which reduces the address resolution process and speeds up command execution.

View all the rules in the INPUT chain of the default table in numeric form, which can be combined with the argument -nl or split with -n-L.

# iptables -nl INPUT Chain INPUT (Policy ACCEPT) Target prot opt source Destination ACCEPT UDP -- 0.0.0.0/0 0.0.0.0/0 ACCEPT ICMP -- 0.0.0.0/0 0.0.0.0/0 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 state RELATED,ESTABLISHED ACCEPT ICMP -- 0.0.0.0/0 REJECT all -- 0.0.0.0/0 0.0.0.0/0 ACCEPT TCP -- 0.0.0.0/0 0.0.0.0/0 State NEW TCP DPT :22 REJECT all -- 0.0.0.0/0 0.0.0.0/0 Reject -with icmp-host-prohibited ACCEPT TCP -- 0.0.0.0/0 0.0.0.0/0Copy the code

Delete or clear a rule

To delete the third rule in the INPUT chain of the filter table, use the -d management option to delete a firewall rule.

# iptables -D INPUT 3
# iptables -n -L INPUT
Copy the code

To clear all firewall rules in a specified chain or table, use the -f management option.

# iptables -F INPUT
# iptables -n -L INPUT
Chain INPUT (policy ACCEPT)
target     prot opt source               destination  
Copy the code

To omit the chain name and clear all chains in a specified table, use the -f management option.

# iptables -F
# iptables -t nat -F
# iptables -t mangle -F
Copy the code

Setting the default policy

The default policy can be controlled by Accept or DROP.

The default policy of the FORWARD chain in the filter table is set to discard, and the default policy of the OUTPUT chain is set to allow.

# iptables -t filter -P FROWARD DROP
# iptables -P OUTPUT ACCEPT
Copy the code

5. Matching conditions of rules

General match: Called a general match, it can be used independently and does not depend on other conditions or extension modules.

Agreements to match

When writing rules, use the form -p protocol name.

To check the network protocol used by the packet, the available protocol type file is located in: /etc/procotols.

# iptables -I INPUT -p icmp -j DROP
# iptables -A FORWARD ! -p icmp -j ACCEPT
Copy the code
Address matching

When writing iptables rules, use -s source address or -d target address.

Check the source or destination address of the packet. (IP address, network segment address)

Do not use the host name or domain name.

For example, to deny the forwarding of data whose source IP address is 192.168.123.123 but allow the forwarding of data whose source IP address is on network segment 192.168.1.0/24, run the following command:

# iptables -A FORWARD -s 192.168.123.123 -j REJECT
# iptables -A FORWARD -s 192.168.1.0/24 -j ACCEPT
Copy the code

For example, if you want to detect frequent scanning and login from a website, you can add firewall rules to block.

# iptables -I INPUT -s 192.168.123.0/24 -j DROP
# iptables -I FORWARD -s 192.168.123.0/24 -j DROP
Copy the code
Network interface matching

When writing iptables rules, use the -i interface name and -o interface name.

It is used to check which interface the packet is coming in or out of the firewall, and corresponding to the inbound/outbound network adapter respectively.

For example, if you want to discard the packets that access the firewall from the extranet interface and the source ADDRESS is a private address;

# iptables -A INPUT -i eth0 -s 10.0.0.0/8 -j DROP
# iptables -A INPUT -i eth0 -s 172.16.0.0/12 -j DROP
# iptables -A INPUT -i eth0 -s 192.168.0.0/16 -j DROP
Copy the code

Implicit match: The specified protocol match is used as a prerequisite, and the corresponding function is automatically loaded into the kernel by iptables when needed.

Common implicit matches: port match, TCP match, ICMP match;

Port matching

When writing iptables rules, use –sport source port or –dport target port.

The protocol type can be TCP or UDP

Source port or destination port used to check data packets.

Single port numbers or port ranges separated by colon: are acceptable, but discontinuous ports are not.

For example, HTTP query packets can be forwarded to network segment 192.168.123.0/24.

# iptables -A FORWARD -s 192.168.123.0/24 -p udp --dport 80 -j ACCEPT
# iptables -A FORWARD -d 192.168.123.0/24 -p udp --dport 80 -j ACCEPT
Copy the code

For example, when the FTP service is set up, ports 20 and 21 are enabled, and ports for passive mode range from 24 100 to 25 200.

# iptables -A INPUT -p tcp --dport 20:21 -j ACCEPT
# iptables -A INPUT -p tcp --dport 24100:25200 -j ACCEPT
Copy the code
The ICMP match

When writing iptables rules, use –icmp-type to specify the ICMP type.

Protocol: ICMP: used to check the type of ICMP packets.

The ICMP type is a string or a number

  • Echo – Request: 8 (ICMP)

  • Echo reply: 0 (ICMP)

  • Destination-unreachable: 3 (destination unreachable)

For example, you want to disable ping from other hosts, but allow local hosts to ping other hosts.

# iptables -A INPUT -p icmp --icmp-type 8 -j DROP
# iptables -A INPUT -p icmp --icmp-type 0 -j ACCEPT
# iptables -A INPUT -p icmp --icmp-type 3 -j ACCEPT
# iptables -A INPUT -p icmp -j DROP
Copy the code

For more available ICMP protocol types, run iptables -p ICMP -h.

Display the matching

This matching mode requires additional kernel modules to support it, calling the corresponding module with the -m module name, and then setting the matching condition.

Common display matches are: multi-port match, IP range match, MAC address match, and status match.

Multi-port matching

When writing iptables rules, use -m multiport –dports port list or -m multiport –sports port list.

Use commas (,) to separate the source port, destination port, and multiple ports to check the data packet.

For example, to allow the host to open ports 80, 443, 110, and so on, provide related services;

# iptables -A INPUT -p tcp -m multiport --dport 80,443,110 -j ACCEPT
Copy the code
IP range matching

-m iprange –src-range IP range or -m iprange –dst-range IP range are used to specify the iptables rules.

Check the source address and destination address of the packet.

IP address range: indicates the start IP address and end IP address.

For example, forbid forwarding TCP packets whose source IP addresses are between 192.168.8.100 and 192.168.8.123.

# iptables -A FORWARD -p tcp -m iprange --src-range 192.168.8.100-192.168.8.123 -j ACCEPT
Copy the code
MAC address matching

When writing iptables rules, use the -m MAC –mac-source MAC address.

The source MAC address used to check packets is applicable only to internal networks.

For example, you can block a host based on its MAC address to prevent it from accessing any applications on the host.

# iptables -a INPUT -m MAC --mac-source MAC address XXX -j DROPCopy the code
State matching

-m state –state specifies the connection state when writing iptables rules.

The status tracking mechanism based on iptables is used to check the connection status of packets.

Common connection states include: New (independent of any connection), Established (in response to a request or a connection has been established), Related (related to a connection);

For example, forbidding forwarding of non— SYN request packets unrelated to a normal TCP connection.

# iptables -A FORWARD -m state --state NEW -p tcp ! --syn -j DROP
Copy the code

Only WEB services on the local host are enabled, but TCP packets sent to the local host are allowed, and other incoming packets are discarded.

# iptables -I INPUT -p tcp -m multiport --dport 80 -j ACCEPT
# iptables -I INPUT -p tcp -m state --state ESTABLISHED -j ACCEPT
# iptables -P INPUT DROP
Copy the code

conclusion

That’s all for today, from Linux firewall foundation, iptables table, chain structure, packet filtering matching process, writing firewall rules and rules matching conditions and other content;

Originality is not easy, if you think this article is a little useful to you, please point for this articlepraise,commentsorforwardingBecause this will be my motivation to output more quality articles, thanks!

See you next time!