-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBasicProxyHTTPServer.py
More file actions
executable file
·283 lines (221 loc) · 7.06 KB
/
BasicProxyHTTPServer.py
File metadata and controls
executable file
·283 lines (221 loc) · 7.06 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#!/bin/env python
'''
proxy based on https://pypi.python.org/pypi/ProxyHTTPServer/
'''
import BaseHTTPServer, httplib, SocketServer, urllib, hashlib, urlparse
from base64 import b64decode
class DecodeError(Exception):
pass
class BasicAuthHandler:
"""Handler for performing basic authentication."""
def __init__(self):
self._request_num = 0
self._users = {}
self._realm_name = "lugh.localdomain"
def set_users(self, users):
assert isinstance(users, dict)
self._users = users
def set_realm(self, realm):
self._realm_name = realm
def _create_auth_dict(self, auth_str):
# Remove the "Basic " part.
first_space_index = auth_str.find(" ")
auth_str = auth_str[first_space_index+1:]
# auth_str now looks like nmVubfk652Vj1mV0
try:
username, password = b64decode(auth_str).split(':')
except:
raise DecodeError
return { "username" : username, "password" : password }
def _return_auth_challenge(self, request_handler):
request_handler.send_response(407, "Proxy Authentication Required")
request_handler.send_header("Content-Type", "text/html")
request_handler.send_header('Proxy-Authenticate', 'Basic realm="%s"' % (self._realm_name))
# XXX: Not sure if we're supposed to add this next header or
# not.
#request_handler.send_header('Connection', 'close')
request_handler.end_headers()
request_handler.wfile.write("Proxy Authentication Required.")
return False
def handle_request(self, request_handler):
"""Performs basic authentication on the given HTTP request
handler. Returns True if authentication was successful, False
otherwise.
If no users have been set, then basic auth is effectively
disabled and this method will always return True.
"""
if len(self._users) == 0:
return True
if 'Proxy-Authorization' not in request_handler.headers:
return self._return_auth_challenge(request_handler)
else:
auth_dict = self._create_auth_dict(request_handler.headers['Proxy-Authorization'])
if auth_dict["username"] in self._users:
password = self._users[ auth_dict["username"] ]
else:
return self._return_auth_challenge(request_handler)
auth_validated = False
if password == auth_dict["password"]:
auth_validated = True
if not auth_validated:
return self._return_auth_challenge(request_handler)
return True
class ProxyHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
basic_auth_handler = BasicAuthHandler()
def doCommon(self):
(scm, netloc, path, params, query, fragment) = urlparse.urlparse(self.path, 'http')
self.short_path = path
if self.basic_auth_handler.handle_request(self):
req = Request(self)
req.delHeaders("accept-encoding", "host", "proxy-connection")
res = req.getResponse()
res.delHeader("transfer-encoding")
res.toClient()
def do_GET(self):
self.doCommon()
def do_POST(self):
self.doCommon()
class Request:
def __init__(self, proxy):
self.proxy = proxy
self.host = proxy.headers.getheader("host")
self.command = proxy.command
self.path = proxy.path
self.headers = proxy.headers.dict
self.conn = httplib.HTTPConnection(self.host)
if self.command == "POST":
self.body = self.proxy.rfile.read(\
int(self.proxy.headers.getheader("content-length")) )
else:
self.body = None
def getHeader(self, k):
if self.headers.has_key(k):
return self.headers[k]
else:
return None
def setHeader(self, k, v):
self.headers[k] = v
def setHeaders(self, dict):
for i in dict.items():
self.setHeader(i[0], i[1])
def delHeader(self, k):
if self.headers.has_key(k):
del self.headers[k]
def delHeaders(self, *list):
for l in list:
self.delHeader(l)
def bodyDecode(self):
m = MapList()
for b in self.body.split("&"):
for p in b.split("="):
if p != "":
m.add(urllib.unquote_plus(p[0]),
urllib.unquote_plus(p[1]))
return m
def bodyEncode(self, mapList):
body = ""
for k in mapList.keys():
for l in mapList.getList(k):
body += "%s=%s&" % (urllib.quote_plus(k),
urllib.quote_plus(l))
if body == "":
self.body = None
else:
self.body = body[:-1]
def getResponse(self):
if self.body:
self.headers["content-length"] = str(len(self.body))
self.conn.request("POST", self.path, self.body, self.headers)
else:
self.conn.request("GET", self.path, headers=self.headers)
return Response(self.proxy, self.conn.getresponse())
class Response:
def __init__(self, proxy, server):
self.proxy = proxy
self.server = server
self.status = server.status
self.body = server.read()
self.headers = MapList()
for l in server.getheaders():
self.headers.add(l[0], l[1])
def getHeader(self, k, index=-1):
if self.headers.hasKey(k, index):
return self.headers.get(k, index)
else:
return None
def setHeader(self, k, v, index=-1):
self.headers.set(k, v, index)
def addHeader(self, k, v):
self.headers.add(k, v)
def addHeaders(self, dict):
for i in dict.items():
self.setHeader(i[0], i[1])
def delHeader(self, k):
if self.headers.hasKey(k):
self.headers.delMap(k)
def delHeaders(self, *list):
for l in list:
self.delHeader(l)
def toClient(self):
self.proxy.send_response(self.status)
for k in self.headers.keys():
for l in self.headers.getList(k):
self.proxy.send_header(k, l)
self.proxy.end_headers()
self.proxy.wfile.write(self.body)
class MapList:
def __init__(self):
self.map = {}
def __str__(self):
return str(self.map)
def add(self, k, v):
if self.map.has_key(k):
self.map[k].append(v)
else:
self.map[k] = [v]
def set(self, k, v, index=-1):
if self.map.has_key(k):
self.map[k][index] = v
else:
self.map[k] = [v]
def get(self,k, index=-1):
return self.map[k][index]
def getList(self,k):
return self.map[k]
def delMap(self, k):
if self.map.has_key(k):
del self.map[k]
def delList(self, k, index=-1):
if self.map.has_key(k):
del self.map[k][index]
def hasKey(self, k, index=-1):
if self.map.has_key(k):
l = self.map[k]
if index < 0:
index += 1
if len(l) > abs(index):
return True
return False
def keys(self):
return self.map.keys()
def mapSize(self):
return len(self.map)
def listSize(self, k):
if self.map.has_key(k):
return len(self.map[k])
else:
return 0
def size(self):
size = 0
for i in self.map.items():
size += len(i[1])
return size
class ThreadingHTTPServer(SocketServer.ThreadingTCPServer, BaseHTTPServer.HTTPServer):
pass
def test(HandlerClass = ProxyHTTPRequestHandler,
ServerClass = ThreadingHTTPServer):
ProxyHTTPRequestHandler.basic_auth_handler.set_users({'jenny':'supersecret'})
ProxyHTTPRequestHandler.basic_auth_handler.set_realm('lugh.localdomain')
BaseHTTPServer.test(HandlerClass, ServerClass)
if __name__ == '__main__':
test()