How to Configure Firewall in Ubuntu Linux VPS to Allow or Deny Ports
Posted in: Linux, Security, Ubuntu, VPS

How to Configure Firewall in Ubuntu Linux VPS to Allow or Deny Ports

Having firewalls installed and configured in Linux environments is important, especially for VPS hosting, as they help safeguard your system from unauthorized access, prevent brute force attacks, and keep your services secure.

UFW, or Uncomplicated Firewall, is a user-friendly tool that simplifies the management of firewall rules on Ubuntu Linux. It provides an easier way to control network traffic. You can allow or block access to specific ports, which improves the security of your server or VPS.

Why Use UFW on a Linux VPS

The primary purpose of UFW is to provide a straightforward way to manage your server’s firewall. Its benefits include:

  • Simplicity: UFW abstracts complex firewall configurations and presents them in an easy-to-use manner. It simplifies firewall management and configuration, making it accessible even for those with limited Linux experience.
  • Flexibility: UFW allows for complex configurations when needed.
  • Resource Efficiency: UFW is lightweight and doesn’t impact system performance.
  • Default Deny Policy: UFW operates on a “default deny” basis, blocking all incoming connections unless explicitly allowed.
  • Integration: It’s well-integrated with Ubuntu and other Debian-based systems.

In this guide, you will learn how to configure UFW / firewall to allow specific ports in Ubuntu. You will also explore various aspects, best practices, and security tips associated with UFW.

To check if UFW is already installed on your Ubuntu system, use the following command:

> sudo ufw version

If UFW is installed, you’ll see the version information. If not, you’ll get an error message.

Installing UFW / Firewall on Ubuntu

In case UFW is not installed, then you can install it.

To install UFW on Ubuntu, use the following command:

> sudo apt install ufw

Once installed, you can enable it to run at every reboot:

> sudo ufw enable

You can check the current status of UFW service to ensure it is running:

> sudo ufw status

If it is not running, then you can start it by using any one of the following commands:

> sudo service ufw start
> sudo systemctl start ufw

Now, the UFW service is running and configured to automatically start at reboot.

Checking Open Ports with UFW

Once UFW is active, you can view the currently open ports by running:

> sudo ufw status numbered

This command provides a numbered list of the active rules, making it easier to manage or delete specific rules later.

For example, the output of the above command may look like this:

     To                         Action      From
     --                         ------      ----
[ 1] 22/tcp                     ALLOW IN    Anywhere
[ 2] 22/tcp (v6)                ALLOW IN    Anywhere (v6)

This above output indicates that incoming connections to port 22 (TCP) are allowed from any source IP address, for both IPv4 and IPv6 traffic. Port 22 is typically used for SSH (Secure Shell) connections, which you would use to manage your Linux VPS.

Allow Ports with UFW / Firewall

Using UFW, you can allow specific ports or a range of ports.

Allowing Specific Ports with UFW

You may want to allow HTTP traffic by enabling port 80:

> sudo ufw allow 80/tcp
Rule added
Rule added (v6)

This would allow TCP connections to port 80, for both IPv4 and IPv6 traffic.

Again, you can check which ports are allowed:

> sudo ufw status numbered

You will see port 80 is also added.

     To                         Action      From
     --                         ------      ----
[ 1] 22/tcp                     ALLOW IN    Anywhere
[ 2] 80/tcp                     ALLOW IN    Anywhere
[ 3] 22/tcp (v6)                ALLOW IN    Anywhere (v6)
[ 4] 80/tcp (v6)                ALLOW IN    Anywhere (v6)

Different services running on your VPS require specific ports to be open for communication. You can enable those ports in the same way as per your requirements.

Here’s a list of commonly used ports for different services:

  • 80 TCP: HTTP (Standard web traffic)
  • 443 TCP: HTTPS (Secure web traffic)
  • 21 TCP: FTP (File transfer)
  • 22 TCP: SSH (Secure shell for remote access)
  • 25 TCP: SMTP (Outgoing email)
  • 110 TCP: POP3 (Retrieving email)
  • 143 TCP: IMAP (Accessing email on a server)
  • 465 TCP: SMTPS (Secure outgoing email)
  • 587 TCP: (Alternative port for outgoing email)
  • 993 TCP: IMAPS (Secure IMAP)
  • 995 TCP: POP3S (Secure POP3)
  • 3306 TCP: MySQL (Database connections)
  • 5432 TCP: PostgreSQL (Database connections)
  • 53 UDP: DNS (If you’re running a DNS server)
  • 123 UDP: NTP (Network Time Protocol)

For instance, if you want to allow HTTP port 80, SSL port 443 (HTTPS), and MySQL database port 3306, you would run the following commands:

> sudo ufw allow 80/tcp
> sudo ufw allow 443/tcp
> sudo ufw allow 3306/tcp

Allowing Port Ranges with UFW

To allow ports ranging from 8000 to 9000 (inclusive), you would use:

> sudo ufw allow 8000:9000/tcp

The port range 8000:9000, separated by a colon includes both the starting port (8000) and the ending port (9000).

Example: Suppose you are running multiple web applications on different ports for testing or development purposes. You might have:

  • A Node.js app on port 8080
  • A Django development server on port 8000
  • A React development server on port 3000
  • Various other services on ports up to 8999

To allow incoming connections to all these services at once, you could use:

> sudo ufw allow 3000:8999/tcp

This single rule would cover all your development servers, making it easier to manage your firewall settings during development. You have to be cautious when opening port ranges, especially on production servers. It’s generally more secure to open only the specific ports you need rather than a broad range.

The requirement for allowing UDP ports would depend on your specific configuration and the services you’re running.

Deny Ports with UFW / Firewall

When you install UFW (Uncomplicated Firewall) and enable the service, its default policy is to deny all incoming connections and allow all outgoing connections.

Here, the SSH port 22 might also be available for incoming connection as configured by your VPS provider. This means no other ports are enabled for incoming traffic unless you specifically configure them.

If you have previously allowed a certain port and now want to deny access to that specific port, you would use the “deny” command. For example, if you had previously allowed FTP traffic on port 21 and now want to block it, you can use the following command:

> sudo ufw deny 21/tcp

This command tells UFW / Firewall to deny incoming TCP connections on port 21, effectively blocking FTP access.

Again, you can check which ports are allowed:

> sudo ufw status numbered

Also, you can delete a specific rule by its number:

> sudo ufw delete [rule number]

To go back to the default policies, which is to deny all incoming connections and allow all outgoing connections, you can use the following commands:

> sudo ufw default deny incoming
> sudo ufw default allow outgoing

How to Rate Limit with UFW / Firewall

UFW / Firewall has a built-in rate-limiting feature that you could use to protect your server from brute-force attacks, especially on SSH (port 22). This feature can limit an IP address from making too many attempts to connect to a service in a short amount of time.

For SSH, you can enable rate-limiting with this command:

> sudo ufw limit 22/tcp

This would allow SSH connections but limit them to 6 or fewer connections per 30 seconds from the same IP address.

In the same way, you can rate limit for other ports as needed.

VPS Providers with Port Restrictions

Many VPS providers like DigitalOcean, Vultr, etc. often implement network-level firewalls as an additional layer of security. These network-level firewalls operate independently of UFW and can block traffic before it reaches your server. You would need to ensure that both your provider’s firewall and UFW are configured correctly to avoid conflicts.

Blocked Ports

Some VPS providers block certain ports by default, particularly those associated with email services that are used for sending emails (25, 465, 587). This is done to prevent abuse, such as the sending of spam emails from compromised servers.

Why Providers Block Email Ports

  • Spam Prevention: Blocking these ports helps prevent spammers from using VPS instances to send bulk unsolicited emails.
  • Reputation Protection: It helps maintain the cloud hosting providers’ IP reputation, which is important for all their customers.
  • Compliance: Some providers block these ports to comply with anti-spam regulations.

How to Get Blocked Ports Opened

If you need to use these blocked ports for legitimate purposes. As an example, if you are running a mail server and find that these ports are blocked, you’ll need to reach out to your provider’s support team and request that they unblock the necessary ports.

  • Explain your use case and why you need these ports opened.
  • You may need to provide details about your intended email usage and any measures you’re taking to prevent abuse.
  • Some providers may require additional verification or may have specific policies for email server usage.

Backup and Restore UFW Rules

It’s a good practice to back up your firewall configuration, especially if you have complex rules set up. To export the current UFW rules to a file:

> sudo ufw status numbered > ufw-rules-backup.txt

This command saves the numbered list of firewall rules in a text file. You can use it later for reference or restoration. You may want to use the same rules on a different server.

To restore the firewall rules:

First, reset UFW to its default state:

> sudo ufw reset

Then, use a loop to read the backup file and add each rule:

You can create a new file named “restore_ufw_rules.sh” using a text editor:

> sudo nano restore_ufw_rules.sh

Copy and paste the below script into this file.

#!/bin/bash

# Check if the backup file exists
if [ ! -f ufw-rules-backup.txt ]; then
    echo "Error: ufw-rules-backup.txt not found!"
    exit 1
fi

# Reset UFW to default state
echo "Resetting UFW to default state..."
sudo ufw reset

# Read the backup file and add each rule
echo "Restoring UFW rules..."
while read line; do
    if [[ $line == [0-9]* ]]; then
        rule=$(echo $line | cut -d ']' -f 2- | sed 's/^[ \t]*//;s/[ \t]*$//')
        echo "Adding rule: $rule"
        sudo ufw $rule
    fi
done < ufw-rules-backup.txt

# Enable UFW
echo "Enabling UFW..."
sudo ufw enable

echo "UFW rules restoration complete. Please check 'sudo ufw status' to verify."

Save the file and exit the text editor (in nano, press Ctrl+X, then Y, then Enter).

> sudo chmod +x restore_ufw_rules.sh

Run the script with sudo permissions:

> sudo ./restore_ufw_rules.sh

Finally, enable UFW if it’s not already enabled:

> sudo ufw enable

This method allows you to back up and restore your UFW rules reliably.

Reload, Reset, Disable, and Uninstall UFW

Here, you will find different commands related to UFW besides what we already covered.

Check UFW status

> sudo ufw status

This command shows the current status of UFW, including whether it’s active or inactive, and lists all the rules currently in effect.

Reload UFW

> sudo ufw reload

This command reloads the firewall rules without disabling the firewall. It’s useful when you’ve made changes to the UFW configuration files directly (not by using “ufw” commands).

Note: You don’t need to reload the UFW service after adding a rule using the “ufw allow” command. UFW automatically applies these changes.

Reloading is only necessary if you’ve manually edited configuration files.

Check user-defined rules

To view user-defined rules (also known as user rules), you can use:

> sudo ufw show user-rules

This command displays all the rules that have been added by users, as opposed to default system rules. You can see which specific ports are open and allowed by the user-defined UFW / firewall rules for incoming or outgoing traffic.

Reset UFW / Firewall rules

> sudo ufw reset

This command resets UFW to its default state. It removes all rules, disables the firewall, and resets to the default policies. Use with caution as it will erase all your custom configurations.

Stop UFW service

> sudo service ufw stop
> sudo systemctl stop ufw

You can use any one of the above commands to stop the UFW service. The firewall rules will no longer be enforced until you start the service again.

Disable UFW / Firewall

> sudo ufw disable

This command disables the firewall. Unlike stopping the service, this ensures UFW doesn’t start automatically on system boot.

Remove UFW

> sudo apt remove ufw

This command removes the UFW package from your system but leaves configuration files.

Purge UFW

> sudo apt purge ufw

This command completely removes UFW from your system, including all configuration files. Use this if you want to remove all traces of UFW from your system.

Best Practices / Security Tips for UFW / Firewall

These are several best practices and security tips to follow when using a firewall:

  • Always start with a default deny policy and only open necessary ports.
  • Be as specific as possible with your rules to minimize attack surfaces.
  • Utilize the “limit” command for rate limiting instead of complex rule sets.
  • Use rate limiting for sensitive services like SSH.
  • Use SSH key authentication instead of password authentication.
  • Keep your system and UFW updated to patch any security vulnerabilities.
Back to Top