Master Linux Firewalls: Complete iptables & firewalld Configuration Guide

Learn the fundamentals of Linux firewalls, compare iptables and firewalld, explore tables, chains, targets, and advanced features, and follow practical scripts for web and database server protection, rule persistence, troubleshooting, performance tuning, and security best practices in a comprehensive step‑by‑step guide.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Linux Firewalls: Complete iptables & firewalld Configuration Guide

iptables and firewalld configuration complete guide

1. Firewall Basics

1.1 What is a firewall

Firewall is a network security device that monitors and controls traffic based on predefined rules. Linux mainly has two firewall solutions: iptables and firewalld.

1.2 iptables vs firewalld

iptables : traditional Linux firewall tool that directly manipulates the netfilter framework.

firewalld : dynamic firewall manager offering higher‑level abstraction and dynamic configuration.

2. iptables Details

2.1 Basic Concepts

2.1.1 Tables

filter : default table for filtering packets.

nat : for network address translation.

mangle : for modifying packet header fields.

raw : for connection tracking configuration.

2.1.2 Chains

INPUT : handles inbound packets.

OUTPUT : handles outbound packets.

FORWARD : handles forwarded packets.

PREROUTING : processes packets before routing decision.

POSTROUTING : processes packets after routing decision.

2.1.3 Targets

ACCEPT : accept packet.

DROP : drop packet.

REJECT : reject packet and send error.

LOG : log packet.

MASQUERADE : IP masquerading.

2.2 Basic Syntax

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 Commands

2.3.1 View Rules

# View all rules
iptables -L -n -v

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

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

2.3.2 Add Rules

# Allow SSH
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
iptables -A INPUT -s 192.168.1.100 -j ACCEPT

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

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

2.3.3 Delete Rules

# Delete 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 Set Default Policy

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

2.4 Advanced Configuration

2.4.1 Port Ranges and Multi‑port

# 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 SSH only during work 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
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o eth0 -j MASQUERADE

# DNAT
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination 192.168.1.100:8080

2.5 Rule Persistence

2.5.1 CentOS/RHEL

# Save rules
service iptables save

# Manual save
iptables-save > /etc/sysconfig/iptables

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

2.5.2 Ubuntu/Debian

# Install persistence package
apt-get install iptables-persistent

# Save
netfilter-persistent save

# Reload
netfilter-persistent reload

3. firewalld Details

3.1 Basic Concepts

3.1.1 Zones

drop : drop all incoming connections.

block : reject all incoming connections.

public : default public zone.

external : external zone for NAT.

dmz : DMZ zone.

work : work zone.

home : home zone.

internal : internal zone.

trusted : trusted zone allowing all connections.

3.1.2 Services

Predefined service definitions contain ports, protocols, etc.

3.1.3 Rich Rules

Provide more complex rule syntax.

3.2 Basic 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

# Get default zone
firewall-cmd --get-default-zone

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

# List active zones
firewall-cmd --get-active-zones

# List all zones
firewall-cmd --get-zones

# Show zone details
firewall-cmd --zone=public --list-all

3.2.3 Service Management

# List available services
firewall-cmd --get-services

# List enabled services
firewall-cmd --list-services

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

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

# Permanent add
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

# List ports
firewall-cmd --list-ports

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

3.3 Advanced Configuration

3.3.1 Custom Services

# Create custom service 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
firewall-cmd --reload

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

3.3.2 Rich Rules

# Allow specific IP 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

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

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

3.3.4 Masquerade and Port Forwarding

# Enable masquerade
firewall-cmd --add-masquerade

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

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

4. Practical Configuration Cases

4.1 Web Server Firewall

4.1.1 iptables

#!/bin/bash
# Web server firewall script

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

# Default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

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

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

# Allow SSH (limit connections)
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

#!/bin/bash
# Web server firewall 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
firewall-cmd --reload

4.2 Database Server Firewall

4.2.1 iptables

#!/bin/bash
# Database server firewall script

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

# Default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT

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

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

# Allow SSH from management subnet
iptables -A INPUT -s 192.168.1.0/24 -p tcp --dport 22 -j ACCEPT

# Allow MySQL from 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

#!/bin/bash
# Database server firewall script

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

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

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

# Add MySQL with source restriction
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
firewall-cmd --reload

5. Troubleshooting and Optimization

5.1 Common Issues

5.1.1 Rules Not Effective

# Check rules
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 logging
firewall-cmd --set-log-denied=all

5.2 Performance Optimization

5.2.1 Rule Optimization

# Place frequently used rules first
iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT

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

# Use multiport for 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 Principles

Least Privilege : only open necessary ports and services.

Whitelist Strategy : default deny all, allow only required connections.

Regular Audits : periodically review and update firewall rules.

Log Monitoring : enable logging and analyze regularly.

6.2 Configuration Recommendations

# Reasonable default policy
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 scans
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 Restore

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

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

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

7. Summary

iptables and firewalld are powerful Linux firewall tools. iptables offers low‑level control for detailed rule requirements, while firewalld provides a user‑friendly interface and dynamic configuration suitable for everyday operations. Choose the tool based on scenario, define appropriate policies, and perform regular security audits and rule optimizations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

security best practicesnetwork securityiptablesfirewalldfirewall rulesLinux firewall
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.