在CentOS 7上限制UDP访问仅允许国内IP

在CentOS 7上限制UDP访问仅允许国内IP

要在CentOS 7上配置防火墙仅允许国内IP访问UDP端口,同时阻止海外访问,可以使用firewalld结合ipset来实现。以下是具体步骤:

方法一:使用firewalld和ipset

安装必要工具(如果尚未安装):

yum install -y ipset firewalld
systemctl enable firewalld
systemctl start firewalld

创建中国IP地址集

# 创建ipset集合
ipset create china hash:net

# 下载中国IP段并添加到集合(可能需要定期更新)
for ip in $(curl -s http://www.ipdeny.com/ipblocks/data/countries/cn.zone); do
  ipset add china 
$ipdone

配置firewalld规则

# 创建新的firewalld zone
firewall-cmd --permanent --new-zone=chinaudp

# 将中国IP集合添加到zone源
firewall-cmd --permanent --zone=chinaudp --add-source=ipset:china

# 允许UDP访问(可根据需要指定端口)
firewall-cmd --permanent --zone=chinaudp --add-port=1-65535/udp

# 默认拒绝所有其他UDP访问
firewall-cmd --permanent --add-rich-rule='rule protocol value="udp" drop'

# 重新加载防火墙配置
firewall-cmd --reload

方法二:使用iptables直接配置

如果你更喜欢使用iptables:

创建中国IP集合

ipset create china hash:net
for ip in $(curl -s http://www.ipdeny.com/ipblocks/data/countries/cn.zone); do
  ipset add china $ip
done

设置iptables规则

# 允许中国IP访问UDP
iptables -A INPUT -p udp -m set --match-set china src -j ACCEPT

# 拒绝其他所有UDP访问
iptables -A INPUT -p udp -j DROP

# 保存规则(需要安装iptables-services)
yum install -y iptables-services
service iptables save
systemctl enable iptables

注意事项

  1. 中国IP列表需要定期更新,可以设置cron任务自动更新

  2. 上述方法会影响所有UDP端口,如果只需要限制特定端口,请修改规则中的端口范围

  3. 在生产环境实施前,建议先在测试环境验证

  4. 确保不会意外阻止系统必要的UDP通信(如DNS等)

自动更新中国IP列表的cron任务

# 创建更新脚本
echo '#!/bin/bash
for ip in $(curl -s http://www.ipdeny.com/ipblocks/data/countries/cn.zone); do
  ipset add china $ip 2>/dev/null
done' > /usr/local/bin/update_china_ip.sh

chmod +x /usr/local/bin/update_china_ip.sh

# 添加每周自动更新任务
(crontab -l 2>/dev/null; echo "0 3 * * 1 /usr/local/bin/update_china_ip.sh") | crontab -

以上配置将确保只有来自中国IP地址的UDP流量能够访问你的CentOS 7服务器。


分享到:
关键词:Linux运维

网友留言(0 条)

发表评论

验证码