Preface
Firewall is just like the Great Wall of China. It is used to protect the people inside the wall from outside malicious invasion. So is the firewall of Linux. It can filter and restrict data packets, which is the package filtering firewall to be explained in this paper.
1. Packet Filtering Firewall
1. Understanding the packet filtering firewall
The firewall system of Linux mainly works in the network layer, which implements filtering and restriction for TCP/IP packets. It is a typical packet filtering firewall (or network layer firewall).
The firewall system of Linux system is based on the implementation of kernel encoding. It has very stable performance and high efficiency, so it is widely used.
netfilter: A system of packet filtering capabilities in the Linux kernel called the "kernel state" of the Linux firewall
Iptables: A tool located at/sbin/iptables that manages firewall rules, called the "user state" of the Linux firewall
Working Level of Package Filtering
Mainly network layer, for IP packets
Reflected in the processing of IP address, port and other information within the packet
2. Relationships
The relationship between netfilter and iptables:
netfilter: belongs to the firewall function system of "kernel state", also known as kernel space.
It is part of the kernel and consists of several packet filter tables that contain the set of rules used by the kernel to control packet filtering processing.
iptables: Firewall management system belonging to User Space.
Is a command program that manages the Linux firewall and makes it easy to insert, modify, and delete rules in packet filter tables, usually in the / sbin/iptables directory.
netfilter/iptables, later referred to as iptables, is a kernel-based firewall with raw, mangle, nat, and filter built in
3. Table and Chain Structure of iptables
3.1. Four-table and Five-chain structure
The purpose of iptables is to provide rules for the implementation of packet filtering mechanisms. Different rules tell netfilter s how to handle packets from certain sources, destined for certain purposes or with certain protocol characteristics, in order to organize and manage firewall rules more conveniently.
iptables use a hierarchical structure of tables and chains, so it analyzes the packet header data of the requested packet and matches them to determine whether access to the host is possible based on our predefined rules
Each rule table is equivalent to a container of kernel space, divided into four default tables according to the different uses of the rule set, different rule chains within each table container, and five chains based on the different timing of processing the data package.
3.2.Four rule tables
raw: Mainly used to determine whether to track the status of a data package contains two rule chains, OUTPUT and PREROUTING.
mangle: Modifies the contents of a packet to mark it for traffic shaping. Contains five rule chains: INPUT, OUTPUT, FORWARD, PREROUTING, POSTROUTING.
**nat:**Responsible for network address translation to modify source, destination IP addresses or ports in a packet. Contains three rule chains: OUTPUT, PREROUTING, POSTROUTING.
**filter:** is responsible for filtering the data package to determine whether it will be released (filtering). It contains three chains: OUTPUT, PREROUTING, POSTROUTING.
3.3.5 Rule Chains
INPUT: Processes inbound packets, matching packets whose destination IP is local.
OUTPUT: Processing outbound packets, generally not configured on this chain.
FORWARD: Processes forwarded packets, matching packets that flow through the machine.
PREROUTING Chain: Processing a packet before routing to modify the destination address for use as DNA T. Equivalent to mapping the IP and port of an internal network server to the IP and port of an external network of a router.
POSTROUTING Chain: Post-processing data packets for routing to modify source addresses for use as SNAT s. Equivalent to an intranet using router NAT conversion to enable an intranet host to access the Internet through a public network IP address.
4. Matching Process for Packet Filtering
4.1. Priority
Rule table application order: raw_mangle_nat_filter
4.2. Matching order between rule chains
Host firewall:
Inbound data (packets from outside, and target address is firewall native): PREROUTING --> INPUT --> native application
Outbound data (packets sent from firewall native to external address): native application ->OUTPUT-. >POSTROUTING
Network firewall:
Forward data (packets that need to be forwarded through the firewall): PREROUTING --> FORWARD --> POSTROUTING
4.3. Matching order within the rule chain
Check from top to bottom in order to find a matching rule that stops (LOG policy exception, meaning logging related logs) or releases or discards.
If no matching rule is found in the chain, the default policy for the chain is followed (in unmodified cases, the default policy is allowed)
Note: Processing matches in the order of the first rule... the second rule follows the principle of "Match stops". Once a match rule is found, subsequent rules will no longer be checked. If no match rule has been found, it will be processed according to the default rule.
Default rules are viewed with iptables-L, and policy ACCEPT is the default release.
The default policy does not participate in the ordering of rules in the chain, and the default policy is not affected when -F empties the chain
4.4. Packet matching process between rule tables and chains
Inbound data flow: When a packet from outside reaches the firewall, it is first processed by the PREROUTING chain (whether to modify the address of the packet, etc.) and then routed (to determine where the packet should go); if the destination address of the packet is the firewall native (such as the Web service port where Internet users access the gateway)The kernel passes it to the INPUT chain for processing (deciding whether to allow it to pass, etc.) and responds by later handing it over to applications at the top of the system, such as an httpd server.
Forwarding data flow direction: when a packet from outside reaches the firewall, it is processed by the PREROUTING chain before routing; if the destination address of the packet is another external address (such as a local area network user accessing the QQ server through a gateway), the kernel passes it to the FORWARD chain for processing (allowing forwarding or interception, discarding) and finally to the POSTROUTING chain.(whether to modify the address of the data package, etc.) for processing.
Outbound data flow direction: Packets sent by the firewall itself to external addresses (for example, when testing public network DNS services in the firewall host), are routed first, the output path is determined, then processed through the OUTPUT chain, and finally handed over to the POSTROUTING chain (whether to modify the address of the packet, etc.). Inbound PREROUTING INPUT application OUTPUT POSTROUTING.
2. Write Firewall Rules
1.iptabes installation
CentOS7 uses firewalld firewall by default, iptables are not installed, if you want to use iptables firewall. You must close firewalld firewall before installing iptables
Close firewalld firewall systemctl stop firewalld.service systemctl disable firewalld.service install iptables firewall yum -y install iptables iptables-services Set up iptables Start Up systemctl start iptables.service systemctl enable iptables.service
2.iptables basic syntax, packet control type
Grammatical Composition
iptables [-t Table Name] Management Options [Chain name] [Matching conditions] [-j control type] Table name, chain name to specify iptables Tables and chains that the command operates on, which are used by default when no table name is specified filter surface Management Options:Express iptables How rules operate, such as insert, add, delete, view, and so on Matching conditions:The characteristics used to specify the packets to be processed. Packets that do not meet the specified criteria will not be processed control type:Processing of packets, such as allow, reject, discard, etc.
Matters needing attention:
When no table name is specified, the default is the filter table
Default refers to all chains in a table when no chain name is specified
Matching criteria must be specified unless the default policy for the chain is set
Options, chain names, control types use uppercase letters, the rest are lowercase
3. Common control types for packets
For firewalls, the control type of data package is very important, which directly affects the release, blocking and logging of data package. In the iptables firewall system, the most commonly used control types are as follows.
ACCEPT: Allow packets to pass through. DROP: Directly discard the packet without giving any response information. REJECT: Rejects the packet from passing and, if necessary, gives the data sender a response message. LOG: stay/var/log/messages Log information is recorded in the file and the data package is passed to the next rule. SNAT:Modify the source address of the package. DNAT:Modify the destination address of the packet. MASQUERADE:Disguise as an unfixed public network IP Address.
"Match Stop" for firewall rules is a special case for LOG operations because LOG is an auxiliary action and does not actually process packets.
Note: Capitalization is required
4. Add, view, delete rules
4.1. Common management options for the iptables command
Management Options | Example usage |
---|---|
-A | Append an iptables-A INPUT to the end of the specified chain |
-I | Insert a new, unspecified ordinal into the specified chain as the first iptables-I INPUT by default |
-P | Specify the default rule iptables-P OUTPUT ACCEPT |
-D | Delete iptables-t nat-D INPUT |
-R | Modify or replace a rule iptables-t nat-R INPUT |
-L | View iptables-t nat-L |
-n | All fields are displayed numerically (e.g. any ip address is 0.0.0.0 instead of anywhere, e.g. protocol port number instead of service name) iptables-L-n, iptables-nL, iptables-vnL |
-v | Show more details when viewing, often with -L |
–line-number | Rule with number iptables-t nat-L-n --line-number/iptables-t nat-L --line-number |
-F | Clear all rules iptables-F in the chain |
-X | Empty rules for custom chains without affecting other chains iptables-X |
-Z | Counters for emptying chains (size and sum of matched packets) iptables-Z |
-S | View all rules of a chain or rules of a chain/a specific rule followed by a number |
4.2. Add new rules
When adding a new firewall rule, use the management options'-A','-I', which append the rule and insert the rule.
If you want to add a firewall rule at the end of the INPUT chain of the filter table, you can do the following (where "-p protocol name" is the matching condition).
[root@localhost ~]# iptables -t filter -A INPUT -p icmp -j REJECT #No host is allowed to ping this host [root@localhost ~]# iptables -I INPUT 2 -p tcp --dport 22 -j ACCEPT #Allow host ssh port [root@localhost ~]# iptables -t filter -A INPUT -p tcp -j ACCEPT #Allow any host tcp [root@localhost ~]# iptables -I INPUT -p udp -j ACCEPT #Allow any host udp
4.3. View Rule List
When viewing existing firewall rules, use the management option'-L', combined with the'-line-numbers'option, to display the sequence number of each rule in the chain.
If you want to view all the rules in the INPUT chain of the filter table and display the rule ordinal, you can do the following
iptables [-t Table Name] -n -L [Chain name] [-- line-numbers]or iptables -[vn]L or iptables - [vn]L #Note: Can't be combined as -Ln [root@localhost ~]# iptables -L INPUT --line-numbers #View all rules in the INPUT chain of the filter table and display the rule ordinal Chain INPUT (policy ACCEPT) num target prot opt source destination 1 ACCEPT udp -- anywhere anywhere udp dpt:domain 2 ACCEPT tcp -- anywhere anywhere tcp dpt:domain 3 ACCEPT udp -- anywhere anywhere udp dpt:bootps 4 ACCEPT tcp -- anywhere anywhere tcp dpt:bootps 5 ACCEPT all -- anywhere anywhere ctstate RELATED,ESTABLISHE D6 ACCEPT all -- anywhere anywhere 7 INPUT_direct all -- anywhere anywhere 8 INPUT_ZONES_SOURCE all -- anywhere anywhere 9 INPUT_ZONES all -- anywhere anywhere 10 DROP all -- anywhere anywhere ctstate INVALID 11 REJECT all -- anywhere anywhere reject-with icmp-host-proh ibited
When the number of firewall rules is large, if the address and port information can be displayed digitally, it can reduce the link of address resolution and speed up the execution of commands to a certain extent.
If you want to view all the rules in the INPUT chain of the filter table as digital addresses, you can do the following
[root@localhost ~]# iptables -nL INPUT #"-n-L" can be written as "-nL" Chain INPUT (policy ACCEPT) target prot opt source destination ACCEPT udp -- 0.0.0.0/0 0.0.0.0/0 udp dpt:53 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:53 ACCEPT udp -- 0.0.0.0/0 0.0.0.0/0 udp dpt:67 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 tcp dpt:67 ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 ctstate RELATED,ESTABLISHED ACCEPT all -- 0.0.0.0/0 0.0.0.0/0 INPUT_direct all -- 0.0.0.0/0 0.0.0.0/0 INPUT_ZONES_SOURCE all -- 0.0.0.0/0 0.0.0.0/0 INPUT_ZONES all -- 0.0.0.0/0 0.0.0.0/0 DROP all -- 0.0.0.0/0 0.0.0.0/0 ctstate INVALID REJECT all -- 0.0.0.0/0 0.0.0.0/0 reject-with icmp-host-prohibite d
4.4. Delete, Empty Rules
When deleting a firewall rule, use the management option'-D'. For example, to delete Rule 10 in the INPUT chain of the filter table, you can do the following
Empty all firewall rules in the specified chain or table using the management option'-F'
For example, to empty all the rules in the INPUT chain of the filter table, you can do the following
[root@localhost ~]# iptables -F INPUT [root@localhost ~]# iptables -nL INPUT Chain INPUT (policy ACCEPT) target prot opt source destination Be careful: If there are multiple identical rules in the rule list, match by content only the one with the smallest deleted ordinal When deleting by number matching, make sure that the rule number is less than or equal to the number of existing rules, otherwise an error occurs When matching deletions by content, make sure the rule exists, otherwise an error will be reported
When using the management option'-F', rules that allow all chains of a specified table to be emptied by omitting the chain name are allowed.
For example, do the following to empty the filter, nat, and mangle tables
[root@localhost ~]# iptables -F [root@localhost ~]# iptables -t nat -F [root@localhost ~]# iptables -t mangle -F Be careful: -F Simply emptying the rules in the chain does not affect-P Default rule set, which needs to be modified manually -P Set DROP After that, use-F Be careful not to remove the rules that allow remote connections from the host. If there are no save rules, the host can be restarted for resolution. If table and chain names are not written, the default is cleared filter All rules in all chains in a table
4.5. Set default policy
Among the chains of iptables, the default policy is the last step in rule matching -- when no rule can be found that matches a packet, the default policy is executed.
The control types of the default policy are ACCEPT (Allowed) and DROP (Discarded).
For example, performing the following actions can set the default policy for FORWARD chains in the filter table to discard and the default policy for OUTPUT chains to allow.
iptables [-t Table Name] -P <Chain name> <control type> [root@localhost ~]# iptables -P INPUT DROP #Not shown after input, clearing all rules will take effect because only DROP is left below, adding remote port 22 [root@localhost ~]# iptables -P FORWARD DROP #In general, when setting up network firewall and host firewall in production environment, the default rule is DROP and the whitelist is set. [root@localhost ~]# iptables -t filter -P FORWARD DROP [root@localhost ~]# iptables -P OUTPUT ACCEPT It is important to note that when using the management option "-F"When emptying the chain, the default policy is unaffected. Therefore, to modify the default policy, you must pass the administrative option "-P"Set it up again. In addition, the default policy does not participate in the ordering of rules in the chain, so there is no difference in setting it before or after other rules.
5. Matching conditions of rules
When writing firewall rules, the setting of matching criteria plays a decisive role. Only when matching criteria are clearly and accurately set, the firewall knows what packets meet the criteria to process and avoid "killing by mistake".
For the same firewall rule, multiple matching criteria can be specified, indicating that these criteria must all satisfy the rule to take effect.
According to the various characteristics of the data package, combined with the module structure of iptables, the settings of matching conditions include three categories: universal matching, implicit matching, and explicit matching.
5.1. Universal Matching
Universal matching, also known as regular matching, can be used independently of other conditions or extensions.
Common common matches include protocol matching, address matching, and network interface matching.
Protocol Matching: -p Protocol Name Address Matching: -S Source address,-d Destination Address #Can be IP, segment, domain name, empty (any address) Interface Matching: -i Inbound network card,-o Outbound Network Card
For example, to discard packets that access the firewall locally through the icmp Protocol and allow forwarding of packets that pass through the firewall other than the icmp protocol, you can do the following.
[root@localhost ~]# iptables -A FORWARD ! -p icmp -j ACCEPT [root@localhost ~]# iptables -A INPUT -s 192.168.9.128 -j DROP [root@localhost ~]# iptables -I INPUT -i ens33 -s 192.168.9.0/24 -j DROP [root@localhost ~]# iptables -I INPUT -p icmp -j DROP [root@localhost ~]# iptables -A FORWARD ! -p icmp -j ACCEPT #Exclamation mark"!" is the opposite
5.2. Implicit Matching
Specific protocol matching is required, including port, TCP tag, ICMP type, etc.
Port Matching: --sport Source Port,--dport Destination Port #Can be individual ports, port ranges --sport 1000 Packets with matching source port 1000 --sport 1000:3000 Match Source Port is 1000-3000 Packets --sport :3000 Match Source Port is 3000 and below packets --sport 1000: Packets with matching source port 1000 or more Be careful: --sport and--dport Must work together-p <Protocol Type>Use [root@localhost ~]# iptables -A INPUT -p tcp --sport 1000:3000 -j REJECT [root@localhost ~]# iptables -A INPUT -p tcp --dport 20:21 -j ACCEPT [root@localhost ~]# iptables -I FORWARD -d 192.168.32.0/24 -P tcp --dport 24500:24600 -j DROP [root@localhost ~]# iptables -A FORWARD -s 192.168.32.0/24 -p udp --dport 53 -j ACCEPT [root@localhost ~]# iptables -A FORWARD -d 192.168.32.0/24 -p udp --sport 53 -j ACCEPT [root@localhost ~]# iptables -A INPUT -s 192.168.32.0/24 -p tcp --dport 53 -j ACCEPT
TCP tag matching: --tcp-flags TCP tag
[root@localhost ~]# iptables -I INPUT -i ens33 -p tcp --tcp-flags SYN,RST,ACK SYN -j ACCEPT #Drop SYN request packages and release other packages
ICMP type matching: --icmp-type ICMP type
Can be string, numeric code "Echo- Request" (Code 8)Indicate Request "Echo- Reply" (Code 0)Represent Echo "Dest ination-Unreachable" (Code 3)Indicates the target is unreachable About other available ICMP The type of agreement that can be executed iptables -p icmp -h"Command to view help information.
[root@localhost ~]# iptables -A INPUT -p icmp --icmp-type 8 -j DROP #Prohibit other hosts from ping ing local machine [root@localhost ~]# iptables -A INPUT -P icmp --icmp-type 0 -j ACCEPT #Allow local ping s to other hosts [root@localhost ~]# iptables -A INPUT -p icmp -j DROP #Allow local ping s to other hosts
[root@localhost ~]# iptables -A INPUT -p icmp --icmp-type 3 -j ACCEPT #Indicate target unreachable when local ping is not connected to other hosts [root@localhost ~]# iptables -A INPUT -p icmp -j REJECT #At this point other hosts need to configure REJECT as the control type for icmp Protocol
5.3. Explicit Matching
Requires that the type be explicitly specified in the form of an'-m extension', including conditions such as multiport, MAC address, IP range, packet status, and so on.
Multiport Matching: -m multiport --sport Source Port List -m multiport --dport Destination Port List
[root@localhost ~]#iptables -A INPUT -p tcp -m multiport --dport 80,22,21,20,53 -j ACCEPT #Allow local machine to open ports 80, 22, 21, 20, 53 [root@localhost ~]# iptables -A INPUT -P udp -m multiport --dport 53 -j ACCEPT #Allow native machine to open port 53
IP Range Matching -m iprang --src-rang IP Range [root@localhost ~]# iptables -A FORWARD -p udp -m iprange --src-range 192.168.80.100-192.168.80.200 -j DROP #Forwarding udp packets whose source address is 192.168.80.100-192.168.80.200 is prohibited
MAC Address Matching: -m mac --mac-source MAC address [root@localhost ~]# iptables -A FORWARD -m mac --mac-source xx:xx:xx:xx:xx:xx -j DROP #Prevent packets from a MAC address from forwarding locally
State Matching: -m state --state Common connection states: NEW :Not connected yet ESTABLISHED :In response to a request or if a connection has been established, the connection state RELATED :Relevant to an existing connection(as FTP Active-passive mode data connection),Derived ecology, generally with ESTABLISHED Cooperative use INVALID:Unable to identify which connection or no state to belong to [root@localhost ~]# iptables -A FORWARD -m state --state NEW -p tcp ! --syn -j DROP #Forwarding of non-syn request packets (such as forged network attack packets) that are unrelated to normal TCP connections is prohibited [root@localhost ~]# iptables -I INPUT -p tcp -m multiport --dport 80,22,21,20,53 -j ACCEPT [root@localhost ~]# iptables -A INPUT -p udp -m multiport --dport 53 -j ACCEPT [root@localhost ~]# iptables -A INPUT -p tcp -m state --state ESTABLISHED, RELATED -j ACCEPT #Check the status of incoming packages. Packages that have established a tcp connection and packages associated with that connection are allowed to pass through.
summary
There are two main types of Linux packet filtering firewalls
netfilter: A system of packet filtering capabilities in the Linux kernel called the "kernel state" of the Linux firewall
Iptables: A tool located at/sbin/iptables that manages firewall rules, called the "user state" of the Linux firewall
The four rule tables for iptables are raw, mangle, nat, filter, and so on.
Five rule chains: INPUT (processing inbound packets), OUTPUT (processing outbound packets), FORWARD (processing forwarded packets), PREROUTING (processing packets before routing), POSTROUTING (postprocessing packets after routing)
Rule table application order: raw_mangle_nat_filter