Linux

firewall-cmd设置只允许中国IP访问指定端口

首先需要获取到所有的中国IP段,有以下两种方法,第一种最简单,但是不够准确,第二种复杂一点但是准确度更高。

第一种:从APNIC获取所有中国IP段

wget -c http://ftp.apnic.net/stats/apnic/delegated-apnic-latest

cat delegated-apnic-latest | awk -F '|' '/CN/&&/ipv4/ {print $4 "/" 32-log($5)/log(2)}'|cat > ip.txt

第二种:需要注册登录maxmind并下载GeoLite Country: CSV Format文件,解压缩后从
GeoLite2-Country-Blocks-IPv4.csv文件内提取中国IP

#首先获取区域所属的geoname_id,CN的id是1814991,这个也可能发生变化
grep "CN" GeoLite2-Country-Locations-en.csv | awk -F ',' '{print $1}'
#根据id从GeoLite2-Country-Blocks-IPv4.csv提取IP列表
grep "1814991" GeoLite2-Country-Blocks-IPv4.csv | awk -F ',' '{print $1}' > /root/ip.txt

利用firewall-cmd创建ipset

firewall-cmd --permanent --new-ipset=chinaIP --type=hash:net

向创建的ipset集合添加IP段

firewall-cmd --permanent --add-entries-from-file=/root/ip.txt --ipset=chinaIP

添加防火墙规则只允许指定的IP段访问目标端口

firewall-cmd --zone=public --add-rich-rule='rule family="ipv4" source ipset=chinaIP port port=5001 protocol=tcp accept' --permanent
#如果要屏蔽指定区域访问把accept换成reject或者drop即可,使用reject对方会收到拒绝连接的信息,使用drop对方不会收到任何响应。

重新加载 firewalld 的持久化配置使规则生效

firewall-cmd --reload

查看ipset集合内有哪些IP段

firewall-cmd --ipset=chinaIP --get-entries

如果需要更新IP数据,重新提取到IP以后需要先删除之前创建的ipset,再重新创建一个同名的ipset并向集合添加新的IP段,因为之前的规则已经创建,所以直接重新加载 firewalld 的持久化配置就可以正常使用了。