Setting up a firewall with UFW and using Fail2Ban adds a strong layer of security to your Linux server. UFW blocks all incoming traffic by default and only allows essential connections like SSH, HTTP, and HTTPS, minimizing exposure to threats. Fail2Ban complements this by monitoring login attempts and automatically banning IPs that fail repeatedly, helping to prevent brute-force attacks. With proper configurationโsuch as a 7-day ban after multiple failed attemptsโyour server becomes far more resilient against unauthorized access and common exploits.
Table of Contents
โ Step 1: Configure UFW (Uncomplicated Firewall)
UFW is a simple way to manage firewall rules on Ubuntu-based servers. To start securing your server:
sudo ufw default deny incoming # Block all incoming traffic by default
sudo ufw default allow outgoing # Allow all outgoing traffic
Next, allow only essential ports:
sudo ufw allow ssh # Allow SSH (usually port 22)
sudo ufw allow http # Allow HTTP (port 80)
sudo ufw allow https # Allow HTTPS (port 443)
Then enable the firewall and check status:
sudo ufw enable
sudo ufw status verbose
๐ Step 2: Install and Configure Fail2Ban
Fail2Ban protects your server from brute-force attacks (like repeated SSH login attempts). Install and configure it with:
sudo apt install fail2ban
cd /etc/fail2ban
sudo cp jail.conf jail.local
sudo vi jail.local
Inside jail.local
, update/add these settings:
bantime = 604800s # Ban IP for 7 days
findtime = 10800s # Search window (3 hours)
maxretry = 6 # Max failed attempts before ban
[sshd]
enabled = true
mode = aggressive # More strict detection
Then restart the service:
sudo systemctl restart fail2ban
๐ View Logs and Unban IPs
To monitor bans:
cd /var/log
cat fail2ban.log
To unban a specific IP (e.g., if you accidentally blocked yourself):
sudo fail2ban-client set sshd unbanip 192.168.1.11
