Pages

Thursday, 5 January 2012

在vps上搭建stunnel+http proxy(或socks proxy),用来翻墙的详细方法(原创文章)



如果你有自己的vps,可在vps上搭建stunnel,用来翻墙。
如果你的vps是centos/fedora系统,则
# yum install stunnel -y
但是我在/etc/stunnel/里面并未发现stunnel.conf,这是因为没有缺省的conf文件的缘故。解决办法:
# yum install yum-utils -y
# repoquery --list stunnel (用此命令可得到stunnel软件包的文件列表)
显示如下内容:
/etc/stunnel
/usr/lib/libstunnel.so
/usr/sbin/stunnel
/usr/sbin/stunnel3
/usr/share/doc/stunnel-4.15
/usr/share/doc/stunnel-4.15/AUTHORS
/usr/share/doc/stunnel-4.15/BUGS
/usr/share/doc/stunnel-4.15/COPYING
/usr/share/doc/stunnel-4.15/COPYRIGHT.GPL
/usr/share/doc/stunnel-4.15/CREDITS
/usr/share/doc/stunnel-4.15/Certificate-Creation
/usr/share/doc/stunnel-4.15/ChangeLog
/usr/share/doc/stunnel-4.15/NEWS
/usr/share/doc/stunnel-4.15/PORTS
/usr/share/doc/stunnel-4.15/README
/usr/share/doc/stunnel-4.15/TODO
/usr/share/doc/stunnel-4.15/VNC_StunnelHOWTO.html
/usr/share/doc/stunnel-4.15/faq.stunnel-2.html
/usr/share/doc/stunnel-4.15/pop3-redirect.xinetd
/usr/share/doc/stunnel-4.15/sfinger.xinetd
/usr/share/doc/stunnel-4.15/stunnel-pop3s-client.conf
/usr/share/doc/stunnel-4.15/stunnel-sfinger.conf
/usr/share/doc/stunnel-4.15/stunnel.conf-sample
/usr/share/doc/stunnel-4.15/transproxy.txt
/usr/share/doc/stunnel-4.15/tworzenie_certyfikatow.html
/usr/share/man/fr/man8/stunnel.8.gz
/usr/share/man/man8/stunnel.8.gz
/usr/share/man/pl/man8/stunnel.8 .gz
上面的/usr/share/doc/stunnel-4.15/stunnel.conf-sample即为stunnel.conf的样板文件。

注意以上为我当时安装stunnel时的版本号4.15. 现在2020-02-04,我 重新安装stunnel,
stunnel的版本已经变成了4.56。所以下面的4.15都要相应的改成4.56


cp /usr/share/doc/stunnel-4.15/stunnel.conf-sample /etc/stunnel/stunnel.conf
等下我们要编辑stunnel.conf文件。

cd /etc/stunnel
openssl req -new -x509 -days 3650 -nodes -out public.crt -keyout private.key
运行上面这条命令后,在当前目录/etc/stunnel里会生成public.crt和private.key文件
然后编辑stunnel.conf文件:
;chroot = /var/run/stunnel/ (说明:注释掉chroot = /var/run/stunnel/ 因为/var/run/stunnel并不存在,所以在其前面加;号。
;setuid = nobody

;setgid = nobody
pid = /stunnel.pid (说明:pid = 的值修改为/stunnel.pid或/opt/stunnel.pid)
client=no
cert = /etc/stunnel/public.crt
key = /etc/stunnel/private.key
[https]
accept  = 440 (注意这里的端口号不一定非要是443不可)
connect = http代理服务器程序proxy.py的端口号8888
(proxy.py的搭建请看https://briteming.blogspot.com/2015/11/proxypy-pythonhttp.html)
然后重启stunnel服务:
killall stunnel
/usr/sbin/stunnel /etc/stunnel/stunnel.conf

然后回到本地机器,带参数--proxy-server=https://vps_ip:440 --ignore-certificate-errors启动chrome,即可在chrome中翻墙。
如果你的客户机器为mac,则在终端里运行open "/applications/Google Chrome.app/" --args --proxy-server=https://vps_ip:440 --ignore-certificate-errors即可。
你可把open "/applications/Google Chrome.app/" --args --proxy-server=https://vps_ip:440 --ignore-certificate-errors保存为start-chrome-stunnel.sh,
赋予start-chrome-stunnel.sh可执行权限:
chmod 755 start-chrome-stunnel.sh
以后,想要用chrome翻墙时,运行./start-chrome-stunnel.sh即可。

如果你想在本地的windows机器中,让非chrome的浏览器也能利用stunnel翻墙,则
用winscp把/etc/stunnel/里的stunnel.pem文件下载到本地某个目录,比如d:\
不过这个stunnel程序有点怪,尽管用yum install stunnel -y命令安装了stunnel,但是在/etc/init.d/里面却没有stunnel的影子,所以暂时还不能用/etc/init.d /stunnel restart命令来重启stunnel.在这里http://www.gaztronics.net/rc/stunnel.php 有一个可下载的init脚本。(http://www.gaztronics.net/rc/stunnel.txt)
cd /etc/init.d
wget http://www.gaztronics.net/rc/stunnel.txt
mv stunnel.txt stunnel
chmod 755 stunnel
chown root:root stunnel
然后修改配置文件stunnel.conf,
然后重启stunnel即可:
/etc/init.d/stunnel restart
(当然 上面蓝色字体也可这样做:
killall stunnel
/usr/sbin/stunnel
这里的/usr/sbin/stunnel即为stunnel服务的执行文件。)
然后在你的本地机器上安装客户端:Stunnel的Windows版本可以点此下载安装过程比较简单,一路Next就行。假设我们把Stunnel安装在默认路径C:\Program Files\stunnel\下。先删除C:\Program Files\stunnel\下的自带的stunnel.pem 。
把上面下载的stunnel.pem复制到C:\Program Files\stunnel\下。然后修改C:\Program Files\stunnel\里的stunnel.conf:

client = yes
[https]
accept  = 127.0.0.1:7777 (说明:这里的7777端口可以随便设置,只要是本地未被占用的端口就行)
connect = 你vps的ip:440 (需跟服务器端设置的端口一致)

客户端除了可以用stunnel外,还可以用socat:
在mac机器上,运行brew install socat 来安装socat,然后运行:

socat tcp-listen:7777,fork openssl:vps-public-ip:440,verify=0

不要关闭此终端。

详见:https://blog.lilydjwg.me/2012/10/25/secure-your-http-proxy-with-tls-ssl.36107.html

不过使用socat不如使用stunnel稳定。


 (关于客户端,其实下载绿色版就可以了,无需下载安装版,我下载的是绿色版的最后的版本- stunnel-4.11.exe: ftp://ftp.stunnel.org/stunnel/archive/4.x/stunnel-4.11.exe,从4.00到4.11都是绿色版。然后从你的vps下载stunnel.pem, stunnel.conf文件。stunnel.conf需要编辑如上.  如果你用了stunnel一段时间,发现打开网页缓慢,你可点击你电脑右下角的stunnel图标,发现提示:比如50 sessions active,此时建议你重启stunnel的客户端,确保active sessions在10以下比较好。)
然后启动d:\stunnelclient\里的stunnel-4.04.exe,(在实际使用时,这个stunnel-4.04.exe经常每隔半小时左右崩溃一次。如果崩溃了,重启它即可),然后设置你的浏览器的http代理为127.0.0.1,端口7777,即可翻墙。
如果过一段时间,你用stunnel翻不了墙了,可能是因为你的vps里的stunnel停止运行了,
登录你的vps,输入命令 /usr/sbin/stunnel,回车.另外用命令ps aux | grep proxy.py检查一下proxy.py是否在运行,如果没有在运行,则运行proxy.py。为了确保stunnel处于运行状态,
你可以运行命令: ps aux | grep stunnel查看stunnel是否已在运行。
注:如果你的centos系统是centos7,需首先卸载firewalld:
systemctl stop firewalld
systemctl disable firewalld
yum erase firewalld
systemctl enable iptables
systemctl start iptables

这段内容的意思是停止firewalld而启用iptables

然后还要记得开放stunnel的端口440 proxy.py的端口3028(因为centos 7的防火墙规则比较严,一些非常用的端口默认是不开放的!):
iptables -I INPUT -p tcp -m tcp --dport 440 -j ACCEPT
iptables -I INPUT -p tcp -m tcp --dport 3028 -j ACCEPT

然后,
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

service iptables save
service iptables restart )


如果你的vps是debian/ubuntu系统,则
# apt-get install stunnel -y
这里的stunnel跟centos/fedora下的stunnel一样,是不能用/etc/init.d/stunnel start命令来启动的,因为/etc/init.d/下没有stunnel文件。
运行apt-get install stunnel -y时,显示:
...
正在添加系统用户"stunnel4" (UID 106)...
正在添加新组"stunnel4" (GID 110)...
正在将新用户"stunnel4" (UID 106)添加到组"stunnel4"...
无法创建主目录"/var/run/stunnel4"
SSL tunnels disabled, see /etc/default/stunnel4
root@AR:~# ls /var/run/
apache2 mount shm     upstart-socket-bridge.pid
apache2.pid network   upstart-udev-bridge.pid
container_type rsyslogd.pid    user
crond.pid saslauthd sshd     utmp
crond.reboot screen sshd.pid    xinetd.pid
lock sendmail stunnel4
motd.dynamic sendsigs.omit.d  udev
(/var/run/stunnel4目录其实是存在的。)
root@AR:~# chown -R stunnel4:stunnel4 /var/run/stunnel4/
root@AR:~# nano /etc/default/stunnel4
(把/etc/default/stunnel4文件里的ENABLED的值改为1,以便让stunnel4随vps的启动而自动启动)
root@AR:~# find / -name stunnel
显示:
/usr/share/doc/stunnel
/usr/lib/stunnel
/usr/bin/stunnel
/etc/stunnel

stunnel的执行文件为/usr/bin/stunnel ,
运行 /usr/bin/stunnel
会有如下错误提示:
2011.05.22 16:01:15 LOG7[2027:3074864816]: Snagged 64 random bytes from /root/.rnd
2011.05.22 16:01:15 LOG7[2027:3074864816]: Wrote 1024 new random bytes to /root/.rnd
2011.05.22 16:01:15 LOG7[2027:3074864816]: RAND_status claims sufficient entropy for the PRNG
2011.05.22 16:01:15 LOG7[2027:3074864816]: PRNG seeded successfully
2011.05.22 16:01:15 LOG7[2027:3074864816]: Certificate: /etc/stunnel/stunnel.pem
2011.05.22 16:01:15 LOG7[2027:3074864816]: Certificate loaded
2011.05.22 16:01:15 LOG7[2027:3074864816]: Key file: /etc/stunnel/stunnel.pem
2011.05.22 16:01:15 LOG7[2027:3074864816]: Private key loaded
2011.05.22 16:01:15 LOG7[2027:3074864816]: SSL context initialized for service stunnel
inetd mode must define a remote host or an executable "

nano /usr/bin/stunnel (打开/usr/bin/stunnel文件查看一下,里面有显示$stunnel_bin='usr/bin/stunnel4';
于是知道stunnel的真正的执行文件为/usr/bin/stunnel4而不是/usr/bin/stunnel
root@AR:~# find / -name stunnel4
显示:
/var/log/stunnel4
/var/lib/stunnel4
/etc/init.d/stunnel4
/etc/default/stunnel4
/etc/logrotate.d/stunnel4
/usr/bin/stunnel4
/usr/share/doc/stunnel4
/usr/share/lintian/overrides/stunnel4
/usr/share/doc-base/stunnel4
/run/stunnel4
root@AR:~#

cd /usr/share/doc/stunnel4/examples/ (进入后,会发现里面有stunnel.conf-sample文件,stunnel.conf-sample就是stunnel.conf的样板文件。)
cp /usr/share/doc/stunnel4/examples/stunnel.conf-sample /etc/stunnel/stunnel.conf
cd /etc/stunnel/
openssl req -new -x509 -days 3650 -nodes -out stunnel.pem -keyout stunnel.pem
这里生成的cert文件和key文件都是stunnel.pem,二者合而为一了。运行上面这条命令后,在/etc/stunnel/里会生成stunnel.pem文件。
然后编辑stunnel.conf文件:
;chroot = /var/run/stunnel/ (说明:注释掉chroot = /var/run/stunnel/ 因为/var/run/stunnel并不存在,所以在其前面加;号。
;setuid = nobody
;setgid = nobody
pid = /stunnel4.pid
client = no
cert = /etc/stunnel/stunnel.pem
key = /etc/stunnel/stunnel.pem
[http proxy]
accept  = 440 (注意这里的端口号不一定非要是443不可)
connect = http代理服务器程序proxy.py的端口号8888

然后重启stunnel4服务:
killall stunnel4
/usr/bin/stunnel4 /etc/stunnel/stunnel.conf
验证一下stunnel4是否在运行中:
root@umh:~# ps aux|grep stunnel4
root      5762  0.0  0.1 365440  2696 ?        Ssl  17:10   0:00 stunnel4 /etc/stunnel/stunnel.conf
root      5777  0.0  0.0  11072   844 pts/0    S+   17:10   0:00 grep stunnel4

root@umh:~#
(出现了stunnel4的进程,说明stunnel4在运行中。)

然后回到本地机器,带参数--proxy-server=https://vps_ip:440 --ignore-certificate-errors启动chrome,即可在chrome中翻墙。


如果你的客户机器为mac,则在终端里运行open "/applications/Google Chrome.app/" --args --proxy-server=https://vps_ip:440 --ignore-certificate-errors即可。
你可把open "/applications/Google Chrome.app/" --args --proxy-server=https://vps_ip:440 --ignore-certificate-errors保存为start-chrome-stunnel.sh,
赋予start-chrome-stunnel.sh可执行权限:
chmod 755 start-chrome-stunnel.sh

以后,想要用chrome翻墙时,运行./start-chrome-stunnel.sh即可。

如果你想在本地的windows机器中,让非chrome的浏览器也能利用stunnel翻墙,则
用winscp把/etc/stunnel/里的stunnel.pem文件下载到本地某个目录,比如d:\,
然后在你的本地机器上下载和安装客户端: ftp://ftp.stunnel.org/stunnel/archive/4.x/stunnel-4.11.exe,
解压到
d:\stunnelclient,把上面下载的stunnel.pem复制到d:\stunnelclient\下。然后修改d:\stunnelclient\里的stunnel.conf:
client = yes
[http proxy]
accept  = 127.0.0.1:7777 (说明:这里的7777端口可以随便设置,只要是本地未被占用的端口就行)
connect = 你vps的ip:440 (需跟服务器端设置的端口一致)

  (关于客户端,下载绿色版就可以了,无需下载安装版,我下载的是绿色版的最后的版本- stunnel-4.11.exe: ftp://ftp.stunnel.org/stunnel/archive/4.x/stunnel-4.11.exe,从4.00到4.11都是绿 色版。然后从你的vps下载stunnel.pem,stunnel.conf文件。stunnel.conf需要编辑如上。   如果你用了stunnel一段时间,发现打开网页缓慢,你可点击你电脑右下角的stunnel图标,发现提示:比如50 sessions active,此时建议你重启stunnel的客户端,确保active sessions在10以下比较好。)
然后启动d:\stunnel\里的stunnel-4.11.exe,(在实际使用时,这个stunnel-4.11.exe经常每隔半小时左右崩溃一次。如果崩溃了,重启它即可),然后设置你的浏览器的http代理为127.0.0.1,端口7777, 浏览器即可翻墙。

如果过一段时间,你用stunnel翻不了墙了,可能是因为你的vps里的stunnel停止运行了,
登录你的vps,输入命令 /usr/bin/stunnel4,回车另外用命令ps aux | grep proxy.py检查一下proxy.py是否在运行,如果没有在运行,则启动proxy.py .为了确保stunnel4 处于运行状态,
你可以运行命令: ps aux | grep stunnel4 ,查看stunnel4是否已在运行。

如果你还想折腾,可参看:
https://sunmaiblog.wordpress.com/2010/09/21/stunnel%E7%9A%84%E8%AE%BE%E7%BD%AE%E5%92%8C%E4%BD%BF%E7%94%A8/

如果你的客户机器是mac,则brew install stunnel,最后显示:
...
A bogus SSL server certificate has been installed to:
  /usr/local/etc/stunnel/stunnel.pem

This certificate will be used by default unless a config file says otherwise!
Stunnel will refuse to load the sample configuration file if left unedited.

In your stunnel configuration, specify a SSL certificate with
the "cert =" option for each service.
==> Summary
🍺  /usr/local/Cellar/stunnel/5.23: 35 files, 672K
yudeMacBook-Air:~ brite$ 
配置文件在此目录内:/usr/local/etc/stunnel/,
nano stunnel-backend-is-http-proxy-on-vps.conf
内容为:

client = yes

cert = public.crt 

key = private.key

[http proxy]

accept  = 127.0.0.1:7777 

connect = vps-public-ip:440


然后,

stunnel stunnel-backend-is-http-proxy-on-vps.conf

然后设置你的浏览器的http代理为127.0.0.1,端口7777, 浏览器即可翻墙。

其实上文所述的服务器端的配置文件/etc/stunnel/stunnel-backend-is-http-proxy.conf可以简单的写为:

client = no

cert = /etc/stunnel/public.crt

key = /etc/stunnel/private.key

[http proxy]

accept  = 440

connect = localhost:8888


然后,

stunnel /etc/stunnel/stunnel-backend-is-http-proxy.conf

服务器端设置完成。


服务器上的代理服务器程序也可为socks proxy,比如socks代理服务器程序:socks-by-andrew-d (https://briteming.blogspot.com/2019/10/gosockssocks-by-andrew-d.html),

nano /etc/stunnel/stunnel-backend-is-socks-proxy.conf

cat /etc/stunnel/stunnel-backend-is-socks-proxy.conf

client = no

cert = /etc/stunnel/public.crt

key = /etc/stunnel/private.key

[socks proxy]

accept  = 441

connect = localhost:5800


然后,

stunnel /etc/stunnel/stunnel-backend-is-socks-proxy.conf

服务器端设置完成。


回到本地机器mac.

cd /usr/local/etc/stunnel/

nano stunnel-backend-is-socks-proxy-on-vps.conf

内容为:

client = yes

cert = public.crt 

key = private.key

[socks proxy]

accept  = 127.0.0.1:7778

connect = vps-public-ip:441


然后,

stunnel stunnel-backend-is-socks-proxy-on-vps.conf

然后设置你的浏览器的socks5代理为127.0.0.1,端口7778, 浏览器即可翻墙。

(相关帖子:https://briteming.blogspot.com/2018/12/macstunnel.html)


虽然stunnel+http proxy或stunnel+socks proxy都能用来翻墙,但stunnel+socks proxy的翻墙效果更坚挺。



相关帖子:http://briteming.blogspot.com/2016/03/vpsstunnel.html
--------------------------------------------------
digitalocean.com也有一篇教程:
https://www.digitalocean.com/community/tutorials/how-to-set-up-an-ssl-tunnel-using-stunnel-on-ubuntu
-----------------------------------------------------------------------

使用stunnel突破网络管制

当前网络审查相当严格,不仅有政府的GFW来扫描过往的数据包,好多公司也有各自的“墙”,用策略来过滤一部分的网络请求,本文描述了如何在比较苛刻的审查条件下进行突破数据包扫描的方法。
公司屏蔽了除21/80/443之外的其他端口,端口绑定协议(也就是21必须是FTP协议,80是HTTP,443是HTTPS),禁止IMCP 协议(也就是说过滤了ping数据包);配合域名过滤以及ip地址过滤,比如对qq/飞信的过滤就是屏蔽了服务器的ip地址;更加变态的是居然有类似 GFW的链接被重置,比如你访问的一个网站上引用到了某个被屏蔽的站点的url,那个网站也会被屏蔽几分钟,机制很诡异。

解决思路:

思路1:在自己的VPS上把SSHD绑定在21或443端口,利用MyEntunnel配合ssh翻墙(这招在突破GFW上很管用,比VPN简单易用,直接得到一个SOCKS代理,配合Firefox的AutoProxy用)。结果由于端口绑定协议,ssh根本不能访问。
思路2:在外网找一台Server,我用的是自己家的ADSL+一台ATOM D510小主机,开放80端口做HTTP(S)代理,成功的解决了ip地址过滤的问题,飞信和qq成功登录。
思路3:同样是借助外网Server,在443端口 上假设stunnel server端,在内网架设stunnel client端,C/S端用密钥对加解密,成功的突破了防火墙的限制,得到加密的一条隧道至一个HTTP代理。至此,突破网络扫描的工作完成,任何TCP 请求都能够顺利通过隧道。

stunnel的机制以及局限性:

作用机制:stunnel(官方站点www.stunnel.org) 其实是一个用SSL加密来保护不受加密的通信的工具,简单的说就是建立一个消息隧道,本地未加密的消息传输到stunnel的客户端,客户端使用加密后传 输给服务器端,服务器端解密后进行数据包的转发,比如转发到一个代理,数据返回的机制类似。穿透防火墙的原理是因为通信采用的是标准的HTTPS,因此网 关不能扫描包内容,也不会进行拦截。这样就保证了数据传输的安全性,在非安全的网络条件下适用。
局限性:stunnel并没有提供客户端程序使用 HTTP代理访问服务器端的支持(或者是我没找到),其实从原理上来说是可以增加一层代理的,因为是标准的HTTPS通信,多一层proxy不影响整个数 据的流通。还有一个不容忽视的问题就是速度被明显的拖慢了,中间环节变多了,速度没可能不慢,我的解决方法是在客户端做一个squid代理缓存,对静态文 件(比如css,图片,js等)高概率(90%)缓存命中,减少重复的通过隧道请求服务器。

stunnel配置方法:

1. 下载stunne和openssl:
2. 生成证书:
openssl req -new -x509 -days 3650 -nodes -out stunnel.pem -keyout stunnel.pem
将产生的stunnel.pem拷贝到服务端/客户端各自的安装目录,替换同名文件
3. 在服务器上安装服务器端,修改配置文件stunnel.conf:
cert = stunnel.pem
key = stunnel.pem
client = no
[https]
accept  = 443
connect = http代理服务器程序proxy.py的端口
//[https]表示声明一个endpoint,此处即监听443端口,转发到proxy.py的端口
4. 在本地机器上安装客户端,修改配置文件stunnel.conf:
cert = stunnel.pem
key = stunnel.pem
client = yes
[https]
accept  = 8888
connect = xxxx.com:443
//同样,声明https这个endpoint,监听本地的8888端口,转发到xxxx.com的443端口
//注意,服务端和客户端使用的stunnel.pem一定要一致(下载服务端的stunnel.pem文件到c:\program files\stunnel\,覆盖该目录下的同名文件)

Cache:

由于使用加密隧道进行通信的时间成本比较大,如果不做本地缓存的话可能会严重的影响速 度。因此,我做了两个缓存服务器,一个在客户端,一个在服务器端,客户端squid配置成对静态文件90%命中,即无视http header中的Expires设置,有点类似强制命中。这样就基本能保证同一个文件不会经常占用速度比较慢的隧道而影响浏览效果,因此客户端squid 的memory缓存和磁盘缓存大小必须设置得比较大.

from www.hackerzhou.me
------------------------------------------------

用 Stunnel 保护隐私


Stunnel 是个好东西,很小巧,它的原理是把服务器端的 http 代理加密成 https 代理,然后在本地也用 stunnel 把 https 代理转成 http 代理,这样在本地就有了一个 http 代理可用。goagent限制太多,自己搭建的服务器就是得花钱和浪费点时间。不过值得,相信我。
服务器端搭建:
1,http代理,用proxy.py随便搞个http代理出来,此时这个代理是http proxy,直接用会被rst。
2,安装 stunnel ,配置大概如下,先用 openssl 产生一个证书:
openssl req -new -x509 -days 3650 -nodes -out /etc/stunnel.pem -keyout /etc/stunnel.pem


cert = /etc/stunnel.pem chroot = /var/run/stunnel4/ pid = /stunnel.pid client = no sslVersion = SSLv3 socket = l:TCP_NODELAY=1 socket = r:TCP_NODELAY=1 socket = l:SO_LINGER=1:1 socket = r:SO_LINGER=1:1 [http] accept = 8888 #stunnel的端口 connect = 127.0.0.1:3128 #本地http端口
然后启动 stunnel,服务器端就搭建好了。但此时代理是https的,必须在本地做好了 stunnel 客户端转成 http 才行。
本地端:
本地端其实超级简单了。Mac上直接用 macport,brew 安装个 stunnel 即可。如果不便,直接下我的编译好的,在这。下载后 chmod +x stunnel
写一个配置文件:
client = yes #扮演客户端啦
pid=/var/run/stunnel.pid
debug = 7
foreground = no #是否前台运行还是后台运行
sslVersion = SSLv3
verify=0
[proxy]
accept = 127.0.0.1:9999
connect = xxx.xxx.xxx.xxx:8888
然后启动 stunnel 即可,执行 ./stunnel stunnel.conf
这样,在本地就有一个 9999 端口的 http 代理,世界清净了,没有 rst 和偷窥。你懂的。
------------------------------------------------------------------

在Android和OS/X系统搭建stunnel加密代理


Android
Important: this is an allowed but unsupported hack. Please do not contact support if below does not work for you.
Install stunnel
Unfortunately Android does not come with stunnel. We found a pre-compiled and working version here: http://blog.tempest.com.br/marco-carnut/autenticacao-mutua-https-android-stunnel.html. (If you have a hard time finding the actual binary, try this link: http://blog.tempest.com.br/static/attachments/marco-carnut/autenticacao-mutua-https-android-stunnel/stunnel4-android21.tar.bz2). There may be other sources as well.
To install the binary we used the following adb commands:
adb shell mount -o rw,remount /system
adb push stunnel /system/bin/
adb shell chmod ug+rwx /system/bin/stunnel
adb shell mount -o ro,remount /system
adb shell mkdir /data/data/org.stunnel
If you do not understand what these commands do or where to find the adb utility, you should probably not proceed. The data directory is required for stunnel’s PID file.
Configure stunnel
On the phone create a file /etc/stunnel.conf with the following content:
sslVersion = TLSv1
client = yes
pid = /data/data/org.stunnel/stunnel.pid
[proxy]
accept  = 127.0.0.1:8080
connect = automatic.securechromenetwork.com:443
If you’re experiencing problems you may temporarily add:
debug = 7
foreground = yes
Be careful adding the foreground directive if you have stunnel start automatically on startup. During our tests adding debug would prevent stunnel from being started. Adding foreground may cause issues during boot.
(Automatically) start stunnel
Create a file /etc/init.d/99stunnel with the following contents:
#!/system/bin/sh
STUNNEL=/system/bin/stunnel
STUNNEL_CONF=/etc/stunnel.conf
LOG=/data/stunnel.log

if [ -e $LOG ]; then
 rm $LOG;
fi; 

if [ ! -e $STUNNEL ]; then
 echo stunnel binary not found | tee -a $LOG
 exit 1;
fi;

if [ ! -e $STUNNEL ]; then
 echo stunnel configuration file not found | tee -a $LOG
 exit 1;
fi;

echo "$( date +"%Y.%m.%d %H:%M:%S" ) starting stunnel" | tee -a $LOG
$STUNNEL $STUNNEL_CONF | tee -a $LOG

PID="$( pidof stunnel)"
if [ -z $PID ]; then
 echo stunnel was not started properly | tee -a $LOG
 exit 1;
else
 echo stunnel running with pid $PID | tee -a $LOG;
fi;

exit 0;
Make sure the script has the proper permissions and owner/group. (Check other scripts in /etc/init.d/ to see what they use). Reboot your phone and double-check that this actually works for you, not all Android flavors execute init.d scripts automatically.
Configure Android to use VPN.tv
Now we need to configure Android to use the proxy provided by stunnel. Some Android versions allow you to configure the proxy for WiFi only, not for 3G. Sometimes the proxy option is missing entirely.
We prefer using ProxyDroid by Max Lv (who also provided the stunnel we linked to above) which can be found in the Android Market.
The proxy you need to configure is:
  • host: 127.0.0.1
  • port: 8080
  • type: http
  • authentication: enabled
  • username/password: as provided by VPN.tv
  • global proxy: OFF
  • DNS proxy: OFF
  • individual proxy: use
China
If you’re in China you’ll probably want to enable Global Proxy and DNS Proxy. For this to work you need to do two additional things:
  • In stunnel.conf, replace automatic.securechromenetwork.com with the relevant IP address, e.g. change automatic.securechromenetwork.com:8080 to 1.2.3.4:8080.
  • In ProxyDroid enter this same IP address Intranet Address, e.g. 1.2.3.4/32.
原文:https://vpn.tv/faq/osx-on-vpn-tv/
OS/X
Important: this is an allowed but unsupported hack. Please do not contact support if below does not work for you.
Install Macports
First install Macports. We need Macports to install stunnel in the next step. Macports and its installation instructions can be found here: http://www.macports.org/install.php.
Install stunnel
Install stunnel using the following command:
sudo port install stunnel
Configure stunnel
Create /opt/local/etc/stunnel/stunnel.conf with the following content:
sslVersion = TLSv1
chroot = /opt/local/var/lib/stunnel/
setuid = nobody
setgid = nogroup
pid = /stunnel.pid
client = yes
libwrap = no

[proxy]
accept  = 127.0.0.1:8080
connect = automatic.securechromenetwork.com:443
TIMEOUTclose = 0
(Automatically) start stunnel
You can now start stunnel simply by typing sudo stunnel in a Terminal window. If you want to make sure stunnel gets started automatically every time you start your computer, please enter the following command:
sudo crontab -e
This opens the crontab in VI. Please add the following line to the file:
@reboot * * * * /opt/local/bin/stunnel
Configure OS/X to use VPN.tv
Open System Preferences and select Network. On the Network window click Advanced… On the Advanced window select the Proxies tab. For both  Web Proxy and Secure Web Proxy set server to localhost : 8080 and fill in your username and password. Click Apply and close the window.
Note that not all OS/X applications automatically use these proxy settings. Some applications will need you to configure the proxy in the application itself.
Know problems
You can not use this hack AND use the Chrome extension. Doing so will cause Chrome to complain about invalid proxy certificates.
原文:https://vpn.tv/faq/android-on-vpn-tv-requires-rooted-phone/
--------------------------------------------------------------------------

stunnel on iphone for certificate authentication




Mobile Safari and the programs I have seen on the iPhone don’t understand certificate-based client authentication. This is a problem that I don’t think they will fix since most enterprises don’t have a fully functional PKI and are still stuck with just passwords or one time password tokens.
However, my employer uses certificates to authenticate users when connecting from the internet to certain messaging services like Outlook Web Access (OWA) or Communicator Web Access (CWA).
Since iDialog uses the CWA connector to access Office Communicator, the only way I can connect to my work with that program is to force client authentication through a proxy.
I hope that apple will implement native support for the client certificate authenticated SSL connections in a future revision of the OS, so that App vendors can get this functionality for free.
Warning: I don’t advise using this process. It is complex and could result in the compromise of your user certificate. This information is provided for reference only.
This is a complex and technical process that puts an copy of your private key on the file system of the iPhone.
Requirements:
  1. Jailbroken iPhone
  2. Client certificate in pkcs12 (export from IE or Firefox) named backup.p12
  3. Stunnel, OpenSSH, and Toggle SSH for iPhone from Cydia
  4. Change root and mobile user passwords on iPhone
Steps:
Break the client cert into two parts, cert.pem and key.pem:
# convert from the pkcs12 file to pem
# use nokeys to get just the cert
openssl pkcs12 -in backup.p12 -nodes -nokeys -out cert.pem
# use nocerts to get just the key
openssl pkcs12 -in backup.p12 -nodes -nocerts -out key.pem
Create a CA file by pulling the certificate chain from your server with openssl s_client and saving the certs to a PEM file. This must be all the certs that will verify your target server. Save this file as ca.pem.
Create an stunnel.conf file with the following settings but insert your server name in the last section at the very bottom:
; Certificate/key is needed in server mode and optional in client mode
cert = cert.pem
key = key.pem

; Protocol version (all, SSLv2, SSLv3, TLSv1)
sslVersion = SSLv3

; PID is created in a var location
pid = /var/run/stunnel.pid

; Some performance tunings
socket = l:TCP_NODELAY=1
socket = r:TCP_NODELAY=1

; Authentication stuff
verify = 3
;use a CAfile based on the certs that your server presents
CAfile = ca.pem

; Some debugging stuff useful for troubleshooting
debug = 7
output = stunnel.log
foreground = yes
; Use it for client mode
client = yes
; Service-level configuration
[https]
accept  = 80
connect = your.ssl.server.tld:443
TIMEOUTclose = 0
Copy these four files to /usr/etc/stunnel on the iPhone with scp as the root user.
Test this configuration by running stunnel from the iPhone over SSH:
/usr/bin/stunnel /usr/etc/stunnel.conf
If this all works, then create grab the stunnel.plist file from Kurt’s Weblog and modify it to launch your stunnel in /usr/bin/.
越狱后将Cydia设置为开发者身份后搜索stunnel即可找到安装.
 http://planet-iphones.com/cydia/id/stunnel
----------------------------------------------------------
  使用 TLS/SSL 加密你的 HTTP 代理

HTTP 代理是明文的,这导致实际访问的 URL 可以被他人监测到。即使使用 HTTPS 协议,经过 HTTP 代理时会发送CONNECT请求,告诉代理要连续到远程主机的指定端口。于是,访问的目标域名暴露了。

有没有办法将传输内容加密呢?比如像 HTTPS 那样,使用 TLS 协议连接到代理服务器,然后再进行 HTTP 请求。很遗憾的是,我在 ziproxy 的配置里没有发现这样的选项。在 shlug 邮件列表里询问后,Shell Xu 提到了 stunnel 这个工具。以前我试过用它把 HTTP 的网站转成 HTTPS 的,但是网站后端程序无法知晓用户实际上使用的是 HTTPS,有些郁闷,就没管它了。

这次再次请出 stunnel,在代理服务器上执行如下命令:   
sudo stunnel -d 0.0.0.0:8081 -r localhost:8080 -p /etc/stunnel/stunnel.pem

这样,所有到服务器的 8081 端口的请求,都会经过 TLS 解密后传递给 8080 端口。同时响应的数据也会被加密后再返回请求方。

接下来的问题是,浏览器无法直接使用这种代理。实际上除了拿 openssl 命令手动连接外,我不知道任何程序能够使用这种代理。那好,本地弄个反过来加密/解密的服务好了。还是使用 stunnel。不过出了点意外:客户系统Arch Linux 的 stunnel 是第四版,不再用命令行参数,转而使用配置文件了。于是参考这篇http://www.freebsddiary.org/stunnel-v3-to-v4.php,写了份 客户系统下的stunnel4 的配置文件:   
compression = lib
foreground = yes
output = /dev/stdout
client = yes
pid = /tmp/stunnel.pid
# or will output to syslog :-(
output = /tmp/stunnel.log

[name]
accept = 8082
connect = server.com:8081

这样在本地 8082 端口监听,把所有请求加密后转发到 server.com 的 8081 端口。同时响应的数据会被解密后再返回。

现在,所有与代理服务器传输的数据都被加密了,不怕被偷窥啦。

后记:

后来,我发现其实代理服务器和我本机都装了两个版本的 stunnel,只是名字中不带版本号的一个是第三版而另一个是第四版而已……

再后来,我猛然想起神器 socat——这家伙是支持 OpenSSL 的!比如客户端这边像下边这样子就可以了:   
$ socat tcp-listen:8082,fork openssl:server.com:8081,verify=0

socat 真是神器啊,cat、netcat、rinetd、stunnel 的功能都覆盖了!

这样使用的时候,每次来新请求时,socat 会 fork 一个新进程来处理。有点浪费资源。不过略微查看了下,stunnel 似乎也一样。

from http://lilydjwg.is-programmer.com/2012/10/25/secure-your-http-proxy-with-tls-ssl.36107.html
---------------------------------------------------------------
Upgrading to stunnel 4

stunnel is a great tool. It allows you to encrypt TCP connections inside SSL. And it's available for both Unix and Windows. I use it to hide various traffic, including the cvsup I run to update this website and the zone files on my DNS servers. See stunnel - another way to avoid plain text passwords and stunnel - encryption and security for my previous articles.
Recently, stunnel 4.0 came out with many new improvements. Much to the annoyance of some users, the command line paramaters changed drastically. Personally, I thought that was a good thing. Version 4 uses a configuration file, and comes with enhanced capability. I like it.
This article will compare my old command line format with the new configuration file format. Hopefull that will help you along the way.
Note that I've had success in mixing v3 and v4 of stunnel. Specifically, I've run v4 on my clients and v3 on the server. With the success there, I'm quite sure that it would work the other way around too.

man pages - make the migration easier
If you are upgrading to version 4, you probably already have that man page. But what you may not have is the version 3 man page. I found that having the old man page greatly simplified the conversion process. Just look up the old parameter, find out what it does, then look up the same option on the version 4 man page.
How did I create these html files? Like this:
nroff -man ~/tmp/stunnel-3.22/stunnel.8 | man2html -title "stunnel(8) - version 3" > stunnel-v3-man.html
man stunnel | man2html -title "stunnel(8) - version 4" > stunnel-v4-man.html
man2html is in the FreeBSD Ports tree and the home page is at http://www.oac.uci.edu/indiv/ehood/man2html.html. This assumes that I had v4 already installed and that I had extracted the tarball for v3 into the ~/tmp directory.

The startup scripts
This section compares the old and new startup scripts (/usr/local/etc/rc.d/stunnel.sh. As you can see the old script put the parameters right in the script. I prefer the new format.
Old codeNew Code
#!/bin/sh

# Where is the program
STUNNEL="/usr/local/sbin/stunnel"

case "$1" in
start)
${STUNNEL} -c -d localhost:5999 -r 192.168.0.73:6000
;;

stop)
killall `basename ${STUNNEL}` ;;

*)
echo ""
echo "Usage: basename $0 { start | stop }"
echo ""
;;
esac
#!/bin/sh
#
# A sample stunnel startup script written by martti.kuparinen@ericsson.com
#
# $FreeBSD: ports/security/stunnel/files/stunnel.sh,v 1.2 2002/09/20 09:29:11 roam Exp $
#

# Where is the program
STUNNEL="/usr/local/sbin/stunnel"

case "$1" in
    start)
        ${STUNNEL} /usr/local/etc/stunnel/stunnel.conf
        ;;

    stop)
        killall `basename ${STUNNEL}`
        ;;

    *)
        echo ""
        echo "Usage: basename $0 { start | stop }"
        echo ""
        ;;
esac

The configuration format
I will provide a one-to-one mapping for each parameter used in the above example. That should help you get started. The configuration file is /usr/local/etc/stunnel/stunnel.conf. The following is for a client.
See man stunnel for more information.
Old parametersNew Parameters
-p /usr/local/etc/stunnel.pem cert = /usr/local/etc/stunnel/stunnel.pem
-s stunnel setuid = stunnel
-g stunnel setgid = stunnel
-c client = yes
-d foreground = no default: background in daemon mode
localhost:5999 accept = 5999
-r 192.168.0.73:6000 connect = 192.168.0.73:6000

A sample client configuration file
Here is the configuration file I use on my web server in order to access my webserver. The IP address hsa been changed.
ClientServer
cert = /usr/local/etc/stunnel/stunnel.pem
chroot = /var/tmp/stunnel

# PID is created inside chroot jail
pid = /stunnel.pid

setuid = stunnel
setgid = stunnel

client = yes

[6000]
accept = 5999
connect = 192.168.0.73:6000
cert = /usr/local/etc/stunnel/stunnel.pem
chroot = /var/tmp/stunnel

# PID is created inside chroot jail
pid = /stunnel.pid

setuid = stunnel
setgid = stunnel

client = no

[5999]
accept = 6000
connect = 5999
The major differences are hightlighted in bold:
  1. The client parameter differs (well, dah....)
  2. The client accepts connections on localhost port 5999
  3. The client talks to the server at 192.168.0.73 on port 6000
  4. The server accepts connections on localhost port 6000
  5. The server directs connections on port 6000 to port 5999

One of my favourite tools
stunnel is one of my basic tools. I use it every day. And it just sits there. And runs. I've enver had to restart stunnel daemon because it has failed. It's great. And very low overhead. A great tool. If you've ever worried about getting TCP traffic from one place to another securely and secretly, then stunnel is for you.

from  http://www.freebsddiary.org/stunnel-v3-to-v4.php
------------------------------------------------------------------------
 在VPS上配置Stunnel代理

現在比較常見的加密訪問網站的途徑:
1、VPN,這個是全局的,不夠靈活。也就是你訪問新浪、網易也是走VPN,加密再從VPN服務器繞一圈,得不償失;
2、SSH tunnel,這個可以建立socks5代理,配合瀏覽器插件,有選擇的針對網址選用代理服務器,效果明顯好於VPN。但是問題在於SSH連接是一個長連接,容易受到幹擾而出現不穩定的情況。

根據今年的一些情況,可以發現上述兩種方式其實都會有一定的模式被探測到,從而容易受到幹擾而出現完全不可用的情況。

我之前一直是自己購買一個便宜的VPS,然後用SSH建立Tunnel的方式。前段時間就發現SSH連接不上了。後來聽說了“Stunnel”這個SSL加密的管道程序。特點是沒有長連接,和純粹的HTTP代理一樣,可以做到按需鏈接,從外界來看,就是HTTPS的訪問。應該要穩定一些。

最近折騰了一番,買了一個新的VPS,在博客裏整理了一下配置的過程,同時也發到這裏和大家分享。

便宜的VPS也就10美元一年,其實是非常的實惠的,不需要依賴於什麽Google的服務或者其他網上的免費資源,即穩定也快速。我訪問Youtube下載視頻,網絡通暢時速度常見有500K到1M的水平,上網高峰期也可以有300K的速度。

下文中提到了一個推薦虛擬主機和VPS的站點,我也是從那個站點上找來的優惠VPS購買信息。我和該網站無任何關系,但是站點裏的鏈接會有返利尾巴,雖然對用戶並無影響,但是在這裏提醒一下。

配置完成後,可以用 Firefox + AutoProxy 插件,或者是 Chrome + SwitchySharp 插件的方式使用。代理的地址就是 127.0.0.1:8080。

Stunnel服務端配置:Debian Linux系統

Stunnel on Debian GNU/Linux 6 (squeeze)
傳統的POP3, SMTP, Samba等服務,都是不加密的協議(即在網絡上明文傳輸數據),通過stunnel,可以將訪問這些服務的連接通過一個加密的管道進行,便於保護個人隱私。
這裏我們要搭建的目標:
服務器為Linux(Debian 6.0 squeeze),運行兩個服務:

HTTP代理服務器程序proxy.py,監聽8080端口,只接受本機請求;
Stunnel運行在服務端模式,監聽443端口。並將443端口的請求轉發到本機的proxy.py的端口8080 。
在本地機器上,Stunnel運行在客戶端模式,監聽8080端口。並將8080端口上接受到的連接,經過SSL加密後,轉發到遠程服務器的443端口。而遠程服務端Stunnel將443端口上連接解密後,投遞到proxy.py。proxy.py代理返回的響應,則也會經過SSL加密再回傳到本地機器的客戶端模式的Stunnel,客戶端Stunnel解密回應後回傳給本地程序(瀏覽器等)。

使用這個Stunnel的方式來代理訪問國外的網站的優點:
國外網站直接連接訪問,可能會有速度慢而且很不穩定的問題,所以使用代理會大大改善。通過瀏覽器插件的方式,可以根據訪問的網址來確定是否使用代理,更加靈活;
使用VPN的問題:我們大部分時間訪問的網站,比如新浪、網易、騰訊、搜狐,都是不需要代理就可以流暢高速的訪問的。如果為了穩定快速訪問國外網站而使用VPN,則會導致這些國內網站也經由VPN訪問,體驗變得極為不佳,得不償失;
采用SSH建立tunnel訪問,SSH是一個TCP長連接,也會有不穩定的問題;
Stunnel服務則是按需建立TCP連接,遠程服務端配置為監聽443端口,采取了SSL的加密方式,則本地主機和遠程服務端之間的交互和HTTPS完全類似,穩定高效。
服務器的準備
首先,你得有一個可以完全控制的Linux系統提供服務端,可以參考這裏購買一個便宜的VPS。不過購買的時候可得看清楚了,要買VPS,不是Web
Hosting服務。後者只有網頁上的控制面板,是用來給你放網站的。前者才是一個有shell訪問的獨立IP的“主機”。我和這個網站並無任何關系,裏面的鏈接可能是有返利尾巴的,但是對於用戶來說並無壞的影響。

購買VPS後,會得到一個IP地址,建議購買一個域名,然後用域名訪問你的主機,省得記IP地址了。當然我這裏的“建議”是建議你去找個便宜的地方買,而不要傻不拉幾的直接在買VPS的同時把域名也放入購物車一起付款了,那樣估計不會便宜的。域名也會有做活動的時候,而且域名也沒必要非得要和VPS在同一個地方買。說白了,就是你有一個隨便哪裏來的域名,然後把這個域名指向這裏買的VPS的IP地址,從而可以方便你訪問這個VPS而已。嫌啰嗦的話,就直接用IP地址訪問就行了……

由於這裏講的是 Debian 的配置,所以在使用之前請確保你的虛擬主機跑的是 Debian 系統。如果在註冊過程中沒有讓你選擇操作系統,那麽請在註冊、支付完成後,登陸你的帳戶,可以修改你的操作系統為 Debian 6 x86(即32位系統,如果內存夠大你也可以選擇x64系統)。註意,修改操作系統就是重裝系統,原有系統的所有數據都將丟失。當然Stunnel和proxy.py的配置,在所有的Linux應該也是大同小異。Debian系統並不是必須。開始配置
SSH登陸到你的虛擬主機。Windows下的SSH客戶端可以用PuTTY。登陸用戶名為root,密碼請登陸你的主機服務商的帳戶後查找。
首先更新下軟件包信息:


# apt-get update
然後安裝 stunnel:


# apt-get install stunnel
切換到 stunnel 配置目錄:


# cd /etc/stunnel
備份默認配置:


# cp stunnel.conf stunnel.conf.backup
修改配置:


# vi stunnel.conf
首先指定 cert 和 key:


cert = /etc/stunnel/stunnel.pem
key = /etc/stunnel/stunnel.pem
這個key文件(“stunnel.pem”)我們稍後生成。

然後註釋掉所有的默認服務,而只保留[https]這一節,不過我這裏把https裏的connect端口設置為了8443,這裏的意思就是,Stunnel會在這臺主機上監聽443端口,並將連接轉到8443端口上。所以你的主機上需要在8443端口有一個服務。而這個服務,稍後我們將安裝一個proxy.py來提供。


;[pop3s]
;accept  = 995
;connect = 110
;[imaps]
;accept  = 993
;connect = 143
;[ssmtp]
;accept  = 465
;connect = 25
[https]
accept  = 443
connect = 8443
;TIMEOUTclose = 0
其他配置方面,可以先打開詳盡的日誌記錄以方便調試:


; Some debugging stuff useful for troubleshooting
debug = 7
output = /var/log/stunnel4/stunnel.log
測試完畢後,建議將上面的 “debug = 7〃註釋掉(順便提及,註釋就是用';'開頭的行),或者修改為5以下的數值。保留在7會產生大量的日誌,日誌文件很快就會變的很大。
另外,默認配置文件是采用了chroot機制,如下所示,這段不需要修改,使用起來沒有問題:


; Some security enhancements for UNIX systems - comment them out on Win32
chroot = /var/lib/stunnel4/
setuid = stunnel4
setgid = stunnel4
; PID is created inside the chroot jail
pid = /stunnel4.pid
這就是Stunnel的配置文件,本身就是很簡單的一個配置文件,主要就是設置了一下key文件的路徑,然後指定了服務端口。
不過除此之外,還要修改一個地方:


# cd /etc/default
# vi stunnel4
這裏要設置為ENABLED=1,默認是不使能stunnel服務的:


# Change to one to enable stunnel automatic startup
ENABLED=1
生成key並啟動Stunnel服務
啟動stunnel服務之前,需要生成一組密鑰:


# cd /etc/stunnel
# openssl req -new -nodes -x509 -out stunnel.pem -keyout stunnel.pem
運行命令後,終端上會有幾個問題需要你輸入你的設定,基本沒有什麽意義,自己隨便給吧:


Generating a 1024 bit RSA private key
.......................++++++
......................++++++
writing new private key to 'stunnel.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:CN
State or Province Name (full name) [Some-State]:Shanghai
Locality Name (eg, city) []:Xxxxxx
Organization Name (eg, company) [Internet Widgits Pty Ltd]:XXX
Organizational Unit Name (eg, section) []:XXX
Common Name (eg, YOUR name) []:XXXXXXX
Email Address []:XXXXXXX@example.com
命令運行完畢,公鑰和密鑰就都在一個文件stunnel.pem裏了。這個文件是訪問服務器的證書,非常重要,切不可外傳。

最後,就是重啟/啟動stunnel服務:


# /etc/init.d/stunnel4 restart
運行結果:


Restarting SSL tunnels: [stopped: /etc/stunnel/pad.stunnel.conf] [Started: /etc/stunnel/pad.stunnel.conf] [Already running: /etc/stunnel/stunnel.conf] stunnel.
如果啟動服務失敗,則去這裏看看日誌吧:
/var/log/stunnel4/stunnel.log。

接下來是proxy.py的安裝了:
https://briteming.blogspot.com/2015/11/proxypy-pythonhttp.html

如此這般,服務端的配置就算是結束了。通過在這個服務器上運行了stunnel和proxy.py服務,我們建立了這樣一個流程:
某個客戶端,通過stunnel連接到了我們的服務器的443端口,這裏的連接是用SSL加密的,客戶端和服務端必須用同一個我們在服務器配置過程中生成的stunnel.pem證書文件,因此這個連接是加密的,可以保護用戶的隱私不被攻擊者窺探。

 此時在服務端,Stunnel收到外界連接到443端口的連接請求,會將收到的數據解密為明文數據,然後投遞到服務器上的8443端口上。而服務器上的proxy.py服務正好監聽在了8443端口上,proxy.py接收到的HTTP請求是明文的,於是就這樣透明的將HTTP請求傳達到它的目的地,並接收到目的地HTTP服務器的回應,回傳給請求來源,這裏就是stunnel服務。stunnel收到回應後,再次加密,回傳給發起請求的源頭,也就是客戶端。客戶端的stunnel程序則相應地解密收到的回應給對應的客戶端程序(一般是瀏覽器)。加密的通道對於最兩頭的客戶端和服務端,就是一個透明的管道。

所以僅僅配置了這裏的服務端還不行,你必須還得在你的客戶端主機上運行一個客戶端模式的Stunnel,然後才可以實現加密代理訪問。請到本文開頭查看Linux或者Windows平臺下Stunnel客戶端的配置。

Stunnel客戶端模式在Debian Linux上的配置

`Stunnel’客戶端配置:Linux: Debian 6.0 (squeeze)
Linux的客戶端配置相比較服務端的配置要簡單不少。首先是和服務端相同的開始部分:安裝Stunnel:


# apt-get install stunnel
先修改/etc/default/stunnel,將”ENABLED”設置為1:

CODE:[Copy to clipboard]

# vi /etc/default/stunnel4
ENABLED=1
接下來的配置則是Linux平臺上客戶端和服務端有所不同的地方了。

證書文件stunnel.pem要直接從服務器上拷出來,而不是另外生成。請使用scp命令來(安全地)傳輸你的證書。例如,你的服務器是12.34.56.78,那麽在你的本地Linux系統裏,輸入命令:


# scp root@12.34.56.78:/etc/stunnel/stunnel.pem /etc/stunnel/stunnel.pem
命令運行後,會提示你輸入密碼,就是遠程服務器root登陸SSH時的密碼。然後修改配置文件/etc/stunnel/stunnel.conf,指定你的證書文件:


cert = /etc/stunnel/stunnel.pem
key = /etc/stunnel/stunnel.pem
也就是去掉行首的 ‘;’ 的註釋符,然後跟上證書文件的路徑。用相對路徑或許也可以,讀者可以自行測試。

在初次配置的時候,可以將調試日誌的輸出級別提到最高的7,可以看到更多的調試信息:


; Some debugging stuff useful for troubleshooting
debug = 7
output = /var/log/stunnel4/stunnel.log
“output”指定的是日誌文件路徑,如果遇到問題,可以打開這個日誌查看。
緊接著是一個關鍵的參數,就是設置Stunnel為客戶端模式:

CODE:[Copy to clipboard]

; Use it for client mode
client = yes
接著修改運行的服務,將默認的幾個服務全部註釋掉,也就是在行首添加 ‘;’:

CODE:[Copy to clipboard]

;[pop3s]
;accept  = 995
;connect = 110

;[imaps]
;accept  = 993
;connect = 143

;[ssmtp]
;accept  = 465
;connect = 25
然後添加我們需要的HTTP代理服務:


[https]
accept  = 8080
connect = 12.34.56.78:443
;TIMEOUTclose = 0
上述內容即添加了一個https服務,該服務監聽本地系統的8080端口,將會加密連接到8080端口的連接,然後轉到遠程服務器12.34.56.78上的443端口,也就是我們在遠程Linux服務器上配置的Stunnel監聽端口。

最後,重啟Stunnel服務:


# /etc/init.d/stunnel4 restart
這樣,在GNU/Linux上的Stunnel就以客戶端模式運行了。順便提及,文中的命令都是用root用戶執行的,如果你習慣於用普通用戶登錄你的客戶端Linux系統,那麽執行命令的時候要添加“sudo”,例如,要重啟客戶端機器上的Stunnel服務:


$ sudo /etc/init.d/stunnel4 restart

Stunnel客戶端模式在Windows上的配置

Windows系統Stunnel客戶端的配置
Stunnel官方就有Windows版本,到下面的地址下載:
https://www.stunnel.org/downloads.html
選擇”stunnel-X.XX-installer.exe“並且安裝到一個“可寫”的位置,因為Windows Vista/7/8系統裏如果安裝到C:\Program Files或者C:\Program Files (x86),會無法寫入配置、日誌或者不方便放置用戶的證書,因此本著偷懶和“綠化”的原則,建議安裝到其他地方。其實你也可以安裝了以後,把整個程序目錄復制出來,然後將原始安裝卸載。Stunnel就成了一個綠色程序。

這裏假設新建一個目錄:C:\local,然後把Stunnel軟件安裝到這裏:
C:\local\stunnel

然後,去你的Linux服務器上獲取證書文件:/etc/stunnel/stunnel.pem。傳輸的方法建議是用SCP的方式。Windows上免費的PuTTY系列工具裏有一個PSCP程序,就可以用來安全地傳輸文件。

下載“putty.zip”工具包:http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html(開頭幾個是單獨文件下載,這裏直接下載整個ZIP包,就是標示了“A .ZIP file containing all the binaries (except PuTTYtel), and also the help files”的地方)。

同理解壓縮到C:\usr\local\putty。打開一個命令行窗口,CD到該目錄。


C:\usr\local\putty> pscp root@12.34.56.78:/etc/stunnel/stunnel.pem .
如果你的SSH服務器端口不是默認的22端口,那麽用-P PORT來指定端口(P是大寫):

CODE:[Copy to clipboard]

C:\usr\local\putty> pscp -P 12345 root@12.34.56.78:/etc/stunnel/stunnel.pem .
命令運行後,一般是會要求你確認服務器的指紋是否正確,按“y”回車確認。然後會提示輸入密碼。密碼輸入以後就會把文件拷貝到當前目錄下。

如果你配置了SSH服務器不接受密碼登陸,而只能用密鑰登陸,那麽你要先把你的SSH密鑰通過PuTTY提供的PUTTYGEN.exe程序導入,然後導出為.ppk格式,接著運行PAGENT.exe,加載這個導出的PuTTY私有格式的密鑰。這時運行上述的PSCP命令即可,不需要輸入密碼。

扯了半天傳輸證書的問題,下面就是配置Stunnel了。配置文件是C:\usr\local\stunnel\stunnel.conf:

一上來我們先配置一下調試日誌的選項:

CODE:[Copy to clipboard]

; Debugging stuff (may useful for troubleshooting)
debug = 7
output = .\stunnel.log
同理,初次使用建議debug level設置為7,調試正常後,可以修改為默認的5或更小的數字。“output”指定的日誌文件設定為“.\stunnel.log”。意思就是在軟件安裝目錄(和stunnel.exe在同一個位置)。

接下來指定證書文件。就是前面從Linux服務器上傳輸過來的”stunnel.pem”文件,將這個文件也放在Stunnel安裝目錄下,然後配置文件裏這樣寫:


; Certificate/key is needed in server mode and optional in client mode
cert = .\stunnel.pem
key = .\stunnel.pem
請註意這裏也是用了相對路徑。這個證書文件就是客戶端Stunnel和服務端Stunnel互相驗證的“密碼”,請務必妥善保存。只有有這個證書的雙方才可以通過SSL加密通信,第三方將無法看到任何信息。

最後是配置服務項:


; Example SSL front-end to a web server
[https]
client = yes
accept  = 8080
connect = 12.34.56.78:443
; "TIMEOUTclose = 0" is a workaround for a design flaw in Microsoft SSL
; Microsoft implementations do not use SSL close-notify alert and thus
; they are vulnerable to truncation attacks
; TIMEOUTclose = 0
TIMEOUTclose = 0
這裏假設你的服務器端IP地址是12.34.56.78,服務端Stunnel監聽端口為443。而Windows上客戶端監聽端口為8080,也就是其他程序可以看到你的本地機器上有一個監聽在8080端口的HTTP代理服務器。同時註意要指定“client = yes”來打開Stunnel的客戶端模式。

同時遵照註釋裏的說明,在Windows平臺我們將“TIMEOUTclose”設置為0。

至於其他的服務,則全部用行首添加’;'的方式註釋掉,或者直接刪除即可:

CODE:[Copy to clipboard]

; Example SSL server mode services

;[pop3s]
;accept  = 995
;connect = 110

;[imaps]
;accept  = 993
;connect = 143

;[ssmtp]
;accept  = 465
;connect = 25

; Example SSL client mode services

;[gmail-pop3]
;client = yes
;accept = 127.0.0.1:110
;connect = pop.gmail.com:995

;[gmail-imap]
;client = yes
;accept = 127.0.0.1:143
;connect = imap.gmail.com:993

;[gmail-smtp]
;client = yes
;accept = 127.0.0.1:25
;connect = smtp.gmail.com:465
保存配置文件後。雙擊安裝目錄裏的stunnel.exe就開始運行了,如果一切正常,雙擊運行後不會有窗口出現,而是在系統托盤欄出現一個stunnel的圖標。右鍵點擊這個圖標可以查看程序日誌、重啟服務、退出等操作。如果出現錯誤,可以查看日誌文件排查問題。測試正常後,就可以配置Windows啟動後自動運行“C:\usr\local\stunnel\stunnel.exe”,這樣就不用去管它了。

最後就是在你的瀏覽器裏配置使用這個代理即可,即代理地址為:127.0.0.1:8080
------------------------
Ubuntu桌面下,设置Stunnel客户端

Stunnel是个好东西,用来加密http浏览(其它协议也行),提高安全性,详细介绍自行Google去。这个软件能在Windows和Linux运行,不过我只需要弄个客户端,偶尔用用,不用这么折腾。

步骤如下
    Ubunutu软件库了已经有这个东西了,不需要编译源码。
    sudo apt-get install stunnel4
    Stunnel可以用配置文件设置或者在命令行设置,这里简单用一下,就用命令行好了。Stunnel可以作服务端(默认)和客户端,我这里只做客户端,则加上“-c”参数。不加则运行为服务端,提示某个文件没权限。
    接着要有一个支持服务器,一般就是支持SSL加密的,用443为端口号的。怎么找自己解决,Google也好,代理搜索验证也好,随便,假如我有一个为“123.456.789.123:443”的服务器,那么就在终端运行:

    sudo stunnel -c -d 127.0.0.1:8999 -r 123.456.789.123:443

    “-d“后是本机端口,随便一个未使用的(Linux要求是1024以上),“-r”后是服务器的ip地址。
    搞定好就在Firefox或者其它工具代理出弄成“127.0.0.1:8999”就行了,所发数据将加密发出到服务器里解密转发到真正目的地。
---------
https://staugur.gitbooks.io/saintic/content/blog/28.html
http://govfate.iteye.com/blog/2092581 (这个有点复杂)
--------------------------



 stunnel是一個老牌加密ssl wrapper,它能把客戶與服務器端的通訊加密,proxy.py是一個輕量級的http代理,它也支援CONNECT的方式,能夠處理https的連線,而且使用的資源很少,服務器啟動只使用2M左右的記憶體,而且速度飛快 以下為部署過程,安裝在最為低階的NAT IPv4 share VPS,128M/128M vSwap OpenVZ虛擬方案,系統是Ubuntu 14.04 LTS 32bit 
1) 登錄vps,以root執行apt-get update -y && apt-get upgrade -y , 確保系統軟件為最新版本 
2) 安装proxy.py:https://briteming.blogspot.com/2015/11/proxypy-pythonhttp.html

接下來安裝stunnel4和配置協同工作 
安裝stunnel4的流程如下 
1) 執行 apt-get install stunnel4 
2) 生成私鑰,執行openssl genrsa -out privatekey.pem 2048 
3) 生成公鑰,執行openssl req -new -x509 -key privatekey.pem -out publickey.pem -days 3650     它會詢問一些資料如地區,那些亂填就好,到第四項組織和CN(Common Name)填入      vps公網IPv4 ,電郵地址直接enter鍵,自簽名證書已製作好 
4) 合併證書,cat privatekey.pem publickey.pem >> /etc/stunnel/stunnel.pem 
5) 新建一個配置文件,/etc/stunnel/stunnel.conf ,內容如下 
client = no 
debug = 7 
output = /var/log/stunnel4/stunnel.log 
[proxy.py] 
accept = 16920 
connect = 127.0.0.1:8888 
cert = /etc/stunnel/stunnel.pem 

其中accept = 16920 是stunnel4對外監聽連接端口,改成你喜歡的,而 connect = 127.0.0.1:8888 必須和proxy.py監聽的本地端口一致 其它的設定如降低權限,請參考 http://www.arda.homeunix.net/stunnel-setup/ 
6) 編輯/etc/default/stunnel4 ;把 ENABLED=0 改為 1,儲存離開 
7) 執行service stunnel4 restart 
再下來配置客戶端,以Chromium為例 
1) 執行cat publickey.pem > publickey.crt 
2) 把publickey.crt複製到本地電腦,以linux可以 scp -P vps_ssh_port root@vps_ip:~/publickey.crt . 
3) 打開設定->顯示進階設定->管理憑證->選"授權單位"->按"滙入"->把publickey.crt導入即可 
4) 下載SwitchyOmega,新建一個情景模式,選代理協議為HTTPS,代理伺服器填入vps的IPv4,      代理埠填入stunnel4的監聽端口,儲存完成 
5) 切換到代理模式,打開 http://whatismyproxy.com 看看是否IP變了 雜項 如要分流,請參考 https://github.com/FelisCatus/SwitchyOmega/wiki/GFWList , iOS的Surge的設置自行google 如果出現問題,可以在/var/log/找到相關訊息,或者執行netstat -nlp看看是否服務器都在監聽中 :)
------------------------------------------------------------------

stunnel一鍵腳本

在第一個網誌寫了安裝stunnel + proxy.py的流程,竟然有數百網友圍觀,出乎意料,
於是有了動力,決定編寫一鍵安裝腳本,方便需要的網友,也正好自己更換/新購vps
不用每次重複勞動,一舉两得 :) 代碼如下

[code]
#! /bin/bash
# author: twfcc@twitter
# $PROG: install_sslproxy.sh
# $Usage: $0 -s|--standard -n|--nat
# description: install stunnel  on NAT IPv4 Share VPS(OpenVZ) or Standard VPS(OpenVZ)
# Public Domain use as your own risk!

Usage="$0 -s|--standard -n|--nat"
msg1="-s or --standard install https proxy on standard openvz vps."
msg2="-n or --nat install https proxy on nat ipv4 share openvz vps"
argu=$1

# Are you root?

if [ $UID -ne 0 ] ; then
    echo "You must be root to execute this script." >&2
    exit 5
fi

# Check argument

case "$argu" in
     -s|--standard) flag=0 ;;
          -n|--nat) flag=1 ;;
                 *) printf "\n$Usage\n$msg1\n$msg2\n\n" >& 2
                    exit 6
                    ;;
esac

# First, we need to install some component and update OS
apt-get update && apt-get upgrade -y
apt-get install build-essential -y
if ! which openssl &> /dev/null ; then
     apt-get install openssl -y
fi
if ! which curl &> /dev/null ; then
    apt-get install curl -y
fi

# get vps public IPv4
myip=$(curl -s v4.ifconfig.co)

# what is the type of this vps?

if [ $flag -ne 0 ] ; then
     internal_ip=$(ifconfig venet0:0 \
                  | awk -F: '$2 ~ /[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/{print $2}' \
                  | cut -d" " -f1)
     port=$(echo -e ${internal_ip##*.})20 #nat-vps we use the last fixed port
else
     pick=($(for i in {19901..19999} ;do echo $i ;done)) #ports from 19901-19999
     count=${#pick[@]} #how many ports
     port=${pick[$((RANDOM%count-1))]} #pick a random port
fi

# install stunnel 
apt-get install stunnel -y

# setup stunnel ; generate self-signed certificate first
openssl genrsa -out privatekey.pem 2048
openssl req -new -x509 -key privatekey.pem -subj \
"/C=CN/ST=MyTunnel/L=Mytunnel/O=$myip/CN=$myip" \
-out publickey.pem -days 1095

#copy both pem together and make a crt for browser

if [ -e privatekey.pem ] && [ -e publickey.pem ] ; then
   cat privatekey.pem publickey.pem > /etc/stunnel/stunnel.pem
   cat publickey.pem > publickey.crt
fi

# we create stunnel.conf

nano stunnel.conf
client = no
debug = 7
output = /var/log/stunnel4/stunnel.log
[proxy.py]
accept = $port
connect = 127.0.0.1:8888
cert = /etc/stunnel/stunnel.pem

mv -f stunnel.conf /etc/stunnel/

# set stunnel as a deamon

cp -f /etc/default/stunnel4 /etc/default/stunnel4.bak
sed -i 's/^ENABLED=0$/ENABLED=1/' /etc/default/stunnel4
service stunnel4 restart
netstat -nlp | grep -i 'stunnel4' &> /dev/null
then
   printf "HTTPS/SSL Proxy is running.\nCopy publickey.crt to browser.\n"
   printf "\nYour IPv4:${myip}\n Port:${port}\nEnjoy!\n"
else
   printf "Failed to install HTTPS/SSL proxy.\n" >&2
   exit 1
fi
exit 0
[/code]

已在nat ipv4 share vps的debian 7/8 x86_64,ubuntu 14.04 x86,普通的vps
ubunbu 1404 x86,debian 8 x86_64成功通過測試,失敗的只有ubuntu 15.05,
這腳本會在nat-vps會選用供應商分配給你的20個端口最後一個:XXX20,前面的三
個數字是你的內網ip最後一組數字,腳本會自動找到,標準vps它會在19901-19999
之間隨機選一個端口,這避免太多人使用腳本安裝變成固定端口(其實沒幾人用,多餘
的做法),安裝前兼查一下該端口/該一段端口有否被佔用中,不然會錯誤

https://github.com/twfcc/sslproxy_installer
https://github.com/twfcc/sslproxy_installer/raw/master/stiny.sh (适合于debian/ubuntu系统)
运行./stiny.sh -s后,(如果是nat vps, 则运行./stiny.sh -n)
显示:
Restarting SSL tunnels: [Started: /etc/stunnel/stunnel.conf] stunnel.
HTTPS/SSL Proxy is running.
Copy publickey.crt and import to browser.

Public IP: my-vps-ip
Port: 29965

Enjoy.
root@ary:~# ps aux|grep stunnel4
root     11033  0.0  0.2  21460   644 pts/5    S    22:43   0:00 /usr/bin/stunnel4 /etc/stunnel/stunnel.conf
root     11034  0.0  0.2  21460   644 pts/5    S    22:43   0:00 /usr/bin/stunnel4 /etc/stunnel/stunnel.conf
root     11035  0.0  0.2  21460   644 pts/5    S    22:43   0:00 /usr/bin/stunnel4 /etc/stunnel/stunnel.conf
root     11036  0.0  0.2  21460   644 pts/5    S    22:43   0:00 /usr/bin/stunnel4 /etc/stunnel/stunnel.conf
root     11037  0.0  0.2  21460   644 pts/5    S    22:43   0:00 /usr/bin/stunnel4 /etc/stunnel/stunnel.conf
root     11038  0.0  0.3  21460   960 ?        Ss   22:43   0:00 /usr/bin/stunnel4 /etc/stunnel/stunnel.conf
root     11050  0.0  0.3   8828   780 pts/5    S+   22:45   0:00 grep --color=auto stunnel
root@ary:~# lsof -i:29965
COMMAND    PID USER   FD   TYPE     DEVICE SIZE/OFF NODE NAME
stunnel4 11038 root   12u  IPv4 3884311753      0t0  TCP *:29965 (LISTEN)
root@ary:~#
可见stunnel4在运行中。这个脚本stiny.sh很好用。
--------------------

简单搭建https proxy服务器

比较简单的方案:轻量级的http代理服务器程序proxy.py + stunnel 

1、安装proxy.py 和 stunnel

首先使用各个 Linux 发行版的包管理器安装stunnel,比如:
$ sudo yum install stunnel // 对于 centos linux
 
$ sudo pacman -S stunnel // 对于 arch linux

安装完成后顺便设置它们随开机启动(可选)。

2、设置 stunnel

把你证书私钥和购买的证书扔到 /etc/stunnel 里,然后编辑文件 stunnel.conf,先指定私钥和证书文件名:
cert = /etc/stunnel/mycert.pem
key = /etc/stunnel/mykey.pem
需要注意的是从证书服务商购买回来的证书通常是几个小文件,大概有是:一个你的域名证书,一个证书链证书,一个root证书。把它们用文本编辑器打开,然后按照上述的顺序复制粘贴成一个文件,这个文件就是上面 ”cert=“ 这行所需的文件。
然后指定端口转换,比如将端口 443 (https 的默认端口)绑定并转发到proxy.py 的监听端口 8888:
[https]
accept = 443
connect = 127.0.0.1:8888
其中 https 这个一项绑定的名称,可以随便起,accept 表示本机监听的端口,connect 表示转换到哪里。完整的意思就是为 127.0.0.1:8888 添加 SSL 加密层,然后通过 443 端口对外服务。

3、客户端设置

目前默认支持 https/spdy 代理的只有 google chrome 浏览器(其他浏览器需要在客户端运行 stunnel 把 https 翻译为 http 才能使用)。而且很诡异的是 chrome 没有自己独立设置 proxy 的地方,使用系统全局的那个 https 设置是不行的(因为系统那个 https 代理指的是当你访问 https 的网站时所走的 http 代理通道,跟我们这篇说的 https proxy 是两码事),所以你还得在 chrome 浏览器里安装插件  TunnelSwitch,然后在这个插件里设置 https 代理为:“你的网站域名:443”,这样所有工作都完成可以直接上网了。

4、一个给爱折腾的人的省钱方案

如果想节省购买 SSL 证书的花费,那么自己生成一个“自签名”的证书也是可以的,不过如果你的 proxy 想共享给其他人使用的话,要慎重考虑这种方式,因为它会让不爱折腾的人觉得很折腾。
用下面命令即可生成一个自签名证书:
openssl genrsa -out key.pem 1024
openssl req -new -key key.pem -subj "/CN=localhost" -out req.pem
openssl x509 -req -days 365 -in req.pem -signkey key.pem -out cert.pem
注意要将上面的 localhost 更改为你的域名,最终有用的分别是私钥文件 key.pem 和证书文件 cert.pem,把这两个文件替换上面第二步所提到的位置即可。
然后在客户端需要导入这个 cert.pem 才能顺利使用你所搭建的 https proxy 服务。各个操作系统的导入证书方法都不太相同。
  • 在 linux 里比较麻烦,需要用 libnss3 工具 certutil 来完成,命令如下:
$ certutil -d "sql:$HOME/.pki/nssdb" -A -n dummy -i cert.pem -t C
  • 在 mac osx 里使用 keychain 工具,把证书拖进”证书“一栏里。
  • 在 windows 里双击证书文件,在选择“导入到位置”那一步选择”根信任“。
然后重启你的 chrome浏览器,就可以了.
-------------------

使用stunnel+proxy.py搭建HTTPS代理服务器

 如果直接使用HTTP代理服务器程序proxy.py是明文传输的,在第一次使用时,会马上“出现技术问题”,因此需要使用stunnel对代理通道进行加密。具体配置步骤如下,Linux发行版是Ubuntu,如果你使用的是其他发行版,包管理与配置文件路径会略有不同。

安装必要的软件

安装apache2-utils用于HTTP认证文件的生成,
apt-get install apache2-utils -y
安装proxy.py:
https://briteming.blogspot.com/2015/11/proxypy-pythonhttp.html
安装stunnel:
apt-get install stunnel4 -y
生成HTTP认证文件,输入对应的密码。这个认证文件用于之后HTTP代理的认证登录,如果不需要登录认证,可以略过。

配置stunnel

接下来,我们需要在proxy.py上添加一层加密。

生成公钥和私钥

生成私钥(privatekey.pem):
openssl genrsa -out privatekey.pem 2048
生成公钥(publickey.pem):
openssl req -new -x509 -key privatekey.pem -out publickey.pem -days 1095
(需要注意的是,Common Name需要与服务器的IP或者主机名一致)
合并:
cat privatekey.pem publickey.pem >> /etc/stunnel/stunnel.pem

修改stunnel配置

新建一个配置文件/etc/stunnel/stunnel.conf,输入如下内容
client = no
[proxy.py]
accept = 4128
connect = 127.0.0.1:3128
cert = /etc/stunnel/stunnel.pem
配置中指定了stunnel所暴露的HTTPS代理端口为4128,可以修改为其他的值。
修改/etc/default/stunnel4配置文件中ENABLED值为1。
ENABLED=1

重启stunnel

service stunnel4 restart
至此,服务器端已配置完成了。

本地浏览器配置

添加证书到受信任的根证书颁发机构列表中

以Windows下Chrome浏览器为例,将服务器上的公钥publickey.pem下载至本地,重命名至publickey.crt,在Chrome中依次点击 “设置” - “显示高级设置” - “HTTP/SSL” - “管理证书”,在“受信任的根证书颁发机构”选项卡中“导入”这个crt证书就完成了。

代理客户端配置

将本地的代理客户端指向https://<你的服务器IP或主机名>:4128,这里的IP或主机名和生成公钥时的Common Name一致,端口为stunnel的端口。如果有配置HTTP认证的话,需要在客户端中配置对应的用户名和密码。如果没有HTTP客户端的话,推荐使用Chrome的插件Proxy SwitchyOmega(使用教程可以参考Github上的Wiki)。
---------------------------
这里介绍一下如何自己搭建一套 SSL Proxy 的方案。

Server(stunnel +proxy.py)

参考 Digital Ocean 这篇文章。给 OpenSSL 打上 CloudFare 这份补丁用以支持 ChaCha,对于移动设备性能更好,事实上,x86 的性能也有显著提升。
openssl $ ./config --prefix=/opt/openssl --openssldir=/opt/openssl no-shared -fPIC && make && [sudo] make install
然后用这个 OpenSSL 编译 stunnel 即可。
stunnel $ ./configure --with-ssl=/opt/openssl && make

Client(haproxy)

haproxy 在 1.5 已经完整支持了 SSL Proxy,所以客户端不再需要运行 stunnel 的 client 模式,同样用打了 ChaCha 补丁的 OpenSSL 编译 haproxy。
make TARGET=linux2628 USE_OPENSSL=1 ADDLIB=”-L/opt/openssl/lib -ldl” ADDINC=-I/opt/openssl/include USE_TFO=1

安全

Server 端开启强校验,自己生成根证书,客户端生成密钥用根证书签名后下发,并用 fail2ban 来防止错误碰撞

性能调优

主要参考 Shadowsocks 的优化,线路稳定的话还可以用一些 CDN 上用的 TCP 优化来提高吞吐率和初始化速度。
可以不缓存,节省内存,还可以减少由于磁盘速度跟不上网络的窘境。
另外因为 stunnel 是流量透传,proxy.py实际请求的时候还是需要重新请求DNS 的,在 Server 端做 DNS 缓存可以有效提速。
----------------

Using stunnel and proxy.py to encrypt HTTP traffic


Recently there has been a lot of coverage in both tech and non-tech news outlets about internet privacy and how to prevent snooping both from service providers and governments. In this article I am going to show one method of anonymizing internet traffic; using a TLS enabled HTTP/HTTPS Proxy.
In this article we will walk through using stunnel to create a TLS tunnel with an instance of Proxy.py on the other side.

How does this help anonymize internet traffic

Proxy.py is an HTTP proxy server. By setting up a Proxy.py instance on a remote server and configuring our HTTP client to use this proxy. We can route all of our HTTP & HTTPS traffic through that remote server. This is a useful technique for getting around network restrictions that might be imposed by ISP’s or Governments.
However, it’s not enough to simply route HTTP/HTTPS traffic to a remote server. This in itself does not add any additional protection to the traffic. In fact, with an out of the box Proxy.py setup, all of the HTTP traffic to Proxy.py would still be unencrypted, leaving it open to packet capture and inspection. This is where stunnel comes into play.
I’ve featured it in earlier articles but for those who are new to stunnel, stunnel is a proxy that allows you to create a TLS tunnel between two or more systems. In this article we will use stunnel to create a TLS tunnel between the HTTP client system and Proxy.py
By using a TLS tunnel between the HTTP client and Proxy.py . our HTTP traffic will be encrypted between the local system and the proxy server. This means anyone trying to inspect HTTP traffic will be unable to see the contents of our HTTP traffic.
This technique is also useful for reducing the chances of a man-in-the-middle attack to HTTPS sites.
I say reducing because one of the caveats of this article is, while routing our HTTP & HTTPS traffic through a TLS tunneled HTTP proxy will help obfuscate and anonymize our traffic. The system running Proxy.py is still susceptible to man-in-the-middle attacks and HTTP traffic snooping.
Essentially, with this article, we are not focused on solving the problem of unencrypted traffic, we are simply moving our problem to a network where no one is looking. This is essentially the same approach as VPN service providers, the advantage of running your own proxy is that you control the proxy.
Now that we understand the end goal, let’s go ahead and get started with the installation of Proxy.py

Installing Proxy.py,pls check:

https://briteming.blogspot.com/2015/11/proxypy-pythonhttp.html
After systemctl completes, we can validate that our change is in place by checking whether port 8888 is bound correctly using the netstat command.
server: $ netstat -na
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 127.0.0.1:8888          0.0.0.0:*               LISTEN
With that done, let’s go ahead and setup stunnel.

Installing stunnel

the installation of stunnel is as easy as executing the apt-get command.
server: $ sudo apt-get install stunnel
Once apt-get has finished we will need to enable stunnel by editing the /etc/default/stunnel4 configuration file.
Find:
# Change to one to enable stunnel automatic startup
ENABLED=0
Replace:
# Change to one to enable stunnel automatic startup
ENABLED=1
By default on Ubuntu, stunnel is installed in a disabled mode. By changing the ENABLED flag from 0 to 1 within /etc/default/stunnel4, we are enabling stunnel to start automatically. However, our configuration of stunnel does not stop there.
Our next step with stunnel, will involve defining our TLS tunnel.

TLS Tunnel Configuration (Server)

By default stunnel will look in /etc/stunnel for any files that end in .conf. In order to configure our TLS stunnel we will be creating a file named /etc/stunnel/stunnel.conf. Once created, we will insert the following content.
[proxy.py]
accept = 0.0.0.0:3128
connect = 127.0.0.1:8888
cert = /etc/ssl/cert.pem
key = /etc/ssl/key.pem
The contents of this configuration file are fairly straight forward, but let’s go ahead and break down what each of these items mean. We will start with the accept option.
The accept option is similar to the listen option from Proxy.py  . This setting will define what interface and port stunnel will listen to for incoming connections. By setting this to 0.0.0.0:3128 we are defining that stunnel should listen on all interfaces on port 3128.
The connect option is used to tell stunnel what IP and port to connect to. In our case this needs to be the IP and port that Proxy.py is listening on; 127.0.0.1:8888.
An easy way to remember how accept and connect should be configured is that accept is where incoming connections should come from, and connect is where they should go to.
Our next two configuration options are closely related, cert & key. The cert option is used to define the location of an SSL certificate that will be used to establish our TLS session. The key option is used to define the location of the key used to create the SSL certificate.
We will set these to be located in /etc/ssl and in the next step, we will go ahead and create both the key and certificate.

Creating a self-signed certificate

The first step in creating a self-signed certificate is to create an private key. To do this we will use the following openssl command.
server: $ sudo openssl genrsa -out /etc/ssl/key.pem 4096
The above will create a 4096 bit RSA key. From this key, we will create a public certificate using another openssl command. During the execution of this command there will be a series of questions. These questions are used to populate the key with organization information. Since we will be using this for our own purposes we will not worry too much about the answers to these questions.
server: $ sudo openssl req -new -x509 -key /etc/ssl/key.pem -out /etc/ssl/cert.pem -days 1826
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:Arizona
Locality Name (eg, city) []:Phoenix
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Example.com
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:proxy.example.com
Email Address []:proxy@example.com
Once the questions have been answered the openssl command will create our certificate file.
After both the certificate and key have been created, we will need to restart stunnel in order for our changes to take effect.
server: $ sudo systemctl restart stunnel4
At this point we have finished configuring the proxy server. We now need to setup our client.

Setting up stunnel (client)

Like the proxy server, our first step in setting up stunnel on our client is installing it with the apt-get command.
client: $ sudo apt-get install stunnel
We will also once again need to enabling stunnel within the /etc/default/stunnel4 configuration file.
Find:
# Change to one to enable stunnel automatic startup
ENABLED=0
Replace:
# Change to one to enable stunnel automatic startup
ENABLED=1
After enabling stunnel we will need to restart the service with the systemctl command.
client: $ sudo systemctl restart stunnel4
From here we can move on to configuring the stunnel client.

TLS Tunnel Configuration (Client)

The configuration of stunnel in “client-mode” is a little different than the “server-mode” configuration we set earlier. Let’s go ahead and add our client configuration into the /etc/stunnel/stunnel.conf file.
client = yes

[proxy.py]
accept = 127.0.0.1:3128
connect = 192.168.33.10:3128
verify = 4
CAFile = /etc/ssl/cert.pem
As we did before, let’s break down the configuration options shown above.
The first option is client, this option is simple, as it defines whether stunnel should be operating in a client or server mode. By setting this to yes, we are defining that we would like to use client mode.
We covered accept and connect before and if we go back to our description above we can see that stunnel will accept connections on 127.0.0.1:3128 and then tunnel them to 192.168.33.10:3128, which is the IP and port that our stunnel proxy server is listening on.
The verify option is used to define what level of certificate validation should be performed. The option of 4 will cause stunnel to verify the remote certificate with a local certificate defined with the CAFile option. In the above example, I copied the /etc/ssl/cert.pem we generated on the server to the client and set this as the CAFile.
These last two options are important, without setting verify and CAFile stunnel will open an TLS connection without necessarily checking the validity of the certificate. By setting verify to 4 and CAFile to the same cert.pem we generated earlier, we are giving stunnel a way to validate the identity of our proxy server. This will prevent our client from being hit with a man-in-the-middle attack.
Once again, let’s restart stunnel to make our configurations take effect.
client: $ sudo systemctl restart stunnel4
With our configurations complete, let’s go ahead and test our proxy.

Testing our TLS-tunneled HTTP Proxy

In order to test our proxy settings we will use the curl command. While we are using a command line web client in this article, it is possible to use this same type of configuration with GUI based browsers such as Chrome or Firefox.
Before testing however, I will need to set the http_proxy and https_proxy environmental variables. These will tell curl to leverage our proxy server.
client: $ export http_proxy="http://localhost:3128"
client: $ export https_proxy="https://localhost:3128"
With our proxy server settings in place, let’s go ahead and execute our curl command.
client: $ curl -v https://google.com
* Rebuilt URL to: https://google.com/
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3128 (#0)
* Establish HTTP proxy tunnel to google.com:443
> CONNECT google.com:443 HTTP/1.1
> Host: google.com:443
> User-Agent: curl/7.47.0
> Proxy-Connection: Keep-Alive
>
< HTTP/1.0 200 Connection established
< Proxy-agent: proxy.py
<
* Proxy replied OK to CONNECT request
* found 173 certificates in /etc/ssl/certs/ca-certificates.crt
* found 692 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ECDHE_ECDSA_AES_128_GCM_SHA256
*   server certificate verification OK
*   server certificate status verification SKIPPED
*   common name: *.google.com (matched)
*   server certificate expiration date OK
*   server certificate activation date OK
*   certificate public key: EC
*   certificate version: #3
*   subject: C=US,ST=California,L=Mountain View,O=Google Inc,CN=*.google.com
*   start date: Wed, 05 Apr 2017 17:47:49 GMT
*   expire date: Wed, 28 Jun 2017 16:57:00 GMT
*   issuer: C=US,O=Google Inc,CN=Google Internet Authority G2
*   compression: NULL
* ALPN, server accepted to use http/1.1
> GET / HTTP/1.1
> Host: google.com
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Location: https://www.google.com/
< Content-Type: text/html; charset=UTF-8
< Date: Fri, 14 Apr 2017 22:37:01 GMT
< Expires: Sun, 14 May 2017 22:37:01 GMT
< Cache-Control: public, max-age=2592000
< Server: gws
< Content-Length: 220
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN
< Alt-Svc: quic=":443"; ma=2592000; v="37,36,35"
<

301 Moved

301 Moved

The document has moved here. * Connection #0 to host localhost left intact
From the above output we can see that our connection was routed through Proxy.py:
< Proxy-agent: proxy.py/1.8.3
And we were able to connect to Google.

301 Moved

301 Moved

The document has moved here.
Given these results, it seems we have a working TLS based HTTP/HTTPS proxy. Since this proxy is exposed on the internet what would happen if this proxy was found by someone simply scanning subnets for nefarious purposes.

Securing our tunnel further with PreShared Keys

In theory as it stands today they could use our proxy for their own purposes. This means we need some way to ensure that only our client can use this proxy; enter PreShared Keys.
Much like an API token, stunnel supports an authentication method called PSK or PreShared Keys. This is essentially what it sounds like. A token that has been shared between the client and the server in advance and used for authentication. To enable PSK authentication we simply need to add the following two lines to the /etc/stunnel/stunnel.conf file on both the client and the server.
ciphers = PSK
PSKsecrets = /etc/stunnel/secrets
By setting ciphers to PSK we are telling stunnel to use PSK based authentication. The PSKsecrets option is used to provide stunnel a file that contains the secrets in a clientname:token format.
In the above we specified the /etc/stunnel/secrets file. Let’s go ahead and create that file and enter a sample PreShared Key.
client1:SjolX5zBNedxvhj+cQUjfZX2RVgy7ZXGtk9SEgH6Vai3b8xiDL0ujg8mVI2aGNCz
Since the /etc/stunnel/secrets file contains sensitive information. Let’s ensure that the permissions on the file are set appropriately.
$ sudo chmod 600 /etc/stunnel/secrets
By setting the permissions to 600 we are ensuring only the root user (the owner of the file) can read this file. These permissions will prevent other users from accessing the file and stumbling across our authentication credentials.
After setting permissions we will need to once again restart the stunnel service.
$ sudo systemctl restart stunnel4
With our settings are complete on both the client and server, we now have a reasonably secure TLS Proxy service.

Summary

In this article we covered setting up both a TLS and HTTP Proxy. As I mentioned before this setup can be used to help hide HTTP and HTTPS traffic on a given network. However, it is important to remember that while this setup makes the client system a much more tricky target, the proxy server itself could still be targeted for packet sniffing and man-in-the-middle attacks.
The key is to wisely select the location of where the proxy server is hosted.
------------

Using stunnel and TinyProxy

Recently there has been a lot of coverage in both tech and non-tech news outlets about internet privacy and how to prevent snooping both from service providers and governments. In this article I am going to show one method of anonymizing internet traffic; using a TLS enabled HTTP/HTTPS Proxy.

In this article we will walk through using stunnel to create a TLS tunnel with an instance of TinyProxy on the other side.

How does this help anonymize internet traffic

TinyProxy is an HTTP & HTTPS proxy server. By setting up a TinyProxy instance on a remote server and configuring our HTTP client to use this proxy. We can route all of our HTTP & HTTPS traffic through that remote server. This is a useful technique for getting around network restrictions that might be imposed by ISP's or Governments.

However, it's not enough to simply route HTTP/HTTPS traffic to a remote server. This in itself does not add any additional protection to the traffic. In fact, with an out of the box TinyProxy setup, all of the HTTP traffic to TinyProxy would still be unencrypted, leaving it open to packet capture and inspection. This is where stunnel comes into play.

I've featured it in earlier articles but for those who are new to stunnel, stunnel is a proxy that allows you to create a TLS tunnel between two or more systems. In this article we will use stunnel to create a TLS tunnel between the HTTP client system and TinyProxy.

By using a TLS tunnel between the HTTP client and TinyProxy our HTTP traffic will be encrypted between the local system and the proxy server. This means anyone trying to inspect HTTP traffic will be unable to see the contents of our HTTP traffic.

This technique is also useful for reducing the chances of a man-in-the-middle attack to HTTPS sites.

I say reducing because one of the caveats of this article is, while routing our HTTP & HTTPS traffic through a TLS tunneled HTTP proxy will help obfuscate and anonymize our traffic. The system running TinyProxy is still susceptible to man-in-the-middle attacks and HTTP traffic snooping.

Essentially, with this article, we are not focused on solving the problem of unencrypted traffic, we are simply moving our problem to a network where no one is looking. This is essentially the same approach as VPN service providers, the advantage of running your own proxy is that you control the proxy.

Now that we understand the end goal, let's go ahead and get started with the installation of TinyProxy.

Installing TinyProxy

The installation of TinyProxy is fairly easy and can be accomplished using the apt-get command on Ubuntu systems. Let's go ahead and install TinyProxy on our future proxy server.

server: $ sudo apt-get install tinyproxy

Once the apt-get command finishes, we can move to configuring TinyProxy.

Configuring TinyProxy

By default TinyProxy starts up listening on all interfaces for a connection to port 8888. Since we don't want to leave our proxy open to the world, let's change this by configuring TinyProxy to listen to the localhost interface only. We can do this by modifying the Listen parameter within the /etc/tinyproxy.conf file.

Find:

#Listen 192.168.0.1

Replace With:

Listen 127.0.0.1

Once complete, we will need to restart the TinyProxy service in order for our change to take effect. We can do this using the systemctl command.

server: $ sudo systemctl restart tinyproxy

After systemctl completes, we can validate that our change is in place by checking whether port 8888 is bound correctly using the netstat command.

server: $ netstat -na
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 127.0.0.1:8888          0.0.0.0:*               LISTEN

Based on the netstat output it appears TinyProxy is setup correctly. With that done, let's go ahead and setup stunnel.

Installing stunnel

Just like TinyProxy, the installation of stunnel is as easy as executing the apt-get command.

server: $ sudo apt-get install stunnel

Once apt-get has finished we will need to enable stunnel by editing the /etc/default/stunnel4 configuration file.

Find:

# Change to one to enable stunnel automatic startup
ENABLED=0

Replace:

# Change to one to enable stunnel automatic startup
ENABLED=1

By default on Ubuntu, stunnel is installed in a disabled mode. By changing the ENABLED flag from 0 to 1 within /etc/default/stunnel4, we are enabling stunnel to start automatically. However, our configuration of stunnel does not stop there.

Our next step with stunnel, will involve defining our TLS tunnel.

TLS Tunnel Configuration (Server)

By default stunnel will look in /etc/stunnel for any files that end in .conf. In order to configure our TLS stunnel we will be creating a file named /etc/stunnel/stunnel.conf. Once created, we will insert the following content.

[tinyproxy]
accept = 0.0.0.0:3128
connect = 127.0.0.1:8888
cert = /etc/ssl/cert.pem
key = /etc/ssl/key.pem

The contents of this configuration file are fairly straight forward, but let's go ahead and break down what each of these items mean. We will start with the accept option.

The accept option is similar to the listen option from TinyProxy. This setting will define what interface and port stunnel will listen to for incoming connections. By setting this to 0.0.0.0:3128 we are defining that stunnel should listen on all interfaces on port 3128.

The connect option is used to tell stunnel what IP and port to connect to. In our case this needs to be the IP and port that TinyProxy is listening on; 127.0.0.1:8888.

An easy way to remember how accept and connect should be configured is that accept is where incoming connections should come from, and connect is where they should go to.

Our next two configuration options are closely related, cert & key. The cert option is used to define the location of an SSL certificate that will be used to establish our TLS session. The key option is used to define the location of the key used to create the SSL certificate.

We will set these to be located in /etc/ssl and in the next step, we will go ahead and create both the key and certificate.

Creating a self-signed certificate

The first step in creating a self-signed certificate is to create an private key. To do this we will use the following openssl command.

server: $ sudo openssl genrsa -out /etc/ssl/key.pem 4096

The above will create a 4096 bit RSA key. From this key, we will create a public certificate using another openssl command. During the execution of this command there will be a series of questions. These questions are used to populate the key with organization information. Since we will be using this for our own purposes we will not worry too much about the answers to these questions.

server: $ sudo openssl req -new -x509 -key /etc/ssl/key.pem -out /etc/ssl/cert.pem -days 1826
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:Arizona
Locality Name (eg, city) []:Phoenix
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Example.com
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:proxy.example.com
Email Address []:proxy@example.com

Once the questions have been answered the openssl command will create our certificate file.

After both the certificate and key have been created, we will need to restart stunnel in order for our changes to take effect.

server: $ sudo systemctl restart stunnel4

At this point we have finished configuring the proxy server. We now need to setup our client.

Setting up stunnel (client)

Like the proxy server, our first step in setting up stunnel on our client is installing it with the apt-get command.

client: $ sudo apt-get install stunnel

We will also once again need to enabling stunnel within the /etc/default/stunnel4 configuration file.

Find:

# Change to one to enable stunnel automatic startup
ENABLED=0

Replace:

# Change to one to enable stunnel automatic startup
ENABLED=1

After enabling stunnel we will need to restart the service with the systemctl command.

client: $ sudo systemctl restart stunnel4

From here we can move on to configuring the stunnel client.

TLS Tunnel Configuration (Client)

The configuration of stunnel in “client-mode” is a little different than the “server-mode” configuration we set earlier. Let's go ahead and add our client configuration into the /etc/stunnel/stunnel.conf file.

client = yes

[tinyproxy]
accept = 127.0.0.1:3128
connect = 192.168.33.10:3128
verify = 4
CAFile = /etc/ssl/cert.pem

As we did before, let's break down the configuration options shown above.

The first option is client, this option is simple, as it defines whether stunnel should be operating in a client or server mode. By setting this to yes, we are defining that we would like to use client mode.

We covered accept and connect before and if we go back to our description above we can see that stunnel will accept connections on 127.0.0.1:3128 and then tunnel them to 192.168.33.10:3128, which is the IP and port that our stunnel proxy server is listening on.

The verify option is used to define what level of certificate validation should be performed. The option of 4 will cause stunnel to verify the remote certificate with a local certificate defined with the CAFile option. In the above example, I copied the /etc/ssl/cert.pem we generated on the server to the client and set this as the CAFile.

These last two options are important, without setting verify and CAFile stunnel will open an TLS connection without necessarily checking the validity of the certificate. By setting verify to 4 and CAFile to the same cert.pem we generated earlier, we are giving stunnel a way to validate the identity of our proxy server. This will prevent our client from being hit with a man-in-the-middle attack.

Once again, let's restart stunnel to make our configurations take effect.

client: $ sudo systemctl restart stunnel4

With our configurations complete, let's go ahead and test our proxy.

Testing our TLS tunneled HTTP Proxy

In order to test our proxy settings we will use the curl command. While we are using a command line web client in this article, it is possible to use this same type of configuration with GUI based browsers such as Chrome or Firefox.

Before testing however, I will need to set the http_proxy and https_proxy environmental variables. These will tell curl to leverage our proxy server.

client: $ export http_proxy="http://localhost:3128"
client: $ export https_proxy="https://localhost:3128"

With our proxy server settings in place, let's go ahead and execute our curl command.

client: $ curl -v https://google.com
* Rebuilt URL to: https://google.com/
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3128 (#0)
* Establish HTTP proxy tunnel to google.com:443
> CONNECT google.com:443 HTTP/1.1
> Host: google.com:443
> User-Agent: curl/7.47.0
> Proxy-Connection: Keep-Alive
>
< HTTP/1.0 200 Connection established
< Proxy-agent: tinyproxy/1.8.3
<
* Proxy replied OK to CONNECT request
* found 173 certificates in /etc/ssl/certs/ca-certificates.crt
* found 692 certificates in /etc/ssl/certs
* ALPN, offering http/1.1
* SSL connection using TLS1.2 / ECDHE_ECDSA_AES_128_GCM_SHA256
* 	 server certificate verification OK
* 	 server certificate status verification SKIPPED
* 	 common name: *.google.com (matched)
* 	 server certificate expiration date OK
* 	 server certificate activation date OK
* 	 certificate public key: EC
* 	 certificate version: #3
* 	 subject: C=US,ST=California,L=Mountain View,O=Google Inc,CN=*.google.com
* 	 start date: Wed, 05 Apr 2017 17:47:49 GMT
* 	 expire date: Wed, 28 Jun 2017 16:57:00 GMT
* 	 issuer: C=US,O=Google Inc,CN=Google Internet Authority G2
* 	 compression: NULL
* ALPN, server accepted to use http/1.1
> GET / HTTP/1.1
> Host: google.com
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 301 Moved Permanently
< Location: https://www.google.com/
< Content-Type: text/html; charset=UTF-8
< Date: Fri, 14 Apr 2017 22:37:01 GMT
< Expires: Sun, 14 May 2017 22:37:01 GMT
< Cache-Control: public, max-age=2592000
< Server: gws
< Content-Length: 220
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN
< Alt-Svc: quic=":443"; ma=2592000; v="37,36,35"
<
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://www.google.com/">here</A>.
</BODY></HTML>
* Connection #0 to host localhost left intact

From the above output we can see that our connection was routed through TinyProxy.

< Proxy-agent: tinyproxy/1.8.3

And we were able to connect to Google.

<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="https://www.google.com/">here</A>.
</BODY></HTML>

Given these results, it seems we have a working TLS based HTTP/HTTPS proxy. Since this proxy is exposed on the internet what would happen if this proxy was found by someone simply scanning subnets for nefarious purposes.

Securing our tunnel further with PreShared Keys

In theory as it stands today they could use our proxy for their own purposes. This means we need some way to ensure that only our client can use this proxy; enter PreShared Keys.

Much like an API token, stunnel supports an authentication method called PSK or PreShared Keys. This is essentially what it sounds like. A token that has been shared between the client and the server in advance and used for authentication. To enable PSK authentication we simply need to add the following two lines to the /etc/stunnel/stunnel.conf file on both the client and the server.

ciphers = PSK
PSKsecrets = /etc/stunnel/secrets

By setting ciphers to PSK we are telling stunnel to use PSK based authentication. The PSKsecrets option is used to provide stunnel a file that contains the secrets in a clientname:token format.

In the above we specified the /etc/stunnel/secrets file. Let's go ahead and create that file and enter a sample PreShared Key.

client1:SjolX5zBNedxvhj+cQUjfZX2RVgy7ZXGtk9SEgH6Vai3b8xiDL0ujg8mVI2aGNCz

Since the /etc/stunnel/secrets file contains sensitive information. Let's ensure that the permissions on the file are set appropriately.

$ sudo chmod 600 /etc/stunnel/secrets

By setting the permissions to 600 we are ensuring only the root user (the owner of the file) can read this file. These permissions will prevent other users from accessing the file and stumbling across our authentication credentials.

After setting permissions we will need to once again restart the stunnel service.

$ sudo systemctl restart stunnel4

With our settings are complete on both the client and server, we now have a reasonably secure TLS Proxy service.

Summary

In this article we covered setting up both a TLS and HTTP Proxy. As I mentioned before this setup can be used to help hide HTTP and HTTPS traffic on a given network. However, it is important to remember that while this setup makes the client system a much more tricky target, the proxy server itself could still be targeted for packet sniffing and man-in-the-middle attacks.

The key is to wisely select the location of where the proxy server is hosted.

from https://bencane.com/2017/04/15/using-stunnel-and-tinyproxy-to-hide-http-traffic/

---------------------------------------------------------------------------------------------

Secure Tunneling

I am becoming increasingly paranoid about transmitting my passwords unencrypted over the internet, especially when I'm away from home and I have to access my PC, so I thought of making an SSH tunnel from my laptop to my PC, and it turns out it's actually quite easy. In case you don't know what tunneling is, it goes like this: Say you want to connect with your browser (running on your laptop) to your home web server, but you want to do it securely. Instead of connecting to your server with your browser directly, you have the browser connect to the tunneling client (also running on your laptop). The tunneling client securely connects to the tunneling server on your home PC (the tunneling client and server are actually the same program, Stunnel), and the tunneling server connects to your webserver, and noone inbetween can read what's going on. So, here we go.

Step 1 - Get the necessary files.

Go to http://www.stunnel.org/download/stunnel/win32/ and get the latest Stunnel.exe and OpenSSL.zip files. Extract them in a directory.

Step 2 - Generating the certificate.

Download the stunnel.cnf file attached to this page and save it in the Stunnel directory. Now, run the following command (OpenSSL.exe and stunnel.cnf should be in the directory if you did everything correctly):
openssl req -new -x509 -days 365 -nodes -config stunnel.cnf -out stunnel.pem -keyout stunnel.pem
OpenSSL will ask you for various details (you're free to not answer them), and you will have your stunnel.pem file. Now, off to generate the configuration files.

Step 3 - Making the configuration files.

First, you have to decide which port you want stunnel to listen to. Choose something that's not likely to be used, like 43537. Next, write the client configuration file and save it as client.conf (the RDC section can be named whatever you like, for example "Web").

Sample client.conf file:

client = yes

[RDC]
connect = myhomeserver:5555
accept = 3389

The accept port is the port you will be connecting to on your laptop. In my case it is 3389 because I want to use Remote Desktop Connection. If you want to connect to a web server it'll probably be 80. Next, the server.conf file.

Sample server.conf file:

cert = stunnel.pem

[RDC]
accept  = 5555
connect = 3389

Step 4 - Running Stunnel and connecting.

This is the final step. On the home computer, run stunnel server.conf, and on the laptop run stunnel client.conf and connect to localhost with your browser (or Remote Desktop client, or whatever). If everything went well, you are now securely connected to the server.

from http://web.archive.org/web/20070816050824/http://www.poromenos.org/tutorials/stunnel

-------------------------------


相关帖子:
https://briteming.blogspot.com/2014/03/stunnel.html
http://briteming.blogspot.com/2015/10/stunnel.html 
http://briteming.blogspot.com/2016/03/vpsstunnel.html