How to use firewalld → firewall-cmd --add-service=ssh --permanent; --reload; --list-all

How to Use Firewalld: Complete Guide to Managing SSH Service with firewall-cmd Commands Table of Contents 1. [Introduction](#introduction) 2. [Prerequisites](#prerequisites) 3. [Understanding Firewalld and SSH Service](#understanding-firewalld-and-ssh-service) 4. [Step-by-Step Guide to Adding SSH Service](#step-by-step-guide-to-adding-ssh-service) 5. [Command Breakdown and Explanations](#command-breakdown-and-explanations) 6. [Practical Examples and Use Cases](#practical-examples-and-use-cases) 7. [Verification and Testing](#verification-and-testing) 8. [Troubleshooting Common Issues](#troubleshooting-common-issues) 9. [Advanced Firewalld Management](#advanced-firewalld-management) 10. [Best Practices and Security Considerations](#best-practices-and-security-considerations) 11. [Alternative Methods and Commands](#alternative-methods-and-commands) 12. [Conclusion](#conclusion) Introduction Firewalld is a dynamic firewall management tool for Linux systems that provides a powerful interface for managing network traffic rules. One of the most common tasks when configuring a Linux server is ensuring SSH (Secure Shell) access is properly configured through the firewall. This comprehensive guide will walk you through the essential firewall-cmd commands for adding, managing, and verifying SSH service rules in firewalld. By the end of this article, you'll understand how to use the key firewall-cmd commands: `--add-service=ssh --permanent`, `--reload`, and `--list-all` to effectively manage SSH access through your firewall. Whether you're a system administrator, DevOps engineer, or Linux enthusiast, mastering these commands is crucial for maintaining secure and accessible server environments. Prerequisites Before diving into firewalld configuration, ensure you have the following: System Requirements - A Linux system with firewalld installed (RHEL, CentOS, Fedora, or compatible distribution) - Root or sudo privileges - Basic understanding of Linux command line - SSH service installed and configured on your system Checking Firewalld Status First, verify that firewalld is installed and running on your system: ```bash Check if firewalld is installed sudo dnf list installed firewalld or for older systems sudo yum list installed firewalld Check firewalld service status sudo systemctl status firewalld Start firewalld if not running sudo systemctl start firewalld Enable firewalld to start at boot sudo systemctl enable firewalld ``` Verifying SSH Service Ensure SSH service is installed and running: ```bash Check SSH service status sudo systemctl status sshd Start SSH service if needed sudo systemctl start sshd Enable SSH to start at boot sudo systemctl enable sshd ``` Understanding Firewalld and SSH Service What is Firewalld? Firewalld is a firewall management tool that acts as a front-end for the Linux kernel's netfilter framework. Unlike traditional iptables configurations, firewalld provides: - Dynamic management: Rules can be changed without restarting the service - Zone-based configuration: Different trust levels for different network connections - Service-based rules: Predefined configurations for common services - Runtime and permanent configurations: Temporary and persistent rule management SSH Service in Firewalld Context SSH (Secure Shell) is a network protocol that provides secure remote access to Linux systems. In firewalld, SSH is defined as a predefined service that includes: - Default port: 22/tcp - Protocol: TCP - Service definition: Located in `/usr/lib/firewalld/services/ssh.xml` When you add the SSH service to firewalld, you're essentially allowing inbound connections on port 22 using the TCP protocol. Step-by-Step Guide to Adding SSH Service Step 1: Adding SSH Service Permanently The first command in our sequence adds the SSH service to the firewall configuration permanently: ```bash sudo firewall-cmd --add-service=ssh --permanent ``` What this command does: - `--add-service=ssh`: Adds the predefined SSH service to the firewall rules - `--permanent`: Makes the change persistent across reboots - The command modifies the permanent configuration but doesn't affect the current runtime Expected output: ``` success ``` Step 2: Reloading Firewalld Configuration After making permanent changes, you need to reload the firewall configuration: ```bash sudo firewall-cmd --reload ``` What this command does: - Applies all permanent configuration changes to the runtime configuration - Reloads firewalld without disrupting existing connections - Makes the SSH service addition active immediately Expected output: ``` success ``` Step 3: Verifying the Configuration Finally, verify that the SSH service has been successfully added: ```bash sudo firewall-cmd --list-all ``` What this command does: - Displays the complete configuration of the default zone - Shows all active services, ports, and rules - Provides a comprehensive overview of current firewall settings Expected output example: ``` public (active) target: default icmp-block-inversion: no interfaces: eth0 sources: services: cockpit dhcpv6-client ssh ports: protocols: masquerade: no forward-ports: source-ports: icmp-blocks: rich-rules: ``` Command Breakdown and Explanations The --add-service Parameter The `--add-service` parameter is used to add predefined services to firewalld zones. Services are XML configuration files that define: ```xml SSH Secure Shell (SSH) is a protocol for logging into and executing commands on remote machines. ``` Available services can be listed with: ```bash sudo firewall-cmd --get-services ``` The --permanent Flag Understanding the difference between runtime and permanent configurations is crucial: Runtime Configuration: - Active immediately - Lost when firewalld restarts or system reboots - Used for temporary testing Permanent Configuration: - Saved to disk in XML files - Survives reboots and service restarts - Requires reload to become active Examples: ```bash Add SSH temporarily (runtime only) sudo firewall-cmd --add-service=ssh Add SSH permanently (requires reload) sudo firewall-cmd --add-service=ssh --permanent Add SSH to both runtime and permanent sudo firewall-cmd --add-service=ssh --permanent sudo firewall-cmd --add-service=ssh ``` The --reload Command The reload operation is essential for applying permanent changes: ```bash Standard reload sudo firewall-cmd --reload Complete reload (more thorough, may briefly interrupt connections) sudo firewall-cmd --complete-reload ``` When to use reload: - After making permanent configuration changes - When permanent and runtime configurations are out of sync - After editing firewalld configuration files manually The --list-all Command This command provides comprehensive zone information: ```bash List default zone configuration sudo firewall-cmd --list-all List specific zone configuration sudo firewall-cmd --zone=public --list-all List all zones sudo firewall-cmd --list-all-zones ``` Practical Examples and Use Cases Example 1: Basic SSH Service Addition Complete workflow for enabling SSH access on a new server: ```bash Check current configuration sudo firewall-cmd --list-all Add SSH service permanently sudo firewall-cmd --add-service=ssh --permanent Reload to apply changes sudo firewall-cmd --reload Verify the configuration sudo firewall-cmd --list-all Test SSH connectivity ssh username@server-ip ``` Example 2: SSH with Custom Port If SSH is running on a non-standard port, you have several options: Option 1: Add custom port ```bash Add custom SSH port (e.g., 2222) sudo firewall-cmd --add-port=2222/tcp --permanent sudo firewall-cmd --reload ``` Option 2: Create custom service ```bash Copy existing SSH service definition sudo cp /usr/lib/firewalld/services/ssh.xml /etc/firewalld/services/ssh-custom.xml Edit the custom service file sudo vi /etc/firewalld/services/ssh-custom.xml Change port from 22 to your custom port Add the custom service sudo firewall-cmd --add-service=ssh-custom --permanent sudo firewall-cmd --reload ``` Example 3: Zone-Specific SSH Configuration Configure SSH for specific zones: ```bash Add SSH to work zone sudo firewall-cmd --zone=work --add-service=ssh --permanent Add SSH to home zone sudo firewall-cmd --zone=home --add-service=ssh --permanent Remove SSH from public zone (if needed) sudo firewall-cmd --zone=public --remove-service=ssh --permanent Reload configuration sudo firewall-cmd --reload Verify each zone sudo firewall-cmd --zone=work --list-all sudo firewall-cmd --zone=home --list-all sudo firewall-cmd --zone=public --list-all ``` Example 4: Temporary SSH Access Grant temporary SSH access for testing: ```bash Add SSH temporarily (runtime only) sudo firewall-cmd --add-service=ssh Verify it's active sudo firewall-cmd --list-services Remove temporary access sudo firewall-cmd --remove-service=ssh Or wait for firewall reload/restart to remove it automatically ``` Verification and Testing Comprehensive Verification Steps After configuring SSH service, perform these verification steps: 1. Check Service Status: ```bash Verify SSH service is in the configuration sudo firewall-cmd --list-services | grep ssh Check if SSH port is open sudo firewall-cmd --list-ports sudo ss -tlnp | grep :22 ``` 2. Test Local Connectivity: ```bash Test SSH connection locally ssh localhost Test with verbose output for troubleshooting ssh -v username@localhost ``` 3. Test Remote Connectivity: ```bash From another machine, test SSH connection ssh username@target-server-ip Test with specific port if using custom port ssh -p 2222 username@target-server-ip ``` 4. Check Firewall Logs: ```bash Monitor firewall logs sudo journalctl -u firewalld -f Check for denied connections sudo journalctl | grep -i denied ``` Network Scanning Verification Use network tools to verify SSH port accessibility: ```bash Install nmap if not available sudo dnf install nmap Scan SSH port from external machine nmap -p 22 target-server-ip Detailed scan with service detection nmap -sV -p 22 target-server-ip ``` Troubleshooting Common Issues Issue 1: SSH Service Not Working After Configuration Symptoms: - SSH connections are refused or timeout - Service appears in firewall configuration but connections fail Troubleshooting steps: ```bash Check if SSH daemon is running sudo systemctl status sshd Verify SSH is listening on the correct port sudo ss -tlnp | grep sshd Check SSH configuration sudo sshd -t Verify firewall configuration sudo firewall-cmd --list-all Check for conflicting iptables rules sudo iptables -L -n ``` Solutions: ```bash Restart SSH service sudo systemctl restart sshd Ensure firewall changes are applied sudo firewall-cmd --reload If using SELinux, check contexts sudo sealert -a /var/log/audit/audit.log ``` Issue 2: Permission Denied After Firewall Changes Symptoms: - SSH connections result in "Permission denied" errors - Authentication failures after firewall modification Troubleshooting: ```bash Check SSH logs sudo journalctl -u sshd Verify SSH configuration syntax sudo sshd -T Check file permissions ls -la ~/.ssh/ ls -la /etc/ssh/ Test with password authentication ssh -o PreferredAuthentications=password username@server ``` Issue 3: Firewall Rules Not Persisting Symptoms: - SSH access lost after reboot - Permanent rules not saved correctly Solutions: ```bash Verify permanent configuration sudo firewall-cmd --permanent --list-all Check configuration files ls -la /etc/firewalld/zones/ Ensure firewalld is enabled sudo systemctl enable firewalld Manually save runtime configuration sudo firewall-cmd --runtime-to-permanent ``` Issue 4: Zone Configuration Problems Symptoms: - SSH works in some networks but not others - Inconsistent connectivity based on source Diagnosis: ```bash Check active zones sudo firewall-cmd --get-active-zones Verify interface assignments sudo firewall-cmd --get-zone-of-interface=eth0 List all zone configurations sudo firewall-cmd --list-all-zones | grep -A 10 ssh ``` Resolution: ```bash Set default zone if needed sudo firewall-cmd --set-default-zone=public Add SSH to specific zones sudo firewall-cmd --zone=public --add-service=ssh --permanent sudo firewall-cmd --reload ``` Advanced Firewalld Management Rich Rules for SSH For more granular control, use rich rules: ```bash Allow SSH from specific IP sudo firewall-cmd --add-rich-rule='rule family="ipv4" source address="192.168.1.100" service name="ssh" accept' --permanent Allow SSH from specific subnet sudo firewall-cmd --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" service name="ssh" accept' --permanent Deny SSH from specific IP sudo firewall-cmd --add-rich-rule='rule family="ipv4" source address="10.0.0.50" service name="ssh" reject' --permanent Apply changes sudo firewall-cmd --reload ``` SSH Rate Limiting Implement rate limiting for SSH connections: ```bash Limit SSH connections (10 connections per minute from same source) sudo firewall-cmd --add-rich-rule='rule service name="ssh" accept limit value="10/m"' --permanent More complex rate limiting with logging sudo firewall-cmd --add-rich-rule='rule service name="ssh" log prefix="SSH-ATTEMPT" level="info" limit value="3/m" accept' --permanent sudo firewall-cmd --reload ``` Multiple SSH Services Configure multiple SSH services for different purposes: ```bash Create admin SSH service on port 2222 sudo cp /usr/lib/firewalld/services/ssh.xml /etc/firewalld/services/ssh-admin.xml Edit the service file sudo sed -i 's/port="22"/port="2222"/' /etc/firewalld/services/ssh-admin.xml sudo sed -i 's/SSH<\/short>/SSH-Admin<\/short>/' /etc/firewalld/services/ssh-admin.xml Add both services sudo firewall-cmd --add-service=ssh --permanent sudo firewall-cmd --add-service=ssh-admin --permanent sudo firewall-cmd --reload ``` Best Practices and Security Considerations Security Best Practices 1. Principle of Least Privilege: ```bash Only allow SSH where necessary sudo firewall-cmd --zone=internal --add-service=ssh --permanent sudo firewall-cmd --zone=public --remove-service=ssh --permanent ``` 2. Source-Based Restrictions: ```bash Restrict SSH to management networks sudo firewall-cmd --add-rich-rule='rule family="ipv4" source address="10.0.0.0/8" service name="ssh" accept' --permanent sudo firewall-cmd --add-rich-rule='rule service name="ssh" reject' --permanent ``` 3. Regular Configuration Audits: ```bash Create audit script cat << 'EOF' > /usr/local/bin/firewall-audit.sh #!/bin/bash echo "=== Firewall Configuration Audit ===" echo "Date: $(date)" echo "Active Zones:" firewall-cmd --get-active-zones echo "SSH Services:" firewall-cmd --list-all | grep -E "(services|ssh)" echo "Rich Rules:" firewall-cmd --list-rich-rules EOF chmod +x /usr/local/bin/firewall-audit.sh ``` Performance Considerations 1. Optimize Rule Order: - Place most common rules first - Use specific rules before general ones - Monitor firewall performance impact 2. Zone Management: ```bash Use appropriate zones for different interfaces sudo firewall-cmd --zone=dmz --change-interface=eth0 --permanent sudo firewall-cmd --zone=internal --change-interface=eth1 --permanent ``` Backup and Recovery 1. Backup Firewall Configuration: ```bash Create backup directory sudo mkdir -p /backup/firewalld Backup configuration files sudo cp -r /etc/firewalld/ /backup/firewalld/$(date +%Y%m%d) Create configuration export sudo firewall-cmd --list-all-zones > /backup/firewall-config-$(date +%Y%m%d).txt ``` 2. Recovery Procedures: ```bash Restore from backup sudo systemctl stop firewalld sudo cp -r /backup/firewalld/20231201/* /etc/firewalld/ sudo systemctl start firewalld ``` Alternative Methods and Commands Using firewall-config GUI For users who prefer graphical interfaces: ```bash Install GUI tool sudo dnf install firewall-config Launch GUI sudo firewall-config ``` Direct iptables Integration For advanced users who need direct iptables access: ```bash Add direct iptables rule sudo firewall-cmd --direct --add-rule ipv4 filter INPUT 0 -p tcp --dport 22 -j ACCEPT --permanent List direct rules sudo firewall-cmd --direct --get-all-rules ``` Scripted Management Create scripts for consistent firewall management: ```bash #!/bin/bash ssh-firewall-setup.sh set -e Configuration variables SSH_SERVICE="ssh" ZONE="public" ALLOWED_NETWORKS=("192.168.1.0/24" "10.0.0.0/8") Function to add SSH service setup_ssh_firewall() { echo "Configuring SSH firewall rules..." # Add SSH service to specified zone firewall-cmd --zone="$ZONE" --add-service="$SSH_SERVICE" --permanent # Add network-specific rules if defined for network in "${ALLOWED_NETWORKS[@]}"; do firewall-cmd --add-rich-rule="rule family='ipv4' source address='$network' service name='$SSH_SERVICE' accept" --permanent done # Reload configuration firewall-cmd --reload # Verify configuration echo "SSH firewall configuration complete:" firewall-cmd --zone="$ZONE" --list-all } Execute setup setup_ssh_firewall ``` Conclusion Mastering firewalld and the essential firewall-cmd commands for SSH management is crucial for maintaining secure Linux systems. The three key commands covered in this guide—`firewall-cmd --add-service=ssh --permanent`, `firewall-cmd --reload`, and `firewall-cmd --list-all`—form the foundation of SSH firewall management. Key Takeaways 1. Always use --permanent for persistent configurations that survive reboots 2. Remember to --reload after making permanent changes to apply them immediately 3. Regularly verify your configuration with --list-all to ensure rules are active 4. Test connectivity after making firewall changes to avoid lockouts 5. Implement security best practices including source restrictions and rate limiting 6. Maintain backups of your firewall configuration for recovery scenarios Next Steps After mastering basic SSH firewall management, consider exploring: - Advanced zone configurations for multi-interface systems - Rich rules for complex access control requirements - Integration with configuration management tools like Ansible - Monitoring and alerting for firewall rule violations - Automated backup and disaster recovery procedures Final Security Reminder Always maintain alternative access methods (console access, out-of-band management) when modifying firewall rules for SSH services. Test changes in non-production environments first, and ensure you have proper backup and recovery procedures in place. By following the practices and procedures outlined in this guide, you'll be well-equipped to manage SSH access through firewalld effectively and securely. Remember that firewall configuration is just one component of a comprehensive security strategy, and should be combined with other security measures such as proper SSH configuration, regular system updates, and monitoring. The commands and techniques covered here provide a solid foundation for firewalld management, but continue learning and staying updated with the latest security practices to maintain robust system security in evolving threat landscapes.