By default, UFW (Uncomplicated Firewall) is disabled on Ubuntu. While enabling it strengthens security, it can also disrupt active connections, potentially locking you out—especially if you're managing a remote server via SSH.

So, how do you enable UFW without losing access?

Pause for a moment, think about it… then scroll down for the answer.

Solution

This is more of a brain teaser than a technical challenge: Allow SSH connection before enabling UFW

$ sudo ufw status
Status: inactive
$ sudo ufw allow ssh
Rules updated
Rules updated (v6)
$ sudo ufw enable
Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup
$ sudo ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
22/tcp                     ALLOW IN    Anywhere                  
22/tcp (v6)                ALLOW IN    Anywhere (v6)  

Now, UFW is enabled and protecting your system, while still allowing you to connect via SSH.