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、 sniff 等)。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。

源码: option/redir.go:7-10 · 锚定版本 v1.13.11 (553cfa1)

外加内嵌的 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-10 · v1.13.11 (553cfa1)

由 Argsment 出品的 Core Tutorial