使用 tun2socks 转发 TUN 设备上的流量到 socks 代理

发布于 2020-03-27 22:06:26

Step1. 准备 socks5 代理

很多代理软件都支持暴露 socks5 协议。略。

Step2. 运行 tun2socks

构建 tun2socks

git clone https://github.com/eycorsican/go-tun2socks
cd go-tun2socks && make

./build/tun2socks  -h
Usage of ./build/tun2socks:
  -blockOutsideDns
    	Prevent DNS leaks by blocking plaintext DNS queries going out through non-TUN interface (may require admin privileges) (Windows only)
  -loglevel string
    	Logging level. (debug, info, warn, error, none) (default "info")
  -proxyServer string
    	Proxy server address (default "1.2.3.4:1087")
  -proxyType string
    	Proxy handler type (default "socks")
  -tunAddr string
    	TUN interface address (default "10.255.0.2")
  -tunDns string
    	DNS resolvers for TUN interface (only need on Windows) (default "8.8.8.8,8.8.4.4")
  -tunGw string
    	TUN interface gateway (default "10.255.0.1")
  -tunMask string
    	TUN interface netmask, it should be a prefixlen (a number) for IPv6 address (default "255.255.255.0")
  -tunName string
    	TUN interface name (default "tun1")
  -tunPersist
    	Persist TUN interface after the program exits or the last open file descriptor is closed (Linux only)
  -udpTimeout duration
    	UDP session timeout (default 1m0s)
  -version
    	Print version

mv build/tun2socks /usr/local/bin/
# 运行 tun2socks
sudo tun2socks -loglevel debug -proxyServer 127.0.0.1:1080 -proxyType socks -tunAddr 10.255.0.2 -tunGw 10.255.0.1

# 查看 TUN 设备
ifconfig
...
utun6: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500
        inet 10.255.0.2 --> 10.255.0.1 netmask 0xffffff00

Step3. 修改路由表,转发 TUN 设备上的流量

# 查看原始路由
sudo route -n get default
# 或者
netstat -nr

# 删除并配置新路由
sudo route delete default
sudo route add default 10.255.0.1
sudo route add vps-public-ip your-default-gateway-ip

# 恢复原始路由
# 停掉 tun2socks 之后,新添加的tun设备会自动删除,刚新添加的路由也会无效
sudo route add default your-default-gateway-ip

到这里,浏览器即使不配置代理,即直连模式也可以正常访问Google了。

相关文章

另外 ClashX Pro (macOS) 支持【增强模式】,自动设置 TUN 设备,通过劫持DNS实现全局透明代理。

comments powered by Disqus