Practical Use of Iptables

Overview
Netfilter/Iptables (hereinafter referred to as Iptables) is an excellent and open-source, completely free firewall tool based on packet filtering that comes with Unix/Linux. It is incredibly powerful and highly flexible, allowing for very detailed control over the packets flowing into and out of the server. Remarkably, it can perform well under very low hardware configurations (I once deployed a gateway firewall on a Celeron 500HZ CPU with 64M memory, efficiently providing internet service to nearly 400 people without compromising in comparison to enterprise-grade professional router firewalls). Iptables is a service integrated into the Linux 2.4 and 2.6 kernels. Its functionality and security are far superior to its predecessors like Ipfwadn and ipchains. Iptables mainly operates at layers two, three, and four of the OSI seven-layer model. If the kernel is recompiled, Iptables can also support seven-layer control (squid proxy + iptables).
Terminology:
- Container: Relationship of inclusion or belonging
- Netfilter/Iptables is a container of tables (four tables)
- Four Tables
- filter: Filters packets
- nat: Used for Network Address Translation (IP, port)
- mangle: Modifies packet service types, TTL, and can configure routing for QOS
- raw Table: Decides if a packet is processed by the state tracking mechanism
- Iptables Tables and Chains Workflow Chart
Iptables Filtering Diagram
Iptables functions using packet filtering mechanisms. It analyzes the header data of incoming data packets based on predefined rules to decide whether the packet can enter the host.– The firewall applies filters layer by layer, actually following the configured rules sequentially from top to bottom, front to back.
– If a rule is matched, indicating whether to block or allow, the packet will not be matched against further new rules.
– If none of the rules clearly indicates to block or allow, meaning no rule matches, the system checks downward until the default rule is matched to give a clear block or allow.
– The firewall’s default rule executes only after all rules in the chain are processed.
– The execution order of Iptables firewall rules is by default from front to back (top to bottom), executed sequentially. Upon encountering a matched rule, it stops further checks; only unmatched ones will continue to be checked.Note: If a DROP rule is placed at the top, the rules below will not match and execute. Hence, use the -I parameter to insert new rules at the top.
Iptables Installation
– Check if iptables is installed: systemctl status iptables
– Install iptables: yum install iptables* -y
– Start iptables: systemctl start iptables
– Disable the firewall: systemctl disable –now firewalld
– Disable selinux: vim /etc/selinux/configIptables Command Explanation
Format: `iptables [-t table] [parameter chain] [parameter protocol] [parameter port] [parameter action]`Parameter Descriptions:
– -t: Specifies the table to operate on
– -L: Lists the current rules
– -v: Displays packet and packet size
– -n: Does not reverse lookup addresses
– -A: Appends a rule to the chain
– -I: Inserts a rule at the top
– -F: Flushes the rules
– -Z: Clears counters (packet number, packet size)
– -D: Deletes a rule from the chain
– -R: Modifies a rule
– -S: Lists all rules
– -N: Creates a custom chain
– -X: Deletes a custom chain
– -P: Specifies the default policy for the chainProtocol List for Iptables:
– TCP: Matches TCP protocol, HTTP belongs to TCP
– UDP: Matches UDP protocol
– ICMP: Matches ICMP protocol, similar to ping
– ALL: Matches all protocolsPort Parameter Description:
– –sport: Source port, port sending the request
– –dport: Destination port, port being accessedActions Table:
– ACCEPT: Allows packets, and after processing this action, no further rules are compared; it directly moves to the next rule chain
– REJECT: Blocks the packet and sends a packet notification to the other side
– DROP: Discards the packet without processing, and after this action, no further rules are compared; it interrupts the filter program directly
– REDIRECT: Redirects the packet to another port, and after processing this action, other rules are still comparedParameters: -i, -o, -m, -j, -s, -d
– -i: Incoming network interface
– -o: Outgoing network interface
– -m: Specifies the module
– -j: Executes the action (from the table above)
– -p: Specifies the protocol
– -s: Source address, address sending the request
– -d: Destination address, address being accessedCommon Iptables Commands
– iptables -h: View help
– iptables -L -v: List all rules (in filter table)
– iptables -L -n: List all rules (in filter table, default, -n is non-reverse lookup)
– iptables -L -n -t nat: List all rules (in nat table)
– iptables -F: Clear all rules (in filter table)
– iptables -F -t nat: Clear all rules (in nat table)
– service iptables save: Save configuration (configuration must be restarted after saving)
– systemctl restart iptables: RestartCommon Iptables Syntax
– -A: Adds to the end of the rules
– -D: Deletes a record
– -I: Adds to the first rule
– -p: (proto) Specifies communication protocol, common protocols: tcp, udp, icmp, all
– -j: (jump) Specifies the target to jump to, common targets: ACCEPT (accept packets), DROP (discard packets), REJECT (redirect)—generally, redirects are not used due to security risksCommon Use Cases
Case 1: Only Allow Access to Port 22, Blocking All Other Ports
bash
[root@m01 ~]# iptables -t filter -A INPUT -p TCP –dport 22 -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -j DROP
[root@m01 ~]# iptables -L -vReview the rules (result too long, not displayed here).
Case 2: Allow Access Only to Ports 22, 80, 443, Block All Others
bash
[root@m01 ~]# iptables -t filter -A INPUT -p TCP –dport 22 -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP –dport 80 -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP –dport 443 -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -j DROPIf you try to access Baidu, you’ll get a timeout because the required ports are not specified.
bash
[root@m01 ~]# curl www.baidu.com
curl: (7) Failed to connect to www.baidu.com:80; Connection timed outCase 3: Allow Only Ports 22, 80, 443, Local Machine Can Access Baidu
bash
[root@m01 ~]# iptables -t filter -A INPUT -p TCP –dport 22 -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP –dport 80 -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP –dport 443 -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -j DROPCase 4: Allow Connection from Port 22 to IP 192.168.15.81
bash
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -d 192.168.15.81 –dport 22 -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -j DROPTest with a new window or VM.
Case 5: Allow IP 192.168.15.71 to Connect via Port 22 to 192.168.15.81 Only
bash
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -s 192.168.15.71 -d 192.168.15.81 –dport 22 -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP -j DROPTest connection from 71 to 81; 81 is disconnected.
Case 6: Make 192.168.15.71 Invisible
bash
[root@prometheus ~]# iptables -t filter -A INPUT -p TCP -d 192.168.15.71 -j DROPThe address within the VM is not visible externally.
Case 7: Block All Requests via eth0 Interface
bash
[root@prometheus ~]# iptables -t filter -A INPUT -p TCP -i eth0 -j DROPCase 8: Block Baidu Access via eth1 Interface
bash
[root@prometheus ~]# iptables -t filter -I OUTPUT -p TCP -o eth1 -j DROPCase 9: Redirect Port 8080 to Port 80
bash
[root@m01 ~]# iptables -t nat -A PREROUTING -p TCP –dport 8080 -j REDIRECT –to-port 80Case 10: Allow Only Windows to SSH into 192.168.15.81
Find the Windows IP address first:
bash
# From Windows:
ipconfig
# Find IPV4 address under WMnet8Then configure:
bash
[root@m01 ~]# iptables -t filter -I INPUT -p TCP -s 192.168.15.1 -d 192.168.15.81 –dport 22 -j ACCEPT
[root@m01 ~]# iptables -t filter -A INPUT -p TCP –dport 22 -j DROPIP Filtering and Port Management
– Block all data from IP 192.168.1.3
bash
iptables -A INPUT -s 192.168.1.3 -j DROP– Open Port 80
bash
iptables -A INPUT -p tcp –dport 80 -j ACCEPT– Open Port Range 22 to 80
bash
iptables -I INPUT -p tcp –dport 22:80 -j ACCEPT– Block Outbound Traffic on Port 80
bash
iptables -I OUTPUT -p tcp –dport 80 -j DROPModules and Advanced Configurations
– **Multiport Module**: Match Multiple Ports and Port Ranges
bash
iptables -t filter -A INPUT -p TCP -m multiport –dports 22,80,443,30000:50000 -j ACCEPT
iptables -t filter -A INPUT -p TCP -j DROP– **IP Range Module**: Specify a Source or Destination IP Range
bash
iptables -t filter -A INPUT -p TCP -m iprange –src-range 192.168.15.1-192.168.15.10 -j ACCEPT
iptables -t filter -A INPUT -p TCP -j DROP– **String Module**: Block Traffic Containing Specific Strings
bash
echo “Helloworld” > index.html
echo “Hello” > demo.html
iptables -t filter -A INPUT -p TCP -m string –string “Helloworld” –algo kmp -j DROPExamples of Other Advanced Use-Cases
– **Time Module**: Restrict Access Based on Time
bash
iptables -t filter -A INPUT -p TCP -m time –timestart 14:00 –timestop 15:00 -j DROP– **ICMP Module**: Refine Ping Restrictions
bash
iptables -t filter -A INPUT -p ICMP -m icmp –icmp-type “echo-request” -j DROP– **Connlimit Module**: Limit Concurrent Connections
bash
iptables -t filter -A INPUT -p TCP –dport 22 -m connlimit –connlimit-above 2 -j DROPLimit Module
Limits packet rate; per second, minute, hour, day.
- Parameters
- –limit rate[/second|/minute|/hour|/day]: Number of packets
- –limit-burst number: Packet count (default: 5)
# Example: Limit rate to around 500k/s, approximately 333 packets per second
# Create a test file
[root@m01 ~]# dd if=/dev/zero of=a.txt bs=100M count=10
10+0 records in
10+0 records out
1048576000 bytes (1.0 GB) copied, 7.64477 s, 137 MB/s
# Limit rate (control is inaccurate!)
[root@m01 ~]# iptables -t filter -A OUTPUT -p TCP -m limit --limit 333/s -j ACCEPT
[root@m01 ~]# iptables -t filter -A OUTPUT -p TCP -j DROP
# Transfer
[root@m01 ~]# scp a.txt [email protected]:/rootThe transfer rate is inaccurate, gradually decreasing until it stabilizes!
Additional Knowledge:
Check CentOS Version
cat /etc/redhat-release
Command to check local port usage:
Command: netstat -nutlp
[root@m01 ~]# netstat -nutlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1591/nginx: master
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1304/sshd
tcp6 0 0 :::80 :::* LISTEN 1591/nginx: master
tcp6 0 0 :::22 :::* LISTEN 1304/sshdiptables Script Setting
#!/bin/sh
iptables -P INPUT ACCEPT
iptables -F
iptables -X
iptables -Z
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
iptables -A INPUT -p tcp --dport 21 -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -p icmp --icmp-type 8 -j ACCEPT
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -P FORWARD DROP
service iptables save
systemctl restart iptables.serviceAdditional Case Study
Enterprise Case
If the log file
/var/log/messages
reports: kernel: nf_conntrack: table full, dropping packet, the solution is as follows:# This result will cause slow business network access
net.nf_conntrack_max = 250000000
net.netfilter.nf_conntrack_max = 250000000
# Shorten response time
net.netfilter.nf_conntrack_timeout_established = 170
net.netfilter.nf_conntrack_timeout_wait = 120
net.netfilter.nf_conntrack_timeout_close_wait = 60
net.netfilter.nf_conntrack_timeout_fin_wait = 100Common Pitfalls
Saving the iptables rules (service iptables save) might fail sometimes after setting them Install iptables during the first step using yum install -y iptables to ensure all packages are complete, as the default system packages may not be sufficient Be cautious not to lock yourself out when filtering ports; you can clear all rules from a virtual machine to resolve
nat NAT Gateway Programming Algorithms Network Security
- Parameters