Score:2

How to deny IP ranges with ufw?

us flag

I am getting repeated login attempts from this IP address, 45.135.232.165, apparently a known Russian abusive host. I want to block all traffic on all ports from the entire subnet 45.135.232.*, so I did

ufw deny from 45.135.232.0/24

ufw status shows the rule as

To                         Action      From
--                         ------      ----
Anywhere                   DENY        45.135.232.0/24

However, lastb still reports daily login attempts from the above mentioned address. What am I missing?

Score:2
us flag

Under normal circumstances, the mentioned command should work perfectly. However, if it’s not working as expected, then you need to see if there’s an existing rule in the iptable allowing the same IP to have access to your machine. If that’s the case, then your system will give it priority over the deny rule because it appears first in the iptable rule set.

To fix this issue, you need to prioritize the ufw deny rule over the other rules set for the same IP/subnet on your system. Run the following command:

              ufw insert 1 deny from 45.135.232.0/24

The insert 1 part in the above command puts the rule at 1st position in the iptables rule set. Hence, it’s prioritized over any other rule set for the same IP.

For different scenarios, you can check here that may help you.

Christian Brinch avatar
us flag
Aha! I did not know that. I thought deny always took precedence over allow. I had allow from anywhere to any port 22 as my first rule.
Score:2
th flag

And if you use ipv6 addresses they won't work with insert 1. It's safer to use prepend that works correctly with both ipv4 and ipv6. If you use something like docker or kubernetes the traffic will be routed to their subnets. So the input rules won't work. They work only for your main host access. You'll need ufw route. And as it has been said some applications can add rules directly to iptables before ufw rules. In that case your rules may not work, because others work first.

ufw prepend deny from 45.135.232.0/24
ufw route prepend deny from 45.135.232.0/24
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.