-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsimple_proxy.py
More file actions
346 lines (256 loc) · 11.6 KB
/
simple_proxy.py
File metadata and controls
346 lines (256 loc) · 11.6 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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#!/usr/bin/python3
import os, sys, socket, textwrap, threading, zlib, ssl, gzip
from datetime import datetime
BUFLEN = 65535
TIMEOUT = 60
PROXY_TRACE = os.getenv("PROXY_TRACE") is not None
def debugTrace(*args):
if PROXY_TRACE :
print(*args)
class SimpleProxy:
def __init__(self, localHostPort, targetHostPort, sslTarget):
print("Listening on %s -> relaying to %s [http%s]" % (localHostPort, targetHostPort, "s" if sslTarget else ""))
self.localHostPort = localHostPort.encode("utf-8")
self.targetHostPort = targetHostPort.encode("utf-8")
self.sslTarget = sslTarget
# Bind to listening socket
soc = socket.socket(socket.AF_INET)
soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if b":" in self.localHostPort :
localHost, localPort = self.localHostPort.split(b":")
localPort = int(localPort)
else:
localHost, localPort = self.localHostPort, 80
soc.bind((localHost, localPort))
# Client = originator, target = destination server
self.proxy = soc
self.printLock = threading.Lock()
def run(self):
while True:
# Wait for connection until proxy killed
self.proxy.listen(0)
self.client, self.remoteInfo = self.proxy.accept()
self.client.settimeout(TIMEOUT)
debugTrace("Client request received and accepted")
threading.Thread(target=ProxyHandler, args=(self.client, self.printLock, self.localHostPort, self.targetHostPort, self.sslTarget)).start()
class ProxyHandler:
def __init__(self, client, printLock, localHostPort, targetHostPort, sslTarget):
self.client = client
self.localHostPort = localHostPort
self.targetHostPort = targetHostPort
self.printLock = printLock
self.sslTarget = sslTarget
self.targetConnect()
# Read/Write until close
while True:
# Read from client and send to target
if not self.readHttp(self.client) : break
if self.httpBody and self.encoding == "gzip" : self.unGzipBody()
if self.sslTarget : self.substituteSchema()
self.substituteHostName()
self.dumpHttp('>>> SENT')
self.original = self.httpCommand
if self.httpBody and self.encoding == "gzip" : self.gzipBody()
if self.contentLength and self.contentLength != len(self.httpBody) : self.updateContentLengthHeader()
self.writeHttp(self.target)
# Read response from target and send back to client
self.readHttp(self.target)
if self.httpBody and self.encoding == "gzip" : self.unGzipBody()
self.dumpHttp('<<< RECEIVED')
if self.sslTarget : self.substituteSchema(forward=False)
self.substituteHostName(forward=False)
if self.httpBody and self.encoding == "gzip" : self.gzipBody()
if self.contentLength and self.contentLength != len(self.httpBody) : self.updateContentLengthHeader()
self.writeHttp(self.client)
def readHttp(self, soc):
debugTrace("readHttp")
inBuffer = b''
chunkBuffer = b''
overHead = 0
self.httpCommand = None
self.httpHeader = None
self.headerProcessed = False
self.contentLength = None
self.encoding = None
self.chunk = False
while True:
try:
inBuffer += soc.recv(BUFLEN)
if len(inBuffer) == 0 : return False
debugTrace("Read %i bytes" % len(inBuffer))
except KeyboardInterrupt :
print(len(inBuffer))
print(inBuffer)
sys.exit(1)
except socket.timeout :
return False
if not self.httpCommand :
i = inBuffer.find(b"\r\n")
if i != -1 :
self.httpCommand = inBuffer[:i].split()
try:
inBuffer = inBuffer[i+2:]
except:
inBuffer = b''
overHead = i+2
if not self.httpHeader :
i = inBuffer.find(b"\r\n\r\n")
if i != -1 :
self.httpHeader = inBuffer[:i]
try:
inBuffer = inBuffer[i+4:]
except:
inBuffer = b''
overHead += i+4
if self.httpHeader and not self.headerProcessed:
self.contentType = self.lookForHeaderValue(b"Content-Type")
self.contentLength = self.lookForHeaderValue(b"Content-Length") or 0
if self.contentLength :
self.contentLength = int(self.contentLength)
debugTrace("Expected content length = ", self.contentLength)
self.encoding = self.lookForHeaderValue(b"Content-Encoding")
if self.lookForHeaderValue(b"Transfer-Encoding") :
self.chunk = self.lookForHeaderValue(b"Transfer-Encoding") == "chunked"
self.headerProcessed = True
if self.chunk :
debugTrace("Chunk received")
if inBuffer.endswith(b"\r\n0\r\n\r\n") :
self.httpBody = inBuffer
return True
elif self.contentLength == 0 or (self.contentLength and len(inBuffer)+overHead >= self.contentLength) :
self.httpBody = inBuffer
return True
def assembleChunks(self, inBuffer):
debugTrace("assembleChunk")
outBuffer = b''
while True:
try:
i = inBuffer.find(b"\r\n")
if i == -1: return outBuffer
size = int(inBuffer[:i], 16)
if size == 0 : return outBuffer
inBuffer = inBuffer[i+2:]
outBuffer += inBuffer[:size]
inBuffer = inBuffer[size+2:]
except:
import pdb
pdb.set_trace()
def targetConnect(self):
debugTrace("targetConnect")
if b":" in self.targetHostPort :
targetHost, targetPort = targetHostPort.split(b":")
targetPort = int(targetPort)
else:
targetHost, targetPort = targetHostPort, (80 if not self.sslTarget else 443)
(soc_family, _, _, _, address) = socket.getaddrinfo(targetHost, targetPort)[0]
soc = socket.socket(soc_family)
soc.connect(address)
soc.settimeout(TIMEOUT)
if self.sslTarget :
self.target = ssl.wrap_socket(soc)
else :
self.target = soc
def lookForHeaderValue(self, header):
debugTrace("lookForHeaderValue ", header)
headers = self.httpHeader.splitlines()
for h in headers :
i = h.find(b":")
name, value = h[:i], h[i+1:]
if name.upper() == header.upper().strip() :
return value.strip().decode("utf-8")
return None
def substituteHostName(self, forward=True):
debugTrace("substituteHostName ", forward)
def condReplace(s, lF, rB):
start = 0
shift = len(lF)
i = s.find(lF, start)
while i != -1 :
start = i+1
if s[i-1] != 46 :
s = s[:i] + rB + s[i+shift:]
i = s.find(lF, start)
return s
if forward :
lookFor, replaceBy = self.localHostPort, self.targetHostPort
else:
lookFor, replaceBy = self.targetHostPort, self.localHostPort
self.httpHeader = condReplace(self.httpHeader, lookFor, replaceBy)
if self.httpBody : self.httpBody = condReplace(self.httpBody, lookFor, replaceBy)
def substituteSchema(self, forward=True):
debugTrace("substituteSchema")
if forward :
lookFor, replaceBy = b"http://" + self.localHostPort, b"https://" + self.targetHostPort
else :
lookFor, replaceBy = b"https://" + self.targetHostPort, b"http://" + self.localHostPort
self.httpHeader = self.httpHeader.replace(lookFor, replaceBy)
if self.httpBody : self.httpBody = self.httpBody.replace(lookFor, replaceBy)
def writeHttp(self, soc):
debugTrace("writeHttp")
outBuffer = b" ".join(self.httpCommand) + b"\r\n" + self.httpHeader + b"\r\n\r\n"
if self.httpBody : outBuffer += self.httpBody
soc.send(outBuffer)
def unGzipBody(self) :
debugTrace("unGzipBody")
if self.chunk :
self.httpBody = gzip.decompress(self.assembleChunks(self.httpBody))
else:
self.httpBody = gzip.decompress(self.httpBody)
def gzipBody(self):
debugTrace("gzipBody")
body = gzip.compress(self.httpBody)
if self.chunk :
hexSize = hex(len(body))[2:].encode("ascii")
self.httpBody = hexSize + b"\r\n" + body
else:
self.httpBody = body
def updateContentLengthHeader(self):
self.contentLength = len(self.httpBody)
headers = self.httpHeader.splitlines()
for h in list(headers) :
if h.lower().startswith(b"Content-Length") :
headers.remove(h)
headers.add(b"Content-Length: "+str(self.contentLength).encode("ascii"))
break
self.httpHeader = b"\r\n".join(headers)
def dumpHttp(self, direction):
try:
self.printLock.acquire()
print("\n"+"*"*120)
print('%-15s %s : %s\n' % (direction, datetime.isoformat(datetime.now()), (b" ".join(self.httpCommand)).decode("utf-8")))
if direction[0] == '<' :
print(" "*44, "Response to : ", (b" ".join(self.original)).decode("utf-8"))
print()
print('Headers:')
for l in self.httpHeader.splitlines():
i = l.find(b":")
print('\t%25s : %s' % (l[:i].decode("utf-8"), l[i+1:].decode("utf-8")))
if self.httpBody :
print('\nBody:')
if "text" not in self.contentType and "xml" not in self.contentType and "urlencod" not in self.contentType :
print("\nBinary body content, size = ", self.contentLength)
elif self.contentLength > 40000 or len(self.httpBody) > 40000 :
print("\nLarge body skipped, size = ", self.contentLength if self.contentLength else len(self.httpBody))
elif self.encoding not in ["deflate"] :
encoding = self.encoding
if encoding == "gzip" :
try:
encoding = contentType.split(";")[1].split("=")[1]
except:
encoding = "latin1"
for l in self.httpBody.decode(encoding or "latin1").splitlines() :
for ll in textwrap.wrap(l, width=120):
print('\t', ll)
else :
print("Body non printable")
except Exception as e:
print("dumpHttp Exception : ", e)
finally:
self.printLock.release()
if __name__ == '__main__':
# Get required parameters, only PROXY_TARGET_HOST is mandatory
localHostPort = os.getenv("PROXY_LOCAL") or "localhost:8880"
targetHostPort = os.getenv("PROXY_TARGET")
sslTarget = os.getenv("PROXY_SSL") is not None
proxy = SimpleProxy(localHostPort, targetHostPort, sslTarget)
proxy.run()