Firewall ConfigurationLinux Security Guide

How to Set Up a Firewall with UFW on Ubuntu 20.04

Introduction

A firewall filters network traffic to and from your server by enforcing rules that allow or block connections. Ubuntu provides the simple front-end ufw (Uncomplicated Firewall) to manage kernel firewalling (iptables). This guide shows how to install, configure, test and maintain a secure Ubuntu firewall UFW on Ubuntu 20.04, including default policies, opening ports, logging, IP-based rules, IP masquerading, and safe troubleshooting.

Prerequisites

  • A server running Ubuntu 20.04.
  • A non-root user with sudo privileges. (sudo runs commands as root; it’s required to modify firewall settings.)
  • Terminal access (local or remote). If you manage the server remotely, plan rules so you don't lock yourself out.

Install UFW

UFW is usually installed by default on Ubuntu. Update package metadata and install ufw if necessary.

sudo apt update
sudo apt install ufw

Explanation: sudo elevates privileges to run package management as root. apt update refreshes package lists and apt install ufw installs the UFW package so you can configure firewall rules.

Check UFW Status

sudo ufw status verbose

Explanation: This shows whether UFW is active and lists current rules. UFW is usually inactive until you enable it.

Make Sure IPv6 Is Handled Correctly

Modern Ubuntu enables IPv6 by default; UFW can write both IPv4 and IPv6 rules. Confirm and change this in the UFW defaults file if needed.

sudo nano /etc/default/ufw

Explanation: Open the configuration file with a text editor. Change the IPV6 value to yes to have UFW manage both IPv4 and IPv6 rules. Save and exit (CTRL+X, Y, ENTER in nano).

Set Default Policies

Start by defining the baseline policy: deny inbound traffic and allow outbound. This implements the principle of least privilege.

sudo ufw default deny incoming
sudo ufw default allow outgoing

Explanation: ufw default sets the default action for packets that don’t match any rule. Denying incoming prevents unsolicited connections; allowing outgoing keeps services able to reach the Internet.

Allow SSH Safely (Do This Before Enabling UFW)

Before enabling the firewall on a remote server, explicitly allow SSH to avoid locking yourself out. Use a service name, port, or application profile.

sudo ufw allow OpenSSH

Explanation: Uses the UFW application profile for OpenSSH and opens port 22 for both IPv4 and IPv6 if available. Alternatively:

sudo ufw allow ssh
sudo ufw allow 22/tcp

Explanation: The first command uses the service name from /etc/services. The second specifically opens TCP port 22. If SSH listens on a custom port (for example 2222), open that port instead:

sudo ufw allow 2222/tcp

Rate-limiting SSH

Enable UFW's rate limit on SSH to defend against brute-force attempts while allowing legitimate use:

sudo ufw limit ssh

Explanation: ufw limit allows connections but temporarily blocks an IP that makes excessive connection attempts (typical default: 6 attempts in 30 seconds).

Enable UFW

After confirming the SSH rule is present, enable UFW. Use the dry-run option for a final check if desired.

sudo ufw --dry-run enable

Explanation: The –dry-run shows what enabling would do without applying changes — useful for testing complex rule changes safely.

sudo ufw enable

Explanation: Enables UFW and applies rules; the command warns if enabling could disrupt existing SSH sessions. Confirm with y if you already allowed SSH.

Open Ports and Allow Services

There are multiple ways to allow traffic: service names, ports, application profiles, or protocol-specific rules.

Allow common web ports

sudo ufw allow http
sudo ufw allow https
# or
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# or via application profile (if available)
sudo ufw allow 'Nginx Full'

Explanation: These commands open HTTP/HTTPS. Profiles like ‘Nginx Full’ are defined under /etc/ufw/applications.d and may open multiple ports at once.

Port Ranges

sudo ufw allow 6000:6007/tcp
sudo ufw allow 6000:6007/udp

Explanation: Use a colon to specify ranges and explicitly mention protocol when needed; UFW creates both tcp and udp rules if protocol is omitted, but ranges require the protocol.

Allow from a Specific IP or Subnet

sudo ufw allow from 203.0.113.4
sudo ufw allow from 203.0.113.4 to any port 22
sudo ufw allow from 192.168.1.0/24 to any port 3306

Explanation: These commands whitelist a single IP or CIDR subnet. Restricting by source is a safer practice than opening ports to the entire internet.

Allow on a Specific Network Interface

sudo ufw allow in on eth0 to any port 80

Explanation: Applies the rule only to traffic entering on the specified interface (replace eth0 with your interface name from

ip addr

).

Denying Connections

Use deny to explicitly block traffic from sources or to ports.

sudo ufw deny http
sudo ufw deny from 203.0.113.0/24
sudo ufw deny proto tcp from 23.24.25.0/24 to any port 80,443

Explanation: Deny rules are structured like allow rules but block matching traffic. Use them to mitigate attacks or to restrict outgoing traffic (deny out).

Delete or Modify Rules

Two common ways to remove rules: by number or by rule specification.

List rules with numbers

sudo ufw status numbered

Explanation: Lists active rules with an index so you can delete by number.

sudo ufw delete 3

Explanation: Deletes rule number 3. Note: numbered lists separate IPv4 and IPv6; deleting a number removes only that listed entry.

Delete by rule specification

sudo ufw delete allow 80
sudo ufw delete allow 'Apache Full'

Explanation: Deleting by name removes both IPv4 and IPv6 entries when applicable and is usually simpler for service-based rules.

Check Status and Logs

sudo ufw status verbose
sudo ufw show added

Explanation: status verbose shows defaults, logging level and rules. show added prints user-added rules even when UFW is inactive.

Enable and view logging

sudo ufw logging on
sudo ufw logging low

Explanation: Turns UFW logging on. Logs are written to /var/log/ufw.log. Choose a level (low, medium, high) depending on noise vs. detail.

Reset or Disable UFW

sudo ufw disable

Explanation: Stops enforcing rules but leaves UFW installed and its service enabled on reboots. Use to temporarily turn firewall protection off.

sudo ufw reset

Explanation: Disables UFW and deletes all user-defined rules, backing up previous rules files. You’ll be prompted to confirm.

IP Masquerading / NAT (Advanced)

To use the machine as a NAT gateway (IP masquerading) you must enable IP forwarding and add NAT rules. This is an advanced configuration—back up configs before editing.

Edit the sysctl settings to enable IPv4 forwarding:

sudo nano /etc/ufw/sysctl.conf

Explanation: Uncomment or add net.ipv4.ip_forward=1 in /etc/ufw/sysctl.conf so the kernel forwards packets.

Set the UFW forward policy:

sudo nano /etc/default/ufw

Explanation: Change DEFAULT_FORWARD_POLICY from \”DROP\” to \”ACCEPT\” to allow forwarded packets.

Add NAT POSTROUTING rules to /etc/ufw/before.rules (replace eth0 and IP range with your values):

sudo nano /etc/ufw/before.rules

Append (example):

*nat
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -s 10.8.0.0/16 -o eth0 -j MASQUERADE
COMMIT

Explanation: The *nat block and POSTROUTING rule create masquerading so private addresses are translated to the public interface address. Replace eth0 with your public interface.

Reload UFW rules by disabling and enabling:

sudo ufw disable
sudo ufw enable

Explanation: Reloads UFW so updated configuration files are read and applied.

Testing Rules (Safe Checks)

Always test changes before relying on them in production.

sudo ufw --dry-run enable
# From an external machine:
nmap -p 22,80,443 your_server_ip

Explanation: –dry-run previews rule application locally. Use nmap from another host to verify expected ports are open/closed externally (replace your_server_ip).

Troubleshooting: If You Get Locked Out

If SSH is blocked and you lose access, use the cloud provider’s web console, rescue mode, or physical access to:

  • Temporarily disable UFW:
    sudo ufw disable
  • Re-add an SSH allow rule:
    sudo ufw allow 22/tcp
  • Check rules:
    sudo ufw status verbose

Explanation: These steps restore remote access so you can fix firewall rules securely.

Security Best Practices

  • Apply the principle of least privilege—only open the ports you need.
  • Restrict access by source IP where possible (ufw allow from).
  • Enable logging and review /var/log/ufw.log regularly for suspicious patterns.
  • Integrate UFW with an IPS like Fail2ban to auto-block brute-force attempts.
  • Audit rules periodically with
    sudo ufw status numbered

    and remove stale entries.

  • Test changes in a staging environment or use –dry-run before enabling in production.

Short FAQ

What does sudo do?

sudo runs a command with elevated (root) privileges. Firewall configuration requires root access, so prefix commands with sudo if you are not logged in as root.

How do I check if UFW is running?

sudo ufw status verbose

Explanation: Reports whether UFW is active and lists configured rules (IPv4 and v6). If it shows Status: inactive, enable it after confirming your rules.

Conclusion

Setting up an UFW Ubuntu 20.04 firewall is a practical, effective way to harden servers. This tutorial covered installing ufw, setting secure default policies, safely allowing SSH, opening ports and ranges, restricting by IP or interface, enabling logging, configuring IP masquerading, testing changes, and basic troubleshooting. Follow the principle of least privilege, audit rules regularly, and integrate tools like Fail2ban for active protection. With UFW configured and monitored, your Ubuntu server will have a strong, maintainable network security baseline.

Komentariši

Vaša email adresa neće biti objavljivana. Neophodna polja su označena sa *