iptables+ipset实现黑白名单

温馨提醒

一、安装

1
2
3
4
5
6
# RHEL
dnf install ipset iptables-services -y

# Ubuntu
apt update
apt install ipset iptables-persistent -y

二、创建 ipset 黑名单和白名单集合

1
2
3
4
5
# 创建黑名单集合
ipset create blacklist hash:net

# 创建白名单集合
ipset create whitelist hash:ip

说明:

hash:net 可接受网段和单个IP

hash:ip 只接受单个IP

三、添加 IP/网段 到集合中

  • 添加黑名单

    1
    2
    
    ipset add blacklist 192.168.1.0/24
    ipset add blacklist 10.0.0.1
  • 添加白名单

    1
    2
    
    ipset add whitelist 192.168.1.10
    ipset add whitelist 192.168.1.101

四、使用 iptables 应用规则

放行白名单IP(优先)

1
iptables -I INPUT -m set --match-set whitelist src -j ACCEPT

拒绝黑名单IP(在白名单之后执行)

1
iptables -A INPUT -m set --match-set blacklist src -j DROP

五、保存规则

  • 写入配置文件

    1
    
    ipset save > /etc/ipset.conf
  • 设置开机自动加载

    vim /etc/systemd/system/ipset-restore.service

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    
    [Unit]
    Description=Restore IP sets from /etc/ipset.conf
    Before=iptables.service
    
    [Service]
    Type=oneshot
    ExecStart=/bin/sh -c '/usr/sbin/ipset restore  < /etc/ipset.conf'
    RemainAfterExit=yes
    
    [Install]
    WantedBy=multi-user.target
    
    
    systemctl daemon-reexec
    systemctl daemon-reload
    systemctl enable ipset-restore
    systemctl enable iptables
  • 保存 iptables 规则

    1
    2
    3
    4
    5
    
    # RHEL
    service iptables save
    
    # Ubuntu
    netfilter-persistent save
  • 验证

    1
    2
    3
    4
    5
    
    # 查看 ipset 集合
    ipset list
    
    # 查看 iptables 规则是否生效
    iptables -L -n --line-numbers

六、清空规则

1
2
3
4
iptables -F

# 清空集合中的 IP,但会保留集合结构
ipset flush whitelist|blacklist

七、删除集合

1
2
# 连同集合本身一起删除,之后不可再使用,除非重新创建
ipset destroy whitelist|blacklist

提示:如果在 iptables 中引用了某个 ipset 集合,需要先删除 iptables 中的对应规则,再删除该集合,否则会报错

八、后期维护

1
2
3
4
5
6
7
8
# 添加黑名单
ipset add blacklist 192.168.1.200

# 删除
ipset del blacklist 192.168.1.200

# 修改后保存
ipset save > /etc/ipset.conf