HackBlue

Tools · Linux command line for security · 09 / 28

How to set up UFW on Ubuntu without locking yourself out

Enable Ubuntu’s Uncomplicated Firewall with a default-deny inbound policy, allow SSH from a management range, and verify with ss and Nmap.

9 min read · practice only with authorization

Plan the rules first

Before enabling a firewall on a remote server, list what must stay reachable. Usually that is SSH from your admin network and the application’s port from its clients. ss -tlnp shows what is listening, which also reveals services that should not be listening at all.

UFW is a front end to nftables or iptables. Its default policy can be deny incoming and allow outgoing, and rules are added in a readable syntax.

Snippet
sudo ss -tlnp
sudo ufw status verbose

Lab: enable it safely

Allow SSH first, ideally from a specific range. Then set defaults, allow the web ports, and enable. Keep your existing SSH session open while you open a second one to confirm access, so a mistake does not strand you.

From your scanner VM, run Nmap against the host before and after. Ports you did not allow should change from closed to filtered.

Snippet
sudo ufw allow from 192.168.56.0/24 to any port 22 proto tcp
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 443/tcp
sudo ufw enable
sudo ufw status numbered
# scanner
sudo nmap -p 22,80,443,5432 192.168.56.101

Logging and rate limits

ufw logging on writes blocked packets to the kernel log with a [UFW BLOCK] prefix. ufw limit ssh adds a simple rate limit that denies a source opening more than six connections in 30 seconds, which slows password guessing.

Docker is a common surprise. It inserts its own iptables rules, so a container published with -p 5432:5432 may be reachable even with UFW denying 5432. Bind published ports to 127.0.0.1 or use Docker’s DOCKER-USER chain.

Review and remove

ufw status numbered lets you delete rules by number. Review the list whenever a service is retired.

IPv6 is controlled by IPV6=yes in /etc/default/ufw. Leave it on so rules apply to both protocols.

Diagram

Enabling UFW on a remote host

  1. List

    Check listeners with ss -tlnp.

  2. Allow SSH

    Add the SSH rule before anything else.

    Command
    sudo ufw allow from 192.168.56.0/24 to any port 22 proto tcp
  3. Default deny

    Set incoming deny, outgoing allow, add app ports, enable.

  4. Verify

    Open a second session and scan from another host.

Check yourself

1. What should you do before running ufw enable on a remote server?

2. A Postgres container is reachable despite UFW denying 5432. Why?

3. What does ufw limit ssh do?