Total Pageviews

Sunday 29 March 2020

使用Gfwlist做透明代理

最近由于特殊需要,开始使用gfwlist黑名单模式,用了一段时间感觉还可以,记录一下。

代理方面推荐用V2ray,Shadowsocks和ShadowsocksR已经有些过时,特别是去年被封了几次之后就转用V2ray了,具体V2ray的部署就不写了,网上教程很多。以下主要注重iptables规则和ipset规则,无论用V2ray或者SSR都可以适用,透明代理可使用ssr-redir或者V2ray的dokodemo-door。

具体规则要比之前那篇更简单些,具体应用平台Openwrt或者Linux 桌面系统均可适用。

Openwrt需要安装的软件:
opkg update && opkg remove dnsmasq && opkg install iptables-mod-nat-extra ipset dnsmasq-full

在/etc/rc.local中加入下面ipset的规则,以便开机就生效。因为gfwlist主要以域名为特征码,所以部分软件的登陆可能会有些问题,下面规则中添加了telegram的ip段以及Resilio sync的中继服务器,可透明代理telegram和Resilio sync,不需要的可自行去掉。

ipset -N gfwlist iphash
#Telegram
ipset add gfwlist 91.108.4.0/22
ipset add gfwlist 91.108.8.0/22
ipset add gfwlist 91.108.12.0/22
ipset add gfwlist 91.108.20.0/22
ipset add gfwlist 91.108.36.0/23
ipset add gfwlist 91.108.38.0/23
ipset add gfwlist 91.108.56.0/22
ipset add gfwlist 149.154.160.0/20
#Resilio Sync
ipset add gfwlist 66.206.5.74
ipset add gfwlist 66.165.255.194
ipset add gfwlist 66.165.233.194
ipset add gfwlist 23.111.157.86

使用gfwlist2dnsmasq.sh生成gfwlist的dnsmasq配置文件放入/etc/dnsmasq.d目录中,如果没有这个目录请自行创建,在/etc/dnsmasq.conf中加入一行配置,重启dnsmasq生效。dns的代理可通过V2ray代理8.8.8.8或者chinadns之类的软件实现。
不想自己生成配置的可直接下载gfwlist.conf保存到/etc/dnsmasq.d中即可:
echo "conf-dir=/etc/dnsmasq.d" >> /etc/dnsmasq.conf
/etc/init.d/dnsmasq restart

防火墙规则中加入两条,假设透明代理的端口为7070,Openwrt中可在/etc/firewall.user里加入:
iptables -t nat -A PREROUTING -p tcp -m set --match-set gfwlist dst -j REDIRECT --to-port 7070

iptables -t nat -A OUTPUT -p tcp -m set --match-set gfwlist dst -j REDIRECT --to-port 7070

重启Openwrt的防火墙即可让透明代理生效,所有gfwlist中的网站都会通过透明代理访问。
/etc/init.d/firewall restart

到此配置结束,总体配置简单很多,gfwlist的好处是不需要翻墙的网站不使用代理,如果访问部分国外网站比较慢,可自行加入代理。

这里提供一个自动脚本,可自动加入需要使用代理的网站。脚本假设你的dns代理是127.0.0.1,端口5353,请自行修改。

cat > /usr/bin/gfwlistadd <#!/bin/sh

echo "server=/$1/127.0.0.1#5353" >> /etc/dnsmasq.d/custom.conf
echo "ipset=/$1/gfwlist" >> /etc/dnsmasq.d/custom.conf
/etc/init.d/dnsmasq restart
/etc/init.d/firewall restart

echo "$1已完成添加。"
eof
chmod 755 /usr/bin/gfwlistadd

添加方法,假设要代理***.abc.com,直接将abc.com的顶级域名加入即可:
gfwlistadd abc.com

到此所有配置完成。