How to block ip addresses with firewalld
How to Block IP Addresses with Firewalld
Firewalld is a powerful, dynamic firewall management tool that provides a flexible and user-friendly interface for managing network traffic on Linux systems. One of its most essential security features is the ability to block specific IP addresses, preventing potentially malicious traffic from reaching your system. This comprehensive guide will walk you through everything you need to know about blocking IP addresses using firewalld, from basic commands to advanced configurations and troubleshooting techniques.
Table of Contents
1. [Introduction to Firewalld](#introduction-to-firewalld)
2. [Prerequisites](#prerequisites)
3. [Understanding Firewalld Zones](#understanding-firewalld-zones)
4. [Basic IP Blocking Commands](#basic-ip-blocking-commands)
5. [Advanced IP Blocking Techniques](#advanced-ip-blocking-techniques)
6. [Managing Blocked IP Lists](#managing-blocked-ip-lists)
7. [Practical Examples and Use Cases](#practical-examples-and-use-cases)
8. [Troubleshooting Common Issues](#troubleshooting-common-issues)
9. [Best Practices and Security Tips](#best-practices-and-security-tips)
10. [Monitoring and Logging](#monitoring-and-logging)
11. [Conclusion](#conclusion)
Introduction to Firewalld
Firewalld serves as a frontend for the Linux kernel's netfilter framework, providing dynamic firewall management with support for network zones, services, and rich rules. Unlike traditional iptables configurations that require complete rule reloads, firewalld allows for real-time rule modifications without interrupting existing connections.
The ability to block IP addresses is crucial for system security, helping administrators prevent access from known malicious sources, reduce brute-force attacks, and maintain network integrity. Whether you're dealing with automated bot attacks, suspicious scanning activities, or specific security threats, firewalld provides multiple methods to effectively block unwanted IP addresses.
Prerequisites
Before proceeding with IP blocking configurations, ensure you have the following requirements in place:
System Requirements
- Linux distribution with firewalld installed (RHEL, CentOS, Fedora, Ubuntu 18.04+, Debian 10+)
- Root or sudo privileges for firewall modifications
- Basic understanding of networking concepts and IP addressing
- SSH or console access to the target system
Installing Firewalld
If firewalld is not already installed on your system, use the following commands:
For RHEL/CentOS/Fedora:
```bash
sudo dnf install firewalld
or for older systems
sudo yum install firewalld
```
For Ubuntu/Debian:
```bash
sudo apt update
sudo apt install firewalld
```
Starting and Enabling Firewalld
Ensure firewalld is running and enabled to start automatically:
```bash
sudo systemctl start firewalld
sudo systemctl enable firewalld
sudo systemctl status firewalld
```
Understanding Firewalld Zones
Firewalld organizes network interfaces and traffic into zones, each with predefined security levels and rules. Understanding zones is essential for effective IP blocking:
Default Zones
- drop: Drops all incoming connections without notification
- block: Rejects all incoming connections with icmp-host-prohibited message
- public: Default zone for public networks with limited trust
- external: For external networks with masquerading enabled
- dmz: Demilitarized zone with limited internal network access
- work: Trusted work environment with more services allowed
- home: Home networks with additional services permitted
- internal: Internal networks with high trust levels
- trusted: All network connections are accepted
Checking Current Zone Configuration
```bash
View active zones
sudo firewall-cmd --get-active-zones
Check default zone
sudo firewall-cmd --get-default-zone
List all available zones
sudo firewall-cmd --get-zones
```
Basic IP Blocking Commands
Blocking a Single IP Address
The most straightforward method to block an IP address is using the `--add-rich-rule` option:
```bash
Block a specific IP address
sudo firewall-cmd --add-rich-rule="rule family='ipv4' source address='192.168.1.100' reject"
Make the rule permanent
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='192.168.1.100' reject"
```
Alternative Method Using Direct Rules
For more granular control, you can use direct iptables rules:
```bash
Block IP using direct rule
sudo firewall-cmd --direct --add-rule ipv4 filter INPUT 0 -s 192.168.1.100 -j DROP
Make it permanent
sudo firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT 0 -s 192.168.1.100 -j DROP
```
Blocking IP Ranges and Subnets
Block entire network ranges using CIDR notation:
```bash
Block an entire subnet
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='192.168.1.0/24' reject"
Block a smaller range
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='10.0.0.0/16' drop"
```
IPv6 Address Blocking
Firewalld also supports IPv6 address blocking:
```bash
Block IPv6 address
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv6' source address='2001:db8::1' reject"
Block IPv6 subnet
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv6' source address='2001:db8::/32' drop"
```
Advanced IP Blocking Techniques
Time-Based IP Blocking
Create rules that block IPs for specific time periods:
```bash
Block IP for 1 hour (3600 seconds)
sudo firewall-cmd --add-rich-rule="rule family='ipv4' source address='192.168.1.100' reject" --timeout=3600
```
Port-Specific IP Blocking
Block IPs only for specific services or ports:
```bash
Block IP from accessing SSH (port 22)
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='192.168.1.100' port protocol='tcp' port='22' reject"
Block IP from accessing HTTP and HTTPS
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='192.168.1.100' port protocol='tcp' port='80' reject"
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='192.168.1.100' port protocol='tcp' port='443' reject"
```
Creating Custom IP Blacklist Zones
Create a dedicated zone for blocked IPs:
```bash
Create a new zone for blocked IPs
sudo firewall-cmd --permanent --new-zone=blacklist
Set the zone target to DROP
sudo firewall-cmd --permanent --zone=blacklist --set-target=DROP
Add IPs to the blacklist zone
sudo firewall-cmd --permanent --zone=blacklist --add-source=192.168.1.100
sudo firewall-cmd --permanent --zone=blacklist --add-source=10.0.0.0/24
Reload firewall to apply changes
sudo firewall-cmd --reload
```
Using IP Sets for Large Block Lists
For blocking numerous IP addresses efficiently, use ipsets:
```bash
Install ipset if not available
sudo dnf install ipset # or apt install ipset
Create an ipset for blocked IPs
sudo ipset create blocked_ips hash:ip
Add IPs to the set
sudo ipset add blocked_ips 192.168.1.100
sudo ipset add blocked_ips 192.168.1.101
sudo ipset add blocked_ips 192.168.1.102
Create firewall rule using the ipset
sudo firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT 0 -m set --match-set blocked_ips src -j DROP
Reload firewall
sudo firewall-cmd --reload
```
Managing Blocked IP Lists
Viewing Currently Blocked IPs
```bash
List all rich rules (includes IP blocks)
sudo firewall-cmd --list-rich-rules
List rules for a specific zone
sudo firewall-cmd --zone=public --list-rich-rules
View direct rules
sudo firewall-cmd --direct --get-all-rules
```
Removing IP Blocks
```bash
Remove a rich rule block
sudo firewall-cmd --remove-rich-rule="rule family='ipv4' source address='192.168.1.100' reject"
Remove permanent rule
sudo firewall-cmd --permanent --remove-rich-rule="rule family='ipv4' source address='192.168.1.100' reject"
Remove direct rule
sudo firewall-cmd --direct --remove-rule ipv4 filter INPUT 0 -s 192.168.1.100 -j DROP
```
Bulk IP Management Script
Create a script for managing multiple IP addresses:
```bash
#!/bin/bash
ip_manager.sh - Script for bulk IP blocking
BLOCKED_IPS_FILE="/etc/firewalld/blocked_ips.txt"
block_ip() {
local ip=$1
echo "Blocking IP: $ip"
firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='$ip' reject"
echo $ip >> $BLOCKED_IPS_FILE
}
unblock_ip() {
local ip=$1
echo "Unblocking IP: $ip"
firewall-cmd --permanent --remove-rich-rule="rule family='ipv4' source address='$ip' reject"
sed -i "/$ip/d" $BLOCKED_IPS_FILE
}
case "$1" in
block)
block_ip $2
firewall-cmd --reload
;;
unblock)
unblock_ip $2
firewall-cmd --reload
;;
list)
firewall-cmd --list-rich-rules | grep "source address"
;;
*)
echo "Usage: $0 {block|unblock|list} [IP_ADDRESS]"
exit 1
;;
esac
```
Practical Examples and Use Cases
Example 1: Blocking Brute Force Attacks
Implement automatic IP blocking for failed SSH attempts using fail2ban integration:
```bash
Install fail2ban
sudo dnf install fail2ban # or apt install fail2ban
Create fail2ban configuration for firewalld
sudo tee /etc/fail2ban/jail.local << EOF
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
backend = systemd
banaction = firewalld-rich-rule[actiontype=]
[sshd]
enabled = true
port = ssh
logpath = %(sshd_log)s
maxretry = 3
EOF
Start and enable fail2ban
sudo systemctl start fail2ban
sudo systemctl enable fail2ban
```
Example 2: Blocking Known Malicious Networks
Block commonly abused IP ranges:
```bash
Block known malicious networks
MALICIOUS_NETWORKS=(
"185.220.100.0/22" # Tor exit nodes range
"198.98.50.0/24" # Known spam network
"103.224.182.0/24" # Malicious bot network
)
for network in "${MALICIOUS_NETWORKS[@]}"; do
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='$network' drop"
echo "Blocked network: $network"
done
sudo firewall-cmd --reload
```
Example 3: Geo-blocking by Country
Block entire countries using IP range lists:
```bash
Download country IP ranges (example for a specific country)
Note: Use reputable sources for IP geolocation data
wget -O country_ips.txt "https://www.ipdeny.com/ipblocks/data/countries/cn.zone"
Block all IPs from the list
while read -r network; do
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='$network' drop"
done < country_ips.txt
sudo firewall-cmd --reload
```
Example 4: Temporary Emergency Blocking
Quickly block suspicious IPs during an active attack:
```bash
#!/bin/bash
emergency_block.sh - Quick IP blocking script
SUSPICIOUS_IPS=(
"203.0.113.100"
"198.51.100.50"
"192.0.2.25"
)
echo "Emergency IP blocking initiated..."
for ip in "${SUSPICIOUS_IPS[@]}"; do
# Immediate temporary block (1 hour)
firewall-cmd --add-rich-rule="rule family='ipv4' source address='$ip' drop" --timeout=3600
echo "Temporarily blocked: $ip"
done
echo "Emergency blocking complete. Rules expire in 1 hour."
echo "Review and make permanent if necessary."
```
Troubleshooting Common Issues
Issue 1: Rules Not Taking Effect
Problem: IP blocking rules appear to be added but don't work.
Solutions:
```bash
Check if firewalld is running
sudo systemctl status firewalld
Reload firewall configuration
sudo firewall-cmd --reload
Check for conflicting rules
sudo firewall-cmd --list-all
Verify rule syntax
sudo firewall-cmd --check-config
```
Issue 2: Accidentally Blocking Legitimate Traffic
Problem: Legitimate users cannot access services after implementing IP blocks.
Solutions:
```bash
Temporarily disable firewalld for testing
sudo systemctl stop firewalld
Check current active rules
sudo firewall-cmd --list-all-zones
Remove specific problematic rule
sudo firewall-cmd --remove-rich-rule="rule family='ipv4' source address='PROBLEMATIC_IP' reject"
Add whitelist rule for important IPs
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='TRUSTED_IP' accept"
```
Issue 3: Performance Issues with Large IP Lists
Problem: System performance degrades with numerous IP blocking rules.
Solutions:
```bash
Use ipsets for better performance
sudo ipset create large_blocklist hash:net maxelem 1000000
Load IPs from file into ipset
while read network; do
sudo ipset add large_blocklist $network
done < large_ip_list.txt
Create single firewall rule for the entire set
sudo firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT 0 -m set --match-set large_blocklist src -j DROP
```
Issue 4: IPv6 Blocking Not Working
Problem: IPv6 addresses bypass blocking rules.
Solutions:
```bash
Ensure IPv6 is enabled in firewalld
sudo firewall-cmd --get-ipv6
Add IPv6 specific rules
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv6' source address='2001:db8::1' reject"
Block IPv6 entirely if not needed
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv6' drop"
```
Issue 5: Persistent Configuration Problems
Problem: Rules disappear after system reboot.
Solutions:
```bash
Always use --permanent flag for persistent rules
sudo firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='IP' reject"
Check permanent configuration
sudo firewall-cmd --permanent --list-all
Ensure firewalld starts at boot
sudo systemctl enable firewalld
Verify permanent rules location
ls -la /etc/firewalld/zones/
```
Best Practices and Security Tips
1. Implement Layered Security
Don't rely solely on IP blocking for security:
```bash
Combine IP blocking with other security measures
Change default SSH port
sudo firewall-cmd --permanent --remove-service=ssh
sudo firewall-cmd --permanent --add-port=2222/tcp
Implement rate limiting
sudo firewall-cmd --permanent --add-rich-rule="rule service name='ssh' accept limit value='3/m'"
```
2. Regular Rule Maintenance
Establish a routine for reviewing and cleaning up IP blocking rules:
```bash
#!/bin/bash
rule_maintenance.sh - Regular firewall maintenance
Backup current configuration
sudo firewall-cmd --permanent --export=/backup/firewall-$(date +%Y%m%d).xml
Review active rules
echo "Current rich rules:"
sudo firewall-cmd --list-rich-rules
Check for duplicate rules
echo "Checking for duplicates..."
sudo firewall-cmd --list-rich-rules | sort | uniq -d
```
3. Documentation and Logging
Maintain detailed records of blocked IPs and reasons:
```bash
Create blocking log entry
log_ip_block() {
local ip=$1
local reason=$2
echo "$(date): Blocked $ip - Reason: $reason" >> /var/log/firewall_blocks.log
}
Usage example
log_ip_block "192.168.1.100" "Brute force SSH attempts"
```
4. Whitelist Critical IPs
Always maintain a whitelist of essential IP addresses:
```bash
Create whitelist zone
sudo firewall-cmd --permanent --new-zone=whitelist
sudo firewall-cmd --permanent --zone=whitelist --set-target=ACCEPT
Add critical management IPs
MANAGEMENT_IPS=(
"10.0.0.100" # Admin workstation
"203.0.113.10" # Monitoring server
"198.51.100.5" # Backup server
)
for ip in "${MANAGEMENT_IPS[@]}"; do
sudo firewall-cmd --permanent --zone=whitelist --add-source=$ip
done
```
5. Monitor and Alert
Implement monitoring for blocked traffic:
```bash
Monitor dropped packets
sudo journalctl -u firewalld -f | grep -i "drop\|reject"
Create alert script for excessive blocking
#!/bin/bash
block_monitor.sh
THRESHOLD=100
CURRENT_BLOCKS=$(firewall-cmd --list-rich-rules | wc -l)
if [ $CURRENT_BLOCKS -gt $THRESHOLD ]; then
echo "Warning: High number of blocked IPs ($CURRENT_BLOCKS)" | mail -s "Firewall Alert" admin@company.com
fi
```
Monitoring and Logging
Enabling Detailed Logging
Configure firewalld to log blocked connections:
```bash
Enable logging for dropped packets
sudo firewall-cmd --set-log-denied=all
Check current logging setting
sudo firewall-cmd --get-log-denied
View logs
sudo journalctl -u firewalld | grep -i "drop\|reject"
```
Creating Custom Log Analysis
Develop scripts to analyze firewall logs:
```bash
#!/bin/bash
log_analyzer.sh - Analyze firewall blocking patterns
LOG_FILE="/var/log/messages"
REPORT_FILE="/tmp/firewall_report.txt"
echo "Firewall Blocking Report - $(date)" > $REPORT_FILE
echo "=================================" >> $REPORT_FILE
Top blocked IPs
echo "Top 10 Blocked IPs:" >> $REPORT_FILE
grep "REJECT\|DROP" $LOG_FILE | awk '{print $13}' | sort | uniq -c | sort -rn | head -10 >> $REPORT_FILE
Blocking by hour
echo -e "\nBlocking Activity by Hour:" >> $REPORT_FILE
grep "REJECT\|DROP" $LOG_FILE | awk '{print $3}' | cut -d: -f1 | sort | uniq -c >> $REPORT_FILE
cat $REPORT_FILE
```
Integration with SIEM Systems
Export firewall data for security information and event management:
```bash
Export firewall rules in structured format
sudo firewall-cmd --list-all --zone=public | tee /var/log/firewall_config.log
Create JSON export for SIEM integration
#!/bin/bash
siem_export.sh
OUTPUT_FILE="/var/log/firewall_blocks.json"
{
echo "{"
echo " \"timestamp\": \"$(date -Iseconds)\","
echo " \"blocked_ips\": ["
firewall-cmd --list-rich-rules | grep "source address" | while read rule; do
ip=$(echo $rule | grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}')
echo " \"$ip\","
done | sed '$s/,$//'
echo " ]"
echo "}"
} > $OUTPUT_FILE
```
Conclusion
Blocking IP addresses with firewalld is a fundamental security practice that helps protect Linux systems from various threats. This comprehensive guide has covered everything from basic IP blocking commands to advanced techniques including zone management, automated blocking systems, and integration with monitoring tools.
Key takeaways from this guide include:
1. Multiple Blocking Methods: Firewalld offers several approaches to IP blocking, from simple rich rules to advanced ipset integration, allowing administrators to choose the most appropriate method for their specific needs.
2. Zone-Based Management: Understanding and utilizing firewalld zones provides better organization and management of network security policies.
3. Automation and Scripting: Implementing automated blocking systems and maintenance scripts significantly improves security posture while reducing administrative overhead.
4. Performance Considerations: For large-scale IP blocking, using ipsets and optimized rule structures ensures system performance remains unaffected.
5. Monitoring and Maintenance: Regular review, logging, and analysis of blocked traffic helps maintain an effective and current security policy.
Remember that IP blocking should be part of a comprehensive security strategy that includes regular system updates, strong authentication mechanisms, intrusion detection systems, and security monitoring. While effective against many threats, IP blocking alone cannot provide complete protection against sophisticated attacks that may use multiple IP addresses or legitimate compromised systems.
As you implement these techniques in your environment, always test changes in a controlled manner, maintain proper documentation, and ensure you have alternative access methods available to prevent accidental lockouts. Regular review and updates of your IP blocking policies will help maintain their effectiveness against evolving security threats.
For continued learning, consider exploring advanced firewalld features such as custom services, complex rich rule configurations, and integration with other security tools to build a robust and comprehensive network security infrastructure.