How to open/close Ports with UFW on Ubuntu/Debian

The Uncomplicated Firewall (ufw) is the default software firewall solution for Debian-based operating systems. It is essentially a wrapper on top of iptables that allows for a more streamlined approach to managing the access on your server.

Prerequisite

Sudo access to Ubuntu or Debian server with Iptable installed in it.

Step 1 : Check UFW Status

UFW is part of the standard Ubuntu/Debian installation and should be present on your system. You can check ufw service running status through below mentioned commands

# systemctl status ufw

UFW is disabled by default. You can check the status of the UFW service with the following command:

# ufw status

or

# ufw status verbose

Note

If UFW firewall is enabled on your Server node then you have to allow required port in UFW also.

Step 2 : Allow port

Rules can be added in two ways: By denoting the port number or by using the service name. You can open the port by specifying the port and protocol (TCP/UDP) in UFW Firewall.

The following example shows the format for rules within ufw :

ufw [allow/deny] from [ip] to [dest/any] port [port]

Note

You can also specify ranges of ports by separating the ports by a colon, such as 2222:3333 . Additionally, you can specify a subnet mask for IP addresses, such as 1.2.3.4/32 . Furthermore, ufw allows for common service whitelisting by name. This means you can you specify ssh in the rule rather than specifying port.

For example, to allow both incoming and outgoing connections on desired port for SSH, you can run

# ufw allow ****

or

# ufw allow ****/tcp

Note

Please replace **** with desired port number to be blocked.

Deny Port/Outgoing Traffic

To close port in ufw please refer command below.

# ufw deny ****/tcp

To prevent outgoing traffic on port please refer below.

# ufw deny out ****

To deny outgoing traffic for the specific ip:

# ufw allow out to xxx.xx.xx.xx port ****

Note

Please replace xxx.xx.xx.xx with desired IP and **** with desired port number to be blocked.

Step 3 : Check UFW Status

You can check the status of UFW at any time with the command: sudo ufw status. This will show a list of all rules, and whether or not UFW is active:

# ufw status
Status: active

To                         Action      From
--                         ------      ----
22                         ALLOW       Anywhere
1167                       ALLOW       Anywhere
10050                      ALLOW       Anywhere
80                         ALLOW       Anywhere
443                        ALLOW       Anywhere
22 (v6)                    ALLOW       Anywhere (v6)
1167 (v6)                  ALLOW       Anywhere (v6)
10050 (v6)                 ALLOW       Anywhere (v6)
80 (v6)                    ALLOW       Anywhere (v6)
443 (v6)                   ALLOW       Anywhere (v6)

Conclusion

You learned how to open ssh port using ufw on Ubuntu or Debian Linux server. See ufw home page here for more info.