1. Overview#
This article introduces knowledge about firewalls, including their functions, classifications, performance, iptables, and firewalld. The focus is on iptables and firewalld. Due to the length of this article, reading will take some time.
2. Firewall#
2.1 Functions of Firewalls#
In the field of computers, a firewall is a device used to protect information security.
Firewalls allow or restrict data transmission based on default configurations or user-defined rules.
- A device used to protect internal network security
- Provides protection based on rules
- User-defined rules
- Allows or restricts external access
2.2 Classifications of Firewalls#
Logically:
- Host Firewall: Protects a single host (serves individuals)
- Network Firewall: Protects a network, located at the network edge, behind which is the local area network (serves groups)
Physically:
- Hardware Firewall: Implements firewall functions at the hardware level, with another part based on software, high performance, and high cost. For example: Cisco, Huawei, Tianrongxin
- Software Firewall: A firewall that processes logic on a general hardware platform, with lower performance compared to hardware firewalls, lower cost, and is built into Linux systems for direct use. For example: WAF (mainly used to intercept all HTTP data or sessions that meet certain rules, commonly seen in cloud platforms)
2.3 Performance of Firewalls#
- Throughput
- Concurrent connections
- New connections
- Latency
- Jitter
3. iptables#
3.1 What is iptables#
Netfilter/iptables can be abbreviated as iptables, which is a packet filtering firewall for the Linux platform, open-source, built into the kernel, and can replace costly enterprise-level hardware firewalls.
Packet filtering means firewall.
Packet redirection means forwarding.
Network address translation means NAT.
- iptables is not a firewall; it is a firewall user agent.
- Used to add user security settings to the "security framework."
- The "security framework" is the firewall.
- Netfilter is the "security framework."
- Netfilter is located in kernel space, a packet processing module within the core layer of the Linux system.
- iptables is a command-line tool used to operate on netfilter in kernel space from user space.
Note: iptables is not a firewall service; the real service is provided by the kernel, and netfilter is the real firewall.
3.2 Working Principle of iptables#
iptables operates according to rules, which are conditions defined by the operations personnel.
Rules are generally defined as "if the packet header meets such conditions, then process this packet accordingly."
Rules are stored in the packet filtering table in kernel space.
These rules specify the source address, destination address, transport protocol (TCP, UDP, ICMP), and service type (HTTP, FTP), etc.
When a packet matches a rule, iptables processes the packet according to the method defined by the rule, such as allowing (ACCEPT), rejecting (REJECT), dropping (DROP), etc.
Note: The main work of configuring a firewall is to add, modify, delete iptables rules, etc.
3.3 Concept of Chains in iptables#
Netfilter is the real firewall, part of the kernel. To make netfilter effective, we need to set "gates" in the kernel, through which incoming and outgoing packets must pass. After inspection, packets that meet the release conditions are allowed, while those that meet the blocking conditions are stopped. Thus, input and output gates appear, which we call chains in iptables.
According to the above diagram, if the server address requested in the packet sent by the user is not the local machine but another server, the packet should be forwarded. This forwarding is supported by the kernel's IP_FORWARD function. At this time, our host functions similarly to a router, corresponding to "PREROUTING," "FORWARD," and "POSTROUTING." This is the 5 chains.
- INPUT: Processes incoming packets.
- OUTPUT: Processes outgoing packets.
- FORWARD: Processes forwarded packets (mainly forwards packets to other network interfaces on the local machine). When a data packet passes through the local machine, the network interface receives the data packet into the buffer, and the kernel reads the packet's IP header. If the packet is not destined for the local machine (the destination IP is not the local machine), it is directly sent to the forward chain for matching. If it matches the forward rules, it is then sent via postrouting to the next hop or destination host.
- PREROUTING: Processes packets before routing decisions are made, modifying the destination IP address of packets arriving at the firewall to determine the target host.
- POSTROUTING: Processes packets after routing decisions are made, modifying the source IP address of packets leaving the firewall to determine which interface to send to the next hop.
We know that the function of a firewall is to match the rules against the packets that pass through, and then execute the corresponding "action." Therefore, when packets pass through these gates, they must match the gate rules. However, there may be multiple rules at a gate, and there can be many. When we put numerous rules at one gate, all packets passing through must match, thus forming a chain of rules to be matched, which we also call a "rule chain."
3.4 Concept of Tables in iptables#
Each "rule chain" has a series of rules set on it, allowing us to combine different "rule chains" into a collection that can accomplish a specific function, which we call a table. There are a total of 5 tables in iptables.
- filter: Filtering function, determines whether to allow the packet, belongs to the real firewall, kernel module: iptables_filter.
- nat: Network address translation function, modifies the source, destination IP addresses, or ports in packets; kernel module: iptable_nat.
- mangle: Repackaging function for packets, sets marks for packets; kernel module: iptable_mangle.
- raw: Determines whether to track packets; kernel module: iptables_raw.
- security: Defines mandatory access control rules; added later.
3.5 Relationship of Chains in iptables#
When applying a firewall, we operate based on tables. As long as we add rules to the rule chains in the corresponding table, we can achieve a specific function.
Thus, we should know which tables include which rule chains, and then operate on the rule chains.
- The filter table can use the following chains to define rules: INPUT, FORWARD, OUTPUT.
- The nat table can use the following chains to define rules: PREROUTING, OUTPUT, POSTROUTING, INPUT.
- The mangle table can use the following chains to define rules: PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING.
- The raw table can use the following chains to define rules: PREROUTING, OUTPUT.
Note: The priority of tables in iptables is: raw->mangle->nat->filter (from high to low).
3.6 Flow of Packets Through iptables#
3.7 Conditions for Matching iptables Rules#
3.71 Basic Matching Conditions#
Source address, destination address, source port, destination port, etc.
Basic matching uses options and functions.
-p Specify the protocol for the rule, tcp udp icmp all
-s Specify the source address of the packet, ip hostname
-d Specify the destination address
-i Input interface
-o Output interface
! Negation
The characteristic of basic matching is: no need to load extension modules, matching rules take effect.
3.72 Extended Matching Conditions#
Extended matching is further divided into implicit matching and explicit matching.
The characteristic of extended matching is: it requires loading extension modules for matching rules to take effect.
The characteristic of implicit matching: when using the -p option to specify the protocol, there is no need to simultaneously use the -m option to specify the extension module, nor is there a need to manually load the extension module;
The characteristic of explicit matching: it must use the -m option to specify the extension mechanism of the extension module to be called and requires manual loading of the extension module.
Implicit matching options and functions:
-p Match protocol, e.g., tcp, udp
--sport Match the source port of the packet, can specify multiple ports, but only continuous port ranges
--dport Match the destination port of the packet, can specify multiple ports, but only continuous port ranges
--tcp-flags mask comp Match the flag bits of the tcp protocol in the packet
--icmp-type
0/0: echo reply allows other hosts to ping
8/0: echo request allows pinging other hosts
Explicit matching options and functions: (-m)
- multiport: Multiple ports
iptables -I INPUT -d 192.168.1.111 -p tcp -m multiport --dports 22,80 -j ACCEPT
// Open local tcp 22, tcp 80 ports in the INPUT chain
iptables -I OUTPUT -s 192.168.1.111 -p tcp -m multiport --sports 22,80 -j ACCEPT
// Open source ports tcp 22, tcp 80 in the OUTPUT chain
- iprange: Multiple IP addresses
iptables -A INPUT -d 192.168.1.111 -p tcp --dport 23 -m iprange --src-range 192.168.2.11-192.168.2.21 -j ACCEPT
// Open multiple source IP addresses in the INPUT chain
iptables -A OUTPUT -s 192.168.1.111 -p tcp --sport 23 -m iprange --dst-range 192.168.2.11-192.168.2.21 -j ACCEPT
// Open multiple destination IP addresses in the OUTPUT chain
- time: Specify the access time range
iptables -A INPUT -d 192.168.1.111 -p tcp --dport 901 -m time --weekdays Mon,Tus,Wed,Thu,Fri --timestart 08:00:00 --time-stop 18:00:00 -j ACCEPT
iptables -A OUTPUT -s 192.168.1.111 -p tcp --sport 901 -j ACCEPT
- string: String, performs string pattern matching detection on application layer data in packets (implemented through algorithms).
--algo {bm|kmp}: Algorithm used for character matching search
--string "STRING": The string to search for
--hex-string “HEX-STRING”: The character to search for, first encoded in hexadecimal format
- connlimit: Connection limit, limits the number of concurrent connections based on each client IP.
--connlimit-upto n Matches when the number of connections is less than or equal to n
--connlimit-above n Matches when the number of connections is greater than n
- limit: Packet rate limit.
- state:
- Tracks the state of data packets between requests and responses on the local machine. There are five states: INVALID, ESTABLISHED, NEW, RELATED, UNTRACKED.
--state state
NEW New connection request
ESTABLISHED Established connection
INVALID Unrecognized connection
RELATED Related connection, the current connection is a new request but belongs to an existing connection
UNTRACKED Untracked connection
3.8 Actions in iptables Rules#
Actions in iptables rules are commonly referred to as targets, divided into basic actions and extended actions.
- ACCEPT: Allows packets to pass through.
- DROP: Directly drops packets without any response information.
- REJECT: Rejects packets from passing through, sending response information to the client.
- SNAT: Source address translation.
- Explanation 1: When the packet is sent out from the network interface, the source address part of the packet is replaced with a specified IP, making the receiving party believe that the packet's source is the replaced IP host, and when responding, it also uses the replaced IP address.
- Explanation 2: Modifies the source address of the packet. When an internal network packet reaches the firewall, the firewall replaces the packet's source IP address with an external address (the destination IP address remains unchanged), allowing internal hosts to communicate with external hosts.
- MASQUERADE: Masquerading, similar to SNAT, suitable for dynamic, temporarily changing IP addresses, such as home broadband. Uses the IP of the network interface sending the data to replace the source IP, used in cases where the IP address is not fixed.
- DNAT: Destination address translation.
- Explanation 1: When the packet is sent out from the network interface, the destination IP in the packet is modified, appearing as if you want to access A, but due to DNAT by the gateway, all packets accessing A have their destination IP addresses modified to B, and the actual final access is B.
- Explanation 2: Changes the destination address of the packet. When the firewall receives packets from the external network, it replaces the destination IP address of the packet (the source IP address remains unchanged) and forwards it to the internal host.
- REDIRECT: Performs port mapping on the local machine.
- LOG: Records log information in the /var/log/message file, then passes the packet to the next rule.
Note: Routing is based on the destination address for routing decisions, so DNAT is performed on the PREROUTING chain, while SNAT is performed when the packet is sent out, thus on the POSTROUTING chain.
3.9 Strategies/Thoughts on iptables Rules#
-
Blacklist
All traffic not explicitly denied can pass through. Under this strategy, administrators must formulate new rules for each new attack that appears, so it is not recommended.
-
Whitelist
All traffic not explicitly allowed must be denied. This strategy is more conservative, gradually opening up hosts as needed. Currently, the whitelist strategy is generally adopted and recommended.
- Choose a table, which determines the processing method of the data packets.
- Choose a chain, which determines the path the data packets will flow through.
- Choose appropriate conditions, which determine the type of condition matching for the data packets.
- Choose actions for processing data packets, formulating corresponding firewall rules.
3.10 Basic Syntax Structure of iptables#
iptables [-t table_name] management_options [chain_name] [condition_matching] [-j target_action or jump]
If no table name is specified, it defaults to the filter table. If no chain name is specified, it defaults to all chains in that table. Unless the default policy for the rule chain is set, matching conditions need to be specified.
3.11 Common Commands for iptables#
Parameter | Function |
---|---|
-P | Set default policy: iptables -P INPUT (DROP |
-F | Flush rule chain |
-L | View rule chain |
-A | Add new rule to the end of the rule chain |
-I num | Insert new rule at the head of the rule chain |
-D num | Delete a specific rule |
-s | Match source address IP/MASK, "!" indicates except this IP. |
-d | Match destination address |
-i interface_name | Match data flowing in from this network interface |
-o interface_name | Match data flowing out from this network interface |
-p | Match protocol, such as tcp, udp, icmp |
--dport num | Match destination port number |
--sport num | Match source port number |
3.11.1 Chain Management in iptables#
-N, --new-chain chain: Create a new custom rule chain
-X, --delete-chain [chain]: Delete a user-defined empty chain with a reference count of 0
-F, --flush [chain]: Flush rules on the specified rule chain
-E, --rename-chain old-chain new-chain: Rename chain;
-Z, --zero [chain [rulenum]]: Zero the counter; note: each rule has two counters (packets: the number of packets matched by this rule, bytes: the total size of packets matched by this rule)
-P, --policy chain target Set the policy for the chain (ACCEPT|DROP|REJECT)
3.11.2 Rule Management in iptables#
-A, --append chain rule-specification: Append new rule to the end of the specified chain
-I, --insert chain [rulenum] rule-specification: Insert new rule at the specified position in the specified chain, default is at the head
-R, --replace chain rulenum rule-specification: Replace the specified rule with a new rule
-D, --delete chain rulenum: Delete rule based on rule number
-D, --delete chain rule-specification: Delete rule based on the rule itself
3.11.3 Displaying Rules in iptables#
-L, --list [chain]: List rules
-v, --verbose: Detailed information
-vv More detailed information
-n, --numeric: Display host addresses and port numbers in numeric format
-x, --exact: Display the exact value of counters, not rounded data
--line-numbers: When listing rules, display their corresponding numbers in the chain
-S, --list-rules [chain]: Display all rules in the specified chain
3.12 Example Applications of iptables#
Installation/Configuration of iptables-services:
sudo apt-get install iptables* // Install
sudo systemctl start iptables.service // Start
sudo systemctl enable iptables.service // Set to start on boot
sudo rpm -ql iptables-services // View configuration files
iptables-save > /etc/sysconfig/iptables // Save rules
iptables-restore < /etc/sysconfig/iptables // Reload
Basic Configuration:
iptables -F
// Delete existing rules
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP
// Configure default chain policy
Whitelist Configuration:
iptables -t filter -F
iptables -P INPUT DROP
iptables -t filter -I INPUT -p tcp --dport=22 -j ACCEPT
iptables -t filter -I INPUT -p tcp --dport=80 -j ACCEPT
Blacklist Configuration:
iptables -P INPUT ACCEPT
iptables -F
iptables -t filter -A INPUT -s 192.168.2.20/24 -p tcp --dport 80 -j DROP
Accessing local data through lo:
iptables -I INPUT -d 127.0.0.1 -p tcp --dport=9000 -i lo -j ACCEPT
iptables -I INPUT -i lo -j ACCEPT
// Allow access to the local machine through the local loopback interface
Allowing connection states to generate derivatives:
iptables -I INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
3.12.1 Application Case of the filter Table#
yum -y install httpd vsftpd sshd
systemctl start httpd vsftpd sshd
iptables -t filter -F
iptables -I INPUT -p tcp --dport 80 -j ACCEPT
iptables -I INPUT -p tcp --dport 20:21 -j ACCEPT
iptables -I INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -j REJECT
Standard Process of iptables:
iptables -F
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -s 192.168.2.0/24 -j ACCEPT # Allow any access from the internal network
iptables -A INPUT -p tcp --syn --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --syn --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --syn --dport 21 -j ACCEPT
iptables -A INPUT -j REJECT
modprobe nf_conntrack_ftp
iptables-save > /etc/sysconfig/iptables
vim /etc/sysconfig/iptables-config
// IPTABLES_MODULES="nf_conntrack_ftp
4. firewalld#
4.1 What is firewalld#
Firewalld merely replaces the iptables service part; its underlying mechanism still uses iptables as the firewall rule management entry.
- Dynamic firewall
- A tool for managing netfilter user space
- Calls iptables commands
4.2 Concept and Function of Zones#
A zone is a pre-prepared collection of firewall policies in firewalld, i.e., policy templates, which can be switched according to different application scenarios.
4.3 Classification of Zones in FireWalld#
The differences between different zones in FireWalld mainly lie in the default behavior of each zone towards data packets.
Firewalld has a total of 9 default zones, which are:
- block (deny)
- dmz (demilitarized)
- drop (discard)
- external (external)
- home (home)
- internal (internal)
- public (public) Firewalld's default zone
- trusted (trusted)
- work (workplace)
4.4 Firewalld Syntax#
firewall-cmd [--zone=zone] action [--permanent]
Note: If the --zone option is not specified, it will be the current default zone. The --permanent option indicates whether to write the changes to the zone configuration file.
4.5 Common Commands for Firewalld#
Parameter | Function |
---|---|
--get-default-zone | Query the name of the default zone |
--set-default-zone=<zone_name> | Set the default zone, effective permanently |
--get-zones | Display available zones |
--get-services | Display predefined services |
--get-active-zones | Display currently used zones and network interface names |
--add-source= | Direct traffic from this IP or subnet to the specified zone |
--remove-source= | No longer direct traffic from this IP or subnet to a specified zone |
--add-interface=<interface_name> | Direct all traffic from this interface to a specified zone |
--change-interface=<interface_name> | Associate a specific interface with a zone |
--list-all | Display the current zone's network configuration parameters, resources, ports, and services |
--list-all-zones | Display all zones' network configuration parameters, resources, ports, and services |
--add-service=<service_name> | Allow traffic for this service in the default zone |
--add-port=<port_number/protocol> | Allow traffic for this port in the default zone |
--remove-service=<service_name> | No longer allow traffic for this service in the default zone |
--remove-port=<port_number/protocol> | No longer allow traffic for this port in the default zone |
--reload | Immediately apply "permanent" configuration rules, overriding current ones. |
4.6 Status of Firewall#
firewall-cmd --state
running
// Check status
firewall-cmd --reload
success
// Reload the firewall, interrupt user connections, clear temporary configurations, load permanent configurations from the configuration file
firewall-cmd --complete-reload
success
// Reload the firewall without interrupting user connections (used when the firewall has serious faults)
firewall-cmd --panic-on
// Emergency mode, forcibly close all network connections
4.7 Actions in FireWalld#
4.7.1 Viewing Operations in Actions#
firewall-cmd xxx
--get-icmptypes // View all supported ICMP types
--get-zones // View all zones
--get-default-zone // View the current default zone
--get-active-zones // View currently used zones
--get-services // View services supported by the current zone
--list-services // View the list of services opened in the current zone
--list-services --zone=home // View the list of services opened in the specified zone
--list-all // View all configurations in the default zone, similar to iptables -L -n
--list-all-zones // View all configurations in all zones
4.7.2 Changing Zone Operations#
firewall-cmd xxx
--set-default-zone=work // Change the default zone
4.7.3 Creating New Rules#
firewall-cmd xxx
--add-interface=eth0 // Add the network interface to the default zone
--add-port=12222/tcp --permanent // Add the port to the open list of the zone
--add-port=5000-10000/tcp --permanent // Add a range of ports to the open list
--add-service=ftp --permanent // Add the service to the open list of the zone (note that the service name must match the name in the zone's supported services list)
--add-source=192.168.1.1 // Add traffic from the source address to the specified zone
--add-masquerade // Enable SNAT (source address translation)
4.7.4 Deleting Rules#
firewall-cmd xxx
--remove-service=http // Remove the http service from the open list in the home zone
--remove-interface=eth0 // Remove the network interface from the default zone
--remove-source=192.168.1.1 // Remove traffic from the source address to the specified zone
4.7.5 Changing Rules#
firewall-cmd xxx
--change-interface=eth1 // Change the specified interface to another zone
4.7.6 Querying Rules#
firewall-cmd xxx
--query-masquerade // Query the status of SNAT
--query-interface=eth0 // Determine whether this network interface exists in this zone
4.7.7 Port Forwarding#
Port forwarding can redirect traffic from a specified address accessing a specified port to a specified address and port. If the destination is not specified, it defaults to the local machine; if an IP is specified but no port is specified, it defaults to the source port.
// Implement SNAT through firewalld
firewall-cmd --add-masquerade --permanent
firewall-cmd --reload
// Forward traffic from port 80 to 8080
firewall-cmd --add-forward-port=port=80:proto=tcp:toport=8080
// Forward traffic from port 80 to
firewall-cmd --add-forward-port=port=80:proto=tcp:toaddr=192.168.2.20
// Delete
firewall-cmd --remove-forwardport=port=80:proto=tcp:toaddr=192.168.2.20 --permanent
// Forward traffic from port 80 to port 8080 of 192.168.2.20
firewall-cmd --add-forward-port=port=80:proto=tcp:toaddr=192.168.2.20:toport=8080
5. Comparison of iptables and firewalld#
- firewalld is a front-end controller for iptables.
- iptables is a static firewall; any policy change requires reloading all policies, losing existing connections.
- firewalld is a dynamic firewall; any policy change does not require reloading all policies, saving the changed parts to iptables without losing existing connections.
- firewalld provides a daemon and service, using iptables underneath.
- firewalld is much more user-friendly than iptables; even without understanding "five tables and five chains" or TCP/IP protocols, most functions can still be implemented.
- firewalld uses zones and services rather than chain rules.
- firewalld defaults to deny, requiring settings to allow traffic.
- iptables defaults to allow, requiring explicit denial to restrict.
6. Conclusion#
This article records some content about firewalls, including the concept of firewalls, iptables, and firewalld, with a focus on iptables and firewalld. There are many commands, and it is not necessary to memorize all of them.