ipset is a companion application for the iptables Linux firewall. It allows you to setup rules to quickly and easily block a set of IP addresses, among other things.
Installation
Debian based system
# apt install ipset
Redhat based system
# yum install ipset
Blocking a list of network
Start by creating a new “set” of network addresses. This creates a new “hash” set of “net” network addresses named “myset”.
1 |
# ipset create myset hash:net |
or
1 |
# ipset -N myset nethash |
Add any IP address that you’d like to block to the set.
1 2 3 4 |
# ipset add myset 14.144.0.0/12 # ipset add myset 27.8.0.0/13 # ipset add myset 58.16.0.0/15 # ipset add myset 1.1.1.0/24 |
Finally, configure iptables to block any address in that set. This command will add a rule to the top of the “INPUT” chain to “-m” match the set named “myset” from ipset (–match-set) when it’s a “src” packet and “DROP”, or block, it.
1 |
# iptables -I INPUT -m set --match-set myset src -j DROP |
Blocking a list of IP addresses
Start by creating a new “set” of ip addresses. This creates a new “hash” set of “ip” addresses named “myset-ip”.
1 |
# ipset create myset-ip hash:ip |
or
1 |
# ipset -N myset-ip iphash |
Add any IP address that you’d like to block to the set.
1 2 |
# ipset add myset-ip 1.1.1.1 # ipset add myset-ip 2.2.2.2 |
Finally, configure iptables to block any address in that set.
1 |
# iptables -I INPUT -m set --match-set myset-ip src -j DROP |
Making ipset persistent
The ipset you have created is stored in memory and will be gone after reboot. To make the ipset persistent you have to do the followings:
First save the ipset to /etc/ipset.conf:
1 |
# ipset save > /etc/ipset.conf |
Then enable ipset.service
, which works similarly to iptables.service
for restoring iptables rules.
Other Commands
To view the sets:
1 |
# ipset list |
or
1 |
# ipset -L |
To delete a set named “myset”:
1 |
# ipset destroy myset |
or
1 |
# ipset -X myset |
To delete all sets:
1 |
# ipset destroy |