Guide
Enable UFW on Ubuntu Server while preserving SSH access
Enable UFW on Ubuntu Server while keeping SSH accessible, with verification and rollback steps.
Published by Tasadduq Burney
17 Oct 2025, 14:23 UTC
2 min141.6K views0

Desired outcome
Configure the Uncomplicated Firewall (UFW) on an Ubuntu Server to block unwanted incoming traffic while allowing SSH connections for remote administration.
Prerequisites
- Ubuntu Server 20.04 LTS or later (UFW is installed by default).
- Administrative access via sudo or root.
- An existing SSH connection to the server (to avoid lock‑out).
- Network connectivity to test from another host (optional).
Procedure
- Check current UFW state – run
sudo ufw status verbose. If the output showsStatus: inactive, proceed; if it is already active, note the existing rules. - Allow SSH – execute
sudo ufw allow ssh(orsudo ufw allow 22/tcp) to create a rule that permits incoming TCP traffic on port 22. - Set default policies – ensure the baseline is secure:
sudo ufw default deny incomingandsudo ufw default allow outgoing. These commands reset the default chains; they are safe to run even if the defaults are already set. - Enable the firewall – run
sudo ufw enable. You will be prompted to confirm because enabling may disrupt existing connections; typeyand press Enter. - Optional: Add additional service rules – for example, to allow HTTP and HTTPS:
sudo ufw allow httpandsudo ufw allow https.
Expected checks
- Run
sudo ufw status verboseagain. The output should indicateStatus: active, show the default policies (Deny incoming, Allow outgoing), and list the SSH rule (e.g.,22/tcp ALLOW IN). - From a separate machine, attempt an SSH connection to the server’s IP address. The connection should succeed.
- Attempt to connect to a port that is not explicitly allowed (e.g., telnet to port 23). The connection should be refused or time out, confirming the deny‑incoming policy.
Recovery options (rollback)
If you accidentally lock yourself out, you can regain access through a console (e.g., via the cloud provider’s serial console or iDRAC/iLO) and then:
- Disable UFW:
sudo ufw disable. - Flush all rules:
sudo ufw reset(this removes user‑added rules and restores defaults). - Re‑apply the SSH allow rule and re‑enable the firewall as described above.
If the firewall was never enabled, simply skipping the sudo ufw enable step leaves the system unchanged.
Limitations
- UFW is designed for host‑based filtering; it cannot replace a perimeter firewall or handle complex NAT scenarios.
- Rule ordering is implicit; you cannot insert a rule at a specific position without deleting and recreating the set.
- Some applications that rely on dynamic port ranges may require additional iptables/nftables rules beyond UFW’s simplicity.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.