Beamtic's logo
  1. Create user
Home

Share via:

Block and Unblock IPs in UFW

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

160 views

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]

Comments

  1. How to configure a SMTP server with letsencrypt on an amazon EC2 instance.
  2. How to have multiple public IPs with one AWS EC2 Instance
  3. 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.
  4. How to create symbolic links for Apache2 v-host files in sites-available.

More in: Linux servers