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]