Basic firewall usage

If you run a server in the cloud, you need to use a firewall to protect it. Let's look at the most basic settings of Ubuntu's ufw system.

At a high level, a firewall is an application that controls what applications are allowed to communicate on which ports. The firewall application controls a list of ports that are exposed to third parties over the Internet. It can further lock down which IP addresses on the public Internet are allowed to access specific ports.

For example, if you have a static IP address for your home or office, you can lock down port 22 (used for SSH access) to only your IP address. You’ll still be able to SSH into a server from the designated location, but the port will be seen as closed to the rest of the world.

Assuming you’ve just created a new Ubuntu server and connected via SSH, you can enable the firewall with two specific rules:

sudo ufw default allow outgoing
sudo ufw default deny incoming

Your server is now configured to allow outgoing network connections to any destination and to deny all incoming connections. Your active connection will remain open, but no new connections will be possible. Do not close your connection at this stage or you’ll lose access to the server!

To add your own IP address to the firewall explicitly, you first need to identify it. Several web services exist that will echo back the IP address you’re using. My typical approach is to leverage OpenDNS via Bash to return my IP address:

dig @resolver1.opendns.com ANY myip.opendns.com +short

Armed with your network’s IP address (assume 123.45.67.89 in this example), you can now explicitly reopen port 22 for SSH to your network:

sudo ufw allow from 123.45.67.89 to any port 22

Other ports can be opened in a similar fashion. To open ports 80 and 443 (for HTTP and HTTPS, respectively) to the entire world, you would use:

sudo ufw allow 80
sudo ufw allow 443

The firewall supports filtering data based on protocol as well – TCP or UDP. You can even whitelist (or block) ranges of IP addresses using CIDR notation rather than enumerating individual addresses.