基于nftables的策略路由

基于nftables和iproute2,设置策略路由

背景

2019年的时候,通过dnsmasq/ipset/iptables/iproute2工具做了一套特定的路由方案,由于当时的WireGuard通道特别不稳定,后续就放弃了。

最近,有了稳定的WireGuard通道(基于V2Ray的DokoDemo),基于直连Cloudflare WARP和Cloudflare Tunnel的需求,又想搞一下策略路由。

简介

时过境迁,当时的需求和工具如今已经变了。

当时的需求是实现基于国别的IP策略路由,无视端口和协议,国内直连,国外通过WireGuard;如今比较简单,只为一些特定域名和IP添加策略路由,大部分的HTTP协议还是走的代理。

工具也由iptables变为nftables了,现在主流发行版都支持nftables了,我又想尝鲜,所以就用nftables了;可惜的是,虽然Netfilter和各个发行版都在推广nftables,好像用的人并不多,能够搜索出来的资料很少,文档中有些晦涩的术语,还是难以理解,只能照葫芦画瓢。

过程

不记录具体的过程了,只记录思路。

  • NixOS上的Dnsmasq不支持nftset,添加自己的Dnsmasq Nix包,添加nftset支持
  • 为Dnsmasq添加相关的nftset配置
  • 为WireGuard添加PostSetup和PostShutdown脚本,分别在WireGuard启动和停止时,进行相关的设置
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# PostSetup脚本
nft add table inet gfw
nft add chain inet gfw route { type route hook output priority filter\; policy accept\; }
nft add set inet gfw gfw-dns { type ipv4_addr\; flags interval\; elements = { 1.1.1.1,8.8.8.8,8.8.4.4 }\; }
nft add set inet gfw gfw-gfwlist { type ipv4_addr\; flags interval\; }

nft add rule inet gfw route ip daddr @gfw-dns counter ct mark set 11
nft add rule inet gfw route ip daddr @gfw-dns counter meta mark set ct mark
nft add rule inet gfw route ip daddr @gfw-gfwlist counter ct mark set 11
nft add rule inet gfw route ip daddr @gfw-gfwlist counter meta mark set ct mark

ip rule add pref 11 fwmark 11 table vpn
1
2
3
## PostShutdown脚本
nft destroy table inet gfw
ip rule delete pref 11 fwmark 11 table vpn
使用 Hugo 构建
主题 StackJimmy 设计