1. Home
  2. Helpful Tips
  3. How to Block an IP Address with UFW

How to Block an IP Address with UFW

If you would like to block an IP address from using your website or other services, you can use UFW.

$ sudo ufw deny from {ipaddress} to any

See the current UFW status:
$ sudo ufw status
Status: active

To Action From
— —— —-
OpenSSH ALLOW Anywhere
80 ALLOW Anywhere
443 ALLOW Anywhere
22 DENY Anywhere
12212 ALLOW Anywhere
3306 DENY Anywhere
Anywhere DENY {ip address}
OpenSSH (v6) ALLOW Anywhere (v6)
80 (v6) ALLOW Anywhere (v6)
443 (v6) ALLOW Anywhere (v6)
22 (v6) DENY Anywhere (v6)
12212 (v6) ALLOW Anywhere (v6)
3306 (v6) DENY Anywhere (v6)

However, I’ve been noticing that this doesn’t work if you don’t order the rules correctly. For example, if you need to block web traffic, the deny rules need to be inserted before the port 80 and 443 Allow Anywhere rules!

To show the priority ordering of ufw rules, do this:
$ sudo ufw status numbered

Status: active

To Action From
— —— —-
[ 1] OpenSSH ALLOW IN Anywhere
[ 2] 80 ALLOW IN Anywhere
[ 3] 443 ALLOW IN Anywhere
[ 4] 22 DENY IN Anywhere
[ 5] 11992 ALLOW IN Anywhere
[ 6] 3306 DENY IN Anywhere
[ 7] {ipaddress} Anywhere DENY IN

My IP deny rule was failing on the web because it was placed last.

You can order rules in two ways:

1. Inserting rules at the earlier priority

For pre-existing broken, delete them:
$ sudo ufw delete

For example, I deleted rule 7 above. If you do not delete pre-existing rules, you’ll get an error: “Skipping inserting existing rule.”

You can insert rules before web traffic (port 80 is rule 2):
$ sudo ufw insert 2 deny from {ipaddress} to any
Rule inserted

This results in something like this:
sudo ufw status numbered
To Action From
-- ------ ----
[ 1] OpenSSH ALLOW IN Anywhere
[ 2] Anywhere DENY IN {ipaddress}
[ 3] Anywhere DENY IN {ipaddress}
[ 4] Anywhere DENY IN {ipaddress}
[ 5] 80 ALLOW IN Anywhere
[ 6] 443 ALLOW IN Anywhere
[ 7] 22 DENY IN Anywhere
[ 8] 11992 ALLOW IN Anywhere
[ 9] 3306 DENY IN Anywhere

If you have a lot of rules to move or insert, you can edit the UFW file manually and reload the service:
$ sudo nano /etc/ufw/user.rules

Below the preamble, you’ll see pairs of rules and these can be cut and pasted above and below each other:
### RULES ###

### tuple ### allow tcp 22 0.0.0.0/0 any 0.0.0.0/0 OpenSSH – in
-A ufw-user-input -p tcp –dport 22 -j ACCEPT -m comment –comment ‘dapp_OpenSSH’

### tuple ### deny any any 0.0.0.0/0 any {ipaddress} in
-A ufw-user-input -s {ipaddress} -j DROP

Then, you reload the service:
$ sudo ufw reload
Firewall reloaded

For further tips on blocking IP addresses, this nixCraft link is helpful.

Updated on August 10, 2017

Was this article helpful?

Related Articles

Leave a Comment