How to Block Specific IP Address with UFW (Uncomplicated Firewall)
How to Block Specific IP Address with UFW (Uncomplicated Firewall)
Jason Jason Photo By Jason Jason, Jan 07, 2017

As any server admin will tell you, having a website means you're going to have people trying to hack it. One of my servers seems like it's under constant attack from various IP addresses, and though there are many things that can be done to mitigate an attack on your server, one of the easiest is to simply block all requests from the specific IP address of the attacker. I like to use Uncomplicated Firewall (UFW) for managing my IP tables entries because as its name implies, it makes things less complicated.

To setup UFW, follow the directions on Digital Ocean. Once you're setup, here are some commands that I like to use:

Block IP Address

sudo ufw insert 1 deny from <ip address>

The insert 1 bit makes this rule go to the very top of the list of rules, and this is important because UFW's default setup goes through the list of rules until it finds an applicable rule. So if you have a rule that allows all incoming traffic on port 80 as your first rule and then the IP block as your second rule, your second rule (the block) would never get applied because your first rule already accepts everybody.

UFW Numbered Status

sudo ufw status numbered

This command will return results like the following:

Status: active

     To                         Action      From
     --                         ------      ----
[ 1] Anywhere                   DENY IN     193.201.225.117           
[ 2] Anywhere                   DENY IN     91.210.146.227            
[ 3] 22                         LIMIT IN    Anywhere                  
[ 4] 443                        ALLOW IN    Anywhere                  
[ 5] 80                         ALLOW IN    Anywhere                  
[ 6] 22 (v6)                    LIMIT IN    Anywhere (v6)             
[ 7] 443 (v6)                   ALLOW IN    Anywhere (v6)             
[ 8] 80 (v6)                    ALLOW IN    Anywhere (v6)             

Delete UFW Rule

If you want to delete a UFW rule, you should run the UFW Numbered Status command (above), and find the ID of the rule (the number on the left). Then you can run the following command:

sudo ufw delete <ID>

That's just about all I need for the type of servers I set up.


Tags & Categories

Security Command Line Linux Tools