Ubuntu编译运行Redsocks2实现透明代理

来源:互联网 发布:广东硅谷软件学院 编辑:程序博客网 时间:2024/04/29 17:12

之前我写过一篇文章《WiFi热点分享ShadowSocks流量实现全局透明代理》里面详细解释了如何使用SSH(或Shadowsocks等其他socks5代理)+redsocks+iptables实现Ubuntu笔记本电脑分享一个Wifi,然后让所有连接这个wifi的客户端都实现透明代理(科学上网),但是这样做受限于redsocks的稳定性问题,因为当时的redsocks是通过Ubuntu的apt-get安装的,版本很旧而且已经停止更新,bug主要表现在。

1、不能关闭已建立的连接,一旦超越linux的最大限制,就会报“Too many open files”异常,导致服务瘫痪,需要每隔一段时间进行重启
2、在我的使用还发现这种方式经常会让NetworkManager对无线网卡的管理崩溃,导致无线网卡停止工作,搜索不到wifi信号,需要经常重启NetworkManager。

3、redsocks1的-p参数有bug,不能生成对应的pid文件。

目前国内带有代理功能的Openwrt路由器普遍使用semigodking 改写的redsocks2,而且redsocks2更新很频繁,经常会有bug修复和新功能出现,所以最好的方式是我们自己去编译github上的源码然后安装使用,编译过程很简单,两分钟即可搞定,从此摆脱redsocks1的bug。

redsocks2的作者应该是个恩山的大神,原贴地址:http://www.right.com.cn/FORUM/forum.php?mod=viewthread&tid=163936,在此要非常感谢大神提供的优秀的透明代理工具

首先找个没有权限限制的目录,比如用户目录下的Downloads,然后克隆github上的c代码

git clone https://github.com/semigodking/redsocks
然后cd到项目根目录

cd ./redsocks
然后安装一个依赖库 libevent2才能编译,否则会报错

sudo apt-get install libevent-dev

然后就可以开心的编译了

make
编译完成之后,会在当前目录下生成一个redsocks2的可执行文件


如果你编译失败,也可以用我之前用Ubuntu16.04编译好的可执行文件,下载地址:http://download.csdn.net/detail/lvshaorong/9664994

注:下载后需要右键,选择属性,找到“权限”选项卡,勾选“允许作为程序执行文件”

然后这个redsocks2文件可以拖出来执行,不过首先我们需要修改它的配置文件,这个目录中有个配置模板文件redsocks.conf.example

我们现在修改这个文件如下

base {// debug: connection progress & client list on SIGUSR1log_debug = off;//log记录连接进度和客户端列表// info: start and end of client sessionlog_info = on;//log记录客户端回话的开始和结束/* possible `log' values are: *   stderr *   "file:/path/to/file" *   syslog:FACILITY  facility is any of "daemon", "local0"..."local7" *///log = "file:/home/alex/log/redsocks.log";//指定log文件的位置,这里要填你本地的位置,而且文件夹必须存在// log = "file:/path/to/file";// log = "syslog:local7";// detach from consoledaemon = on;//on就在后台执行,off就占用当前终端来显示log,关闭终端redsocks也关闭,所以推荐后台执行on/* Change uid, gid and root directory, these options require root * privilegies on startup. * Note, your chroot may requre /etc/localtime if you write log to syslog. * Log is opened before chroot & uid changing. */// user = nobody;// group = nobody;// chroot = "/var/chroot";/* possible `redirector' values are: *   iptables   - for Linux *   ipf        - for FreeBSD *   pf         - for OpenBSD *   generic    - some generic redirector that MAY work */redirector = iptables;//转发工具,Ubuntu使用iptables即可/* Override per-socket values for TCP_KEEPIDLE, TCP_KEEPCNT, * and TCP_KEEPINTVL. see man 7 tcp for details. * `redsocks' relies on SO_KEEPALIVE option heavily. *///tcp_keepalive_time = 0;//tcp_keepalive_probes = 0;//tcp_keepalive_intvl = 0;}redsocks {/* `local_ip' defaults to 127.0.0.1 for security reasons, * use 0.0.0.0 if you want to listen on every interface. * `local_*' are used as port to redirect to. */local_ip = 0.0.0.0;//本地监听的地址,为了是iptables的端口转发生效,必须填写0.0.0.0local_port = 12345;//本地监听端口,如果12345被别的程序占了就换一个// listen() queue length. Default value is SOMAXCONN and it should be// good enough for most of us.listenq = 128; // SOMAXCONN equals 128 on my Linux box.// `max_accept_backoff` is a delay to retry `accept()` after accept// failure (e.g. due to lack of file descriptors). It's measured in// milliseconds and maximal value is 65535. `min_accept_backoff` is// used as initial backoff value and as a damper for `accept() after// close()` logic.// min_accept_backoff = 100;// max_accept_backoff = 60000;// `ip' and `port' are IP and tcp-port of proxy-server// You can also use hostname instead of IP, only one (random)// address of multihomed host will be used.// The two fields are meaningless when proxy type is 'direct'.ip = 192.168.1.21;//socks5服务器的ip和端口,可以是SSH或者Shadowsocks的port = 44401;// known types: socks4, socks5, http-connect, http-relay// New types: direct, shadowsockstype = socks5;//协议,一般SSH和Shadowsocks填socks5    // Specify interface for outgoing connections.    // This is useful when you have multiple connections to    // internet or when you have VPN connections.    // interface = tun0;// Change this parameter to 1 if you want auto proxy feature. // When autoproxy is set to non-zero, the connection to target// will be made directly first. If direct connection to target// fails for timeout/connection refuse, redsocks will try to// connect to target via the proxy.autoproxy = 0;//是否开启自动代理,0为不开启,推荐不要开启// timeout is meaningful when 'autoproxy' is non-zero.// It specified timeout value when trying to connect to destination// directly. Default is 10 seconds. When it is set to 0, default// timeout value will be used.timeout = 10;//自动代理超时// login = "foobar";// field 'login' is reused as encryption   // method of shadowsocks// password = "baz";}//模板上还有redudp和reddns设置,但是运行时会报错,所以直接删掉ipcache {    // Configure IP cache    cache_size = 4;   // Maximum number of IP's in 1K.     stale_time = 900; // Seconds to stale an IP in cache since it is added                      // into cahce.                      // Set it to 0 to disable cache stale.    port_check = 1;   // Whether to distinguish port number in address    cache_file = "/tmp/ipcache.txt"; // File used to store blocked IP's in cache.    autosave_interval = 3600; // Interval for saving ip cache into file.                              // Set it to 0 to disable autosave.    // When autosave_interval and stale_time are both 0, IP cache behaves like    // a static blacklist. }// you can add more `redsocks' and `redudp' sections if you need.

模板上还有redudp和reddns设置,但是运行时会报错,所以直接删掉,如果想解决DNS污染的问题,可以参考我之前的两篇文章《Ubuntu16.04用Pdnsd替换dnsmasq防止DNS污染》《一分钟快速搭建Windows防污染DNS服务器——Pcap_DNSProxy》,或者通过Ubuntu apt-get的redsocks(redsocks第一代)进行udp转tcp的DNS查询,但是那样做会影响这台Ubuntu电脑本身的上网。但是如果你不处理DNS污染,你还是上不去facebook,google,twitter,Ins,youtube等网站的。

然后使用iptables将所有的tcp流量都转发到redsocks2进行代理即可,配置如下

iptables -t nat -A PREROUTING -d 127.0.0.0/24 -j RETURN  iptables -t nat -A PREROUTING -d 192.168.0.0/16 -j RETURN  iptables -t nat -A PREROUTING -d 10.42.0.0/16 -j RETURN  iptables -t nat -A PREROUTING -d 0.0.0.0/8 -j RETURN  iptables -t nat -A PREROUTING -d 10.0.0.0/8 -j RETURN  iptables -t nat -A PREROUTING -d 172.16.0.0/12 -j RETURN  iptables -t nat -A PREROUTING -d 224.0.0.0/4 -j RETURN  iptables -t nat -A PREROUTING -d 240.0.0.0/4 -j RETURN  iptables -t nat -A PREROUTING -d 169.254.0.0/16 -j RETURN    iptables -t nat -A PREROUTING -p tcp -s 10.42.0.0/16 -j REDIRECT --to-ports 12345  

其中修改的是PREROUTING表,这样只会对Wifi网卡的流量起作用,而不会对本机起作用,如果想让本机起作用,可以把相同的规则加上server的ip return加到OUTPUT表上。

上面的10.42.0.0/16是Ubuntu系统分享wifi后,wifi子网连入设备的IP地址,上面最后一句话的意思就是把所有来自Wifi的数据包都发送到redsocks2的监听端口12345去

然后就可以启动redsocks2了

redsocks2 -c <配置文件的地址>
然后使用netstat -ntlp观察12345端口是否被redsocks2监听即可

如果想实现手机,笔记本电脑通过该电脑进行透明代理,那么可以开启Ubuntu的wifi分享功能让手机连入,然后开心的fan wall了,Ubuntu16.04开启Wifi分享功能网上说的很多,我这里就不浪费篇幅了

http://jingyan.baidu.com/article/363872ecd8f35d6e4ba16f97.html

如果想让局域网其他的电脑通过你的电脑进行透明代理,那么只需要让局域网的其他电脑将网关设置为你的电脑的局域网IP地址即可。Ubuntu默认就可以做网关使用,只要你的电脑网关配置正确即可,如果我的电脑ip是192.168.1.81的话,真实的网关是192.168.1.254,那么局域网内其他电脑可以做如下配置


像Openwrt这样的系统默认是不能做网关的,因为FORWARD表默认被DROP了,我们可以通过iptables手动打开

sudo iptables -I FORWARD -j ACCEPT


另外,如果你不使用SSH进行代理,而是Shadowsocks,那么不需要用redsocks多走一层,直接用ss-redir即可,方法可以看我之前的一篇文章《Ubuntu编译运行ss-redir打造透明代理Wifi环境》


后记:

在运行了一段时间后发现,redsocks2在上游代理出现问题的时候,还是会向Redsocks1一样使NetworkManager崩溃导致无线网卡停止工作,但是频率不redsocks1降低了很多。

我写了一个启动,停止和终止redsocks2的脚本,可以放在定时任务里定时重启,记得使用root权限,分享给大家

启动脚本 start.sh

/home/alex/redsocks2 -c ./config/redsocks.conf

停止脚本,注意下面不是单引号,而是键盘左上角那个引号,stop.sh

kill -9  `pgrep redsocks2 `

重启脚本

start.shstop.sh

除了使用pgrep自动探测pid以外,还可以在启动脚本里添加-p参数,然后使用kill `cat /home/alex/pid/redsocks2.pid`(参数是我自己规定的pid文件位置)获得pid,但是这样麻烦,就不用这种方式了。




0 0