1.1 Principles of Security Optimization Configuration in Enterprises
Whenever possible, avoid assigning public internet IPs to servers. Instead, use proxy forwarding or firewall mapping. If external IP access is involved and concurrent access isn’t particularly high, activate iptables firewall services.
In situations of high concurrency, do not enable iptables due to potential performance impacts. Instead, leverage hardware firewalls to enhance architectural security.
1.1.1 Real-World Application of iptables in Production
Main Application Areas
1. Host Firewall (INPUT chain in the filter table).
2. Shared internet access in a local area network (POSTROUTING chain in the nat table). A semi-router, NAT functionality.
3. Port and IP mapping (PREROUTING chain in the nat table), the NAT functionality of hardware firewalls.
4. One-to-one IP mapping.
Additional Notes:
①iptables is a kernel-based firewall, extraordinarily powerful, and operates by filtering data packets. Significantly, it can run extremely well on very low hardware configurations.
Note: iptables primarily works at layers 2, 3, and 4 of the OSI model. Layer 7 control can be achieved using squid proxy + iptables.
②iptables is generally enabled on the external network and disabled internally in production, depending on the specific scenario. For high concurrency situations, do not enable iptables as it impacts performance because iptables consume CPU resources. Therefore, in such cases, hardware firewalls are meticulously utilized. selinux is also disabled in production for intrusion detection purposes.
③As much as possible, do not assign a public internet IP to servers in production. Opt for proxy forwarding. For example, Nagios does not require an external IP.
④ If concurrency is not significant, under external IP environments, enable the firewall.
⑤ Initially generate a configuration file using default rules, and subsequently modify this file for any edits, additions, or deletions.
⑥ Block IPs based on IP addresses and the number of network connections. (Scheduled task for time-based blocking; if a rule exists, do not apply a secondary block.)
1.1.2 Summary of Common Use Cases in Enterprises:
1) Linux host firewall, a standalone firewall (filter table).
2) Shared internet access in a local area network (nat postrouting table).
3) Mapping external addresses to internal addresses and ports (nat prerouting table).
1.2 Introduction to iptables Firewall
Netfilter/Iptables (hereafter referred to as Iptables) is an excellent and open-source packet filtering firewall tool included in Unix/Linux. It is highly powerful and flexible, allowing fine-grained control over packets flowing into and out of the server. Particularly, it performs exceptionally well even on servers with very low hardware configurations (such as a Celeron 500MHz CPU and 64MB RAM used as a gateway firewall), servicing nearly 400 internet users without lagging behind professional enterprise routers and firewalls. Common enterprise network open-source products include iptables + zebra + squid.
iptables are integrated in the Linux 2.4 and 2.6 kernels, offering significantly enhanced functionality and security compared to its predecessors, ipfwadm and ipchains. iptables mainly operates at layers 2, 3, and 4 of the OSI model, and with kernel recompilation, it can even support 7-layer control (squid proxy + iptables included).
1.2.1 Terminology in iptables
Many individuals just encountering iptables may find its terminology confusing and unclear. Here is a basic description to help with understanding:
Container: Represents a relationship of inclusion or belonging.
1.2.2 What is a Container?
Most people recognize that a container holds items, such as a box, bag, or jar. Indeed, that’s correct. A dictionary defines a container as a storage device for packaging or carrying items, such as a box, jar, or wrap of flexible material. In iptables, it describes the relationship of inclusion or belonging.
1.2.3 What is Netfilter/iptables?
Netfilter acts as a container for tables. To better understand, if we consider Netfilter as an apartment building, then tables would be the individual apartments within that building. The “tables” belong to the “Netfilter” building.
1.2.4 What is a Table?
Tables are containers for chains, meaning all chains belong to their corresponding table. Referring back to the analogy, if Netfilter is the building, then tables are the apartments within it.
1.2.5 What is a Chain?
Chains are containers for policies. Continuously referencing the analogy, if tables are apartments, chains are akin to the furniture (like cabinets) within those apartments.
1.2.6 What is a Policy?
A policy is easier to comprehend. It refers to the specific rules and methods for filtering information with iptables, similar to how a cabinet is organized and filled.
Basic terminology is outlined in the table below:
Netfilter |
Table |
Chain |
Policy |
---|---|---|---|
An apartment building |
Apartments within |
Furniture in apartments |
Organization of furniture items |
1.3 iptables Tables and Chains
After describing iptables terminology, one should now have a preliminary understanding of iptables tables and chains. By default, iptables is divided into three tables based on functionality and each table contains different chains: filter, nat, and mangle. In practice, iptables includes four tables and five chains, but one mainly needs to remember two tables: filter and nat.
The table below shows the relationship between tables and chains.
Four tables:
Table |
Chain |
---|---|
Filter |
The default table, responsible for firewall data filtering. |
INPUT |
For packets designated to the local socket, i.e., data packets arriving at the local firewall server. |
FORWARD |
Packets routed through, i.e., passing through the local firewall server. |
OUTPUT |
Locally created data packets |
NAT |
Referred to when a new packet connection is established |
PREROUTING |
Immediately alters packets as they come in |
OUTPUT |
Alters locally created packets before routing |
POSTROUTING |
Changes packet information as packets are about to leave |
Mangle |
Specifically for manipulating packet attributes |
INPUT |
Packets entering the device itself |
FORWARD |
Modifies routing information of packets |
PREROUTING |
Changes incoming packets before routing |
OUTPUT |
Alters locally created packets before routing them |
POSTROUTING |
Changes packet information before they leave |
Raw |
Used mainly for configuring exemptions from connection tracking with the NOTRACK target. |
PREROUTING |
For packets arriving via any network interface |
OUTPUT |
For packets generated by local processes |
Five Chains
1.3.3 Detailed Introduction to Mangle Table InformationGenerally not used frequently as it’s associated with special marks, so further details are not necessary.1.4 iptables Working Process1.4.1 Explanation of the Working ProcessAs previously explained, iptables operates using a packet filtering mechanism. It analyzes the header data of incoming packets and matches them against pre-set rules to decide whether the packet can enter the host.Packet flow is from left to right.Diagram – iptables Packet Processing Flowchart
Diagram – Simplified iptables Packet Processing Flowchart Abstract Description: The above diagram could be described using Beijing Metro Line 1 and Line 2:Line 1: Primarily for NAT functionality
Enterprise Case Studies:
1) LAN internet sharing (router and gateway), using the NAT POSTROUTING chain.
2) Mapping external IP and ports to internal IP and ports (DMZ functionality), using the NAT PREROUTING chain
Line 2: Primarily for FILTER functionality, i.e., firewall functionality FILTER INPUT FORWARD
Enterprise Case Studies:
Main application in server firewalls, using the FILTER INPUT chain
Diagram – iptables Data Packet Forwarding Flowchart1.4.2 Summary of the iptables Workflow
1. The firewall applies a layered filtering approach. It filters in sequence from top to bottom and front to back according to configuration rules.
2. If a packet matches a defined rule—indicating either blocking or allowing—it stops further rules from being applied to this packet.
3. If no rules state a block or allow decision for a packet, the packet is tested against subsequent rules until the default policy applies.
4. Default firewall rules are executed only after all rules in the corresponding chain have been processed.
1.5 Operational Aspects of iptablesSystem Environment Explanation [root@clsn ~]# cat /etc/redhat-release
CentOS release 6.9 (Final)
[root@clsn ~]# hostname -I
10.0.0.188 172.16.1.188
Software Version [root@clsn ~]# iptables -V
iptables v1.4.7
1.5.1 Description of iptables ParametersExpand numbers (display exact digits)Example of using !bash
[root@clsn ~]# iptables ! -V
Not 1.4.7 😉
[root@clsn ~]# iptables -V
iptables v1.4.7Note: In iptables, all chain names must be uppercase, tables must be lowercase, actions must be uppercase, and matches must be lowercase.1.5.2 Preparation Before ConfigurationBefore configuring the firewall, you must first initialize the firewallbash
[root@clsn ~]# /etc/init.d/iptables start
iptables: Applying firewall rules: [ OK ]Clear all iptables rulesbash
[root@clsn ~]# iptables -Z
[root@clsn ~]# iptables -X
[root@clsn ~]# iptables -FView iptables rulesbash
[root@clsn ~]# iptables -nvL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destinationChain FORWARD (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destinationChain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
pkts bytes target prot opt in out source destinationView other table configurations (-t parameter)bash
[root@clsn ~]# iptables -nL -t raw
Chain PREROUTING (policy ACCEPT)
target prot opt source destinationChain OUTPUT (policy ACCEPT)
target prot opt source destinationView the sequence number of configuration rulesbash
[root@clsn ~]# iptables -nvL –number-list
–line-number # Show the number of the rule1.6 iptables Filter Table Configuration Examples1.6.1 Basic ConfigurationExample 1: Configure 22/ssh port access control rulesbash
iptables -A INPUT -p tcp –dport 22 -j DROP # Prohibit everyone from accessing port 22
iptables -I INPUT -p tcp –dport 22 -j ACCEPT # Restore connection method
iptables -I INPUT 2 -p tcp –dport 22 -j ACCEPT # Use the insertion specified line number information to specify which line to insert the rule
iptables -D INPUT -p tcp –dport 22 -j ACCEPT # Delete the specified rule
iptables -D INPUT 2 # Delete the corresponding rule based on the rule line numberOnly allow IP 10.0.0.1 to connect to this server via SSHbash
iptables -I INPUT -s 10.0.0.1 -p tcp –dport 22 -j ACCEPTExample 2: Block subnet access (block the 172.16.1.0 subnet from accessing 172.16.1.188)bash
iptables -A INPUT -s 172.16.1.0/24 -d 172.16.1.188 -j DROPExample 3: Prohibit a specific 172.16.1.0 subnet from accessing the server host’s port 22bash
iptables -A INPUT -s 172.16.1.0/24 -d 172.16.1.188 -p tcp –dport 22 -j DROPDirection Explanation:bash
# Control in the incoming direction
iptables -I INPUT -i eth0 -p tcp –dport 22 -j ACCEPT
# Control in the outgoing direction
iptables -I OUTPUT -o eth0 -p tcp –sport 22 -j DROP1.6.2 Configuration Example 4: Only allow the 10.0.0.0 subnet to connect to the server host, all other subnets are prohibited*First method:*bash
iptables -A INPUT -s 10.0.0.0/24 -d 172.16.1.8 -j ACCEPTChange the default policy to reject.*Second method:*! — Indicates inverting rule informationbash
iptables -A INPUT ! -s 10.0.0.0/24 -d 172.16.1.8 -j DROP — centos6 usage
iptables -A INPUT -s ! 10.0.0.0/24 -d 172.16.1.8 -j DROP — centos5 usageExplanation: Only parameters specified in the iptables help manual can use the inversion symbol (iptables –help)1.6.3 Configuration Example 5: Test matching a range of ports.bash
iptables -A INPUT -p tcp –dport 22:80 -j DROP # Set continuous multi-port control strategy
iptables -A INPUT -p tcp -m multiport –dport 22,80 -j DROP # Set non-continuous multi-port control strategy-m parameter indicates adding an extended matching function, multiport realizes non-continuous multi-port extended matching1.6.4 Configuration Example 6: Match ICMP typesBan ping strategy principleThe iptables server is either the ping initiator or receiver**Initiator:**Input chain: Prohibit icmp-type 0bash
iptables -A INPUT -i eth0 -p icmp –icmp-type 0 -j DROPOutput chain: Prohibit icmp-type 8bash
iptables -A OUTPUT -o eth0 -p icmp –icmp-type 8 -j DROP**Receiver:**Input chain: Prohibit icmp-type 8bash
iptables -A INPUT -i eth0 -p icmp –icmp-type 8 -j DROPOutput chain: Prohibit icmp-type 0bash
iptables -A OUTPUT -o eth0 -p icmp –icmp-type 0 -j DROPSimplified configuration:bash
iptables -A INPUT -i eth0 -p icmp -m icmp –icmp-type any -j DROP # Prohibit all types of icmpSpecify type to prohibit icmpbash
iptables -A INPUT -p icmp –icmp-type 8
iptables -A INPUT -p icmp –icmp-type 8 -j DROP
iptables -A INPUT -p icmp -m icmp –icmp-type any -j ACCEPT
iptables -A FORWARD -s 192.168.1.0/24 -p icmp -m icmp –icmp-type any -j ACCEPTExplanation: Only type 8 really affects ping, or any can be used; know many icmp types with iptables -p icmp -h**Description of ICMP Types**| TYPE | CODE | Description | Query | Error |
|——|——|—————————————-|——-|——-|
| 0 | 0 | Echo Reply—Ping response | x | |
| 3 | 0 | Network Unreachable | | x |
| 3 | 1 | Host Unreachable | | x |
| 3 | 2 | Protocol Unreachable | | x |
| 3 | 3 | Port Unreachable | | x |
| 3 | 4 | Fragmentation needed but no frag. bit set | | x |
| 3 | 5 | Source routing failed | | x |
| 3 | 6 | Destination network unknown | | x |
| 3 | 7 | Destination host unknown | | x |…Source host isolated (obsolete)——Source host has been isolated (no longer in use)
Parameter |
Parameter Description | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Display Related Parameters | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-n/–numeric |
Display address or port information in numeric form | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-L/ –list |
List rules in a chain or all chains | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
–list-rules/-S |
Print the rules in a chain or all chains | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
–line-number |
Print rule line number when listing rule information | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-v |
Display detailed information, can be cumulative | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-h |
Display help information | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Initialization Related Parameters | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
iptables -F |
Clear all rules, but doesn’t handle default rules | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
iptables -X |
Delete user-defined chains | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
iptables -Z |
Reset chain counters (packet counters and byte counters) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Common Configuration Parameters | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-t Table Name |
Specify which table to configure, and specify the table name. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
–append/-A Chain Name |
Append or add corresponding rule policies to the specified chain (chain name must be uppercase), default insertion at the end. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
–check/-C |
Check for the existence of a rule | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
–insert/-I Chain Name |
Insert corresponding rules to the specified chain, with default insertion at the beginning (can insert at a specific position by rule number)—used for sealing IP addresses. | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
–delete/-D Chain Name |
Delete specified rule (can be deleted by rule number) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
–replace/-R |
Replace rule rulenum (1 = first) in chain | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-P (uppercase) Chain Name |
Alter the final default rule policy on the chain | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
–new/-N |
Create a new user-defined chain | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-p Protocol Name |
Specify the protocol name in the rule: all, tcp, udp, icmp | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
–dport |
Specify the matching destination port information | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
–sport |
Specify the matching source port information | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-j Action |
Action to be taken after matching a packet | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ACCEPT |
Allow | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
DROP |
Discard (no response) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
REJECT |
Refuse (send explicit rejection to requester) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
MASQUERADE |
Used for masquerading on the internet | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SNAT |
Shared address internet access | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
DNAT |
Destination address rewriting | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-i |
Specifies incoming traffic interface in INPUT chain rules (only applicable to INPUT chain) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-o |
Specifies outgoing traffic interface in OUTPUT chain rules (only applicable to OUTPUT chain) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
-s |
Specifies source IP address or source network information |
x |
3 |
9 |
Destination network administratively prohibited——The destination network has been administratively prohibited |
x |
3 |
10 |
Destination host administratively prohibited——The destination host has been administratively prohibited |
x |
3 |
11 |
Network unreachable for TOS——Network unreachable due to Type of Service (TOS) |
x |
3 |
12 |
Host unreachable for TOS——Host unreachable due to Type of Service (TOS) |
x |
3 |
13 |
Communication administratively prohibited by filtering——Communication administratively prohibited by filtering |
x |
3 |
14 |
Host precedence violation——Host precedence violation |
x |
3 |
15 |
Precedence cutoff in effect——Precedence cutoff in effect |
x |
4 |
0 |
Source quench——Source quench (basic flow control) |
5 |
0 |
Redirect for network——Redirect for network |
5 |
1 |
Redirect for host——Redirect for host |
5 |
2 |
Redirect for TOS and network——Redirect for Type of Service and network |
5 |
3 |
Redirect for TOS and host——Redirect for Type of Service and host |
8 |
0 |
Echo request——Echo request (Ping request) |
x |
9 |
0 |
Router advertisement——Router advertisement |
10 |
0 |
Route solicitation——Route solicitation |
11 |
0 |
TTL equals 0 during transit——Time to Live (TTL) equals 0 during transit |
x |
11 |
1 |
TTL equals 0 during reassembly——Time to Live (TTL) equals 0 during reassembly |
x |
12 |
0 |
IP header bad (catchall error)——Bad IP header (catchall error) |
x |
12 |
1 |
Required options missing——Required options missing |
x |
13 |
0 |
Timestamp request (obsolete)——Timestamp request (obsolete) |
x |
14 |
Timestamp reply (obsolete)——Timestamp reply (obsolete) |
x |
15 |
0 |
Information request (obsolete)——Information request (obsolete) |
x |
16 |
0 |
Information reply (obsolete)——Information reply (obsolete) |
x |
17 |
0 |
Address mask request——Address mask request |
x |
18 |
0 |
Address mask reply——Address mask reply Data source: http://www.cnitblog.com/yang55xiaoguang/articles/59581.html 1.6.5 Firewall State Mechanism ConfigurationBrief description of state sets:
Note: Allow associated state packets to pass (web services should not use FTP services) When firewall services are configured on an FTP server, the following strategies need to be configured
Implement discovery of sent_syn state
Implement discovery of sent_rcvd state
1.6.6 Implementing Rate Limiting with iptableslimit is a matching module of iptables, and it can be used with other iptables commands to achieve rate limiting. Firstly, it must be clear that limit itself is only a “matching” module. As we know, the basic principle of iptables is “match–process”, and limit can only play a matching role in this process. It cannot itself perform any processing on network packets. I’ve seen some examples online claiming that a single iptables statement with a limit match rule can achieve rate limiting, which is incorrect. In fact, using limit to rate limit requires two steps: 1. Allow packets that conform to the limit match rule 2. Discard/Reject packets not allowed Example:
Statement Meaning: When ping packets from 10.0.0.7 exceed 5, rate limit them to one packet every 10 seconds. Parameter Explanation:
How does the limit module specifically work? The limit match is based on the Token Bucket model. The token bucket is a common buffering principle in network communications, with two important parameters: bucket capacity “n” and token generation rate “s”.
|