说明

系统是 Debian12,默认的网络工具是 nftables

可以查看是否启用

1
systemctl status nftables

没有启用的话设置开机自启,并启用

1
2
systemctl enable nftables
systemctl start nftables

nftables 默认的配置文件在 /etc/nftables.conf

查看当前的表

1
nft list tables

查看特定表中的规则

1
nft list table <table-name>

查看所有的规则集

1
nft list ruleset

配置

可以使用命令执行测试,重启后并不会被保存

这里可以将自己所在的网段替换掉 127.0.0.1,实现只有自己才能访问指定的端口

可以根据:ASN查询,知道自己的CIDR,ip不怎么变动的话可以通过CIDR实现配置,基本不需要修改

1
2
3
4
5
6
7
8
9
10
11
12
# 创建名为 "filter" 的表格
nft create table filter
# 在 "filter" 表中添加名为 "input" 的链
nft add chain filter input { type filter hook input priority 0 \; }
# 在 "filter" 表中添加名为 "allowed_ips" 的集合
nft add set filter allowed_ips { type ipv4_addr\; flags interval\; }
# 向 "allowed_ips" 集合添加一个元素
nft add element filter allowed_ips { 127.0.0.1 }
# 在 "filter" 表的 "input" 链中添加一个规则。当数据包是 TCP 协议、目标端口为 235、源 IP 地址在 "allowed_ips" 集合中时,将接受该数据包
nft add rule filter input tcp dport 235 ip saddr @allowed_ips accept
# 当数据包是 TCP 协议、目标端口为 235 时,将丢弃该数据包
nft add rule filter input tcp dport 235 drop

如果需要持久化的保存,可以修改 /etc/nftables.conf 文件,加入以下配置(自行修改放行的端口,下面的示例文件时235端口)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
table ip firewall {

set allowed_ips {
type ipv4_addr
flags interval
elements = { 127.0.0.1 }
}

chain input {
type filter hook input priority filter; policy accept;
tcp dport 235 ip saddr @allowed_ips accept
tcp dport 235 drop
}
}

使用以下命令重新加载 nftables 配置

1
nft -f /etc/nftables.conf

这会重新加载配置文件并应用新的规则。

动态获取

说明:我的443端口是一个只有自己可以正常访问的网页服务,通过 /var/log/nginx/access.log 获取当前的ip,将它加入到 allowed_ips 集合中

动态获取的目的是精准放行ip

1
2
3
4
5
6
7
8
9
10
#!/bin/bash

log_file="/var/log/nginx/access.log"

# 对访问了指定路径的ip加入到白名单
ip=$(grep 'GET /aaaaa/bbbbb=' "$log_file" | awk '{print $1}' | tail -n 1)

if ! /usr/sbin/nft list set firewall allowed_ips | grep -q "$ip"; then
/usr/sbin/nft add element firewall allowed_ips { $ip }
fi

加入定时任务

1
2
3
4
5
# 每30分钟执行一次
*/30 * * * * /root/nft/ip.sh

# 定期删除所有元素
0 4 * * * /usr/sbin/nft flush set filter allowed_ips