以下是一个 nftables
配置文件示例,用于配置只允许 Cloudflare 的 IP 地址访问网站的 80 和 443 端口(HTTP 和 HTTPS),同时拒绝其他来源的流量:
配置文件路径
可以将该配置保存为 /etc/nftables.conf
:
#!/usr/sbin/nft -f
# 创建表
table ip filter {
# 创建 input 链
chain input {
type filter hook input priority 0; policy drop;
# 允许 loopback 接口流量
iif lo accept
# 允许已建立和相关的连接
ct state established,related accept
# 禁止无效的连接
ct state invalid drop
# 允许 Cloudflare 的 IPv4 地址访问 80 和 443 端口
tcp dport { 80, 443 } ip saddr @cloudflare_ipv4 accept
# 记录并拒绝其他流量
log prefix "Dropped input: " flags all counter drop
}
}
table ip6 filter {
chain input {
type filter hook input priority 0; policy drop;
# 允许 loopback 接口流量
iif lo accept
# 允许已建立和相关的连接
ct state established,related accept
# 禁止无效的连接
ct state invalid drop
# 允许 Cloudflare 的 IPv6 地址访问 80 和 443 端口
tcp dport { 80, 443 } ip6 saddr @cloudflare_ipv6 accept
# 记录并拒绝其他流量
log prefix "Dropped input: " flags all counter drop
}
}
# 定义 Cloudflare 的 IP 列表
define cloudflare_ipv4 = {
173.245.48.0/20,
103.21.244.0/22,
103.22.200.0/22,
103.31.4.0/22,
141.101.64.0/18,
108.162.192.0/18,
190.93.240.0/20,
188.114.96.0/20,
197.234.240.0/22,
198.41.128.0/17,
162.158.0.0/15,
104.16.0.0/13,
104.24.0.0/14,
172.64.0.0/13,
131.0.72.0/22
}
define cloudflare_ipv6 = {
2400:cb00::/32,
2606:4700::/32,
2803:f800::/32,
2405:b500::/32,
2405:8100::/32,
2a06:98c0::/29,
2c0f:f248::/32
}
步骤
保存配置文件
将上述内容保存为 /etc/nftables.conf
。
加载配置
运行以下命令以加载配置:
sudo nft flush ruleset
sudo nft -f /etc/nftables.conf
验证规则生效
查看当前规则集以确保规则已正确加载:
sudo nft list ruleset
启用并持久化
确保 nftables
服务在系统重启后依然应用配置:
sudo systemctl enable nftables
sudo systemctl restart nftables
定期更新 Cloudflare 的 IP 列表
为了确保规则总是包含最新的 Cloudflare IP 地址,可以创建一个脚本定期更新上述规则。参考之前的脚本(使用 curl
获取 Cloudflare 的 IP 列表),并重载 nftables
配置即可。