Skip to content

重定向 & TProxy — sing-box ​

sing-box 为 Linux 透明代理提供两种专用入站:redirect(iptables REDIRECT,仅 TCP)与 tproxy(iptables / nftables TPROXY,TCP+UDP)。

type: "redirect" ​

json
{
  "inbounds": [{
    "type": "redirect",
    "tag": "redir-in",
    "listen": "127.0.0.1",
    "listen_port": 12345
  }]
}

只内嵌 ListenOptions 字段(listen、listen_port、tcp_fast_open、netns 等)。REDIRECT 仅 TCP。

配套的 iptables:

sh
iptables -t nat -N SING_BOX
iptables -t nat -A SING_BOX -d 192.168.0.0/16 -j RETURN
iptables -t nat -A SING_BOX -d 10.0.0.0/8 -j RETURN
iptables -t nat -A SING_BOX -p tcp -j REDIRECT --to-ports 12345
iptables -t nat -A OUTPUT -p tcp -j SING_BOX

type: "tproxy" ​

字段类型默认值允许值描述
networkNetworkList(tcp+udp)tcp | udp | 限定为仅 TCP 或仅 UDP。TPROXY 双栈支持;REDIRECT 仅 TCP。
udp_mappingUDPNATBehaviorendpoint_independentendpoint_independent | address_dependent | address_and_port_dependentUDP NAT 映射行为:同一源地址与端口对所有目标复用同一映射(默认),或按目标地址 / 地址加端口分别建立映射。
udp_filteringUDPNATBehaviorendpoint_independentendpoint_independent | address_dependent | address_and_port_dependentUDP NAT 过滤行为:接受任意远端的数据包(默认),或仅接受已发送过数据包的远端地址 / 地址加端口。
udp_nat_maxuint320 (auto)<uint32>UDP NAT 会话上限;达到上限时关闭最久未使用的会话。为 0 时:iOS 上为 4096,其他平台按总内存在 4096–16384 之间选取(无法检测时为 16384)。

源码: option/redir.go:7-13 · 锚定版本 v1.14.2 (af6e64c)

外加内嵌的 ListenOptions。

json
{
  "inbounds": [{
    "type": "tproxy",
    "tag": "tproxy-in",
    "listen": "0.0.0.0",
    "listen_port": 12345,
    "network": "tcp,udp"
  }]
}

对应的 iptables mangle 规则:

sh
iptables -t mangle -N SING_BOX
iptables -t mangle -A SING_BOX -d 192.168.0.0/16 -j RETURN
iptables -t mangle -A SING_BOX -d 10.0.0.0/8 -j RETURN
iptables -t mangle -A SING_BOX -m mark --mark 0x100 -j RETURN
iptables -t mangle -A SING_BOX -p tcp -j TPROXY --on-port 12345 --tproxy-mark 0x1
iptables -t mangle -A SING_BOX -p udp -j TPROXY --on-port 12345 --tproxy-mark 0x1
iptables -t mangle -A PREROUTING -j SING_BOX

ip rule add fwmark 0x1 table 100
ip route add local 0.0.0.0/0 dev lo table 100

逃生 mark(上面的 0x100)应与 sing-box 出站套接字上设置的 fwmark 对应 —— 通过出站的 routing_mark 字段或 route.default_mark 配置。

说明 ​

  • 两种入站都需要 CAP_NET_ADMIN。以 root 运行 sing-box,或用 setcap 给二进制赋予该 capability。
  • 新部署推荐 tproxy —— 它同时处理 UDP,并且无需 NAT 翻译(原始目的地从套接字直接读出)。
  • 这两种入站类型 仅 Linux。其他平台请用 TUN 做透明代理。

跨内核说明 ​

源码: option/redir.go:7-13 · v1.14.2 (af6e64c)

由 Argsment 出品的 Core Tutorial