ipset介绍

ipset是iptables的扩展,它允许你创建 匹配整个地址集合的规则。而不像普通的iptables链只能单IP匹配, ip集合存储在带索引的数据结构中,这种结构即时集合比较大也可以进行高效的查找,除了一些常用的情况,比如阻止一些危险主机访问本机,从而减少系统资源占用或网络拥塞,IPsets也具备一些新防火墙设计方法,并简化了配置.官网:http://ipset.netfilter.org/

ipset配置步骤

一、安装ipset

yum -y install ipset

二、创建ipset规则

ipset create blacklist hash:net
ipset create whitelist hash:net

三、添加黑/白名单IP

ipset add blacklist 192.168.0.1
ipset add whitelist 192.168.0.2
ipset add blacklist 192.168.0.0/24

四、ipset默认存储位置,以及保存

/etc/sysconfig/ipset

如果需要保存到其他路径,使用如下命令

ipset save -f /opt/ipset.conf

五、关联ipset和iptables

iptables -I INPUT -m set --match-set blacklist src -j DROP -m comment --comment "Reject from blacklist"
iptables -I INPUT -m set --match-set whitelist src -j ACCEPT -m comment --comment "Allow from whitelist"

六、保存iptables规则

service iptables save

实现自动化的添加ip黑名单

通过脚本自动化的从query.log筛选出异常的IP地址并加入到ipset的blacklist中

#!/bin/bash
# query log location
query_location=\'/var/named/data/query.log\'
# Get the time 2s before the current time.
date_time=$(date +%H:%M:%S -d \'-2 Seconds\')
printf "The IP traffic statistics time point is %s\n" $date_time
# Get the ip access count list at the current time in the dns query log, and display the corresponding information, such as: total number, ip number, maximum access ip.
num_list=`grep $date_time $query_location | awk -F \'[ #]\' \'{print $5}\' | sort | uniq -c | awk \'{print $1}\' | sort -n`
total_num=0
for n in $num_list
do
  total_num=`echo "$total_num+$n" | bc`
done
printf "The total number of queries in 1 second is %s\n" $total_num
max_num=`echo $num_list | awk \'{print $NF}\' -`
max_num_ip=`grep $date_time $query_location | awk -F \'[ #]\' \'{print $5}\' | sort | uniq -c | grep $max_num | awk \'{print $2}\'`
printf "The highest queried IP is:\n%s\nThe total amount of queries is: %s\n" "$max_num_ip" $max_num
if [ "$max_num" -lt "100" ]
then
  echo "There is no ip address for the exception query!"
else
  ipset list
  for l in $num_list
  do
    if [ "$l" -ge "100" ]
    then
      ip_stop=`grep $date_time $query_location | awk -F \'[ #]\'  \'{print $5}\' | sort | uniq -c | grep $l | awk \'{print $2}\'`
      echo $ip_stop
      ipset add blacklist $ip_stop
    fi
  done
  ipset list
  echo "IPs with more than 100 ips have been blacklisted!"
fi

再添加cron任务即可。

至此,DNS异常IP的ipset配置已经完成。

版权声明:本文为sunnydou原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/sunnydou/p/15062618.html