Marcio Cunha

How to configure firewall rules with UFW on Linux

Learn how to block unnecessary ports, create secure default policies, and manage your Linux server traffic simply using UFW.

Marcio Cunha•6 min
Also available in:PortuguêsEspañol
Summary
  • UFW simplifies iptables management by providing a user-friendly layer for network rules.
  • Default deny inbound policies protect hidden services against unauthorized intrusion attempts.
  • Opening specific ports requires caution to expose only essential services externally.
  • Subnet and IP access control ensures restricted access for sensitive corporate environments.
  • Monitoring firewall status and logs prevents unexpected issues with unwanted connections.

What is UFW and why you should use it

When we keep a server connected to the internet, it becomes visible to thousands of automated scans every day. To prevent attackers from exploiting open ports, we need a firewall, a security system that controls network traffic by allowing only trusted connections. In the Linux ecosystem, the low-level default tool is called iptables, but its syntax is notoriously complex and intimidating for system administrators. This is precisely where UFW comes in, standing for Uncomplicated Firewall, serving as a friendly facilitator that translates simple commands into robust packet filtering rules.

In practice, UFW acts like a strict doorman who checks every piece of data entering or leaving your machine, deciding whether it has permission to pass based on a list of predefined rules. Before diving into practical commands, it is worth remembering the importance of maintaining an organized infrastructure environment, which ranges from port security to automation routines with tools like setting up the Cron scheduler on Linux without errors. Next, we will see how to install, enable, and structure secure policies from scratch.

Installation and initial verification of UFW

Most Debian and Ubuntu-based Linux distributions come with UFW pre-installed, but it is always wise to ensure it is present and updated on your system. The first step for any administrator is to check the current service status to understand if it is already active or blocking traffic. To do this, we use the terminal with administrative privileges, ensuring we have the authority to safely alter the operating system's network settings.

Open your terminal and run the commands below to check the installation and current firewall status. If it is not installed, your distribution's package manager will do the work quickly.

sudo apt update && sudo apt install ufw -y
sudo ufw status verbose

If the output indicates the status is inactive, do not worry, as this is the expected behavior on a clean installation. Before enabling UFW, we need to set default policies to avoid locking ourselves out of the remote server during the remote configuration process over SSH.

Setting secure default inbound and outbound policies

The golden rule of any defensive security architecture is default denial. This means that unless an explicit rule authorizes traffic, everything else must be strictly blocked. In networking contexts, we configure the firewall to reject everything attempting to enter the server without permission, while allowing the server itself to send requests to the internet and receive their respective responses.

To apply this inbound-deny and outbound-allow strategy, we run direct commands that shape the baseline behavior of the firewall. This approach drastically reduces the machine's attack surface, preventing open ports left by forgotten software from remaining vulnerable to malicious exploits. See the necessary commands to lock down input and free output:

sudo ufw default deny incoming
sudo ufw default allow outgoing

With these guidelines established, the server starts ignoring any unauthorized external connection attempt. However, if we enable the firewall at this exact moment without freeing the remote terminal port, we will lose access to the machine if connected via SSH. We will solve this in the next step.

Opening essential access for remote administration

SSH access, which stands for Secure Shell, is the standard protocol we use to administer Linux servers remotely in an encrypted manner. Since we blocked all incoming connections in the previous step, we must explicitly open the port used by SSH before turning on the firewall, otherwise the connection will drop immediately.

By default, the SSH service operates on port 22, although many administrators change this port for security reasons against automated brute-force attacks. To release standard access, we use the service name itself or the corresponding port number. Run the command below in the terminal:

sudo ufw allow ssh

If you use a customized port for your remote access, simply replace the term ssh with the corresponding number, such as 2222/tcp. With guaranteed administrative access, we can now enable UFW permanently and test the functionality of the applied rules.

Enabling UFW and validating active rules

Now that the administration port is properly open and default policies are set, we can turn on the firewall safely. During the activation process, the system will issue a warning stating that the operation might interrupt existing SSH connections, but since we already opened port 22, the process will happen without unwanted interruptions.

To enable UFW and inspect the complete panel of active rules, use the sequential commands below in your server's terminal. Using the verbose parameter displays additional details that help audit the security state:

sudo ufw enable
sudo ufw status numbered

The status numbered command is especially useful because it displays a numerical index next to each registered rule. This immensely facilitates removing or modifying future rules by simply referencing the corresponding line number instead of re-typing the entire complex rule.

Allowing and blocking ports for specific services

With the firewall active and secure, the next step in systems administration routine is opening ports for services that actually need to expose content to the internet, such as HTTP and HTTPS web servers. Similarly, we can block specific IP addresses that are making suspicious intrusion attempts against our infrastructure.

To open common ports like port 80 for unencrypted web pages and port 443 for secure sites, we use direct commands in the terminal. In addition, we can restrict access to trusted networks or ban malicious IPs. See practical examples of how to manage these exceptions:

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw deny from 203.0.113.50 to any port 22
sudo ufw allow from 192.168.1.0/24 to any port 3306

These rules allow granular control, ensuring that only legitimate traffic reaches databases or internal services. In development or network diagnostic environments, complementary tools like the ability to inspect network packets with tcpdump on Linux help validate if packets are reaching open ports correctly. To explore these architectural concepts further in production, see our related technical analysis on How to test ATX power supplies with a dummy load.

Final considerations on auditing and network maintenance

Maintaining a configured firewall is not a task done once and forgotten. Systems security is an ongoing process that requires periodic reviews of active rules, removal of legacy ports no longer in use, and constant monitoring of operating system logs to identify anomalous traffic patterns. UFW fulfills this role masterfully by hiding iptables complexity without sacrificing the control needed to keep corporate or personal environments safe against cyber threats.

Adopting good network administration practices from the beginning of configuration avoids future headaches with intrusions and data leaks. Take time to document exceptions created in your firewall and perform regular external connectivity tests to ensure only intentional services remain visible to the rest of the world.