How to Use Ubuntu UFW to Block Specific IP Addresses

If you manage an internet-facing Ubuntu server, you will eventually notice repeated, malicious login attempts in your authentication logs. These automated bots constantly scan for vulnerable SSH ports or web applications. One of the most effective ways to stop these attacks is to permanently block the offending IP address using the Uncomplicated Firewall (UFW).

Step 1: Check the Status of UFW

Before adding rules, ensure that UFW is actually enabled on your system. Run the following command:

sudo ufw status verbose

If the output says Status: inactive, you need to enable it. Warning: Before enabling UFW, ensure you have an allow rule for your SSH connection, or you will lock yourself out!

sudo ufw allow ssh
sudo ufw enable

Step 2: Block a Single IP Address

To block all incoming traffic from a specific, malicious IP address (for example, 203.0.113.50), use the deny command.

sudo ufw deny from 203.0.113.50

UFW will respond with Rule added. This IP address is now completely blocked from accessing any port or service on your server.

Step 3: Block an Entire Subnet

Sometimes attackers use multiple IP addresses from the same hosting provider or region. Instead of blocking them one by one, you can block the entire CIDR block (subnet). For example, to block the entire 203.0.113.0/24 range:

sudo ufw deny from 203.0.113.0/24

Step 4: Block an IP Address from a Specific Port

If you have a public web server but you want to block a specific IP address from accessing a private administration port (like port 8080), you can specify the destination port in your rule.

sudo ufw deny from 203.0.113.50 to any port 8080

This allows the IP to still view your public website on port 80, but drops their packets if they try to access the admin panel on 8080.

Step 5: How Rule Ordering Works

Firewalls process rules in order, from top to bottom. As soon as a packet matches a rule, the firewall takes action (allow or deny) and stops reading the rest of the list.

If you have a broad rule at the top (e.g., Allow all traffic to port 80) and you add a deny rule for an IP address below it, the attacker will still be able to access port 80! You must insert your deny rules at the very top of the chain.

Use the insert command to place a deny rule at position 1:

sudo ufw insert 1 deny from 203.0.113.50

Step 6: Deleting a Block Rule

If you accidentally block a legitimate user, you need to remove the rule. First, list all your rules with their corresponding numbers:

sudo ufw status numbered

Locate the number of the rule you want to delete (e.g., rule #3). Then, delete it by number:

sudo ufw delete 3

Press y to confirm the deletion.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.