If you’re new to Linux, iptables probably seems intimidating, so here’s the easy way out.
UFW stands for Uncomplicated FireWall and it’s way simpler than iptables You get a bit less flexibility, but it’s all worth it because you need to spend half as much time managing your firewall. Also, if you’re using Vultr, or another provider that offers IPv6 and IPv4 addresses on your VPS, UFW adds rules for both, something iptables can’t do.
UFW has three basic modes of operation:
Allow is used to well, allow, requests to go through certain ports. For example, to allow SSH, you just run:
sudo ufw allow 22/tcp
and port 22 is now allowed on both IPv4 and IPv6. Or, to prevent simple DoS attacks and/or some brute force attacks, you can limit the port to 6 new connections every 30 seconds, with:
sudo ufw limit 22/tcp
Unfortunately, there is no easy way to change the limits themselves, you can only choose to limit or allow. Anyways, what happens when you change ports and want to close one? Well, just use the
sudo ufw delete limit 22/tcp
or, if you used
sudo ufw delete allow 22/tcp
and open the new port.
One more thing, on a fresh Ubuntu install, run
sudo ufw enable
to activate UFW.
Adding iptables rules
What happens if you want to add some custom iptables rules? Well, UFW supports this by editing the
/etc/ufw/before.rules for IPv4 and
/etc/ufw/before6.rules for IPv6. Everything in there gets added to the iptables chain before the rest of the UFW rules. If you want to add rules after the UFW chain, then add your iptables rules(which you get from
UFW even has some built-in profiles for certain application. For example, instead of specifying the port for SSH, you can just run:
sudo ufw allow SSH
and port 22/tcp will be opened. You can also use profiles for
https, and more.
Great, now you have UFW up and running. But what if you use Fail2ban? The default
ipables mode won’t work anymore because UFW overrides that. Luckily all you need to do is change
iptables-allports in your
jail.local file to
ufw and restart fail2ban. Now, fail2ban should insert rules into UFW. You can verify this by running
sudo ufw status after an IP is blocked, and you should see the following near the top:
To Action From -- ------ ---- Anywhere REJECT 18.104.22.168
#Allow a port sudo ufw allow port/proto #Limit a port sudo ufw limit port/proto #Delete an allow rule sudo ufw delete allow port/proto #Delete a limit rule sudo ufw limit port/proto