-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathmix_proxy.py
More file actions
196 lines (167 loc) · 5.43 KB
/
mix_proxy.py
File metadata and controls
196 lines (167 loc) · 5.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#!/usr/bin/env python
#coding: utf-8
import os
import re
import ssl
import sys
import time
import json
import base64
import socket
import urlparse
import warnings
import requests
import threading
from hashlib import md5
warnings.filterwarnings("ignore")
'''
Mix proxy with HTTP and HTTPS.
Use local key file and cert file to get https flow.
If there is a "connect" method first, then https it is.
Else it's a http packet.
Request to remote server with python requests lib.
Function content_deal() is with a hook which can edit or save requests to somewhere.
Function res_deal() is whith a hook which can edit response to client.
'''
def https_things(sock):
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.load_cert_chain(certfile = "key.crt", keyfile = "key.pem")
connstream = context.wrap_socket(sock, server_side=True)
client_conn(connstream, True)
def print_help():
print 'Usage:'
print ' python %s (default 127.0.0.1) port' % sys.argv[0]
print ' python %s bind_address port' % sys.argv[0]
print 'Example:'
print ' python %s 10086' % sys.argv[0]
print ' python %s 127.0.0.1 10086' % sys.argv[0]
exit()
def get_str(res):
code = str(res.status_code)
reason = res.reason
data = ''
headers = res.headers
if 'Content-Encoding' in headers.keys():
del headers['Content-Encoding']
if 'Transfer-Encoding' in headers.keys():
del headers['Transfer-Encoding']
headers['Content-Length'] = len(res.content)
data += 'HTTP/1.1 %s %s\r\n' % (code, reason)
for key in res.headers.keys():
data += '%s: %s\r\n' % (key, headers[key])
data += '\r\n' + res.content
return data
def get_res(data, connstream, https):
try:
headers = {}
post = ''
if data[0:7] == 'CONNECT':
connstream.sendall("HTTP/1.1 200 Connection established\r\n\r\n")
https_things(connstream)
return
if not re.search('(GET|POST) (.*) HTTP',data):
return
methods = re.findall('(GET|POST) (.*) HTTP',data)[0]
url = methods[1]
method = methods[0]
if method == 'GET':
head = data.split('\r\n')[1:]
for h in head:
if ': ' in h[2:]:
headers[h.split(': ')[0]] = h.split(': ')[1]
host = headers['Host'].replace(' ', '')
if not https:
uri = url
else:
uri = "https://%s%s" % (host, url)
print uri
content_deal(headers, host, method, postdata = '', uri = uri)
if 'Host' in headers.keys():
del headers['Host']
res = requests.get(uri, headers = headers, verify = False)
response = get_str(res)
response = res_deal(response)
connstream.sendall(response)
connstream.close()
return
elif method == 'POST':
body = data.split('\r\n\r\n')[1]
head = data.split('\r\n\r\n')[0].split('\r\n')[1:]
for h in head:
if ': ' in h[2:]:
headers[h.split(': ')[0]] = h.split(': ')[1]
host = headers['Host'].replase(' ', '')
if not https:
uri = url
else:
uri = "https://%s%s" % (host, url)
print uri
content_deal(headers, host, method, postdata = body, uri = uri)
if 'Host' in headers.keys():
del headers['Host']
res = requests.post(uri, headers = headers, data = body, verify = False)
response = get_str(res)
response = res_deal(response)
connstream.sendall(response)
connstream.close()
return
except Exception, e:
if 'url' in dir():
print url
print "Http Error: " + str(e)
try:
err = "HTTP/1.1 500 Internal Server Error\r\n"
err += "Content-Length-Type: text/html;\r\n"
err += "Content-Length: 17\r\n\r\n"
err += "HTTP Error"
connstream.sendall()
connstream.close()
except Exception, e:
pass
finally:
return
def res_deal(response):
return response
def content_deal(headers, host, method, postdata, uri):
pass
def client_conn(connstream, https=False):
try:
connstream.settimeout(0.5)
data = ""
while True:
tmp = connstream.recv(10240)
data += tmp
if tmp == '':
break
except Exception, e:
pass
connstream.settimeout(10)
get_res(data, connstream, https)
def main(addr, port):
try:
bindsocket = socket.socket()
bindsocket.bind((addr, port))
bindsocket.listen(300)
except Exception, e:
print e
exit()
while True:
try:
connstream, fromaddr = bindsocket.accept()
t = threading.Thread(target = client_conn, args = (connstream,))
t.start()
except Exception, e:
print e
if 'connstream' in dir():
connstream.close()
if __name__ == '__main__':
port = 10086
addr = '127.0.0.1'
if len(sys.argv) == 1:
print_help()
if len(sys.argv) == 2:
port = int(sys.argv[1])
if len(sys.argv) >= 3:
port = int(sys.argv[2])
address = sys.argv[1]
main(addr, port)