sing-box tun配置

十一月 23, 2025 #tun

sing-box 配置tun的原理

# Routing Policy DataBase
sudo ip rule add priority 9000 from all to 172.20.0.0/30 table 2022  
sudo ip rule add priority 9003 not iif lo lookup 2022
# 9003: not from all iif lo lookup 2022  # 生成的结果中自动添加了from all

ip rule

0:    from all lookup local
9000: from all to 172.20.0.0/30 lookup 2022
# 不匹配路由前缀为0(不匹配缺省路由)
9001: from all lookup 2022 suppress_prefixlength 0
# 地址非53端口的所有流量
9002: not from all dport 53 lookup main suppress_prefixlength 0
9002: from all ipproto icmp goto 9010
9002: from all iif tun0 goto 9010
9003: not from all iif lo lookup 2022
9003: from 0.0.0.0 iif lo lookup 2022
9003: from 172.20.0.0/30 iif lo lookup 2022
9010: from all nop
32766: from all lookup main
32767: from all lookup default
ip route show table 2022
default dev tun0

ip route show table main
default via 11.11.11.1 dev pppoe-wan proto static
11.11.11.1 dev pppoe-wan proto kernel scope link src 11.11.11.5
192.168.11.0/24 dev br-lan proto kernel scope link src 192.168.11.1

创建路由名称 并使路由生效

echo 100 custom >> /etc/iproute2/rt_tables 
ip route add default via 192.168.1.100 dev eth1 table custom
ip rule add to 192.168.1.200 lookup custom

fwmark

iptables -t mangle -A FORWARD -i eth3 -p tcp --dport 80 -j MARK --set-mark 1  
iptables -t mangle -A FORWARD -i eth3 -p tcp --dport 25 -j MARK --set-mark 2  
iptables -t mangle -A FORWARD -i eth3 -p tcp --dport 110 -j MARK --set-mark 2  
iptables -t mangle -A FORWARD -i eth3 -j MARK --set-mark 3  
ip rule add fwmark 1 table 1  
ip rule add fwmark 2 table 2  
ip rule add fwmark 3 table 3

使用 ip rule 配置路由规则

内核需要根据规则,来为数据包选择要进行的操作或选择使用的路由表——当数据包能够匹配某些规则,则对该数据包执行该规则所对应的动作,比如查找一个路由表。Linux 的默认规则会让入向和出向的流量都 "lookup" 默认路由表。

添加路由规则的 ip rule 用法如下: