放行中国区域ipv6流量,禁止其他v6流量进出

放行中国区域ipv6流量,禁止其他v6流量进出

📌 目标

✅ 仅允许中国主要 IPv6 地址段的 出站入站
✅ 阻止所有其他 IPv6 出站和入站流量


完整操作步骤

🟢 步骤 1:安装 ipsetiptables-persistent

首先,确保系统安装了 ipset(用于管理 IP 地址列表)和 iptables-persistent(用于持久化规则)。

sudo apt update sudo apt install -y ipset iptables-persistent

🟢 步骤 2:创建 IPv6 地址列表

使用 ipset 定义 中国主要 IPv6 地址段,用于放行。

sudo ipset create china6 hash:net family inet6

然后,添加中国的主要 IPv6 地址段:

sudo ipset add china6 2400::/12   # 中国电信
sudo ipset add china6 2403::/16   # 中国移动
sudo ipset add china6 2404::/16   # 中国联通
sudo ipset add china6 2405::/16   # 教育网

# 额外的中国 IPv6 地址段
sudo ipset add china6 2407::/16
sudo ipset add china6 2408::/16
sudo ipset add china6 2409::/16
sudo ipset add china6 240e::/16
sudo ipset add china6 2402::/16   # 腾讯

🟢 步骤 3:配置 ip6tables 规则

1. 清除旧规则

sudo ip6tables -F 
sudo ip6tables -X 
sudo ip6tables -Z
 

2. 允许本地回环

sudo ip6tables -A INPUT -i lo -j ACCEPT
sudo ip6tables -A OUTPUT -o lo -j ACCEPT

3. 允许已建立的连接

sudo ip6tables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
sudo ip6tables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

4. 允许中国 IPv6 地址段的入站流量

sudo ip6tables -A INPUT -m set --match-set china6 src -j ACCEPT

5. 允许中国 IPv6 地址段的出站流量

sudo ip6tables -A OUTPUT -m set --match-set china6 dst -j ACCEPT

6. 设置默认策略

sudo ip6tables -P INPUT DROP      # 默认丢弃所有 IPv6 入站流量
sudo ip6tables -P OUTPUT DROP     # 默认丢弃所有 IPv6 出站流量
sudo ip6tables -P FORWARD DROP    # 默认丢弃所有 IPv6 转发流量

 

 

🟢 步骤 4:持久化规则

1. 保存 ipset 规则

sudo ipset save > /etc/ipset.rules

ipset 规则在开机时自动恢复:

echo "ipset restore < /etc/ipset.rules" | sudo tee -a /etc/rc.local
sudo chmod +x /etc/rc.local

2. 保存 ip6tables 规则

sudo ip6tables-save | sudo tee /etc/iptables/rules.v6

然后启用 iptables-persistent

sudo systemctl enable netfilter-persistent
sudo systemctl restart netfilter-persistent

🟢 步骤 5:验证配置

1. 检查 ipset 是否生效

sudo ipset list china6

2. 检查 ip6tables 规则是否生效

sudo ip6tables -L -v

3. 测试 IPv6 出站(应该成功)

ping6 -c 4 2400:3200::1   # 这是中国电信的 DNS

4. 测试 IPv6 出站(应该失败)

ping6 -c 4 2606:4700:4700::1111   # Cloudflare(非中国)

5. 测试 IPv6 入站

使用其他设备(如 VPS 或朋友的 IPv6 服务器),尝试访问你的服务器:

ping6 -c 4 <你的IPv6地址>

如果来源是 中国 IPv6,应该成功;如果是 非中国 IPv6,应该失败。

PS:清除现有的防火墙规则:

sudo ip6tables -F   # 清空所有规则
sudo ip6tables -X   # 删除所有自定义链

总结

默认封锁所有 IPv6 流量
仅允许中国 IPv6 地址段的入站和出站
允许本地回环和已建立的连接
开机自动恢复 ipsetip6tables 规则

这样配置后,你的服务器 只能 与中国的 IPv6 地址通信,其他国家的 IPv6 地址将全部被拦截。🚀

如果你有其他需求,比如允许特定端口,或者允许某些非中国 IPv6 地址,欢迎继续交流!😊

sudo ip6tables -F 
sudo ip6tables -X 
sudo ip6tables -Z
© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享