Linux--Firewall basics and writing firewall rules (super detailed) (netfilter and iptables, four tables and five chains, matching process of packet filtering, common management options and matching conditions in firewall rules)


Preface

  • In the Internet, enterprises provide users with various services through various application systems, such as Web sites, email systems, FTP servers, database systems, etc.
  • So, how to protect these servers and filter unwanted access or even malicious intrusion by the enterprise?
  • Next, we will learn about the firewall in CentOS 6 system-netfilter and iptables, and the firewall firewalld in CentOS 7 system

1. Linux firewall basics

1 Overview

  • Linux's firewall system mainly works at the network layer, filtering and restricting TCP/IP packets, which is a typical packet filtering firewall (or called a network layer firewall)
  • Reflected in the processing of the IP address, port and other information in the packet
  • The firewall of the Linux system is implemented based on kernel coding, with very stable performance and extremely high efficiency, and therefore it is widely used

2.netfilter 与 iptables

  • In many security materials, netfilter and iptables are both used to refer to the Linux firewall, which often confuses readers
  • The main differences between the two are as follows:

2.1 netfilter

  • It is part of the kernel, composed of some data packet filtering tables, and does not exist in the form of program files or files
  • These tables contain the set of rules used by the kernel to control packet filtering processing
  • A firewall function system belonging to "Kernel Space" (Kernel Space, also known as Kernel Space)

2.2 iptables

  • It is a command program used to manage the Linux firewall. It makes it easy to insert, modify and delete the rules in the packet filter table, usually located in the /sbin/iptables directory
  • A firewall management system that belongs to "User Space" (User. Space, also known as User Space)

2.3 Summary

  • A correct understanding of the relationship between the two helps to understand how the Linux firewall works
  • Both can represent Linux firewall

3. Table and chain structure of iptables

3.1 Introduction

  • The role of iptables is to provide rules (or policies) for the realization of the packet filtering mechanism. Through various rules, it tells netfilter how to deal with data packets from certain sources, to certain purposes, or with certain protocol characteristics.
  • Netfilter/iptables will be referred to as iptables later
  • In order to organize and manage firewall rules more conveniently, iptables adopts a hierarchical structure of "tables" and "chains", and after all the rules in the table are configured, they take effect immediately without restarting the service.

3.2 Rule table (four tables)

  • In order to differentiate the function of the rule set, iptables manages four different rule tables, whose functions are implemented by independent kernel modules.
  • The names of these four tables and the chains they contain are shown in the figure below
    mark
  • raw 表
    • Determine whether to track the status of the packet
    • Contains two rule chains: OUTPUT and PREROUTING
  • mangle table
    • Modify the content of the data packet, or set a mark for the data packet for advanced applications such as traffic shaping and policy routing
    • Contains five rule chains: INPUT, OUTPUT, FORWARD, PREROUTING, POSTROUTING
  • nat table
    • Responsible for network address translation, used to modify the source, destination IP address or port in the data packet
    • Contains three rule chains: OUTPUT, PREROUTING, POSTROUTING
  • filter table
    • Responsible for filtering data packets and determining how to process the data packets according to specific rules requirements (filtering)
    • Contains three rule chains: INPUT, FORWARD, OUTPUT
  • Among the four rule tables of iptables, the mangle table and raw table are relatively less used

3.3 Rule chain (five chains)

  • When processing various data packets, iptables is divided into five different rule chains by default according to the different intervention timing of firewall rules
  • INPUT chain: Process inbound data packets and match the monthly IP address to the data packets of this machine
  • OUTPUT chain: processing outbound data packets, generally do not configure on this chain
  • FORWARD chain: processing and forwarding data packets, matching data packets flowing through the machine
  • PREROUTING chain: Process data packets before routing, used to modify the destination address, used for DNAT; equivalent to mapping the IP and port of the internal network server to the external IP and port of the router
  • POSTROUTING chain: Process data packets after routing selection, used to modify the source address, used for SNAT; equivalent to the internal network through the router NAT conversion function to achieve the internal network host through a public network IP address

4. The matching process of packet filtering

  • iptables manages four default tables and five chains, and various firewall rules are stored in the chain in turn

4.1 Matching order between rule tables

  • When the packet arrives at the firewall, the priority order is (if any):
    raw >> mangle >> nat >> filter

4.2 Sequence between rule chains

  • According to the division principle of the rule chain, the processing timing of different chains is relatively fixed, so the application order between the rule chains depends on the flow direction of the data packet
  1. Inbound data flow direction: After
    the data packet from the outside reaches the firewall, it is first processed by the PEROUTING chain (whether the data packet address is modified, etc.), and then routing is selected (to determine where the data packet should be sent); if the destination address of the data packet It is the firewall native, then the kernel will pass it to the INPUT chain for processing (decide whether to allow passage), and then pass it to the upper-level application of the system for corresponding
  2. Forwarding data flow direction: After
    the data packet from the outside reaches the firewall, it is first processed by the PREOUTING chain, and then route selection; if the destination address of the data packet is other external addresses, the kernel will pass it to the FORWARD chain for processing (allow forwarding, Intercept or discard), and finally hand it over to the POTROUTING chain for processing (whether to modify the address of the data packet, etc.)
  3. Outbound data flow: The
    firewall sends data packets to external addresses, which are first processed by the OUTPUT chain, then route selection, and then handed over to the POTROUTING chain for processing (whether to modify the address of the data packet, etc.)

4.3 The sequence of the firewall rules within the rule chain

  • When the data packet passes through each rule chain, check it in order from top to bottom, and stop when it finds a matching rule (except for the LOG policy, which means to record related logs)
  • If no matching rule is found in the chain, it will be processed according to the chain’s default policy (unmodified, the default policy is allowed)

Two, write firewall rules

1. Install iptables

  • Centos 7 uses firewalld firewall by default, iptables is not installed, if you want to use iptables firewall. The firewalld must be turned off before installing iptables
[root@localhost ~]# systemctl stop firewalld
[root@localhost ~]# systemctl disable firewalld

[root@localhost ~]# yum -y install iptables iptables-services.x86_64 
...略
[root@localhost ~]# systemctl start iptables.service 

2. Basic grammar

When using iptables commands to manage and write firewall rules, the basic command format is as follows:

iptables [-t 表名] 管理选项 [链名] [匹配条件] [-j 控制类型]

Precautions:

  1. When the table name is not specified, it refers to the filter table by default
  2. When the chain name is not specified, it refers to all chains in the table by default
  3. Unless the default policy of the chain is set, the matching conditions must be specified
  4. Use uppercase letters for options, chain names, and control types, and lowercase the rest

3. Commonly used control types

  1. ACCEPT: Allow data packets to pass
  2. DROP: Drop the data packet directly without giving any response information
  3. REJECT: Reject the data packet to pass, if necessary, a response message will be sent to the data sender
  4. SNAT: modify the source address of the packet
  5. DNAT: Modify the destination address of the data packet
  6. MASQUERADE: disguised as a non-fixed public IP address
  7. LOG: Record the log information in the /var/log/messages file, and then pass the data packet to the next rule; LOG is just an auxiliary action and does not actually process the data packet

4. Common management options

  • Before proficiently writing various firewall rules, you must first master basic operations such as viewing rules, adding rules, deleting rules, and clearing rules in the chain.
  • The following will introduce several management options commonly used in iptables commands
Option name Functions and features
-A Append (--append) a new rule at the end of the specified chain
-I Insert (--insert) a new rule at the beginning of the specified chain. If the sequence number is not specified, it will default to the first rule
-R Modify, replace (--replace) a rule in the specified chain, you can specify the rule number or specific content
-P Set the default policy of the specified chain (--policy)
-D Delete (--delete) a rule in the specified chain, you can specify the rule number or specific content
-F Flush (--flush) all the rules in the specified chain, if the chain name is not specified, all the chains in the table are cleared
-L List (--list) all the rules in the specified chain, if the chain name is not specified, all the chains in the table are listed
-n Use numeric format (--numeric) to display output results, such as displaying IP addresses instead of host names
-v Display detailed information, including the number of matching packets and matching bytes for each rule
--line-numbers When viewing rules, display the serial number of the rule

4.1 Add new rules

  • When adding a new firewall rule, use the management options "-A" and "-I", the former is used to append rules, the latter is used to insert rules
  • For example, to add a firewall rule to the end of the INPUT chain in the filter table, you can perform the following operations ("-p protocol name" as the matching condition)
[root@localhost ~]# iptables -t filter -A INPUT -p tcp -j ACCEPT 
  • When using the management option "I", it is allowed to specify the sequence number of the newly added rule at the same time. If the sequence number is not specified, it will default to the first one
  • For example, the two rules added by the following operation will be located in the first and second entries of the filter table respectively, and the "-t filter" option is omitted, and the filter table is used by default
iptables -I INPUT 2 -p tcp --dport 22 -j ACCEPT

4.2 View the rule table

  • When viewing existing firewall rules, use the management option "-L", combined with the "–line-numbers" option, you can also display the sequence number of each rule in the chain
#基本格式:
iptables [-t 表名] -n -L [链名] [--line-numbers]
  • For example, if you want to view all the rules of the INPUT chain of the filter table and display the serial number, you can perform the following operations
[root@localhost ~]# iptables -L INPUT  --line-numbers 
Chain INPUT (policy ACCEPT)
num  target     prot opt source               destination         
1    ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED
2    ACCEPT     icmp --  anywhere             anywhere            
3    ACCEPT     all  --  anywhere             anywhere            
4    ACCEPT     tcp  --  anywhere             anywhere             state NEW tcp dpt:ssh
5    REJECT     all  --  anywhere             anywhere             reject-with icmp-host-prohibited
6    ACCEPT     tcp  --  anywhere             anywhere            
7    REJECT     icmp --  anywhere             anywhere             reject-with icmp-port-unreachable
  • When the number of firewall rules is large, if the address and port information can be displayed in digital form, it can reduce the link of address resolution and speed up the execution of commands to a certain extent
  • For example, if you want to view all the rules in the INPUT chain of the filter table in the form of a numeric address, you can perform the following operations
[root@localhost ~]# iptables -n -L INPUT
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     all  --  0.0.0.0/0            0.0.0.0/0            state RELATED,ESTABLISHED
ACCEPT     icmp --  0.0.0.0/0            0.0.0.0/0           
ACCEPT     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/0           
REJECT     icmp --  0.0.0.0/0            0.0.0.0/0            reject-with icmp-port-unreachable

4.3 Set default policy

  • In each chain of iptables, the default strategy is the last link in the rule matching-when no matching packet rule is found, the default strategy is executed
  • The control type of the default policy is ACCEPT (allow) and DROP (drop)
#基本格式
iptables [-t 表名] -p <链名> <控制类型>
  • For example, perform the following operations to set the default policy of the FORWARD chain in the filter table to discard, and the default policy of the OUTPUT chain to allow
iptables -P FORWARD DROP

iptables -P OUTPUT ACCEPT
  • Generally, when setting up a network firewall and a host-based firewall in a production environment, the default rule is DROP and a whitelist is set to strengthen security

4.4 Delete and clear rules

  • When deleting a firewall rule, use the management option "-D"
  • For example, to delete the third rule in the INPUT chain of the filter table, you can perform the following operations
    mark
  • Clear all firewall rules in the specified chain or table, use the management option "-F"
  • For example, to clear all the rules in the INPUT chain of the filter table, you can perform the following operations
[root@localhost ~]# iptables -F INPUT
[root@localhost ~]# iptables -n -L
INPUT        ##确认删除效果 
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
  • When using the management option "-F", the chain name is allowed to be omitted, and all the rules of all chains in the table are cleared by default
  • For example, perform the following operations to clear the filter table, nat table, and mangle table respectively
iptables -F
iptables -t nat -F
iptables -t mangle -F
  • It should be noted that when the management option "-F" is used to clear the chain, the default policy is not affected
  • Therefore, if you want to modify the default policy, you must reset it through the management option "-P"
  • After setting DROP with -P, be careful when using -F! Prevent remote connection of the host after clearing the relevant rules that allow remote connections. In this case, if the rules are not saved, you can restart the host to solve the problem (buy a ticket~)

5. The matching condition of the rule

  • When writing firewall rules, the setting of matching conditions plays a decisive role
  • Only when the matching conditions are clearly and accurately set, can the firewall know what data packets that meet the conditions will be processed to avoid "manslaughter"
  • For the same firewall rule, you can specify multiple matching conditions, which means that these conditions must all meet the rule to take effect
  • According to the various characteristics of the data packet, combined with the module structure of iptables, the matching condition settings include the following three categories:

5.1 General matching

  • General matching is also called regular matching. This matching method can be used alone and does not depend on other conditions or extension modules
  • Common general matching includes protocol matching, address matching, and network interface matching

5.1.1 Protocol matching

  • When writing iptables rules, use the form of "-p protocol name" to specify to check the network protocol used by the packet, such as TCP, UDP, ICMP (for all IP packets), etc.
  • The available protocol types are stored in the /etc/protocols file of the Linux system
  • For example, if you want to discard data packets that access the firewall's local machine through the icmp protocol, allow forwarding of data packets that pass through the firewall except for the ICMP protocol
[root@localhost ~]# iptables -I INPUT -p icmp -j DROP 
[root@localhost ~]# iptables -A FORWARD ! -p icmp -j ACCEPT 

5.1.2 Address matching

  • Use "-s source address" or "-d destination address" to specify when writing iptables rules to check the source address or destination address of the packet
  • IP address and network segment address are acceptable, but it is not recommended to use host name and domain name address. Relatively speaking, the resolution process will affect efficiency
  • For example, if you want to deny forwarding data whose source address is 192.168.1.11, allow forwarding data whose source address is in the 192.168.7.0/24 network segment
[root@localhost ~]# iptables -A FORWARD -s 192.168.11.1 -j REJECT 
[root@localhost ~]# iptables -A FORWARD -s 192.168.7.0/24 -j ACCEPT 
  • When encountering small-scale network scanning attacks, blocking the IP address is a more effective way
  • For example, if a network segment (10.20.30.0/24) is frequently scanned, login exhaustive and other bad attempts are detected, you can immediately add a firewall to block it
[root@localhost ~]# iptables -I INPUT -s 10.20.30.0/24 -j DROP 
[root@localhost ~]# iptables -I FORWARD -s 10.20.30.0/24 -j DROP 

5.1.3 Network interface matching

  • When writing iptables rules, use the form of "-i interface name" and "-o interface name" to check which interface of the firewall the data packet is connected to or sent from, corresponding to the inbound and outbound network cards
  • For example, if you want to discard data packets that access the firewall's local machine from the external network interface (eth1) and the source address is a private address, you can do the following
[root@localhost ~]# iptables -A INPUT -i eth1 -s 10.0.0.0/8 -j DROP 
[root@localhost ~]# iptables -A INPUT -i eth1 -s 172.16.0.0/12 -j DROP 
[root@localhost ~]# iptables -A INPUT -i eth1 -s 192.168.0.0/16 -j DROP 

5.2 Implicit matching

  • This matching method requires the specified protocol matching as a precondition, which is equivalent to a sub-condition, so it cannot be used alone, and its corresponding function is automatically (implicitly) loaded into the kernel by iptables when needed
  • Common implicit matching includes port matching, TCP tag matching, and ICMP type matching

5.2.1 Port matching

  • When writing iptables, use the form of "–sport source port" or "–dport destination port", and the target protocol is TCP or UDP to check the source port or destination port of the data packet
  • A single port number or a port range separated by a colon ":" is acceptable, but multiple ports that are not continuous cannot use this method
  • For example, to allow forwarding of DNS query packets for the network segment 192.168.4.0/24
[root@localhost ~]# iptables -A FORWARD -s 192.168.4.0/24 -p udp --dport 53 -j ACCEPT 
[root@localhost ~]# iptables -A FORWARD -s 192.168.4.0/24 -p udp --sport 53 -j ACCEPT 
  • For another example, when building a vsftpd server, if you want to open ports 20 and 21, and the passive mode ports are 24500~24600, you can refer to the following operations to set firewall rules
[root@localhost ~]# iptables -A INPUT -p tcp --dport 20:21 -j ACCEPT 
[root@localhost ~]# iptables -A INPUT -p tcp --dport 24500:24600 -j ACCEPT 
  • usage
--sport 1000                #匹配源端口是1000的数据包
--sport 1000: 3000          #匹配源端口是1000-3000的数据包
--sport : 3000              #匹配源端口是3000及以下的数据包
--sport 1000:               #匹配源端口是1000及以上的数据包

注意: --sport 和--dport 必须配合-p <协议类型>使用
  • TCP tag matching
--tcp-flags TCP标记

iptables -I INPUT -i ens33 -p tcp --tcp-flags SYN,RST,ACK SYN -j ACCEPT
#丢弃SYN请求包,放行其他包

5.2.2 ICMP type matching

  • Use the form of "–icmp-type ICMP type" when writing iptables rules, and the target protocol is ICMP to check the type of ICMP packets
  • ICMP type is represented by string or numeric code
    • "Echo-Request" (code 8) means request
    • "Echo-Reply" (code 0) means echo
    • "Destinat ion-Unreachable" (code 3) means the target is unreachable
  • For other available ICMP protocol types, you can execute the "iptables -p icmp -h" command to view help information
iptables -A INPUT -p icmp - icmp-type 8 -j DROP          #禁止其它主机ping本机
iptables -A INPUT -p icmp --icmp-type 0 -j ACCEPT       #允许本机ping其它主机

iptables -A INPUT -p icmp --icmp-type 3 -j ACCEPT       #当本机ping不通其它主机时提示目标不可达
#此时其它主机需要配置关于icmp协议的控制类型为REJECT

iptables -A INPUT -p icmp -j REJECT

5.3 Display match

  • This matching method requires additional kernel modules to provide support. You must manually call the corresponding module in the form of "-m module name" before setting the matching conditions
  • Common display matching includes multi-port matching, IP range matching, MAC address matching, and status matching

5.3.1 Multi-port matching

  • Use when writing iptables rules:
“-m multiport --dports 端口列表”  
“-m multiport --sports 端口列表”  
  • The above two forms are used to check the source port and destination port of the data packet, and multiple ports are separated by commas
  • For example, if you want to allow the machine to open ports 80, 22, 21, 20, 53 to provide email services, you can do the following
iptables -A INPUT -p tcp -m multiport --dport 80,22,21,20,53 -j ACCEPT

5.3.2 IP range matching

  • Use the following form when writing iptables rules
-m iprang --src-rang IP范围
  • Used to check the source and destination addresses of data packets, where the IP range is expressed in the form of "start address-end address"
  • For example, if you want to prohibit forwarding udp packets whose source address is 192.168.80.100-192.168.80.200
iptables -A FORWARD -p udp -m iprange --src-range 192.168.80.100-192.168.80.200 -j DROP

5.3.3 MAC address matching

  • Use the following form when writing iptables rules
iptables -A FORWARD -m mac --mac-source xx:xx:xx:xx:xx:xx -j DROP(MAC地址)
#禁止来自某MAC地址的数据包通过本机转发
  • Used to check the source MAC address of the packet
  • Due to the limitations of the MAC address itself, such matching conditions are generally only applicable to internal networks

5.3.4 State matching

  • The following form when writing iptables rules
-m state --state 连接状态
  • Check the connection status of data packets based on the iptables state tracking mechanism
  • Common connection states are:
    • NEW: Not related to any connection, connection has not yet started
    • ESTABLISHED: In response to the request or the connection has been established, the connection state
    • RELATED: Relevant to existing connections (such as data connection in FTP active and passive mode), derived state, generally used in conjunction with ESTABLISHED
    • INVALID: Cannot be identified which connection belongs to or does not have any status
  • For example, if you want to prohibit forwarding non-syn request packets that are not related to normal TCP connections (such as forged network attack packets), you can do the following
iptables -A FORWARD -m state --state NEW -p tcp ! --syn -j DROP
  • For another example, if only the web service of this machine (port 80) is opened, but the TCP response packet sent to this machine is released, and other inbound data packets are discarded, the corresponding inbound control rules can refer to the following operations
iptables -I INPUT -p tcp -m multiport --dport 80 -j ACCEPT
iptables -I INPUT -p tcp -m state --state ESTABLISHD -j ACCEPT
iptables -P INPUT DROP

Three, summary

  • netfilter is a kernel mechanism for filtering firewall functions, and iptables is a user-mode tool for managing firewall rules
  • The iptables rule system by default includes four tables (filter, nat, mangle, raw) and five chains (INPUT, OUTPUT, FORWARD, PREROUTING, POSTROUTING)
  • The matching order of the table is raw → mangle → nat → filter
  • The matching sequence of the chain depends on the specific data flow, and follows the principle of "match and stop", except for the LOG operation
  • The matching condition types of iptables rules include general matching, implicit matching, and explicit matching. For explicit matching, the module must be loaded with "-m module name"

Guess you like

Origin blog.csdn.net/weixin_51486343/article/details/111873084