├── LICENSE
├── README.md
├── StartSSL.CA.pem
├── changlog.txt
├── config.json
├── cp.py
├── handleHTTP.py
├── hello.html
├── images.jpg
├── myssl.py
├── you_cannot_pass.jpg
├── z_client.py
├── z_server.py
└── z_tcptrans.py
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 前言
2 | ----
3 | 从前,我的github账号都是只读模式的,就是上来聊天发issue的。
4 | 但是,SS作者clowwindy被某party请喝茶,项目关闭,看到clowwindy君说的那些话,想一想,自己略惭愧,的确从来贡献过什么
5 | SO,花了一晚上时间,整理了一下自己写过的可以公开的代(po)码(lan),都放到git上来了。
6 |
7 | A socks5 proxy through SSL
8 | --------------------------
9 | --------------------------
10 |
11 | 在13年10月份,wallproxy突然看不了U2B了(具体原因未知据说是GAE限制),Google IP也大量被封,感觉一直用这个翻墙方式不是事儿啊
12 | 就开始寻觅新的梯子,找到了SS,当时是1.4版的。读了SS的代码,感觉加密和混淆上有缺陷,so就有了我这个东西。main函数和SS 1.4版还是很一样的。
13 |
14 | #### 功能
15 | 和当时1.4版的SS差不多,区别有3点:
16 | 1、使用SSL连接替代SS的加密模块。这么做的想法是:SS不能防重放、防篡改等,加密这块最好别自己造轮子。
17 | 2、固定工作在443端口,当收到的TCP流头20个字节不是约定好的密码,就将这个连接作为https处理,否则作为代理处理。这么做的想法是:SS当时的建议是将SS服务端开在995等已知端口上,但是GFW会主动探测开放的端口具体运行的什么服务的,所以这样等于坦白给GFW说“我是代理哦”的感觉。固定在443并验证链接,这样收到墙的探测链接就返回正常的HTTP相应。
18 | 3、多了一个通过短链接转发TCP端口的z_tcptrans.py:z_tcptrans本地打开一个端口做服务器,当有链接来时,将数据通过多个短链接转发到服务器,服务器再转到指定的IP:端口上,并定时断开重建这些短链接。这么做的想法是:SS的流量特征就是SS里面承载的数据流的特征,虽然用SS了,但是通过流量分析还是能知道你里面跑的具体什么数据类型。
19 |
20 | #### 实际效果
21 | 13年11月开始用到14年底,不知道怎么回事VPS Control Panel被别人登录,估计证书也被泄漏,忙毕设懒得再折腾,停止使用,有1年时间。
22 | 缺点很明显,建立连接开销大,但是传输速度和SS没区别。~~
23 | 由于是在SSL里面承载socks5,并且几乎都是用代理浏览网页,流量特征和正常https服务器无异,这一年期间没有出现过断流、IP速度劣化、被封端口\IP等。~~ 已无效,详见 http://blog.zorinaq.com/?e=81 ,伟光正的墙已经识别tls over tls!
24 | 我把VPS的ssh设置为监听127.0.0.1 ,然后通过z_tcptrans在本地开一个端口转到服务器22上去连SSH,想法是流量分散到一堆只持续1分钟左右的短链接上,流量特征应该就不好看出来是SSH了。
25 | 通过日志发现每15分钟左右,GFW会在新建SSL时暂时阻塞,伪造一个随机的大陆IP对443端口发 http get 探测一次,然后放行。
26 | 还有一个更大的缺点:只有python版,不像SS那样有完善的各种平台版本的客户端。
27 |
28 | #### 后期计划
29 | 发现自己越来越懒了,这个东西从13年11月底开始就基本没变动过,除了14年2月把暴雪验证器放进HTTP里面,方便给工会人用我wow账号。
30 | VPS Control Panel被黑后曾经想学SS也做成异步构架,没坚持下来,只把eventloop框框写好,就扔那里了。
31 | 判断头20字节那块也有缺陷,要改。changlog里面记录一堆todo,也没做。。。。。
32 | 说不定那天心血来潮,会继续这个东西,因为现在SS太容易短流了,基本上30分钟就要换个VPS才能继续用要不没速度,整天在自己3台廉价VPS切来切去的。
33 |
--------------------------------------------------------------------------------
/StartSSL.CA.pem:
--------------------------------------------------------------------------------
1 | -----BEGIN CERTIFICATE-----
2 | MIIGNDCCBBygAwIBAgIBGDANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJJTDEW
3 | MBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwg
4 | Q2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNh
5 | dGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjA1NDE3WhcNMTcxMDI0MjA1NDE3WjCB
6 | jDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsT
7 | IlNlY3VyZSBEaWdpdGFsIEN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rBgEFBQcCARYoaHR0cDovL3d3dy5zdGFydHNzbC5jb20vaW50ZXJtZWRpYXRl
24 | LnBkZjANBgkqhkiG9w0BAQUFAAOCAgEAIQlJPqWIbuALi0jaMU2P91ZXouHTYlfp
25 | tVbzhUV1O+VQHwSL5qBaPucAroXQ+/8gA2TLrQLhxpFy+KNN1t7ozD+hiqLjfDen
26 | xk+PNdb01m4Ge90h2c9W/8swIkn+iQTzheWq8ecf6HWQTd35RvdCNPdFWAwRDYSw
27 | xtpdPvkBnufh2lWVvnQce/xNFE+sflVHfXv0pQ1JHpXo9xLBzP92piVH0PN1Nb6X
28 | t1gW66pceG/sUzCv6gRNzKkC4/C2BBL2MLERPZBOVmTX3DxDX3M570uvh+v2/miI
29 | RHLq0gfGabDBoYvvF0nXYbFFSF87ICHpW7LM9NfpMfULFWE7epTj69m8f5SuauNi
30 | YpaoZHy4h/OZMn6SolK+u/hlz8nyMPyLwcKmltdfieFcNID1j0cHL7SRv7Gifl9L
31 | WtBbnySGBVFaaQNlQ0lxxeBvlDRr9hvYqbBMflPrj0jfyjO1SPo2ShpTpjMM0InN
32 | SRXNiTE8kMBy12VLUjWKRhFEuT2OKGWmPnmeXAhEKa2wNREuIU640ucQPl2Eg7PD
33 | wuTSxv0JS3QJ3fGz0xk+gA2iCxnwOOfFwq/iI9th4p1cbiCJSS4jarJiwUW0n6+L
34 | p/EiO/h94pDQehn7Skzj0n1fSoMD7SfWI55rjbRZotnvbIIp3XUZPD9MEI3vu3Un
35 | 0q6Dp6jOW6c=
36 | -----END CERTIFICATE-----
37 | -----BEGIN CERTIFICATE-----
38 | MIIHyTCCBbGgAwIBAgIBATANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJJTDEW
39 | MBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwg
40 | Q2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNh
41 | dGl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6Eri8sxHkfY+BUZo7jYn0TZNmezwD7dOaHZrzZVD1oNB1
73 | ny+v8OqCQ5j4aZyJecRDjkZy42Q2Eq/3JR44iZB3fsNrarnDy0RLrHiQi+fHLB5L
74 | EUTINFInzQpdn4XBidUaePKVEFMy3YCEZnXZtWgo+2EuvoSoOMCZEoalHmdkrQYu
75 | L6lwhceWD3yJZfWOQ1QOq92lgDmUYMA0yZZwLKMS9R9Ie70cfmu3nZD0Ijuu+Pwq
76 | yvqCUqDvr0tVk+vBtfAii6w0TiYiBKGHLHVKt+V9E9e4DGTANtLJL4YSjCMJwRuC
77 | O3NJo2pXh5Tl1njFmUNj403gdy3hZZlyaQQaRwnmDwFWJPsfvw55qVguucQJAX6V
78 | um0ABj6y6koQOdjQK/W/7HW/lwLFCRsI3FU34oH7N4RDYiDK51ZLZer+bMEkkySh
79 | NOsF/5oirpt9P/FlUQqmMGqz9IgcgA38corog14=
80 | -----END CERTIFICATE-----
81 |
--------------------------------------------------------------------------------
/changlog.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/warriorpaw/z-ssl-proxy/b1b4ffbb3e01b0bd762986f2e20c0f397ea0e878/changlog.txt
--------------------------------------------------------------------------------
/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "server": "v03.warriorpaw.com",
3 | "server_port":443,
4 | "local_port": 1080,
5 | "local":"127.0.0.1",
6 | "password":"tes1222t123",
7 | "crt":"SSL_v03.crt",
8 | "key":"SSL_v03.pem",
9 | "ipv6":"0",
10 | "CA":"StartSSL.CA.pem",
11 | "tcptrans":[[0,"127.0.0.1",22,1090],[0,"127.0.0.1",22,1091],[0,"127.0.0.1",1026,1100]]
12 | }
13 |
--------------------------------------------------------------------------------
/cp.py:
--------------------------------------------------------------------------------
1 | import compileall
2 |
3 | compileall.compile_dir(r'./server')
4 |
--------------------------------------------------------------------------------
/handleHTTP.py:
--------------------------------------------------------------------------------
1 | import os
2 | from time import time
3 | import hmac
4 | from hashlib import sha1
5 | from struct import pack, unpack
6 | try:
7 | from http.client import HTTPConnection
8 | except ImportError:
9 | from httplib import HTTPConnection
10 |
11 | TimeOffset = 0
12 | html = '
Hello!%s
'
13 |
14 | def updata_time():
15 | global TimeOffset
16 | conn = HTTPConnection("mobile-service.blizzard.com")
17 | conn.request("POST", "/enrollment/time.htm", None)
18 | response = conn.getresponse()
19 | if response.status != 200:
20 | conn.close()
21 | return
22 | t = time()
23 | ret = response.read()
24 | conn.close()
25 | remoteTime = int(unpack(">Q", ret)[0])
26 | TimeOffset = float(remoteTime)/1000 - t
27 |
28 | def getToken(secret, time, digits=8, seconds=30):
29 | t = int(time)
30 | msg = pack(">Q", int(t / seconds))
31 | r = hmac.new(secret, msg, sha1).digest()
32 | k = r[19]
33 | if isinstance(k, str):
34 | k = ord(k)
35 | idx = k & 0x0f
36 | h = unpack(">L", r[idx:idx+4])[0] & 0x7fffffff
37 | return h % (10 ** digits)
38 |
39 | def getkey():
40 | ret = ''
41 | for a, b in zip('a9t\x95\xd1\x94\x02\x91C\xfa\x8aB\xc2%1\xf5\xee\xae\xa7\x0c',
42 | sha1(html).digest()
43 | ):
44 | ret += chr(ord(a) ^ ord(b))
45 | return ret
46 |
47 | def filepath(f):
48 | return os.path.join(os.path.split(os.path.realpath(__file__))[0], f)
49 |
50 | def send404(self):
51 | self.protocal_version = "HTTP/1.1"
52 | self.send_response(404)
53 | self.send_header("Content-type", "text/html; charset=gb2312")
54 | self.end_headers()
55 | self.wfile.write('404 - YOU CAN NOT PASS!!!!
')
56 |
57 | def version_string(self):
58 | return "BaseHTTP 0.1 //Made By WarriorPaw"
59 |
60 | def do_GET(self):
61 | #if not self.servername == self.headers.get('Host', ""):
62 | # send404(self)
63 | if self.path == "" or self.path == "/":
64 | self.protocal_version = "HTTP/1.1"
65 | self.send_response(200)
66 | self.send_header("Content-type", "text/html; charset=UTF-8")
67 | self.end_headers()
68 | self.wfile.write(open(filepath('hello.html'),'r').read())
69 | elif self.path == "/you_cannot_pass.jpg":
70 | self.protocal_version = "HTTP/1.1"
71 | self.send_response(200)
72 | self.send_header("Content-type", "image/jpeg")
73 | self.end_headers()
74 | self.wfile.write(open(filepath('you_cannot_pass.jpg'),'rb').read())
75 | elif self.path == "/favicon.ico":
76 | self.protocal_version = "HTTP/1.1"
77 | self.send_response(200)
78 | self.send_header("Content-type", "image/jpeg")
79 | self.end_headers()
80 | self.wfile.write(open(filepath('images.jpg'),'rb').read())
81 | elif self.path == "/httplog":
82 | self.protocal_version = "HTTP/1.1"
83 | self.send_response(200)
84 | self.send_header("Content-type", "text/html; charset=UTF-8")
85 | self.end_headers()
86 | buf = ''
87 | with open(filepath('http.log'),'r') as l:
88 | for line in l:
89 | buf = buf + line + ''*2
90 | self.wfile.write(buf)
91 | elif self.path == "/bma":
92 | self.protocal_version = "HTTP/1.1"
93 | self.send_response(200)
94 | self.send_header("Content-type", "text/html; charset=UTF-8")
95 | self.end_headers()
96 | if TimeOffset == 0:
97 | updata_time()
98 | t = time() + TimeOffset + 15
99 | k = getToken(getkey(), t - t % 60 + 15)
100 | self.wfile.write(html % ("%08d -- %02d" % (k, int(60 - t % 60))))
101 | else:
102 | send404(self)
103 |
--------------------------------------------------------------------------------
/hello.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | Hello!There~
4 |
5 |
6 | This is WarriorPaw's private test server.
7 | Only for study and personal using.
8 | Thanks !
9 | Your IP has been recorded.
10 |
11 |
--------------------------------------------------------------------------------
/images.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/warriorpaw/z-ssl-proxy/b1b4ffbb3e01b0bd762986f2e20c0f397ea0e878/images.jpg
--------------------------------------------------------------------------------
/myssl.py:
--------------------------------------------------------------------------------
1 | import ssl, socket, SocketServer, BaseHTTPServer, select
2 | from cStringIO import StringIO
3 |
4 | class TCPServer(SocketServer.TCPServer):
5 | def __init__(self,
6 | server_address,
7 | RequestHandlerClass,
8 | certfile = None,
9 | keyfile = None,
10 | ssl_version=ssl.PROTOCOL_SSLv23,
11 | bind_and_activate=True):
12 | SocketServer.TCPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate)
13 | if certfile or keyfile:
14 | self.socket = ssl.wrap_socket(self.socket,
15 | server_side=True,
16 | certfile = certfile,
17 | keyfile = keyfile,
18 | ssl_version = ssl_version)
19 |
20 |
21 | class ThreadingTCPServer(SocketServer.ThreadingMixIn, TCPServer): pass
22 |
23 | class ThreadingzProxyServer(ThreadingTCPServer):
24 | # copy from BaseHTTPServer.py
25 | allow_reuse_address = 1
26 | def server_bind(self):
27 | ThreadingTCPServer.server_bind(self)
28 | host, port = self.socket.getsockname()[:2]
29 | self.server_name = socket.getfqdn(host)
30 | self.server_port = port
31 |
32 | class zProxyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
33 | def handleProxy(self):
34 | pass
35 |
36 | def verify(self):
37 | pass
38 |
39 | def handle(self):
40 | self.data = self.connection.recv(65535)
41 | if self.verify():
42 | del self.data
43 | self.handleProxy()
44 | else:
45 | if len(self.data) < 10:
46 | con = 0
47 | while 1:
48 | r, w, e = select.select([self.connection], [], [], 0.0001)
49 | if con > 20:
50 | break
51 | if self.connection in r:
52 | self.data = self.data + self.connection.recv(65535)
53 | else:
54 | break
55 | con += 1
56 | tmp_rfile = self.rfile
57 | self.rfile = StringIO(self.data)
58 | # copy from BaseHTTPServer.py
59 | self.close_connection = 1
60 | self.handle_one_request()
61 | del self.rfile
62 | del self.data
63 | self.rfile = tmp_rfile
64 | while not self.close_connection:
65 | self.handle_one_request()
66 |
--------------------------------------------------------------------------------
/you_cannot_pass.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/warriorpaw/z-ssl-proxy/b1b4ffbb3e01b0bd762986f2e20c0f397ea0e878/you_cannot_pass.jpg
--------------------------------------------------------------------------------
/z_client.py:
--------------------------------------------------------------------------------
1 | import select, socket, ssl, os
2 | import sys, struct, random, hashlib
3 | import json
4 | import logging
5 | import threading
6 | import SocketServer
7 |
8 | def filepath(f):
9 | return os.path.join(os.path.split(os.path.realpath(__file__))[0], f)
10 |
11 | def send_all(sock, data):
12 | bytes_sent = 0
13 | con = 0
14 | while True:
15 | r = sock.send(data[bytes_sent:])
16 | if r < 0:
17 | return r
18 | bytes_sent += r
19 | if bytes_sent == len(data):
20 | return bytes_sent
21 | con = con + 1
22 | if con > 14:
23 | raise Exception('send too many times!')
24 |
25 | class ThreadingTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
26 | allow_reuse_address = True
27 |
28 | class Socks5Server(SocketServer.StreamRequestHandler):
29 | def handle_tcp(self, sock, remote):
30 | try:
31 | fdset = [sock, remote]
32 | while True:
33 | r, w, e = select.select(fdset, [], [])
34 | if sock in r:
35 | data = sock.recv(4096)
36 | if len(data) <= 0:
37 | break
38 | result = send_all(remote, data)
39 | if result < len(data):
40 | raise Exception('failed to send all data')
41 |
42 | if remote in r:
43 | data = remote.recv(4096)
44 | if len(data) <= 0:
45 | break
46 | result = send_all(sock, data)
47 | if result < len(data):
48 | raise Exception('failed to send all data')
49 | finally:
50 | sock.close()
51 | remote.close()
52 |
53 | def send_PW(self, sock):
54 | sock.send(PW + '\x00' * random.randint(10,80))
55 | rePW = sock.recv(2048)
56 | return (rePW[:len(PW)] == PW)
57 |
58 | def handle(self):
59 | try:
60 | sock = self.connection
61 | sock.recv(262)
62 | sock.send("\x05\x00")
63 | data = self.rfile.read(4) or '\x00' * 4
64 | mode = ord(data[1])
65 | if mode != 1:
66 | logging.warn('mode != 1')
67 | return
68 | addrtype = ord(data[3])
69 | addr_to_send = data[3]
70 | if addrtype == 1:
71 | addr_ip = self.rfile.read(4)
72 | addr = socket.inet_ntoa(addr_ip)
73 | addr_to_send += addr_ip
74 | elif addrtype == 3:
75 | addr_len = self.rfile.read(1)
76 | addr = self.rfile.read(ord(addr_len))
77 | addr_to_send += addr_len + addr
78 | elif addrtype == 4:
79 | addr_ip = self.rfile.read(16)
80 | addr = socket.inet_ntop(socket.AF_INET6, addr_ip)
81 | addr_to_send += addr_ip
82 | else:
83 | logging.warn('addr_type not support')
84 | # not support
85 | return
86 | addr_port = self.rfile.read(2)
87 | addr_to_send += addr_port
88 | port = struct.unpack('>H', addr_port)
89 | try:
90 | reply = "\x05\x00\x00\x01"
91 | reply += socket.inet_aton('0.0.0.0') + struct.pack(">H", 2222)
92 | self.wfile.write(reply)
93 | #R_P = REMOTE_PORT[random.randint(0,len(REMOTE_PORT) - 1)]
94 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
95 | remote = ssl.wrap_socket(s,
96 | ca_certs= CA,
97 | cert_reqs=ssl.CERT_REQUIRED)
98 | remote.connect(self.server.seradd)
99 | if not self.server.seradd[0] == remote.getpeercert()['subjectAltName'][0][1]:
100 | logging.error('Server crt error !! Server Name don\'t mach !!')
101 | logging.error(remote.getpeercert()['subjectAltName'][0][1])
102 | return
103 | if not self.send_PW(remote):
104 | logging.warn('PW error !')
105 | return
106 | remote.send(addr_to_send)
107 | logging.info('connecting %s:%d' % (addr, port[0]))
108 | except socket.error, e:
109 | logging.warn(e)
110 | return
111 | self.handle_tcp(sock, remote)
112 | except socket.error, e:
113 | logging.warn(e)
114 |
115 | class local_server(threading.Thread):
116 | def __init__(self, server):
117 | threading.Thread.__init__(self)
118 | self.server = server
119 | def run(self):
120 | self.server.serve_forever()
121 |
122 | def main():
123 | global PW, CA
124 | logging.basicConfig(level=logging.DEBUG,
125 | format='%(asctime)s %(levelname)-8s %(message)s',
126 | datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')
127 |
128 | with open(filepath('config.json'), 'rb') as f:
129 | config = json.load(f)
130 | logging.info('loading config from %s' % filepath('config.json'))
131 |
132 | SERVER = config['server']
133 | REMOTE_PORT = config['server_port']
134 | PORT = config['local_port']
135 | LOCAL = config['local']
136 | PW = hashlib.sha1(config['password'] + "3dfghuyrfplndd3e2sdrr4dddff").digest()
137 | IPv6 = int(config['ipv6'])
138 | CA = filepath(config['CA'])
139 |
140 | if IPv6:
141 | ThreadingTCPServer.address_family = socket.AF_INET6
142 |
143 | try:
144 | server = ThreadingTCPServer((LOCAL, PORT), Socks5Server)
145 | server.seradd = (SERVER, REMOTE_PORT)
146 | print "starting local at", PORT, 'to', SERVER
147 | local_server(server).start()
148 | except socket.error, e:
149 | logging.error(e)
150 | except KeyboardInterrupt:
151 | server.shutdown()
152 | sys.exit(0)
153 |
154 | if __name__ == '__main__':
155 | main()
156 |
--------------------------------------------------------------------------------
/z_server.py:
--------------------------------------------------------------------------------
1 | import myssl, select, handleHTTP, socket
2 | import sys, struct, os, random, hashlib, time, threading
3 | import json
4 | import logging
5 |
6 | #MAXSYN = 2 ** 15
7 | MAXSYNBUFFER = 64
8 | MAXSYN = 1024
9 | #REMOTE_lines = 4
10 |
11 | def filepath(f):
12 | return os.path.join(os.path.split(os.path.realpath(__file__))[0], f)
13 |
14 | def random_data(len):
15 | d = ''
16 | for i in range(0, len):
17 | d += chr(random.randint(0,255))
18 | return d
19 |
20 | def send_all(sock, data):
21 | bytes_sent = 0
22 | con = 0
23 | while 1:
24 | r = sock.send(data[bytes_sent:])
25 | if r < 0:
26 | return r
27 | bytes_sent += r
28 | if bytes_sent == len(data):
29 | return bytes_sent
30 | con = con + 1
31 | if con > 20:
32 | raise Exception('send too many times!')
33 |
34 | def read_all(sock):
35 | data_len = sock.recv(2)
36 | con = 0
37 | if len(data_len) <= 0:
38 | raise Exception('read_all zero data!')
39 | data_len = struct.unpack("H",data_len)[0]
40 | if data_len <= 0:
41 | raise Exception('read_all data_len error!')
42 | data = ''
43 | while data_len > 0:
44 | d = sock.recv(data_len)
45 | if len(d) <= 0:
46 | raise Exception('read_all read error!')
47 | data += d
48 | data_len -= len(d)
49 | con += 1
50 | if con > 20:
51 | raise Exception('read too many times!')
52 | return data
53 |
54 | class zProxyHandle(myssl.zProxyRequestHandler):
55 | def handle_socket5(self, sock, remote):
56 | try:
57 | fdset = [sock, remote]
58 | while 1:
59 | r, w, e = select.select(fdset, [], [])
60 | if sock in r:
61 | data = sock.recv(4096)
62 | if len(data) <= 0:
63 | break
64 | result = send_all(remote, data)
65 | if result < len(data):
66 | raise Exception('failed to send all data')
67 | if remote in r:
68 | data = remote.recv(4096)
69 | if len(data) <= 0:
70 | break
71 | result = send_all(sock, data)
72 | if result < len(data):
73 | raise Exception('failed to send all data')
74 | if not len(r):
75 | break
76 | finally:
77 | sock.close()
78 | remote.close()
79 |
80 | def socket5proxy(self):
81 | try:
82 | sock = self.connection
83 | addrtype = ord(sock.recv(1))
84 | if addrtype > 4:
85 | return addrtype
86 | if addrtype == 1:
87 | addr = socket.inet_ntoa(self.rfile.read(4))
88 | elif addrtype == 3:
89 | addr = self.rfile.read(ord(sock.recv(1)))
90 | elif addrtype == 4:
91 | addr = socket.inet_ntop(socket.AF_INET6,self.rfile.read(16))
92 | else:
93 | # not support
94 | logging.warn('addr_type not support')
95 | return
96 | port = struct.unpack('>H', self.rfile.read(2))
97 | try:
98 | logging.info('connecting %s:%d' % (addr, port[0]))
99 | remote = socket.create_connection((addr, port[0]))
100 | except socket.error, e:
101 | logging.warn(e)
102 | return
103 | self.handle_socket5(sock, remote)
104 | except socket.error, e:
105 | logging.warn(e)
106 | return
107 |
108 | def handleProxy(self):
109 | addrtype = self.socket5proxy()
110 | if addrtype:
111 | self.tcpproxy(addrtype)
112 |
113 | def tcpproxy(self, addrtype):
114 | self.tcpruning = True
115 | try:
116 | sock = self.connection
117 | if addrtype == 8:
118 | self.remote = TCP_CLIENTS.handleproxy(self)
119 | if self.remote:
120 | self.handle_TCP()
121 | return
122 | elif addrtype == 5:
123 | addr = socket.inet_ntoa(self.rfile.read(4))
124 | elif addrtype == 6:
125 | addr = self.rfile.read(ord(sock.recv(1)))
126 | elif addrtype == 7:
127 | addr = socket.inet_ntop(socket.AF_INET6,self.rfile.read(16))
128 | else:
129 | # not support
130 | logging.warn('addr_type not support')
131 | return
132 | port = struct.unpack('>H', self.rfile.read(2))
133 | clientID = hashlib.sha1(str(self.client_address) + random_data(20) + str(time.time())).digest()
134 | self.remote = TCP_CLIENTS.newproxy(clientID, addr, port[0], self)
135 | if self.remote:
136 | self.handle_TCP()
137 | return
138 | except socket.error, e:
139 | logging.warn(e)
140 | return
141 |
142 | def handle_TCP(self):
143 | try:
144 | sock = self.connection
145 | fset = [sock]
146 | while self.tcpruning:
147 | r, w, e = select.select(fset, [], [])
148 | if sock in r:
149 | self.remote.send(read_all(sock))
150 | else:
151 | break
152 | except:
153 | print 'handle_TCP'
154 | print sys.exc_info()
155 | finally:
156 | self.destroy()
157 |
158 | def destroy(self):
159 | self.tcpruning = False
160 | self.remote.remove(self)
161 | self.connection.close()
162 |
163 | def send(self, data):
164 | try:
165 | result = send_all(self.connection, data)
166 | if result < len(data):
167 | raise Exception('failed to send all data')
168 | return True
169 | except:
170 | print 'Hsend'
171 | print sys.exc_info()
172 | self.destroy()
173 | return False
174 |
175 | def verify(self):
176 | global PW
177 | if self.data[:20] == PW:
178 | #Going up, as a proxy
179 | self.connection.send(PW + '\x00' * random.randint(30,150))
180 | return True
181 | else:
182 | #Going down, as a HTTP
183 | return False
184 | def log_message(self, format, *args):
185 | s = ("%s - - [%s] %s\n" %
186 | (self.client_address[0],
187 | self.log_date_time_string(),
188 | format%args))
189 | l = open(HTTPLOG,'a+')
190 | l.write(s)
191 | l.close()
192 | sys.stderr.write(s)
193 |
194 | version_string = handleHTTP.version_string
195 | do_HEAD = handleHTTP.send404
196 | do_PUT = handleHTTP.send404
197 | do_POST = handleHTTP.send404
198 | do_DELETE = handleHTTP.send404
199 | do_CONNECT = handleHTTP.send404
200 | do_GET = handleHTTP.do_GET
201 |
202 | class tcpproxyhandle:
203 | def __init__(self):
204 | self.clientlist = {}
205 |
206 | def newproxy(self, clientID, addr, port, client):
207 | try:
208 | remote = socket.create_connection((addr, port))
209 | client.connection.send(clientID + '\x00' * random.randint(10,80))
210 | reID = client.connection.recv(65535)
211 | if reID[:20] == clientID:
212 | t = tcp_remote(remote, clientID)
213 | t.Load(client)
214 | t.start()
215 | self.clientlist[clientID] = t
216 | return t
217 | except:
218 | print sys.exc_info()
219 |
220 | def handleproxy(self, client):
221 | try:
222 | ID = client.connection.recv(65535)[:20]
223 | if ID in self.clientlist:
224 | client.connection.send(ID + '\x00' * random.randint(10, 80))
225 | t = self.clientlist[ID]
226 | t.Load(client)
227 | return t
228 | except:
229 | print sys.exc_info()
230 |
231 | def removeID(self, ID):
232 | if ID in self.clientlist:
233 | del self.clientlist[ID]
234 |
235 | class tcp_remote(threading.Thread):
236 | def __init__(self, sock, clientID):
237 | threading.Thread.__init__(self)
238 | self.sock = sock
239 | self.ID = clientID
240 | self.clients = []
241 | self.mutex = threading.Lock()
242 | self.SendSYN = 0
243 | self.RecvSYN = 0
244 | self.SYNbuffer = {}
245 |
246 | def run(self):
247 | sock = self.sock
248 | fset = [sock]
249 | try:
250 | while len(self.clients):
251 | r, w, e = select.select(fset, [], [])
252 | if sock in r:
253 | data = sock.recv(1020)
254 | if len(data) <= 0:
255 | break
256 | data = struct.pack("H",self.SendSYN) + data
257 | self.SendSYN = (self.SendSYN + 1) % MAXSYN
258 | data = struct.pack("H",len(data)) + data
259 | while len(self.clients):
260 | if random.choice(self.clients[-4:]).send(data):
261 | break
262 | else:
263 | break
264 | except:
265 | print 'tcp_remote'
266 | print sys.exc_info()
267 | finally:
268 | self.destroy()
269 |
270 | def Load(self, client):
271 | self.clients.append(client)
272 |
273 | def remove(self, client):
274 | if client in self.clients:
275 | self.clients.remove(client)
276 | if not len(self.clients):
277 | self.destroy()
278 |
279 | def send(self, data):
280 | def _send(self, data):
281 | result = send_all(self.sock, data)
282 | if result < len(data):
283 | raise Exception('failed to send all data')
284 | self.RecvSYN = (self.RecvSYN + 1) % MAXSYN
285 | try:
286 | self.mutex.acquire()
287 | syn = struct.unpack("H",data[:2])[0]
288 | if syn == self.RecvSYN:
289 | _send(self, data[2:])
290 | while len(self.SYNbuffer):
291 | if self.RecvSYN in self.SYNbuffer:
292 | #print 'SYN out', self.RecvSYN
293 | _send(self, self.SYNbuffer.pop(self.RecvSYN))
294 | else:
295 | break
296 | else:
297 | if len(self.SYNbuffer) >= MAXSYNBUFFER:
298 | raise Exception('SYNbuffer overflow')
299 | #print 'SYN need', self.RecvSYN, 'save', syn
300 | self.SYNbuffer[syn] = data[2:]
301 |
302 | except:
303 | print 'Tsend'
304 | print sys.exc_info()
305 | self.destroy()
306 | finally:
307 | self.mutex.release()
308 |
309 |
310 | def destroy(self):
311 | TCP_CLIENTS.removeID(self.ID)
312 | while len(self.clients):
313 | self.clients.pop().destroy()
314 | self.sock.close()
315 |
316 |
317 | def main():
318 | global PW, HTTPLOG, TCP_CLIENTS
319 | logging.basicConfig(level=logging.DEBUG,
320 | format='%(asctime)s %(levelname)-8s %(message)s',
321 | datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')
322 |
323 | with open(filepath('config.json'), 'rb') as f:
324 | config = json.load(f)
325 | logging.info('loading config from %s' % filepath('config.json'))
326 |
327 | SERVER = config['server']
328 | PORT = config['server_port']
329 | PW = hashlib.sha1(config['password'] + "3dfghuyrfplndd3e2sdrr4dddff").digest()
330 | IPv6 = int(config['ipv6'])
331 | CRT = filepath(config['crt'])
332 | KEY = filepath(config['key'])
333 | TCP_CLIENTS = tcpproxyhandle()
334 |
335 |
336 | if IPv6:
337 | ThreadingTCPServer.address_family = socket.AF_INET6
338 |
339 | HTTPLOG = filepath('http.log')
340 |
341 | server = myssl.ThreadingzProxyServer((SERVER,PORT),
342 | zProxyHandle,
343 | CRT,
344 | KEY)
345 | logging.info("starting server at %s:%d" % tuple(server.server_address[:2]))
346 | try:
347 | server.serve_forever()
348 | except socket.error, e:
349 | logging.error(e)
350 | server.shutdown()
351 | server.server_close()
352 | except KeyboardInterrupt:
353 | server.shutdown()
354 | server.server_close()
355 | sys.exit(0)
356 |
357 | if __name__ == '__main__':
358 | main()
359 |
--------------------------------------------------------------------------------
/z_tcptrans.py:
--------------------------------------------------------------------------------
1 | import select, socket, ssl, os
2 | import sys, struct, random, hashlib, time, threading
3 | import json
4 | import logging
5 | import threading
6 | import SocketServer
7 |
8 | #MAXSYN = 2 ** 15
9 | MAXSYN = 1024
10 | MAXSYNBUFFER = 200
11 | #REMOTE_lines = 4
12 |
13 | def filepath(f):
14 | return os.path.join(os.path.split(os.path.realpath(__file__))[0], f)
15 |
16 | def send_all(sock, data):
17 | bytes_sent = 0
18 | con = 0
19 | while 1:
20 | r = sock.send(data[bytes_sent:])
21 | if r < 0:
22 | return r
23 | bytes_sent += r
24 | if bytes_sent == len(data):
25 | return bytes_sent
26 | con = con + 1
27 | if con > 14:
28 | raise Exception('send too many times!')
29 |
30 | def read_all(sock):
31 | data_len = sock.recv(2)
32 | if len(data_len) <= 0:
33 | raise Exception('read_all zero data!')
34 | data_len = struct.unpack("H",data_len)[0]
35 | if data_len <= 0:
36 | raise Exception('read_all data_len error!')
37 | data = ''
38 | while data_len > 0:
39 | d = sock.recv(data_len)
40 | if len(d) <= 0:
41 | raise Exception('read_all read error!')
42 | data += d
43 | data_len -= len(d)
44 | return data
45 |
46 |
47 | class ThreadingTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
48 | allow_reuse_address = True
49 |
50 | class Mytimer(threading.Thread):
51 | def __init__(self, callback):
52 | threading.Thread.__init__(self)
53 | self.callback = callback
54 | self.over = False
55 |
56 | def run(self):
57 | while not self.over:
58 | self.callback()
59 | time.sleep(random.randint(5,20))
60 |
61 | def kill(self):
62 | self.over = True
63 |
64 | class TcpProxyClient(SocketServer.StreamRequestHandler):
65 | def handle_tcp(self):
66 | sock = self.connection
67 | fset = [sock]
68 | try:
69 | while len(self.remotes):
70 | r, w, e = select.select(fset, [], [])
71 | if sock in r:
72 | data = sock.recv(1020)
73 | if len(data) <= 0:
74 | print 'handle_tcp close!!!!!!!!!!!!'
75 | break
76 | data = struct.pack("H",self.SendSYN) + data
77 | self.SendSYN = (self.SendSYN + 1) % MAXSYN
78 | data = struct.pack("H",len(data)) + data
79 | while len(self.remotes):
80 | if random.choice(self.remotes[-4:]).send(data):
81 | break
82 | except:
83 | print 'handle_tcp'
84 | print sys.exc_info()
85 | finally:
86 | self.destroy()
87 |
88 | def timer_connect(self):
89 | while len(self.remotes) > 4:
90 | self.remotes[0].destroy()
91 | newline = random.randint(1,4)
92 | for i in range(0,newline):
93 | remote = self.newconnect()
94 | if not remote:
95 | break
96 | try:
97 | remote.send('\x08' + self.ID + '\x00' * random.randint(10,50))
98 | reID = remote.recv(65535)[:20]
99 | if not reID == self.ID:
100 | remote.close()
101 | break
102 | r = tcp_remote(remote, self)
103 | r.start()
104 | self.remotes.append(r)
105 | except:
106 | print 'Time'
107 | print sys.exc_info()
108 | remote.close()
109 | break
110 |
111 | def remove(self, remote):
112 | if remote in self.remotes:
113 | self.remotes.remove(remote)
114 | if not len(self.remotes):
115 | self.destroy()
116 |
117 | def send(self, data):
118 | def _send(self, data):
119 | result = send_all(self.connection, data)
120 | if result < len(data):
121 | raise Exception('failed to send all data')
122 | self.RecvSYN = (self.RecvSYN + 1) % MAXSYN
123 | try:
124 | self.mutex.acquire()
125 | syn = struct.unpack("H",data[:2])[0]
126 | if syn == self.RecvSYN:
127 | _send(self, data[2:])
128 | while len(self.SYNbuffer):
129 | if self.RecvSYN in self.SYNbuffer:
130 | _send(self, self.SYNbuffer.pop(self.RecvSYN))
131 | else:
132 | break
133 | else:
134 | if len(self.SYNbuffer) >= MAXSYNBUFFER:
135 | raise Exception('SYNbuffer overflow')
136 | self.SYNbuffer[syn] = data[2:]
137 | #print 'SYN len', len(self.SYNbuffer)
138 | except:
139 | print 'Hsend'
140 | print sys.exc_info()
141 | self.destroy()
142 | finally:
143 | self.mutex.release()
144 |
145 | def handle(self):
146 | if self.Start():
147 | try:
148 | self.handle_tcp()
149 | except socket.error, e:
150 | logging.warn(e)
151 | self.destroy()
152 |
153 | def send_PW(self, sock):
154 | sock.send(PW + '\x00' * random.randint(10,80))
155 | rePW = sock.recv(65535)
156 | return (rePW[:20] == PW)
157 |
158 | def newconnect(self):
159 | try:
160 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
161 | remote = ssl.wrap_socket(s,
162 | ca_certs= CA,
163 | cert_reqs=ssl.CERT_REQUIRED,
164 | ssl_version = ssl.PROTOCOL_SSLv3)
165 | remote.connect(self.server.seradd)
166 | if not self.server.seradd[0] == remote.getpeercert()['subjectAltName'][0][1]:
167 | logging.error('Server crt error !! Server Name don\'t mach !!')
168 | logging.error(remote.getpeercert()['subjectAltName'][0][1])
169 | return
170 | if not self.send_PW(remote):
171 | logging.warn('PW error !')
172 | return
173 | except socket.error, e:
174 | logging.warn(e)
175 | return
176 | return remote
177 |
178 | def Start(self):
179 | self.remotes = []
180 | self.mutex = threading.Lock()
181 | self.SendSYN = 0
182 | self.RecvSYN = 0
183 | self.SYNbuffer = {}
184 | try:
185 | addr_to_send = '\x05'
186 | addr_to_send += socket.inet_aton(self.server.r_sock[0])
187 | addr_to_send += struct.pack('>H', self.server.r_sock[1])
188 | remote = self.newconnect()
189 | if not remote:
190 | return
191 | remote.send(addr_to_send)
192 | self.ID = remote.recv(65535)[:20]
193 | remote.send(self.ID + '\x00' * random.randint(10,50))
194 | r = tcp_remote(remote, self)
195 | r.start()
196 | self.remotes.append(r)
197 | except socket.error, e:
198 | logging.warn(e)
199 | return
200 | self.mytimer = Mytimer(self.timer_connect)
201 | self.mytimer.start()
202 | return True
203 |
204 | def destroy(self):
205 | self.connection.close()
206 | self.mytimer.kill()
207 | #self.server.shutdown()
208 | while len(self.remotes):
209 | self.remotes.pop().destroy()
210 |
211 |
212 | class tcp_remote(threading.Thread):
213 | def __init__(self, sock, local):
214 | threading.Thread.__init__(self)
215 | self.sock = sock
216 | self.local = local
217 | self.tcpruning = True
218 |
219 | def run(self):
220 | sock = self.sock
221 | fset = [sock]
222 | try:
223 | while self.tcpruning:
224 | r, w, e = select.select(fset, [], [])
225 | if sock in r:
226 | self.local.send(read_all(sock))
227 | except:
228 | print 'tcp_remote'
229 | print sys.exc_info()
230 | finally:
231 | self.destroy()
232 |
233 | def send(self, data):
234 | try:
235 | result = send_all(self.sock, data)
236 | if result < len(data):
237 | raise Exception('failed to send all data')
238 | return True
239 | except:
240 | print 'Tsend'
241 | print sys.exc_info()
242 | self.destroy()
243 | return False
244 |
245 | def destroy(self):
246 | self.tcpruning = False
247 | self.local.remove(self)
248 | self.sock.close()
249 |
250 | class local_server(threading.Thread):
251 | def __init__(self, server):
252 | threading.Thread.__init__(self)
253 | self.server = server
254 | def run(self):
255 | self.server.serve_forever()
256 |
257 | def main():
258 | global PW, CA
259 | logging.basicConfig(level=logging.DEBUG,
260 | format='%(asctime)s %(levelname)-8s %(message)s',
261 | datefmt='%Y-%m-%d %H:%M:%S', filemode='a+')
262 |
263 | with open(filepath('config.json'), 'rb') as f:
264 | config = json.load(f)
265 | logging.info('loading config from %s' % filepath('config.json'))
266 |
267 | SERVER = config['server']
268 | SERVER_PORT = config['server_port']
269 | #PORT = config['local_port']
270 | LOCAL = config['local']
271 | PW = hashlib.sha1(config['password'] + "3dfghuyrfplndd3e2sdrr4dddff").digest()
272 | IPv6 = int(config['ipv6'])
273 | CA = filepath(config['CA'])
274 | tcptrans = config['tcptrans']
275 |
276 | if IPv6:
277 | ThreadingTCPServer.address_family = socket.AF_INET6
278 |
279 | try:
280 | for s, r_add, r_port, l_port in tcptrans:
281 | server = ThreadingTCPServer((LOCAL, l_port),TcpProxyClient)
282 | server.seradd = (SERVER, SERVER_PORT)
283 | server.r_sock = (r_add, r_port)
284 | print 'TCPTrans', l_port, 'to', server.r_sock[0],server.r_sock[1],'@',server.seradd[0]
285 | local_server(server).start()
286 | except socket.error, e:
287 | logging.error(e)
288 | except KeyboardInterrupt:
289 | server.shutdown()
290 | sys.exit(0)
291 |
292 | if __name__ == '__main__':
293 | main()
294 |
--------------------------------------------------------------------------------