How to Install UFW on Ubuntu

Uncomplicated Firewall (UFW) delivers straightforward network traffic control for Ubuntu servers and desktops. Built as a user-friendly frontend to iptables, UFW strips away configuration complexity while preserving robust firewall capabilities. The tool manages basic port rules, application-specific profiles, detailed security logging, and both IPv4 and IPv6 traffic through a consistent command-line interface.

This guide covers installing UFW on Ubuntu, configuring default security policies, managing firewall rules for SSH and common services, monitoring traffic with logs, and optionally using the GUFW graphical interface. You’ll establish secure policies, control service access, and maintain visibility into network activity.

Verify UFW Installation

Ubuntu includes UFW by default on standard desktop and server installations. First, verify that UFW is available on your system:

ufw version

Expected output confirming UFW is installed:

ufw 0.36.2
Copyright 2008-2023 Canonical Ltd.

If you see a “command not found” error instead, UFW was removed or you are using a minimal installation. Install it with the following commands:

sudo apt update
sudo apt install ufw

After installation completes, run ufw version again to confirm UFW is ready for configuration.

Enable IPv6 Support in UFW

UFW supports IPv6 by default on modern Ubuntu installations, so most systems already apply firewall rules to both protocols. If you’re working with legacy hosts or minimal server images, verify IPv6 support by opening the UFW configuration file:

sudo nano /etc/default/ufw

Find the line that reads IPV6=no and change it to IPV6=yes. On most current Ubuntu installations, this setting is already enabled:

# Set to yes to apply rules to support IPv6 (no means only IPv6 on loopback
# accepted). You will need to 'disable' and then 'enable' the firewall for
# the changes to take affect.
IPV6=yes

If you make changes, save the file and exit the editor. For the changes to take effect, disable and re-enable UFW:

sudo ufw disable && sudo ufw enable

Set UFW Default Policies

Default policies define how UFW handles traffic that doesn’t match any specific rule. The recommended security posture denies all incoming connections (preventing unauthorized access) while allowing all outgoing connections (permitting your applications to reach external services). Set these defaults with the following commands:

sudo ufw default deny incoming
sudo ufw default allow outgoing

Expected output confirming the policy changes:

Default incoming policy changed to 'deny'
Default outgoing policy changed to 'allow'

With these defaults in place, your server rejects all unsolicited incoming connections while allowing internal applications to communicate outward freely. You must now explicitly allow each service that needs to accept incoming traffic.

Allow SSH Connections

If you manage your server remotely via SSH, allow SSH connections before enabling the firewall. Skip this section if you only access the system locally.

sudo ufw allow ssh

This command allows incoming SSH connections on the default port (22). Alternatively, if your SSH server uses a custom port, specify it directly:

sudo ufw allow 2222/tcp

This allows incoming connections on port 2222. Replace the port number with your actual SSH port if different.

Protect SSH with Rate Limiting

To protect SSH from automated brute-force attacks, UFW provides a rate-limiting feature that tracks connection attempts from each source IP address. When an IP address attempts to initiate more than six connections within 30 seconds, UFW temporarily blocks further connections from that address. This approach distinguishes between normal use and likely malicious behavior without completely blocking legitimate users.

To enable rate limiting for SSH, use the limit command instead of allow:

sudo ufw limit ssh

For custom SSH ports, specify the port number with the protocol:

sudo ufw limit 2222/tcp

Rate limiting adds an extra security layer to services exposed to the internet. Consider using this feature for any service that accepts authentication attempts, as it significantly reduces the effectiveness of automated credential-stuffing attacks.

Enable UFW on Ubuntu

If you are connected via SSH, complete the SSH allow step above before enabling UFW. Enabling the firewall without an SSH rule will immediately disconnect your session and lock you out of the server.

Preview Rules Before Activation

Before activating the firewall, preview which rules UFW will apply:

sudo ufw show added

Expected output showing your configured rules:

Added user rules (see 'ufw status' for running firewall):
ufw allow 22/tcp

This verification step confirms that SSH access rules exist before you potentially lock yourself out. If the output is empty or missing your SSH rule, add it now before proceeding.

Activate the Firewall

Once you confirm your rules are correct, enable UFW:

sudo ufw enable

UFW prompts you to confirm because enabling the firewall may disrupt existing connections:

Command may disrupt existing ssh connections. Proceed with operation (y|n)? y
Firewall is active and enabled on system startup

Enter y to confirm. UFW now enforces your rules and starts automatically on boot.

Configure Common Service Rules

After enabling UFW and securing SSH access, you can allow other connections, such as HTTP, HTTPS, or FTP, using the ufw allow command followed by the service name or port number.

For example:

sudo ufw allow http
sudo ufw allow https
sudo ufw allow 21/tcp

These commands allow incoming connections for HTTP (port 80), HTTPS (port 443), and FTP (port 21). Moreover, if you need to allow connections for a range of ports, you can specify the range like this:

sudo ufw allow 8000:9000/tcp

This command allows incoming connections on TCP ports 8000 through 9000. Port ranges are particularly useful when hosting multiple development servers or microservices that need consecutive port assignments.

Allow Access from Specific IP Addresses

To restrict access to a specific IP address, use the from parameter:

sudo ufw allow from 203.0.113.4

This grants full access to the specified IP address. Consequently, to allow access to a specific port from a particular IP address:

sudo ufw allow from 203.0.113.4 to any port 22

Allow Access from Subnets

To allow an entire subnet of IP addresses, use CIDR notation to specify a netmask. For instance, to allow all IP addresses ranging from 192.168.1.1 to 192.168.1.254:

sudo ufw allow from 192.168.1.0/24

You can combine subnet filtering with specific ports:

sudo ufw allow from 192.168.1.0/24 to any port 22

This limits SSH access to the specified subnet only, which is particularly useful for restricting administrative access to your local network.

Allow Connections to Specific Network Interfaces

For servers with multiple network interfaces, you can create rules that apply only to a specific interface. First, identify your network interfaces:

ip addr

Network interfaces are typically named eth0, eth1, enp3s2, or similar. To allow HTTP traffic only on the public-facing interface eth0:

sudo ufw allow in on eth0 to any port 80

Similarly, for database servers that should only accept connections on a private network interface eth1:

sudo ufw allow in on eth1 to any port 3306

Interface-specific rules provide fine-grained control over which networks can reach particular services, preventing accidental exposure of internal services to public networks.

Deny Specific Connections

Conversely, to deny specific connections, use the ufw deny command followed by the service name or port number. For example:

sudo ufw deny 25/tcp

This command denies incoming connections on port 25 (SMTP).

Delete Firewall Rules

When rules become outdated or unnecessary, you can delete them using the ufw delete command followed by the rule’s parameters. For example:

sudo ufw delete allow 21/tcp

This command deletes the rule that allows incoming connections on port 21 (FTP).

Delete Rules by Number

For complex firewall configurations with many rules, deleting by number is more efficient than retyping the entire rule. Initially, display the numbered list of rules:

sudo ufw status numbered

This displays each rule with its assigned number. To delete a rule by number:

sudo ufw delete 3

This removes the third rule from the list. Note that when deleting IPv6 rules by number, you must delete the IPv4 and IPv6 versions separately since they appear as distinct numbered entries. Deleting by name (e.g., sudo ufw delete allow http) removes both IPv4 and IPv6 rules automatically.

View Active UFW Rules and Status

After configuring your rules, check the firewall status and view active rules:

sudo ufw status verbose

This displays the UFW status, default policies, and all configured rules. The verbose flag shows additional details like logging level and routing policy:

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)

Enable and Monitor UFW Logs

UFW provides logging functionality to track its actions and monitor potential issues. This section covers how to configure and view logs to maintain visibility into firewall activity.

Configure UFW Log Settings

To enable logging for UFW, use the ufw logging command followed by the desired log level. UFW supports four log levels that determine the amount of detail captured:

LevelWhat It Logs
lowBlocked packets only
mediumBlocked packets + new connections
highPackets with rate limiting
fullEverything without rate limiting

For most users, medium provides a good balance between detail and log file size:

sudo ufw logging medium

The medium level logs blocked packets and new connections, providing visibility into denied traffic and established connections without overwhelming your disk with every packet detail.

View UFW Logs

UFW logs are stored in /var/log/ufw.log by default. View the log file with less, the tail command, or cat:

sudo less /var/log/ufw.log

This opens the log file in less, allowing you to scroll through the contents.

Manage Application Profiles

UFW supports application profiles, which are predefined rules for popular applications. These profiles simplify the process of allowing or denying connections for specific applications by bundling the correct ports and protocols into a single named rule. Application profiles are particularly useful when software packages include multiple ports or both TCP and UDP requirements, reducing the chance of misconfiguration compared to manual port rules. You can view available application profiles with the following command:

sudo ufw app list

To view the details of a specific profile, use the ufw app info command followed by the profile name:

sudo ufw app info 'Apache Full'

To allow or deny connections for an application profile, use the ufw allow or ufw deny command followed by the profile name:

sudo ufw allow 'Apache Full'

Test UFW Rules

Before applying new rules to production systems, test them using the nc (netcat) tool to simulate connections and verify firewall behavior.

Install netcat if it is not already available:

sudo apt install netcat-openbsd

On the server, start a listener on port 8080:

nc -l 8080

The terminal waits for incoming connections. From a second machine or terminal session, connect to the server:

nc 192.168.1.10 8080

Replace 192.168.1.10 with your server’s actual IP address. If the connection succeeds, text you type in either terminal appears in the other, confirming the port is open through UFW. If the connection times out or is refused, UFW is blocking the traffic and you need to add an allow rule for that port.

Disable or Reset UFW

For comprehensive firewall management on Ubuntu, you may need to temporarily disable UFW for troubleshooting network issues or testing application connectivity. Use the following command:

sudo ufw disable

To reset UFW to its default settings and remove all rules, use the ufw reset command. This is useful when you want to start fresh after experimenting with complex rule sets or when transitioning to a new security configuration:

sudo ufw reset

This action erases all your custom rules, requiring you to reconfigure UFW from scratch.

Install GUFW

As an alternative to command-line management, GUFW is a graphical front-end for managing UFW rules. To install GUFW on Ubuntu, use the following commands:

sudo apt update
sudo apt install gufw

After installation, you can launch GUFW from your application menu. The graphical interface makes it easy to manage your firewall rules without using the command line, particularly useful for users who prefer visual tools over terminal commands.

UFW Security Best Practices

Maintaining effective firewall protection requires ongoing attention and adherence to security principles. Following these practices ensures your UFW configuration remains secure and aligned with your system’s evolving needs.

Apply the Principle of Least Privilege

The principle of least privilege dictates that you should only grant the minimum level of access necessary for a service to function. UFW’s default deny-incoming policy aligns with this principle, requiring you to explicitly allow each connection type.

Be specific when creating rules. Instead of allowing broad port ranges, open only the exact ports your applications require. When a service only needs access from specific locations, restrict the rule to that source IP address or subnet. For example, to allow MySQL access only from an application server at 203.0.113.100:

sudo ufw allow from 203.0.113.100 to any port 3306

Audit Firewall Rules Regularly

Server requirements change over time as services are added, removed, or reconfigured. Therefore, set a recurring reminder to review your firewall rules quarterly. List your rules with sudo ufw status numbered and evaluate each one:

  • Is the service associated with this port still running and in use?
  • Is the level of access (from anywhere vs. specific IP) still appropriate?
  • Could this rule be made more restrictive without breaking functionality?

To view your numbered rules, run:

sudo ufw status numbered

This displays output similar to:

Status: active

     To                         Action      From
     --                         ------      ----
[ 1] 22/tcp                     ALLOW IN    Anywhere
[ 2] 80/tcp                     ALLOW IN    Anywhere
[ 3] 443/tcp                    ALLOW IN    Anywhere
[ 4] 3306/tcp                   ALLOW IN    192.168.1.100
[ 5] 8080/tcp                   ALLOW IN    Anywhere
[ 6] 22/tcp (v6)                ALLOW IN    Anywhere (v6)
[ 7] 80/tcp (v6)                ALLOW IN    Anywhere (v6)
[ 8] 443/tcp (v6)               ALLOW IN    Anywhere (v6)
[ 9] 8080/tcp (v6)              ALLOW IN    Anywhere (v6)

If you identify an outdated rule, such as port 8080 for a development server that no longer runs, remove it by number:

sudo ufw delete 5

Remember to delete both IPv4 and IPv6 versions when removing rules by number. After deleting rule 5 (8080/tcp), you would need to run sudo ufw status numbered again and delete the corresponding IPv6 rule. Alternatively, delete by service name to remove both versions simultaneously:

sudo ufw delete allow 8080/tcp

Remove unnecessary rules immediately. Furthermore, a rule that was essential six months ago might now represent an unnecessary security risk.

Monitor UFW Logs for Suspicious Activity

Firewall logs provide valuable intelligence about traffic reaching your server, including blocked malicious attempts. Keep logging at the medium level with sudo ufw logging medium (or adjust to the level you selected earlier) and regularly review /var/log/ufw.log for patterns.

To monitor logs in real-time, use:

sudo tail -f /var/log/ufw.log

A typical blocked connection appears in the log as:

Nov  8 14:23:45 server kernel: [UFW BLOCK] IN=eth0 OUT= MAC=00:00:00:00:00:00 SRC=198.51.100.42 DST=203.0.113.10 LEN=40 TOS=0x00 PREC=0x00 TTL=52 ID=54321 PROTO=TCP SPT=54892 DPT=23 WINDOW=65535 RES=0x00 SYN URGP=0

Key log fields to monitor:

  • SRC: Source IP address (who sent the packet) – 198.51.100.42 in this example
  • DPT: Destination port (which service they tried to reach) – port 23 (Telnet) in this case
  • PROTO: Protocol (TCP or UDP) – TCP here
  • SPT: Source port (originating port from the sender) – 54892

To check for repeated connection attempts from a specific IP address across multiple ports (indicating port scanning), run:

sudo grep "SRC=198.51.100.42" /var/log/ufw.log | grep "BLOCK" | wc -l

A high count (50+ attempts within a short timeframe) indicates automated scanning activity. Specifically, watch for single IP addresses repeatedly attempting to connect to multiple blocked ports, which indicates port scanning activity and potential attack reconnaissance.

Verify IPv4 and IPv6 Coverage

Modern Ubuntu distributions enable IPv6 by default, and UFW applies rules to both protocols automatically when IPV6=yes in /etc/default/ufw. Therefore, verify this setting to ensure you’re not accidentally leaving IPv6 traffic unprotected.

Check your UFW IPv6 configuration:

grep IPV6 /etc/default/ufw

This should return IPV6=yes. When checking sudo ufw status verbose, look for (v6) entries corresponding to each IPv4 rule:

sudo ufw status verbose

Example output showing dual-protocol coverage:

Status: active
Logging: on (medium)
Default: deny (incoming), allow (outgoing), disabled (routed)
New profiles: skip

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

Notice how each service rule appears twice: once for IPv4 and once with (v6) for IPv6, confirming dual-protocol coverage. To verify if your system actually has IPv6 connectivity, check your network interfaces:

ip -6 addr show scope global

If this command returns IPv6 addresses (starting with 2000::/3 for global unicast), your system uses IPv6 and requires firewall protection on both protocols. Additionally, if your network doesn’t use IPv6, consider disabling it entirely at the kernel level to eliminate it as a potential attack vector.

Integrate with Intrusion Prevention Systems

While UFW enforces a static ruleset, it does not dynamically react to active threats. Integrate UFW with Fail2ban on Ubuntu to automatically block repeated attack attempts. Fail2ban monitors log files for patterns like failed login attempts and creates temporary UFW deny rules to block offending IP addresses, providing automated, responsive protection against brute-force attacks.

Troubleshoot Common UFW Issues

Even well-configured firewalls encounter problems. This section covers the most common UFW issues and their solutions.

Recover from SSH Lockout

If you enabled UFW without allowing SSH and lost remote access, you need physical or console access to the server. Once you have console access, disable the firewall:

sudo ufw disable

Add the SSH rule and re-enable:

sudo ufw allow ssh
sudo ufw enable

Verify the rule exists before attempting to reconnect:

sudo ufw status | grep 22

Expected output:

22/tcp                     ALLOW       Anywhere
22/tcp (v6)                ALLOW       Anywhere (v6)

UFW Fails to Start After Reboot

If UFW does not start automatically after rebooting, check whether it is enabled in systemd:

sudo systemctl status ufw

If the service shows as inactive, enable and start it:

sudo systemctl enable ufw
sudo systemctl start ufw

Verify UFW is running:

sudo ufw status

Rules Not Taking Effect

If newly added rules do not seem to work, first confirm UFW is active:

sudo ufw status

If the status shows “inactive,” enable UFW with sudo ufw enable. Additionally, verify the rule syntax matches what you expect:

sudo ufw status numbered

Check rule ordering. UFW processes rules from top to bottom and stops at the first match. If a broad deny rule appears before a specific allow rule, the traffic gets blocked. Delete the problematic rule and re-add it in the correct order.

Remove UFW from Ubuntu

In most cases, simply disabling UFW with sudo ufw disable is sufficient when you need to temporarily stop firewall enforcement. Complete removal is only necessary when switching to a different firewall solution like firewalld or nftables.

First, disable the firewall to prevent any disruption:

sudo ufw disable

Remove the UFW package and its configuration files:

sudo apt remove --purge ufw

If you installed GUFW, remove it as well:

sudo apt remove --purge gufw

Clean up any orphaned dependencies:

sudo apt autoremove

Verify UFW is no longer installed:

ufw version

Expected output confirming removal:

-bash: ufw: command not found

Removing UFW leaves your system without a firewall. If you need continued protection, install an alternative firewall like iptables or nftables before removing UFW, or ensure your network has adequate perimeter security.

Conclusion

UFW provides robust network security for Ubuntu through straightforward command-line controls and optional GUFW graphical management. The firewall handles default deny policies that block unwanted traffic, application profiles that simplify service configuration, and detailed logging that tracks connection attempts. Your Ubuntu system now maintains controlled network access with visible traffic monitoring, balancing security requirements against legitimate service availability. For additional intrusion prevention, consider pairing UFW with Fail2ban to automatically block repeated attack attempts.

Leave a Comment