Block and Unblock IPs in UFW

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

3291 views
d

By. Jacob

Edited: 2020-06-28 15:44

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:

#!/bin/bash
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:

#!/bin/bash
echo "Enter the IP that you want to unblock in UFW:"
read ipaddr

ufw delete deny from $ipaddr

Denying outgoing traffic

UFW is also an excellent way to block outgoing traffic to specific websites. Unfortunately, it does not seem like we can block a hostname, so if a website changes its IP address, we will need to block it again; that can however be automated with a bash script.

To block all outgoing traffic to a specific IP address, we may type this command:

ufw deny out from any to [ip_address]

Tell us what you think:

  1. Understanding file permissions in Unix / Linux based systems, and how to make files immutable.
  2. In this article I will explain how to enable a swapfile on small instances, and why it might be useful, even if you do have enough physical memory.
  3. How to determine an optimal value for pm.max_children and related php-fpm settings for your server and web applications.
  4. Tutorial showing how to configure a VirtualBox Guest VM with HOST-only and NAT adapter, while using the WWW folder from the HOST OS.
  5. You may have wondered what the /etc/php/8.0/conf.d/ directory is for in Debian and Ubuntu, and whether it is better to edit the conf.d files than editing php.ini directly; find out in this Tutorial.

More in: Linux servers