How to Block a Big List of IP Addresses with ipset and iptables

By | December 11, 2018

Sometimes you need to block a certain number of IP addresses. It is ok, when you have 10 addresses to reject. But what if you have 2000? Here is the solution that will allow you to limit any number of addresses.

I’m going to use ipset. In my sample there is a CentOS machine, so I will use yum, for other systems use the appropriate package manager. First of all, let’s download it.

yum install ipset

Then we will need to create the list of IP addresses we want to block. This list should consist of IP addresses only, one per line.  Let’s create a list first:

ipset -N blacklist iphash

Let’s verify that everything is fine about the list we just created:

ipset -L blacklist

You should see something link this:
Name: blacklist
Type: hash:ip
Revision: 0
Header: family inet hashsize 1024 maxelem 65536
Size in memory: 16480
References: 0
Members:

Let’s add some test IP addresses to the list:

ipset -A blacklist 192.168.1.58
ipset -A blacklist 8.8.8.8

Let’s verify these addresses were added:

ipset -L blacklist

You should see something like this:
Name: blacklist
Type: hash:ip
Revision: 0
Header: family inet hashsize 1024 maxelem 65536
Size in memory: 16512
References: 0
Members:
192.168.1.58
8.8.8.8

Ok, it’s working. Now you should add all your IPs to the list and then verify that all of them were added. When you’re done, let’s add our ipset rule to iptables.

iptables -v -I INPUT -m set --match-set blacklist src -j DROP

That’s all! Restart iptables

service iptables restart

And now your blacklist should be active! Inspired by this post.

 

2 thoughts on “How to Block a Big List of IP Addresses with ipset and iptables

  1. Sysgone

    “That’s all! Restart iptables

    service iptables restart

    And now your blacklist should be active! Inspired by this post.”

    Wrong, after restarts, your rules will disappear. You must save iptables rules first or

Leave a Reply