We'll now set up UFW (Uncomplicated Firewall) on our Ubuntu server.
Before You Begin
Please read the following before continuing forward:
You may get locked Out of SSH if you don't follow the steps correctly. Misconfiguring ufw can lock you out of your own server, especially if SSH is not correctly allowed.
Adding the rule to allow SSH access before enabling ufw is crucial.
Using restrictive or incorrect rules can lead to blocking essential services, causing disruptions that are difficult to troubleshoot.
While ufw provides a basic firewall, it lacks features like dynamic IP blocking, which is where tools like fail2ban come in. Fail2ban monitors logs for repeated failed login attempts and temporarily bans IPs, adding an extra layer of defense against brute-force attacks. We will set that up in the next section.
ufw Set up
1
Allow OpenSSH Through UFW:
sudoufwallowOpenSSH
This ensures that SSH connections remain allowed when the firewall is active.
2
Enable UFW
Before you execute this command, ensure that you entered the previous command.
sudoufwenable
Note: You'll be prompted to confirm. Type y and press Enter.
3
Verify the SSH Rule
sudoufwstatusverbose
Ensure that you see (OpenSSH) in the list:
To Action From
-- ------ ----
22/tcp (OpenSSH) ALLOW IN Anywhere
22/tcp (OpenSSH (v6)) ALLOW IN Anywhere (v6)
4
Allow Additional Services:
You may want to allow other services to have access, you can allow them too.
HTTP:
sudoufwallowhttp
HTTPS:
sudoufwallowhttps
5
Check your Rules
sudoufwstatusverbose
6
Verify Connectivity
Open a new terminal window and attempt to SSH into your server to ensure that the firewall isn't blocking access
Upon successful login, we can continue and set up fail2ban. Good job on not locking yourself out!
Locked Out?
If you locked yourself out via SSH, see if your server provider has console access from their site. You should be able to connect via console.
If they do not have this service, you will have to contact them to see if they can log in directly through their console and disable the rule.