Master Firewall Concepts, Zones, Rich Rules, Port Forwarding, and NAT on CentOS/RHEL
In today's interconnected world, network security is paramount. firewalld is the dynamic firewall management tool that comes standard with CentOS/RHEL 7+ and provides a powerful, flexible way to control network traffic. Unlike traditional iptables, firewalld uses a zone-based approach that makes firewall management intuitive and dynamic.
This comprehensive guide covers everything from basic firewall concepts to advanced configurations including rich rules, port forwarding, masquerading, and real-world lab scenarios. All commands and examples are tested and verified on CentOS 8.5.
Understanding Firewall Fundamentals
The Network Security Analogy
Think of your network as a secure building. The firewall is like the security checkpoint at the entrance. Zones are different security levels — the public lobby (public zone) has minimal access, while the executive floor (trusted zone) allows full access. Services are like specific rooms or functions (web server, database), and rich rules are custom security policies for VIP visitors or special circumstances.
Traditional iptables vs. firewalld
Before firewalld, Linux administrators used iptables directly, which required complex command-line syntax and immediate rule application. firewalld introduces several key advantages:
| Feature | iptables | firewalld |
|---|---|---|
| Configuration Model | Direct rule manipulation | Zone-based with runtime/permanent modes |
| Dynamic Updates | Rules applied immediately (no rollback) | Runtime changes don't affect permanent config |
| Interface Management | Manual interface binding | Automatic zone assignment by interface |
| Service Definitions | Manual port/protocol specification | Pre-defined services with XML definitions |
| Rich Rules | Complex iptables syntax required | Intuitive, human-readable rule syntax |
firewalld Pre-defined Zones
Zones are the heart of firewalld's design philosophy. Each zone represents a different level of trust for network connections. You can assign network interfaces, sources (IP addresses), or connections to specific zones.
Public Zone (Default)
Use Case: Untrusted networks where you don't trust other computers. Only selected incoming connections are accepted.
Default Services: ssh, dhcpv6-client
Internal Zone
Use Case: Trusted internal networks where most services are accepted.
Default Services: ssh, mdns, samba-client, dhcpv6-client
Trusted Zone
Use Case: Completely trusted networks with full access.
Default Services: All services allowed
External Zone
Use Case: External networks with masquerading enabled for NAT.
Default Services: ssh, dhcpv6-client, masquerading enabled
Home Zone
Use Case: Home networks with moderate trust level.
Default Services: ssh, mdns, samba-client, dhcpv6-client
Managing Zones
- 1 List Available Zones
firewall-cmd --get-zones - 2 View Active Zones
firewall-cmd --get-active-zonesThis shows which zones are currently active and what interfaces/sources are assigned to them.
- 3 Get Zone Details
firewall-cmd --zone=public --list-allShows all settings for the public zone including services, ports, sources, and interfaces.
- 4 Change Default Zone
firewall-cmd --set-default-zone=internalSets the default zone for new connections. This is a permanent change.
Practice Lab 1: Zone Exploration
Explore your system's current firewall configuration:
# Check current status
firewall-cmd --state
# List all zones
firewall-cmd --get-zones
# See active zones and their assignments
firewall-cmd --get-active-zones
# View detailed configuration of default zone
firewall-cmd --list-allPacket Flow Through firewalld
Understanding how packets flow through firewalld is crucial for troubleshooting and advanced configuration. Here's the packet processing order:
- PREROUTING - Raw table (connection tracking), NAT rules
- Routing Decision - Determine if packet is for local system or forwarding
- INPUT Chain - For packets destined to local system
- Mangle table INPUT
- Filter table INPUT (firewalld rules applied here)
- Local Process - Packet delivered to application
- OUTPUT Chain - For locally generated packets
- Raw table OUTPUT
- Mangle table OUTPUT
- NAT table OUTPUT
- Filter table OUTPUT
- POSTROUTING - NAT and mangle tables for final packet modification
firewalld Rule Processing
Within the filter table INPUT chain, firewalld applies rules in this order:
- Direct Rules - Custom iptables rules added via firewalld
- Rich Rules - Complex rules with logging, limits, etc.
- Service Rules - Pre-defined service allow rules
- Port Rules - Explicitly allowed ports
- Zone Default Policy - ACCEPT or DROP based on zone
Managing Services: Add and Remove
Services are pre-defined collections of ports and protocols that make firewall management much simpler than specifying individual ports.
Working with Services
- 1 List Available Services
firewall-cmd --get-servicesThis shows all pre-defined services available in firewalld.
- 2 List Currently Allowed Services
firewall-cmd --list-servicesShows services allowed in the default zone.
- 3 Add a Service (Runtime)
firewall-cmd --add-service=httpThis allows HTTP traffic immediately but won't persist after reboot.
- 4 Add a Service (Permanent)
firewall-cmd --permanent --add-service=http firewall-cmd --reloadThe
--permanentflag makes the change persistent. You must reload to apply permanent changes to runtime. - 5 Remove a Service
firewall-cmd --permanent --remove-service=http firewall-cmd --reload
Practice Lab 2: Web Server Access
Configure your firewall to allow web server access:
# Check if http service is available
firewall-cmd --get-services | grep http
# Add http service permanently
sudo firewall-cmd --permanent --add-service=http
# Add https service permanently
sudo firewall-cmd --permanent --add-service=https
# Reload to apply changes
sudo firewall-cmd --reload
# Verify the services are active
firewall-cmd --list-servicesNow your web server should be accessible from external networks!
Real-World Scenario: Multi-Service Application
Deploy a web application that requires multiple services (web, database, monitoring):
# Allow web traffic
firewall-cmd --permanent --add-service={http,https}
# Allow database access from application servers only
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.10.0/24" port protocol="tcp" port="3306" accept'
# Allow monitoring (SNMP)
firewall-cmd --permanent --add-service=snmp
# Allow SSH for administration
firewall-cmd --permanent --add-service=ssh
# Apply all changes
firewall-cmd --reloadPort Forwarding and Masquerading
Port forwarding and masquerading (NAT) are essential for scenarios where you need to redirect traffic or share a single public IP among multiple internal systems.
Port Forwarding
Port forwarding redirects incoming traffic from one port to another port, either on the same machine or a different machine.
- 1 Enable Masquerading (Required for NAT)
firewall-cmd --permanent --add-masquerade firewall-cmd --reload - 2 Forward Local Port to Different Local Port
firewall-cmd --permanent --add-forward-port=port=80:proto=tcp:toport=12345This forwards incoming traffic on port 80 to port 12345 on the same machine.
- 3 Forward to Different Machine
firewall-cmd --permanent --add-forward-port=port=80:proto=tcp:toaddr=192.168.1.100:toport=80Forwards port 80 traffic to internal server 192.168.1.100 on port 80.
- 4 List Forward Ports
firewall-cmd --list-forward-ports - 5 Remove Forward Port
firewall-cmd --permanent --remove-forward-port=port=80:proto=tcp:toport=12345
Practice Lab 3: Application Port Forwarding
Your web application runs on port 12345, but you want it accessible on standard HTTP port 80:
# First, ensure your application is running on port 12345
# netstat -tlnp | grep 12345
# Enable masquerading for NAT functionality
sudo firewall-cmd --permanent --add-masquerade
# Forward port 80 to port 12345
sudo firewall-cmd --permanent --add-forward-port=port=80:proto=tcp:toport=12345
# Reload firewall
sudo firewall-cmd --reload
# Test by accessing http://your-server-ip (should reach your app on 12345)Practice Lab 4: Internal Web Server Access
Make an internal web server accessible from the internet through your firewall:
# Assume internal web server is at 192.168.1.50
# External traffic comes to your firewall's public IP
# Enable masquerading
sudo firewall-cmd --permanent --add-masquerade
# Forward external port 8080 to internal server port 80
sudo firewall-cmd --permanent --add-forward-port=port=8080:proto=tcp:toaddr=192.168.1.50:toport=80
# Also allow the forwarded port through the firewall
sudo firewall-cmd --permanent --add-port=8080/tcp
# Reload
sudo firewall-cmd --reloadNow external users can access http://your-public-ip:8080 to reach the internal web server.
Advanced Configuration with Rich Rules
Rich rules provide a powerful way to create complex firewall rules with conditions, logging, rate limiting, and more. They use an XML-like syntax that's much more readable than raw iptables commands.
Rich Rule Syntax
The basic syntax for rich rules is:
rule [family="ipv4|ipv6"] [source address="address[/mask]"] [destination address="address[/mask]"] [service name="service"] [port port="port" protocol="tcp|udp"] [log [prefix="prefix"] [level="level"]] [limit value="rate/duration"] [accept|reject|drop]Common Rich Rule Examples
- 1 Allow SSH from Specific IP Range
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" service name="ssh" accept' - 2 Rate Limit SSH Connections
firewall-cmd --permanent --add-rich-rule='rule service name="ssh" limit value="3/minute" accept'Allows only 3 SSH connections per minute, helping prevent brute force attacks.
- 3 Log and Drop Suspicious Traffic
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="203.0.113.0/24" port port="22" protocol="tcp" log prefix="SSH-ATTACK: " level="warning" drop' - 4 Time-Based Access Control
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.0.0/8" service name="http" log prefix="WEB-ACCESS: " accept'Note: firewalld doesn't support time-based rules natively. For time-based control, combine with cron jobs to enable/disable rules.
Advanced Lab: Comprehensive Security Policy
Implement a multi-layered security policy for a production web server:
# Allow HTTP/HTTPS from anywhere
firewall-cmd --permanent --add-service={http,https}
# Allow SSH only from admin network with rate limiting
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.10.0/24" service name="ssh" limit value="5/minute" accept'
# Block and log all other SSH attempts
firewall-cmd --permanent --add-rich-rule='rule service name="ssh" log prefix="BLOCKED-SSH: " level="warning" drop'
# Allow database access only from application servers
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.20.0/24" port port="3306" protocol="tcp" accept'
# Rate limit ping requests to prevent DoS
firewall-cmd --permanent --add-rich-rule='rule protocol value="icmp" limit value="1/second" accept'
# Block all other ICMP
firewall-cmd --permanent --add-rich-rule='rule protocol value="icmp" drop'
# Apply changes
firewall-cmd --reloadReal-World Scenario: E-commerce Security
Secure an e-commerce platform with multiple security layers:
# Web traffic (HTTP/HTTPS) - allow all
firewall-cmd --permanent --add-service={http,https}
# Admin access - restricted IP range only
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="203.0.113.100/32" service name="ssh" accept'
# Payment gateway communication - specific IP only
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="198.51.100.50/32" port port="443" protocol="tcp" accept'
# Database replication - internal network only
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.1.0/24" port port="3306" protocol="tcp" accept'
# Monitoring and backup servers
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="{10.0.2.10,10.0.2.11}" service name="rsync" accept'
# Log all dropped packets for security monitoring
firewall-cmd --permanent --set-log-denied=all
firewall-cmd --reloadBest Practices and Security Hardening
Security Best Practices
- Principle of Least Privilege - Only allow necessary services and ports
- Default Deny Policy - Use restrictive zones by default
- Regular Auditing - Periodically review firewall rules and remove unused ones
- Logging and Monitoring - Enable logging for denied packets and monitor logs
- Separation of Duties - Use different zones for different network segments
- Regular Updates - Keep firewalld and system updated
Performance Considerations
- Rule Ordering - Place most frequently matched rules first
- Avoid Overlapping Rules - Simplify rule sets to reduce processing overhead
- Use Services Instead of Ports - Services are more maintainable and readable
- Minimize Rich Rules - Use them only when simple service/port rules aren't sufficient
⚠️ Critical Security Notes
- Always test firewall changes in a non-production environment first
- Never lock yourself out - always have console access when making SSH rule changes
- Remember that firewalld rules are case-sensitive
- Permanent changes require
--reloadto take effect in runtime - Direct iptables commands can conflict with firewalld - avoid mixing them
Troubleshooting and Reference
🔧 Common Issues & Solutions
- Service not accessible after adding? → Check if you used
--permanentand ran--reload, verify the service is actually running - Port forwarding not working? → Ensure masquerading is enabled, check if the target service is running and accessible locally
- Rich rules not matching? → Check rule syntax carefully, remember rich rules are processed before service/port rules
- Can't connect after firewall changes? → Use console access to restore connectivity, check
firewall-cmd --list-allfor current configuration - firewalld service not running? → Start with
systemctl start firewalldand enable withsystemctl enable firewalld
📌 Comprehensive Command Reference
# Basic Status
firewall-cmd --state # Check if running
firewall-cmd --get-default-zone # Show default zone
firewall-cmd --get-active-zones # Show active zones
# Services
firewall-cmd --get-services # List all services
firewall-cmd --list-services # List allowed services
firewall-cmd --add-service=http # Add service (runtime)
firewall-cmd --permanent --add-service=http # Add service (permanent)
# Ports
firewall-cmd --add-port=8080/tcp # Add port (runtime)
firewall-cmd --permanent --add-port=8080/tcp # Add port (permanent)
firewall-cmd --list-ports # List allowed ports
# Rich Rules
firewall-cmd --list-rich-rules # List rich rules
firewall-cmd --add-rich-rule='rule...' # Add rich rule
# Port Forwarding
firewall-cmd --add-masquerade # Enable masquerading
firewall-cmd --add-forward-port=... # Add port forward
firewall-cmd --list-forward-ports # List port forwards
# Zones
firewall-cmd --get-zones # List all zones
firewall-cmd --zone=internal --list-all # Show zone details
# Configuration
firewall-cmd --reload # Reload configuration
firewall-cmd --runtime-to-permanent # Save runtime config to permanent📚 Additional Resources
man firewalld- Main firewalld documentationman firewalld.zone- Zone configuration documentationman firewalld.richlanguage- Rich rule syntax documentation/usr/lib/firewalld/services/- Location of service definition files/etc/firewalld/- Location of custom firewall configuration