Ultimate Linux Firewall Showdown: Complete Configuration Guide for iptables and firewalld

Click the blue “Best Programmer” to follow me!

Add a “Star“, every day at 18:03 to learn technology together!


Complete Guide to Configuring iptables and firewalld Firewalls

1. Basic Concepts of Firewalls

1.1 What is a Firewall

A firewall is a network security device that monitors and controls incoming and outgoing network traffic based on predetermined security rules. In Linux systems, there are mainly two firewall solutions: iptables and firewalld.

1.2 iptables vs firewalld

  • iptables: A traditional Linux firewall tool that directly manipulates the kernel’s netfilter framework.
  • firewalld: A dynamic firewall manager that provides a higher level of abstraction and dynamic configuration capabilities.

2. Detailed Explanation of iptables

2.1 Basic Concepts of iptables

2.1.1 Tables

  • filter table: The default table used for filtering packets.
  • nat table: Used for network address translation.
  • mangle table: Used for modifying packet header information.
  • raw table: Used for configuring connection tracking.

2.1.2 Chains

  • INPUT: Handles incoming packets.
  • OUTPUT: Handles outgoing packets.
  • FORWARD: Handles forwarded packets.
  • PREROUTING: Processes packets before routing decisions.
  • POSTROUTING: Processes packets after routing decisions.

2.1.3 Targets

  • ACCEPT: Accepts packets.
  • DROP: Drops packets.
  • REJECT: Rejects packets and returns an error message.
  • LOG: Logs packets.
  • MASQUERADE: IP masquerading.

2.2 Basic Syntax of iptables

iptables [-t table] -[ADI] chain rule-specification
iptables [-t table] -[FLZ] [chain]
iptables [-t table] -N chain
iptables [-t table] -X [chain]
iptables [-t table] -P chain target

2.3 Common iptables Commands

2.3.1 Viewing Rules

# View all rules
iptables -L -n -v

# View rules for a specific table
iptables -t nat -L -n -v

# View rule numbers
iptables -L INPUT --line-numbers

2.3.2 Adding Rules

# Allow SSH connections
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow HTTP and HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Allow specific IP access
iptables -A INPUT -s 192.168.1.100 -j ACCEPT

# Allow local loopback
iptables -A INPUT -i lo -j ACCEPT

# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

2.3.3 Deleting Rules

# Delete a specific rule
iptables -D INPUT -p tcp --dport 80 -j ACCEPT

# Delete by line number
iptables -D INPUT 3

# Flush all rules
iptables -F
iptables -X
iptables -Z

2.3.4 Setting Default Policies

# Set default deny policy
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

2.4 Advanced iptables Configuration

2.4.1 Port Ranges and Multiple Ports

# Port range
iptables -A INPUT -p tcp --dport 3000:3010 -j ACCEPT

# Multiple ports
iptables -A INPUT -p tcp -m multiport --dports 80,443,8080 -j ACCEPT

2.4.2 Time Restrictions

# Allow access only during working hours
iptables -A INPUT -p tcp --dport 22 -m time --timestart 09:00 --timestop 18:00 -j ACCEPT

2.4.3 Connection Limits

# Limit concurrent connections
iptables -A INPUT -p tcp --dport 22 -m connlimit --connlimit-above 3 -j REJECT

# Limit connection rate
iptables -A INPUT -p tcp --dport 22 -m limit --limit 5/min --limit-burst 10 -j ACCEPT

2.4.4 NAT Configuration

# SNAT (Source Address Translation)
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE

# DNAT (Destination Address Translation)
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.1.100:8080

2.5 iptables Rule Persistence

2.5.1 CentOS/RHEL Systems

# Save rules
service iptables save

# Or save manually
iptables-save > /etc/sysconfig/iptables

# Restore rules
iptables-restore < /etc/sysconfig/iptables

2.5.2 Ubuntu/Debian Systems

# Install iptables-persistent
apt-get install iptables-persistent

# Save rules
netfilter-persistent save

# Restore rules
netfilter-persistent reload

3. Detailed Explanation of firewalld

3.1 Basic Concepts of firewalld

3.1.1 Zones

  • drop: Drops all incoming connections.
  • block: Rejects all incoming connections.
  • public: Public zone, the default zone.
  • external: External zone used for NAT.
  • dmz: DMZ zone.
  • work: Work zone.
  • home: Home zone.
  • internal: Internal zone.
  • trusted: Trusted zone, allows all connections.

3.1.2 Services

Predefined service configurations that include port, protocol, and other information.

3.1.3 Rich Rules

Provides a more complex rule configuration syntax.

3.2 Basic firewalld Commands

3.2.1 Service Management

# Start firewalld
systemctl start firewalld

# Stop firewalld
systemctl stop firewalld

# Restart firewalld
systemctl restart firewalld

# Check status
systemctl status firewalld
firewall-cmd --state

3.2.2 Zone Management

# View default zone
firewall-cmd --get-default-zone

# Set default zone
firewall-cmd --set-default-zone=public

# View active zones
firewall-cmd --get-active-zones

# View all zones
firewall-cmd --get-zones

# View zone information
firewall-cmd --zone=public --list-all

3.2.3 Service Management

# View available services
firewall-cmd --get-services

# View open services
firewall-cmd --list-services

# Add service
firewall-cmd --add-service=http
firewall-cmd --add-service=https

# Remove service
firewall-cmd --remove-service=http

# Permanently add service
firewall-cmd --permanent --add-service=http

3.2.4 Port Management

# Add port
firewall-cmd --add-port=8080/tcp

# Remove port
firewall-cmd --remove-port=8080/tcp

# View open ports
firewall-cmd --list-ports

# Permanently add port
firewall-cmd --permanent --add-port=8080/tcp

3.3 Advanced firewalld Configuration

3.3.1 Custom Services

# Create custom service configuration file
cat > /etc/firewalld/services/myapp.xml << EOF
<?xml version="1.0" encoding="utf-8"?>
<service>
  <short>MyApp</short>
  <description>My Application Service</description>
  <port protocol="tcp" port="8080"/>
  <port protocol="tcp" port="8443"/>
</service>
EOF

# Reload configuration
firewall-cmd --reload

# Add custom service
firewall-cmd --add-service=myapp

3.3.2 Rich Rule Configuration

# Allow specific IP access to specific port
firewall-cmd --add-rich-rule='rule family="ipv4" source address="192.168.1.100" port protocol="tcp" port="22" accept'

# Limit connection rate
firewall-cmd --add-rich-rule='rule service name="ssh" limit value="10/m" accept'

# Block specific IP
firewall-cmd --add-rich-rule='rule family="ipv4" source address="192.168.1.200" drop'

# Port forwarding
firewall-cmd --add-rich-rule='rule family="ipv4" forward-port port="80" protocol="tcp" to-port="8080"'

3.3.3 Interface Binding

# Bind interface to zone
firewall-cmd --zone=internal --add-interface=eth1

# View interface binding
firewall-cmd --get-zone-of-interface=eth1

# Change interface zone
firewall-cmd --zone=public --change-interface=eth1

3.3.4 IP Masquerading and Port Forwarding

# Enable IP masquerading
firewall-cmd --add-masquerade

# Port forwarding
firewall-cmd --add-forward-port=port=80:proto=tcp:toport=8080:toaddr=192.168.1.100

# View forwarding rules
firewall-cmd --list-forward-ports

4. Practical Configuration Examples

4.1 Web Server Firewall Configuration

4.1.1 iptables Configuration

#!/bin/bash
# Web server firewall configuration script

# Flush existing rules
iptables -F
iptables -X
iptables -Z

# Set default policy
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# Allow local loopback
iptables -A INPUT -i lo -j ACCEPT

# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow SSH (limit connection count)
iptables -A INPUT -p tcp --dport 22 -m connlimit --connlimit-above 3 -j REJECT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Allow HTTP and HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Allow FTP
iptables -A INPUT -p tcp --dport 21 -j ACCEPT
iptables -A INPUT -p tcp --dport 20 -j ACCEPT

# Allow DNS
iptables -A INPUT -p udp --dport 53 -j ACCEPT

# Save rules
service iptables save

4.1.2 firewalld Configuration

#!/bin/bash
# Web server firewall configuration script

# Set default zone
firewall-cmd --set-default-zone=public

# Add services
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-service=ftp

# Limit SSH connections
firewall-cmd --permanent --add-rich-rule='rule service name="ssh" limit value="3/m" accept'

# Reload configuration
firewall-cmd --reload

4.2 Database Server Firewall Configuration

4.2.1 iptables Configuration

#!/bin/bash
# Database server firewall configuration

# Flush existing rules
iptables -F
iptables -X
iptables -Z

# Set default policy
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# Allow local loopback
iptables -A INPUT -i lo -j ACCEPT

# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow SSH (only for management subnet)
iptables -A INPUT -s 192.168.1.0/24 -p tcp --dport 22 -j ACCEPT

# Allow MySQL (only for application servers)
iptables -A INPUT -s 192.168.1.100 -p tcp --dport 3306 -j ACCEPT
iptables -A INPUT -s 192.168.1.101 -p tcp --dport 3306 -j ACCEPT

# Save rules
service iptables save

4.2.2 firewalld Configuration

#!/bin/bash
# Database server firewall configuration

# Create database zone
firewall-cmd --permanent --new-zone=database

# Set default zone
firewall-cmd --set-default-zone=database

# Add SSH service (limit source IP)
firewall-cmd --permanent --zone=database --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" service name="ssh" accept'

# Add MySQL service (limit source IP)
firewall-cmd --permanent --zone=database --add-rich-rule='rule family="ipv4" source address="192.168.1.100" service name="mysql" accept'
firewall-cmd --permanent --zone=database --add-rich-rule='rule family="ipv4" source address="192.168.1.101" service name="mysql" accept'

# Reload configuration
firewall-cmd --reload

5. Troubleshooting and Optimization

5.1 Common Issues Troubleshooting

5.1.1 Rules Not Taking Effect

# Check if rules are correctly added
iptables -L -n -v
firewall-cmd --list-all

# Check service status
systemctl status iptables
systemctl status firewalld

# Check logs
tail -f /var/log/messages
journalctl -u firewalld -f

5.1.2 Connection Refused

# Enable logging
iptables -A INPUT -j LOG --log-prefix "INPUT DROP: "

# View logs
tail -f /var/log/messages

# firewalld logs
firewall-cmd --set-log-denied=all

5.2 Performance Optimization

5.2.1 Rule Optimization

# Place commonly used rules at the top
iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT

# Use state matching to reduce rule count
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Use multiport to match multiple ports
iptables -A INPUT -p tcp -m multiport --dports 80,443,8080 -j ACCEPT

5.2.2 Monitoring and Statistics

# View rule statistics
iptables -L -n -v --line-numbers

# Reset counters
iptables -Z

# Real-time monitoring
watch -n 1 'iptables -L -n -v'

6. Security Best Practices

6.1 Basic Security Principles

  1. 1. Principle of Least Privilege: Only open necessary ports and services.
  2. 2. Whitelist Policy: Deny all connections by default, only allow necessary connections.
  3. 3. Regular Audits: Regularly check and update firewall rules.
  4. 4. Log Monitoring: Enable logging and analyze regularly.

6.2 Configuration Recommendations

# Set reasonable default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

# Enable connection tracking
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Limit connection rate
iptables -A INPUT -p tcp --dport 22 -m limit --limit 5/min --limit-burst 10 -j ACCEPT

# Prevent scanning
iptables -A INPUT -p tcp --tcp-flags ALL NONE -j DROP
iptables -A INPUT -p tcp --tcp-flags ALL ALL -j DROP

6.3 Backup and Recovery

# Backup iptables rules
iptables-save > /root/iptables.backup.$(date +%Y%m%d)

# Restore iptables rules
iptables-restore < /root/iptables.backup.20231201

# Backup firewalld configuration
cp -r /etc/firewalld /root/firewalld.backup.$(date +%Y%m%d)

7. Conclusion

Both iptables and firewalld are powerful firewall tools in Linux systems. iptables provides lower-level control, suitable for scenarios with detailed firewall rule requirements; firewalld offers a more user-friendly management interface and dynamic configuration capabilities, making it more suitable for daily operations management.

The choice of which tool to use mainly depends on the specific application scenario and personal preference. In actual deployment, it is recommended to develop appropriate firewall strategies based on the specific needs of the system and to conduct regular security audits and rule optimizations.

Remember that the firewall is just one component of network security; it should be combined with other security measures (such as intrusion detection, log monitoring, regular updates, etc.) to build a complete security protection system.

Ultimate Linux Firewall Showdown: Complete Configuration Guide for iptables and firewalld

Leave a Comment