方永、南天紫云

道亦有道

OpenWrt配置透明代理
2023年02月11日

上篇,固件更新了,更为重要的是配置好透明代理。

方案是Phantun + WireGuard + SmartDns

首先是 Phantun的配置:

Phantun官网即可下载预编译的binary,然后在 /etc/init.d/ 目录添加名为phantun的文件:

#!/bin/sh /etc/rc.common
# Copyright (C) 2006-2011 OpenWrt.org

START=50

USE_PROCD=1
PROG=/usr/local/bin/phantun

start_service() {
        procd_open_instance
        procd_set_param command "$PROG" --local 127.0.0.1:1234 --remote x.com:5678
        procd_set_param respawn
        procd_close_instance
}

phantun将以服务的形式启动和管理。 若需要调试,在shell中直接运行 RUST_LOG=info /usr/local/bin/phantun --local 127.0.0.1:1234 --remote x.com:5678

同时需要在luci中添加interface,位置在 Network -> Interfaces,点击 Add new interface...,device 选tun0Fireall Settingsfirewall-zonelan

然后是 WireGuard的配置:

在luci中添加interface,配置项就不细说了,最后生成的配置在/etc/config/network中:

config interface 'wg0'
        option proto 'wireguard'
        option private_key 'xxx'
        list addresses '10.0.0.2'
        option mtu '1250'
        option nohostroute '1'
        option ip4table '21'

config wireguard_wg0 'wgserver'
        option public_key 'xxx'
        option endpoint_host '127.0.0.1'
        option endpoint_port '1234'
        option route_allowed_ips '1'
        option persistent_keepalive '25'
        list allowed_ips '0.0.0.0/0'
        option description 'xxx'

wg show 查看,应该已经握手成功。

接下来配置路由,相关命令如下:

nft add set inet fw4 fq { type ipv4_addr \;}
nft add element inet fw4 fq { 10.0.0.1 }
nft add rule inet fw4 mangle_output ip daddr @fq counter mark set 0x15
nft add rule inet fw4 mangle_prerouting ip daddr @fq counter mark set 0x15
ip rule add fwmark 0x15 table 21
ip -4 route add default dev wg0 table 21

意思就是添加一个名为fq的 nft set,并将所有目的地址在这个set中的数据包添加标记0x15, 然后添加规则将所有标记0x15的数据包使用表21的路由配置,在21的路由表中,添加默认路由到wg0。

当然,这只是调试时的写法,nft命令对应的配置添加到/etc/nftables.d/10-custom-filter-chains.nft:

set fq {
    type ipv4_addr
    elements = { 10.0.0.1 }
}

chain mangle_prerouting {
    type filter hook prerouting priority mangle; policy accept;
    ip daddr @fq counter mark set 0x15;
}

chain mangle_output {
    type route hook output priority mangle; policy accept;
    ip daddr @fq counter mark set 0x15;
}

ip命令对应的配置添加到/etc/config/network:

config rule
        option lookup '21'
        option mark '0x15'

再添加WireGuard对应interface的SNAT,Network -> Firewall -> NAT Rules,点击Add,然后Source zone选 lan, Action选择MASQUERADE,保存后在/etc/config/firewall生成的配置项如下:

config nat
        option src 'lan'
        option target 'MASQUERADE'
        list proto 'all'

此时 ping 10.0.0.1,可以ping通,10.0.0.1为WireGuard的一个peer的地址。

SmartDns的配置:

官网下载ipk并安装, 注意必须是39以后的版本,代理相关的配置有以下两行:

domain-set -name fq -type list -file fq.list
domain-rules /domain-set:fq/ -nameserver fq -nftset #4:inet#fw4#fq

将需要代理的域名放在/etc/smartdns/fq.list

配置完成。