Real-IP Tun Example
Real-IP 模式的复杂性主要来自于两个方面:
- 如何使得 Clash Outbound 还能正确的连接互联网
- 如何使得 DIRECT 出口的流量不要经过 Tun NIC 回到 Clash 造成回环
很显然,不能使用添加 Default 路由到 Tun NIC 的方式使用 Clash Tun 模式。否则 Clash 将无法连接远程代理服务器。
需要注意的是,当 Clash 作为网关工作,如果运行 Clash 的主机本身并不需要通过 Tun 代理,仅仅是转发其他设备的流量,那么上述两个复杂性将不会存在,相应的也会后更简单的配置方法。
本章将以运行 Clash 的 Linux 的主机本身也需要代理的条件下,给出一个使用方法。
- 将 Clash 运行在一个单独的用户下,用以给操作系统一个区分网络流量是否是 Clash 发出的特征。
- 使用 iptables 在 mangle 表中,将流量打上 fwmark,再由 IP rule 决定将这些有 mark的 流量使用策略路由 (policy route)将流量转发给 Tun NIC。
- 在 mangle 表 OUTPUT 链中使用
uid-owner
排除 Clash 发出的流量 - 在 mangle 表 PREROUTING 中,将其他设备发来的流量打上 fwmark
假设 clash 运行在 alice 用户下,该用户的 UID 为 129,我们 fwmark 也用 129,clash 策略路由的路由表 id 也为 129。
用户 uid,fwmark ,路由表 id 是三个不相关的值。这里仅仅是为了举例方便都设置成 129.
这里假设 Tun NIC 已经提前创建好,名称为
clash0
,owner 也为 alice,并且已经被 bring up.首先在 mangle 表中创建 CLASH 链,主要用于排除一些局域网地址。如果你会使用 ipset ,可以参考下面被注释的
chnroute
项,排除一些国内地址。iptables -t mangle -N CLASH # 创建 Clash Chain
# 排除一些局域网地址
iptables -t mangle -A CLASH -d 0.0.0.0/8 -j RETURN
iptables -t mangle -A CLASH -d 10.0.0.0/8 -j RETURN
iptables -t mangle -A CLASH -d 127.0.0.0/8 -j RETURN
iptables -t mangle -A CLASH -d 169.254.0.0/16 -j RETURN
iptables -t mangle -A CLASH -d 172.16.0.0/12 -j RETURN
iptables -t mangle -A CLASH -d 192.168.0.0/16 -j RETURN
iptables -t mangle -A CLASH -d 224.0.0.0/4 -j RETURN
iptables -t mangle -A CLASH -d 240.0.0.0/4 -j RETURN
# iptables -t mangle -A CLASH -m set --match-set chnroute dst -j RETURN
iptables -t mangle -A CLASH -j MARK --set-xmark 129
然后在 PREROUTING 链中,给所有