重定向 & 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_BOXtype: "tproxy"
| 字段 | 类型 | 默认值 | 允许值 | 描述 |
|---|---|---|---|---|
network | NetworkList | (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 做透明代理。
跨内核说明
- Xray-core 使用 Dokodemo-door 入站配合
streamSettings.sockopt.tproxy达到同样效果。参见 Redirect/TProxy — Xray-core。 - mihomo 在顶层
redir-port/tproxy-port快捷字段以及listeners:中type: redir/type: tproxy条目下提供同样的 内核侧机制。参见 Redirect/TProxy — mihomo。
源码: option/redir.go:7-10 · v1.13.11 (553cfa1)
