UFW Tutorial for Ubuntu
UFW manages iptables in a little bit easier way than actually writing IPtables commands. This article will give a few examples of UFW usage.
Why Use a Firewall?
Every server listens on a port. Most clients know to go to that specific port to communicate and interact with the server. You may not want people interacting with all of the services on your server. The orange box of this netstat command shows all open ports.
Even though they are open and listening, we can use a firewall to let them speak to only certain computers, or no external computers.
Find Your IP, So You Can Allow Yourself
http://whatismyip.org is a good graphical tool, but you can also pull your ip information from the command line using ifconfig or curl.
Installing UFW on Ubuntu
First we install ufw packages
apt-get install ufw
Default Deny Rule
Next, set the default policy to deny everything.
ufw default deny
UFW Allow Services
We’ll need to add the services and ports we want. Here are a few examples that are specific
ufw allow proto tcp from 10.123.0.0/16 to 0.0.0.0/0 port 22 comment "ipv4 only"
ufw allow proto tcp from 192.0.2.2 to any port 22 comment "both ipv4 and ipv6"
And here are some more wide open examples (ipv4 + ipv6 because of “any”):
ufw allow proto tcp from any to any port 80
ufw allow proto tcp from any to any port 443
ufw allow from 192.0.2.2
You can also specify named ports as found in the /etc/services:
ufw allow ssh
ufw allow http
ufw allow https
Here is a sample of the list of named services:
Enabling Firewall Rules
Finally, enable logging and then enable the changes you made:
ufw logging on
ufw enable
View UFW Status/Rules
You can review iptables directly:
iptables -L
or you can see ufw’s status like so:
ufw status
ufw status numbered
Deleting Rules
First, find the rule numbers, then delete them (x = the rule number):
ufw status numbered
ufw delete X
Script to Automate Dynamic Access
You may be interested in this related tutorial on updating UFW rules using cron/bash to allow dynamic remote access.