Introduction
Securing a Linux server starts with restricting incoming network traffic. While `iptables` is the standard Linux firewall utility, its syntax can be complex and unforgiving. Uncomplicated Firewall (UFW) provides a much simpler, user-friendly command-line interface for managing `iptables` rules. This guide demonstrates how to configure a secure baseline firewall using UFW on Ubuntu Server.
Prerequisites
You need an Ubuntu Server (20.04, 22.04, or newer) and a user account with sudo privileges. Warning: If you are configuring a remote server via SSH, you must allow SSH traffic before enabling UFW, or you will lock yourself out.
Step 1: Check UFW Status
UFW is installed by default on Ubuntu, but it is typically disabled. Check its current status by running:
sudo ufw status
It should return Status: inactive.
Step 2: Set Default Policies
A secure firewall denies all incoming traffic by default and allows all outgoing traffic. This ensures that no external entity can connect to your server unless you explicitly open a port, while your server can still reach the internet to download updates. Set the defaults:
sudo ufw default deny incoming
sudo ufw default allow outgoing
Step 3: Allow SSH Connections
Before enabling the firewall, you must allow SSH connections. You can open the default SSH port (22) by referencing the service name or the port number:
sudo ufw allow ssh
If you have configured your SSH daemon to listen on a non-standard port (e.g., 2222), you must specify the port number instead:
sudo ufw allow 2222/tcp
Step 4: Allow Specific Application Traffic
Next, open the ports required by the applications hosted on your server. For a standard web server hosting HTTP and HTTPS, run:
sudo ufw allow http
sudo ufw allow https
You can also allow a specific IP address to access a specific port (e.g., allowing your office IP to access a MySQL database on port 3306):
sudo ufw allow from 198.51.100.25 to any port 3306
Step 5: Enable UFW
Once your SSH and application ports are allowed, enable the firewall:
sudo ufw enable
Type y and press Enter when prompted with the warning about disrupting existing SSH connections. You can review your active rules at any time using:
sudo ufw status verbose
Step 6: Deleting Rules
If you make a mistake, you can delete a rule by viewing the rules as a numbered list:
sudo ufw status numbered
Then, delete the specific rule by its number (e.g., rule 3):
sudo ufw delete 3