Security

Firewall rules: opening and closing ports

With the principle of least privilege, open essential ports and close the rest. A practical firewall tutorial with UFW and iptables, along with fixing the lockout error.

Security

Why Is the Firewall Your Server's Most Important Line of Defense?

When you first bring up a server, all ports are in listening mode by default. This means anyone on the internet can connect to your services—unless you stop them yourself. This is where the firewall comes into play. A firewall is not a luxury tool but a fundamental necessity for any server connected to the internet. Without it, your server is like a house with a front door but no lock.

In this article, you're not going to read abstract theories. You're going to learn how to open essential ports with a firewall, close the rest, and most importantly, avoid locking yourself out of your server. This last point—the lockout error—is one of the most common mistakes made by novice (and even experienced!) administrators.

The Principle of Least Privilege; the Starting Point of Every Firewall Rule

Before you even run a single command, you must accept one principle: anything that isn't necessary must be closed. This means instead of thinking "which ports should I open?", you should think "which ports am I forced to open?". This mindset is the Principle of Least Privilege, which is fundamental in network security.

For a typical web server, the minimum essential ports are usually:

  • Port 22 (SSH) for server management
  • Port 80 (HTTP) for web traffic
  • Port 443 (HTTPS) for encrypted traffic
  • Port 53 (DNS) only if your server provides DNS services
  • Port 25 (SMTP) only if your server sends email

All other ports—from 3306 for MySQL to 5432 for PostgreSQL and 6379 for Redis—should be opened only for specific IP addresses, not for the entire internet. If your database and web server are on the same machine, you don't even need to open the database port to the outside; connecting via localhost is sufficient.

Before You Start; Identifying Currently Open Ports

The first step is to see the current status. With this command, you can see which ports are listening:

ss -tulpn

The output of this command shows a list of TCP and UDP ports along with the process listening on them. If you see unknown services, it's time to investigate why they're running on your server. Do this before making any changes to have an accurate picture of your current attack surface.

Practical Firewall Implementation with UFW

If your server runs Ubuntu or Debian, UFW (Uncomplicated Firewall) is the simplest and safest way to manage firewall rules. UFW is essentially a user interface for iptables that hides its complexity.

First, install and enable UFW:

sudo apt update
sudo apt install ufw -y
sudo ufw enable

Now set the default rule to deny so that any incoming connection that hasn't been explicitly allowed is rejected:

sudo ufw default deny incoming
sudo ufw default allow outgoing

These two lines are the heart of the principle of least privilege. Incoming is closed, outgoing is open. Now open the essential ports:

sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

If you want SSH to be accessible only from a specific IP (which is highly recommended), replace the first line with:

sudo ufw allow from 203.0.113.10 to any port 22 proto tcp

In this example, replace 203.0.113.10 with your actual IP address. This reduces SSH's attack surface from the entire internet to a single address.

Checking Firewall Status

After applying the rules, check the status:

sudo ufw status verbose

The output should look something like this:

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

To                         Action      From
--                         ------      ----
22/tcp                     ALLOW IN    203.0.113.10
80/tcp                     ALLOW IN    Anywhere
443/tcp                    ALLOW IN    Anywhere

If you entered a rule incorrectly, remove it with sudo ufw delete allow 80/tcp.

Managing the Firewall with iptables for Advanced Scenarios

UFW is sufficient for 90% of cases, but if you need more complex rules—such as rate limiting connections or port forwarding—you'll need to work directly with iptables. iptables manages the INPUT, OUTPUT, and FORWARD chains.

Simple example: closing port 3306 (MySQL) to everyone except a specific IP:

sudo iptables -A INPUT -p tcp --dport 3306 -s 198.51.100.20 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 3306 -j DROP

The order of rules in iptables is critical. The first rule that allows must come before the second rule that drops. iptables evaluates rules in order, and the first matching rule is executed.

To rate-limit SSH connections (preventing brute force):

sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP

These rules allow a maximum of 3 new SSH connections every 60 seconds. A fourth connection within that time window is silently dropped.

Saving iptables Rules

Important note: iptables rules are lost when the server reboots. For permanent persistence, depending on your Linux distribution, use one of these methods:

# On Ubuntu and Debian
sudo apt install iptables-persistent -y
sudo netfilter-persistent save

# On CentOS and RHEL
sudo yum install iptables-services -y
sudo systemctl enable iptables
sudo service iptables save

The Lockout Error; How It Happens and How to Recover

The most famous scary scenario for any server administrator is this: you apply a firewall rule and immediately your SSH connection drops. There's no way back. This usually happens for one of two reasons:

  1. You set the default rule to deny but didn't open port 22.
  2. You opened port 22 but only for the wrong IP (e.g., the office IP instead of your home IP).

First recovery method: If you have access to the server via a web console (such as VNC or noVNC in the control panel), log in from there and remove the incorrect rule. Do this with sudo ufw delete deny 22/tcp or sudo iptables -D INPUT -p tcp --dport 22 -j DROP.

Second recovery method: If you don't have a console, enable the "server access" or "rescue mode" option from the server management panel. In this mode, the server boots with a temporary operating system, and you can mount the main disk and remove the firewall rules from the configuration file.

Preventive tip: Before applying any new rule, set a timer for yourself:

sudo shutdown -r +5

This command reboots the server in 5 minutes. If the rule was wrong and the connection drops, wait for the server to reboot, and the temporary rules (which weren't saved) will be gone. After confirming the rules are correct, cancel the reboot with sudo shutdown -c.

Another Common Mistake: Opening the Database Port to the Entire Internet

Many developers open port 3306 or 5432 to everyone so they can connect to the database from home. This almost always ends in a security disaster. Bots are constantly scanning these ports, and if your database has a weak password, it will be hacked in less than 24 hours.

The right way: either use an SSH Tunnel, or open the port only for your own IP. An SSH Tunnel works like this:

ssh -L 3306:localhost:3306 user@your-server-ip

This command connects port 3306 on your local machine to port 3306 on the server (via SSH). Now you can connect to the database using localhost:3306, without opening a single extra port on the firewall.

Final Testing and Continuous Firewall Monitoring

After applying the rules, be sure to test from outside the server. From another machine (or a mobile phone with cellular data), run this command:

nc -zv your-server-ip 22
nc -zv your-server-ip 3306

The first should succeed, and the second should fail with a Connection refused or timeout error. If port 3306 responds from outside, your rule isn't working correctly.

Continuous monitoring is also important. Check firewall logs to see who's trying to access closed ports. In UFW, logs are in /var/log/ufw.log. A high number of failed attempts on a specific port is a sign of scanning or an attack.

Finally, remember that a firewall is just one layer of security. Combine it with SSH keys instead of passwords, regular operating system updates, and resource monitoring. If you're looking for infrastructure where these principles are followed by default, ServerNet's cloud services can be a good starting point; but regardless of your choice, take firewall rules seriously. This is the simplest and most effective thing you can do for your server's security.

ServerNet Support

ServerNet engineering & editorial team — specialists in infrastructure, networking and web hosting.

Security Services
Share:

Comments 0

No comments yet — be the first!

Leave a comment

Related service

Security Services

Penetration testing by OSCP-certified specialists, infrastructure hardening and 24/7 security monitoring — reports managers understand and engineers can act on.