Share via:

Block and Unblock IPs in UFW

How to easily block and unblock IPs in the UFW firewall.


Edited: 2020-05-05 23:21

Blocking an IP in Linux using UFW is fairly straight forward. But, if you also got other rules in the firewall, then you need to remember to prioritize the new rule you are adding. Unfortunately, there seem to be no simple "block command"—we can however create our own.

To block an IP address, add a rule with the priority of "1":

ufw insert 1 deny from [ip_address]

Note. Rules will need to be added with a priority if you want to block access to all web services, hence the "insert 1".

To unblock an IP address, simply run this command:

ufw delete deny from [ip_address]

It is also possible to add a rule with a comment to better remember why you blocked someone:

ufw insert 1 deny from [ip_address] comment 'hacker'

Creating a wrapper script

I often create wrapper scripts for commands I do not use very often, as it saves me the time of looking up how they are used every time I need to use them.

Wrapper scripts can be placed in /usr/local/bin, which allows you to call them from anywhere — it even enables TAB completion.

If you find it hard to memorize how to use the command, you can create a small wrapper .sh script and place it in /usr/local/bin banip_ufw.sh:

printf "\nEnter the IP that you want to ban in UFW:\n"
read ipaddr

printf "\nType a short comment:\n"
read comment

ufw insert 1 deny from $ipaddr to any comment "$comment"

We can also make a script for unblocking users, unbanip_ufw.sh:

echo "Enter the IP that you want to unblock in UFW:"
read ipaddr

ufw delete deny from $ipaddr