Security & Firewalls Beginner 15 min

How to Secure an Ubuntu Server with UFW Firewall and Fail2ban

Protect Linux servers from automated dictionary attacks, unauthorized ports, and malicious SSH brute force

IndSoft Cloud Engineering
Reviewed October 2026
Production Verified Commands

Guide Overview & Architecture Outcome

By following this guide, you will lock down unnecessary ports on your Ubuntu server using Uncomplicated Firewall (UFW) and deploy Fail2ban to automatically block malicious IP addresses attempting brute-force SSH logins.

Prerequisites & System Requirements

Any Ubuntu 22.04 or 24.04 server. Works on all IndSoft VPS and Dedicated Servers.

1

Check Default UFW Status and Set Base Policies

Configure safe default policies: drop incoming connections and allow outgoing traffic.

bash · step-1-command.sh
sudo ufw default deny incoming sudo ufw default allow outgoing
Expected System Output:
Default incoming policy changed to 'deny' Default outgoing policy changed to 'allow'
2

Allow Critical Services Before Enabling Firewall

CRITICAL: Always allow SSH before turning on UFW to avoid locking yourself out of your server.

bash · step-2-command.sh
sudo ufw allow OpenSSH sudo ufw allow 80/tcp sudo ufw allow 443/tcp sudo ufw enable
Expected System Output:
Firewall is active and enabled on system startup
3

Install and Configure Fail2ban

Install Fail2ban and copy the base configuration to a persistent local jail file.

bash · step-3-command.sh
sudo apt install fail2ban -y sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local sudo nano /etc/fail2ban/jail.local
Expected System Output:
Setting up fail2ban (1.0.2-3) ... Created symlink /etc/systemd/system/multi-user.target.wants/fail2ban.service
4

Activate SSH Brute-Force Jail

Configure maxretry = 5 and bantime = 1h under the [sshd] section in jail.local, then restart the service.

bash · step-4-command.sh
sudo systemctl restart fail2ban sudo fail2ban-client status sshd
Expected System Output:
Status for the jail: sshd |- Filter | |- Currently failed: 0 | `- Total failed: 0 `- Actions |- Currently banned: 0 `- Total banned: 0

Check That It Worked (Verification)

Run this quick verification check to confirm your installation is responding properly:

verify-service.sh
sudo fail2ban-client ping
Expected Response:
Server replied: pong

Troubleshooting Common Errors

Quick resolutions for frequent setup pitfalls and configuration issues.

Diagnostic Tips
Locked out of SSH after enabling UFW
Access your server via IndSoft out-of-band VNC Console in the Client Portal and run sudo ufw allow 22/tcp.
Fail2ban fails to read systemd logs
On Ubuntu 24.04, ensure backend = systemd is set under [DEFAULT] in /etc/fail2ban/jail.local.
Legitimate IP address accidentally banned
Unban your IP using sudo fail2ban-client set sshd unbanip YOUR_IP_ADDRESS.