简介:

IP sets are a framework inside the Linux kernel, which can be administered by the ipset utility. Depending on the type, an IP set may store IP addresses, networks, (TCP/UDP) port numbers, MAC addresses, interface names or combinations of them in a way, which ensures lightning speed when matching an entry against a set.

If you want to

  • store multiple IP addresses or port numbers and match against the collection by iptables at one swoop;
  • dynamically update iptables rules against IP addresses or ports without performance penalty;
  • express complex IP address and ports based rulesets with one single iptables rule and benefit from the speed of IP sets

then ipset may be the proper tool for you.

IP sets was written by Jozsef Kadlecsik and it is based on ippool by Joakim Axelsson, Patrick Schaaf and Martin Josefsson.Many thanks to them for their wonderful work!

文档链接:https://ipset.netfilter.org/


安装:

yum install ipset

源码安装:(官网下载http://ipset.netfilter.org/install.html)

yum -y install libmnl-devel libmnl
tar -jxvf ipset-6.30.tar.bz2 && cd ipset-6.30 && ./configure --prefix=/usr/local/ipset
make && make install

使用:

① 创建ipset集合:

ipset create ipset_name hash:net     ## method:datatype-->method可以bitmap、hash、llist;datatype可以ip、net(网段)、mac、port

例如:
ipset create blacklist hash:net maxelem 1000000 #黑名单
ipset create whitelist hash:net maxelem 1000000 #白名单

② 加入/删除一个条目

ipset add blacklist 10.60.10.4
ipset del blacklist 10.60.10.4
ipset add bb 10.0.0.0-10.255.255.255
ipset add bb 10.0.0.0/8 ##等同上面方式

#查看已创建的ipset
ipset list

#检查目标IP是否在ipset集合中
ipset test blacklist 10.60.10.4

#清空ipset集合条目
ipset flush blacklist
ipset flush ##清空ipset中所有集合的条目。删除条目,不删除集合

#删除指定ipset集合
ipset destroy blacklist
ipset destroy ##删除所有集合

③ 创建防火墙规则

iptables -I INPUT -m set --match-set blacklist src -p tcp -j DROP     ##黑名单,默认策略设置为ACCEPT
iptables -I INPUT -m set --match-set whitelist src -p tcp -j ACCEPT ##白名单,默认策略设置为DROP
service iptables save ##保存配置。CentOS7以上需要安装“iptables-services”

④ 备份(可选)

ipset save blacklist -f blacklist.txt
ipset save whitelist -f whitelist.txt ##将ipset规则保存到文件,后期版本不支持-f,文件格式:add setname ip
ipset restore -f blacklist.txt
ipset restore -f whitelist.txt ##将文件中ipset规则导入


备注:

1)hash:ip集合添加方式

ipset add aa 1.1.1.1

ipset add aa 1.1.1.2-1.1.1.5


2)hash:net集合添加方式

ipset add bb 1.1.1.1-1.1.1.10

ipset add bb 10.0.0.0-10.255.255.255

ipset add bb 10.0.0.0/8

ipset add bb 1.1.1.1


3)hash:ip,port集合添加方式

ipset add cc 1.1.1.1,80

ipset add cc 1.1.1.2-1.1.1.4,8080                 ##默认端口都是tcp


4)hash:ip,port,net集合添加方式

ipset add dd 1.1.1.1,80,1.1.1.2-1.1.1.4