Report this

What is the reason for this report?

How To Setup a Firewall with UFW on an Ubuntu and Debian Cloud Server

Updated on April 6, 2022
Shaun Lewis

By Shaun Lewis

English
How To Setup a Firewall with UFW on an Ubuntu and Debian Cloud Server

Introduction

Setting up a functioning firewall is crucial to securing your cloud server. Previously, setting up a firewall was done through complicated or arcane utilities. Many of these utilities (e.g., iptables) have a lot of functionality built into them, but do require extra effort from the user to learn and understand them.

Another option is UFW, or Uncomplicated Firewall. UFW is a front-end to iptables that aims to provide a more user-friendly interface than other firewall management utilities. UFW is well-supported in the Linux community, and is typically installed by default on many distributions.

In this tutorial, you’ll set up a firewall using UFW to secure an Ubuntu or Debian cloud server. You’ll also learn how to set up UFW default rules to allow or deny connections for ports and IP addresses, delete rules you’ve created, disable and enable UFW, and reset everything back to default settings if you prefer.

Prerequisites

To follow this tutorial, you will need a server that’s running either Ubuntu or Debian. Your server should have a non-root user with sudo privileges. To set this up for Ubuntu, follow our guide on Initial Server Setup with Ubuntu 20.04. To set this up for Debian, follow our guide on Initial Server Setup with Debian 11. Both of these initial server setup guides will ensure that you have UFW installed on your machine and that you have a secure environment you can use to practice creating firewall rules.

Using IPv6 with UFW

If your Virtual Private Server (VPS) is configured for IPv6, ensure that UFW is configured to support IPv6 so that it configures both your IPv4 and IPv6 firewall rules. To do this, open the UFW configuration file in your preferred text editor. Here we’ll use nano:

  1. sudo nano /etc/default/ufw

Confirm that IPV6 is set to yes:

/etc/default/ufw
# /etc/default/ufw # # 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

After you’ve made your changes, save and exit the file. If you’re using nano, press CTRL + X, Y, and then ENTER.

Now restart your firewall by first disabling it:

  1. sudo ufw disable
Output
Firewall stopped and disabled on system startup

Then enable it again:

  1. sudo ufw enable
Output
Firewall is active and enabled on system startup

Your UFW firewall is now set up to configure the firewall for both IPv4 and IPv6 when appropriate. Next, you’ll adjust default rules for connections to your firewall.

Setting Up UFW Defaults

You can improve your firewall’s efficiency by defining default rules for allowing and denying connections. UFW’s default is to deny all incoming connections and allow all outgoing connections. This means anyone trying to reach your server would not be able to connect, while any application within the server is able to connect externally. To update the default rules set by UFW, first address the incoming connections rule:

  1. sudo ufw default deny incoming
Output
Default incoming policy changed to 'deny' (be sure to update your rules accordingly)

Next, address the outgoing connections rule:

  1. sudo ufw default allow outgoing
Output
Default outgoing policy changed to 'allow' (be sure to update your rules accordingly)

Note: If you want to be more restrictive, you can deny all outgoing requests. This option is based on personal preference. For example, if you have a public-facing cloud server, it could help prevent any kind of remote shell connections. Although, it does make your firewall more cumbersome to manage because you’ll have to set up rules for all outgoing connections as well. You can set this as the default with the following:

  1. sudo ufw default deny outgoing

Allowing Connections to the Firewall

Allowing connections requires changing the firewall rules, which you can do by issuing commands in the terminal. If you turned on your firewall now, for example, it would deny all incoming connections. If you’re connected over SSH to your server, this would be a problem because you would be locked out of your server. Prevent this from happening by enabling SSH connections to your server:

  1. sudo ufw allow ssh

If your changes were successful, you’ll receive the following output:

Output
Rule added Rule added (v6)

UFW comes with some defaults such as the ssh command used in the previous example. Alternatively, you can allow incoming connections to port 22/tcp, which uses Transmission Control Protocol (TCP) to accomplish the same thing:

  1. sudo ufw allow 22/tcp

If you tried this after you’ve already run allow ssh, however, you’ll receive the following message since the rule already exists:

Output
Skipping adding existing rule Skipping adding existing rule (v6)

If your SSH server is running on port 2222, you could allow connections with the same syntax, but replace it with port 2222. Please note that if you use the port number by itself, it effects tcp and udp as well:

  1. sudo ufw allow 2222/tcp
Output
Rule added Rule added (v6)

Securing Web Servers

To secure a web server with File Transfer Protocol (FTP) access, you’ll need to allow connections for port 80/tcp.

Allowing connections for port 80 is useful for web servers such as Apache and Nginx that listen to HTTP connection requests. To do this, allow connections to port 80/tcp:

  1. sudo ufw allow 80/tcp

UFW typically provides the profiles with the rules required for the web server to function. If not, the web server profiles may be stored as “WWW” and open as ftp or tcp, as in the following examples:

  1. sudo ufw allow www

You can also use ftp or port 21 to allow for FTP connections:

  1. sudo ufw allow ftp
  1. sudo ufw allow 21/tcp

For FTP connections, you also need to allow connections for port 20:

  1. sudo ufw allow 20/tcp

Your adjustments will depend on what ports and services you need to open, and testing may be necessary. Remember to leave your SSH connection allowed as well.

Specifying Port Ranges

You can also specify ranges of ports to allow or deny with UFW. To do this, you must first specify the port at the low end of the range, follow that with a colon (:), and then follow that with the high end of the range. Lastly, you must specify which protocol (either tcp or udp) you want the rules to apply to.

For example, the following command will allow TCP access to every port from 1000 to 2000, inclusive:

  1. sudo ufw allow 1000:2000/tcp

Likewise, the following command will deny UDP connections to every port from 1234 to 4321:

  1. sudo ufw deny 1234:4321/udp

Specifying IP Addresses

You can allow connections from a specific IP address such as in the following. Be sure to replace the IP address with your own information:

  1. sudo ufw allow from your_server_ip

As these examples demonstrate, you have a lot of flexibility when it comes to adjusting firewall rules by selectively allowing certain ports and IP address connections. Check out ourguide to learn more about allowing incoming connections from a specific IP address or subnet.

Denying Connections

If you wanted to open up all of your server’s ports — which is not recommended — you could allow all connections and then deny any ports you don’t want to give access to. The following example is how you would deny access to port 80:

  1. sudo ufw deny 80/tcp

Deleting Rules

If you want to delete some of the rules you’ve administered, use delete and specify the rule you want to eliminate:

  1. sudo ufw delete allow 80/tcp
Output
Rule deleted Rule deleted (v6)

If the rules are long and complex, there’s an alternative two-step approach. First, generate a numbered list of current rules:

  1. sudo ufw status numbered

Then, with this numbered list, review which rules are currently allowed and delete the rule by referring to its number:

  1. sudo ufw delete number
Output
Status: active To Action From -- ------ ---- [ 1] OpenSSH ALLOW IN Anywhere [ 2] 22/tcp ALLOW IN Anywhere [ 3] 2222/tcp ALLOW IN Anywhere [ 4] 80 ALLOW IN Anywhere [ 5] 20/tcp ALLOW IN Anywhere …

For example, if port 80 is number 4 on the list, you’d use the following syntax. You may also be prompted with a question if you want to proceed with the operation. You can decide yes y or no n:

  1. sudo ufw delete 4
Output
Deleting: allow 80 Proceed with operation (y|n)? y Rule deleted (v6)

Enabling UFW

Once you’ve defined all the rules you want to apply to your firewall, you can enable UFW so it starts enforcing them. If you’re connecting via SSH, make sure to set your SSH port, commonly port 22, to allow connections to be received. Otherwise, you could lock yourself out of your server:

  1. sudo ufw enable
Output
Firewall is active and enabled on system startup

To confirm your changes went through, check the status to review the list of rules:

  1. sudo ufw status
Output
Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere 22/tcp ALLOW Anywhere 2222/tcp ALLOW Anywhere 20/tcp ALLOW Anywhere 80/tcp DENY Anywhere …

You can also use verbose for a more comprehensive output:

  1. sudo ufw status verbose

To disable UFW, run the following:

  1. sudo ufw disable
Output
Firewall stopped and disabled on system startup

Resetting Default Settings

If for some reason you need to reset your cloud server’s rules to their default settings, you can do so with the ufw reset command. Please note that you’ll receive a prompt to write y or n before resetting everything since doing so can disrupt existing SSH connections:

  1. sudo ufw reset
Output
Resetting all rules to installed defaults. This may disrupt existing ssh connections. Proceed with operation (y|n)? y Backing up 'user.rules' to '/etc/ufw/user.rules.20220217_190530' Backing up 'before.rules' to '/etc/ufw/before.rules.20220217_190530' Backing up 'after.rules' to '/etc/ufw/after.rules.20220217_190530' Backing up 'user6.rules' to '/etc/ufw/user6.rules.20220217_190530' Backing up 'before6.rules' to '/etc/ufw/before6.rules.20220217_190530' Backing up 'after6.rules' to '/etc/ufw/after6.rules.20220217_190530'

Resetting to default settings will disable UFW and delete any rules you previously defined. The default settings, however, will not change to their original settings if you modified them at all. Now you can start fresh with UFW and customize your rules and connections to your preference.

Conclusion

In this tutorial, you learned how to set up and configure your cloud server to allow for or restrict access to a subset of ports or IP addresses. Additionally, you practiced deleting any rules you no longer want and confirming those changes were accounted for by disabling and then enabling your UFW firewall. Finally, you’ve learned how to reset your UFW firewall back to default settings. To read more about what’s possible with UFW, check out our guide on UFW Essentials: Common Firewall Rules and Commands.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author

Shaun Lewis
Shaun Lewis
Author

Still looking for an answer?

Was this helpful?
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Great article, glad I found this because looking at the iptables firewall option was way over my head as a noob. Quick question, aside from having this firewall setup, should I still use the iptables firewall option as well or is there another form of server security I should be using as well. Thanks for the info here and the help.

@james: UFW is an iptables wrapper, you’re indirectly using iptables while using ufw. ;]

useful article, I set up everything I needed in 5 minutes…

This works in Debian too; you might want to change the title so as not to imply that it’s just for Ubuntu.

@caesarsgrunt: Thanks! Updated.

So to allow ssh should I use:

sudo ufw allow ssh

AND

sudo ufw allow 22/tcp ?

Thanks

No, you should use only one of them, not both.

What’s the easiest way to add a whole range of specific IP addresses, such as https://www.cloudflare.com/ips?

Thanks for this. Made it pretty quick for me to get started. Used iptable setups before, but they can be annoying to setup, and have remember the rules etc.

On my debian/wheezy64 i keep having problems with ufw: trying to enable it causes the error “ERROR: problem running ufw-init” and it will not autostart at boot, does anyone know how to solve this? On my local wheezy installation everything works fine, but my box at digitalocean won’t do it :(

@manuel.bua: Try editing <pre>/etc/default/ufw</pre> and setting IPv6 to no.

@KamalNasser: that did it, thanks! So i suspect this has to do with the fact it’s a VPS since my parallel wheezy installation in VirtualBox is working fine.

@manuel.bua: It’s because our platform does not support IPv6 so you have to disable ufw’s IPv6 support in order for ufw to work :]

Ok, thanks for clarifying: keep up the good work guys, this platform is really awesome and i’m looking forward to making big use out of it!

Nice. How do I forward port 8080(tomcat) to 80 via ufw? Vic

@cekvenich.vic: Edit <strong>/etc/ufw/before.rules</strong> and add <pre>*nat :PREROUTING - [0:0]

iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

don’t delete the ‘COMMIT’ line or these nat table rules won’t be processed

COMMIT</pre> at the very top of the file.

Save and restart ufw:

<pre>sudo service ufw restart</pre>

What is the difference between sudo ufw insert 1 allow 80 and sudo ufw allow 80/tcp If I only want to allow web browser traffic (http/https) on this port, what shall enter?

Both should work fine. The first command explicitly tells ufw to insert the rule at the top while the second command will insert it at the bottom.

Loved the article - was one of the first available in my google search on UFW – been a while!

I followed these instructions and when UFW is enabled I cannot access my site via a browser going to my IP address (when I could before). The only rules I have on my UFW are:

To Action From


2222/tcp ALLOW IN Anywhere 2222/tcp ALLOW IN Anywhere (v6)

(Where 2222 is my SSH port, but in reality 2222 is not it, just using this for privacy concerns).

I figured it out… rookie mistake I suppose. I had to open up port 80 so that my site could load since nginx is listening on that port.

Very nicely written article. Admins from RHEL/Centos are more comfortable with iptables. Do you think UFW will simplify life ? Can this be installed with yum ? Is their any way to restrict server access by source ip ? Appreciate if you could also help with some syntax to avoid DDOS attacks.

@Deepak: UFW is a wrapper for iptables, but it usually easier to manage. I believe you will have to compile ufw yourself if you want to install it on a Redhat-based system such as CentOS. <blockquote>Is their any way to restrict server access by source ip ? </blockquote>Yes, read this article and you’ll know how to do that :] <blockquote>Appreciate if you could also help with some syntax to avoid DDOS attacks.</blockquote>There isn’t much you can do using UFW to protect against DDoS attacks other than rate-limiting access to port 80 but that wouldn’t help much if it’s a relatively large <strong>D</strong>DoS attack.

I will be adding a ev SSL, do I need to allow port 443 for https?

Also, im adding a slave server, do I need to open up a specific port on the master for the slave server? And then open a port on the slave server itself to connect to the master?

For Postfix, to receive email, do I open up port 25? Would I just enter sudo ufw allow 25/tcp # smtp?

@Jason: Correct.

@KiwoT: Yes, you will need to allow connections to port 443. What do you mean by a slave server?

Thanks for creating the turorial. I’ve got one question though; I have set up UFW to, on default, deny all ingoing and outgoing (excluding SSH and webserver) requests. Because of this I am unable to make DNS requests (ping digitalocean.com throws ‘Unknown host’, PHP cURL can’t connect, apt-get ‘fails to fetch’). Do you know how I can whitelist it? I’ve tried allowing port 53 (on UDP and TCP) and 1024-65535 (on UDP), but that didn’t work. Neither did ’ iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT '.

I’m having the exact same issue as Remi is.

Ah, I figured it out. If you were getting any errors like I was following this guide helped me. http://blog.bodhizazen.net/linux/how-to-use-ufw-in-openvz-templates/

Hi,

I have a ubuntu 13.10 box, i successfully installed and started ufw with no problems. Is still true that we have to disable ipv6 from /etc/default/ufw ? If i’m getting no errors , should eitherway disable it? (haven’t tried yet rebooting)

@Remi and @wiz.master49, if you disable outgoing connections… that’s whay you get, that you cannot go out… You should allow outlgoing conections unless you really know what you’re doing.

Cheers.

Hi,

Having trouble getting ufw to start on reboot. I disabled IPv6 from the /etc/default/ufw but it still shows inactive after reboot. This is a pretty fresh machine without much installed so not sure where to troubleshoot.

I’ve set it up following this guide and it works fine. The only part I’m wondering about is:

“You can also specify port ranges with UFW. To allow ports 1000 through 2000”

OK, but is this necessary? If so, why? And how do you determine which port range to open? Or can you just skip this step?

@frism: No it’s not necessary, it’s just explaining the concept.

I’m having the same problem as Sean W. Everytime I boot my servers (Ubuntu 12.04) ufw status is inactive. I’ve tried everything Google throws at me without any luck.

Any ideas what might be causing this?

@tjlein: Is there any error ouput when you run:

<pre> sudo ufw enable </pre>

Does it report: “Firewall is active and enabled on system startup” and still not work?

@Andrew SB: Running ufw enable reports “Firewall is active and enabled on system startup”.

When I reboot the server and run command ufw status it returns “Status: inactive”

I have also tried to install sysv-rc-conf in which I selected ufw to start at reboot. Still not active after reboot.

Now I just noticed that actually on some servers ufw is active after reboot but on others not. I’m trying to figure out why. All servers are Ubuntu 12.04 and they differ usually only by web server (nginx vs apache), database (postgresql vs mysql) and programming languages (python vs php).

Okay I managed to get ufw starting at boot on those servers it did not work. Ufw and iptables where both setup so that they would start at boot. I guess this leads to ufw not starting? When I removed iptables from starting at boot ufw started working. I’m not exactly sure if this is okay though?

@tjlein: That makes sense. ufw is just a nice front end to iptables. It tries to start iptables, sees that it is already started, and then disables itself thinking that you’ve made manual changes to iptables it shouldn’t overwrite.

If you want to make sure for yourself that the firewall is working, just try to connect to a port you have closed:

<pre> telnet YOUR.IP.ADDRESS PORT# </pre>

If the port is firewalled, you should get “telnet: Unable to connect to remote host: Connection refused”

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.