-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathproxy_engine.py
More file actions
371 lines (302 loc) · 11.4 KB
/
Copy pathproxy_engine.py
File metadata and controls
371 lines (302 loc) · 11.4 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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import asyncio
import time
import socketio
import mitmproxy.http
import mitmproxy.tcp
from mitmproxy import ctx
from mitmproxy.options import Options
from mitmproxy.tools.dump import DumpMaster
from mitmproxy.connection import Client, Server
MAIN_SERVER = "http://127.0.0.1:80"
sio = socketio.Client()
class DranaInterceptorAddon:
def __init__(self, loop):
self.loop = loop
self._silent_replay = {}
while True:
try:
sio.connect(MAIN_SERVER)
print("[Proxy] Connected to Main Server")
break
except Exception:
print("[Proxy] Waiting for Main Server...")
time.sleep(2)
sio.on("trigger_replay_in_engine", self.handle_replay)
sio.on("silent_replay_request_engine", self.handle_silent_replay)
def extract_project_uuid(self, request):
project_uuid = None
if not request:
return "uncategorized"
ua = request.headers.get("User-Agent", "")
if "DranaProject/" in ua:
try:
parts = ua.split("DranaProject/")
if len(parts) > 1:
project_uuid = parts[1].split(" ")[0].strip()
except:
pass
if not project_uuid:
project_uuid = request.headers.get("X-Drana-Project")
return project_uuid or "uncategorized"
def handle_replay(self, data):
asyncio.run_coroutine_threadsafe(
self.safe_replay(data),
self.loop
)
async def safe_replay(self, data):
try:
await asyncio.wait_for(
self.replay_from_raw(
raw_text=data.get("new_request", ""),
flow_type=data.get("type", "http"),
flow_id=data.get("flow_id")
),
timeout=10
)
except Exception as e:
sio.emit("resend_response_update", {
"flow_id": data.get("flow_id"),
"error": True,
"message": str(e),
"done": True
})
async def replay_from_raw(self, raw_text, flow_type, flow_id):
if not raw_text.strip():
return
if flow_type.lower() == "tcp":
sio.emit("resend_response_update", {
"status": "TCP",
"headers": "TCP replay not supported statelessly",
"content": raw_text
})
return
self.replay_http_https(raw_text, flow_id)
def replay_http_https(self, raw_text, flow_id):
lines = raw_text.splitlines()
method, path, _ = lines[0].split(" ", 2)
headers = {}
body = b""
in_body = False
for line in lines[1:]:
if line.strip() == "":
in_body = True
continue
if in_body:
body += line.encode() + b"\n"
else:
if ":" in line:
k, v = line.split(":", 1)
headers[k.strip()] = v.strip()
host = headers.get("Host")
if not host:
raise Exception("Replay failed: Host header missing")
scheme = "https" if headers.get(":scheme") == "https" else "http"
port = 443 if scheme == "https" else 80
if ":" in host:
host, port = host.split(":", 1)
port = int(port)
req = mitmproxy.http.Request.make(
method=method,
url=f"{scheme}://{host}{path}",
headers=headers,
content=body,
)
client = Client(peername=("127.0.0.1", 0), sockname=("127.0.0.1", 0))
server = Server(address=(host, port))
flow = mitmproxy.http.HTTPFlow(client, server)
flow.request = req
flow.metadata["drana_replay_ui_id"] = flow_id
ctx.master.commands.call("replay.client", [flow])
print(f"[Proxy] Replayed {method} {host}{path}")
def _build_replay_flow(self, raw_text):
lines = raw_text.splitlines()
method, path, _ = lines[0].split(" ", 2)
headers = {}
body = b""
in_body = False
for line in lines[1:]:
if line.strip() == "" and not in_body:
in_body = True
continue
if in_body:
body += line.encode() + b"\n"
elif ":" in line:
k, v = line.split(":", 1)
headers[k.strip()] = v.strip()
host = headers.get("Host")
if not host:
raise Exception("Host header missing")
scheme = "https" if headers.get(":scheme") == "https" else "http"
port = 443 if scheme == "https" else 80
if ":" in host:
host, port = host.split(":", 1)
port = int(port)
req = mitmproxy.http.Request.make(
method=method,
url=f"{scheme}://{host}{path}",
headers=headers,
content=body,
)
client = mitmproxy.connection.Client(
peername=("127.0.0.1", 0),
sockname=("127.0.0.1", 0)
)
server = mitmproxy.connection.Server(address=(host, port))
flow = mitmproxy.http.HTTPFlow(client, server)
flow.request = req
return flow
def process_flow(self, flow, type_label, override_id=None):
request = flow.request if hasattr(flow, "request") else None
response = flow.response if hasattr(flow, "response") else None
project_uuid = self.extract_project_uuid(request)
if request and "Drana-Katana-Crawler" in request.headers.get("User-Agent", ""):
fetch_dest = request.headers.get("Sec-Fetch-Dest")
if fetch_dest and fetch_dest != "document":
return
summary = {
"time": time.strftime("%H:%M:%S"),
"scheme": type_label,
"method": request.method if request else type_label,
"host": request.host if request else "Unknown",
"path": request.path if request else "",
"status": response.status_code if response else 0,
"content_type": response.headers.get("Content-Type", "").split(";")[0] if response else "-",
"size": f"{len(response.content)}B" if response and response.content else "0B",
"time_taken": "0ms"
}
req_raw = ""
if request:
host_header = f"Host: {request.host}\n" if "Host" not in request.headers else ""
req_raw = (
f"{request.method} {request.path} HTTP/{request.http_version}\n"
f"{host_header}"
+ "\n".join(f"{k}: {v}" for k, v in request.headers.items())
+ "\n\n"
+ request.get_text(strict=False)
)
res_raw = ""
if response:
res_raw = (
f"HTTP/{request.http_version} {response.status_code}\n"
+ "\n".join(f"{k}: {v}" for k, v in response.headers.items())
+ "\n\n"
+ response.get_text(strict=False)
)
final_id = override_id if override_id else flow.id
event_type = "update_request_data" if override_id else "new_request_data"
sio.emit(event_type, {
"id": final_id,
"project_id": project_uuid,
"type": type_label.lower(),
"summary": summary,
"full_data": {
"request_raw_text": req_raw,
"response_raw_text": res_raw
}
})
def response(self, flow: mitmproxy.http.HTTPFlow):
if flow.metadata.get("__silent_replay__"):
fut = self._silent_replay.get(flow.id)
if fut and not fut.done():
raw_response = (
f"HTTP/{flow.response.http_version} {flow.response.status_code}\n"
+ "\n".join(f"{k}: {v}" for k, v in flow.response.headers.items())
+ "\n\n"
+ flow.response.get_text(strict=False)
)
fut.set_result({
"status": flow.response.status_code,
"body": raw_response
})
return
elif flow.metadata.get("drana_replay_ui_id"):
self.process_flow(
flow,
"HTTPS" if flow.request.scheme == "https" else "HTTP",
override_id=flow.metadata["drana_replay_ui_id"]
)
sio.emit("resend_response_update", {
"flow_id": flow.metadata["drana_replay_ui_id"],
"status": flow.response.status_code,
"headers": "\n".join(f"{k}: {v}" for k, v in flow.response.headers.items()),
"content": flow.response.get_text(strict=False),
"done": True
})
return
self.process_flow(
flow,
"HTTPS" if flow.request.scheme == "https" else "HTTP"
)
def tcp_message(self, flow: mitmproxy.tcp.TCPFlow):
sio.emit("new_request_data", {
"id": flow.id,
"project_id": "uncategorized",
"type": "tcp",
"summary": {
"time": time.strftime("%H:%M:%S"),
"scheme": "TCP",
"method": "TCP",
"host": "Unknown",
"path": "",
"status": "-",
"content_type": "-",
"size": "0B",
"time_taken": "0ms"
},
"full_data": {
"request_raw_text": flow.messages[-1].content.decode("utf-8", "replace"),
"response_raw_text": ""
}
})
def handle_silent_replay(self, data):
asyncio.run_coroutine_threadsafe(
self._handle_silent_replay(data),
self.loop
)
async def _handle_silent_replay(self, data):
request_id = data.get("id")
raw_request = data.get("raw_request")
if not raw_request:
sio.emit("silent_replay_response_engine", {
"id": request_id,
"error": "Empty raw_request"
})
return
try:
result = await self.silent_replay(raw_request)
sio.emit("silent_replay_response_engine", {
"id": request_id,
"result": result
})
except Exception as e:
sio.emit("silent_replay_response_engine", {
"id": request_id,
"error": str(e)
})
async def silent_replay(self, raw_request: str, timeout=10):
flow = self._build_replay_flow(raw_request)
flow.metadata["__silent_replay__"] = True
fut = self.loop.create_future()
self._silent_replay[flow.id] = fut
ctx.master.commands.call("replay.client", [flow])
try:
return await asyncio.wait_for(fut, timeout)
finally:
self._silent_replay.pop(flow.id, None)
if __name__ == "__main__":
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
opts = Options(
listen_host="127.0.0.1",
listen_port=8080,
http2=True,
ssl_insecure=True
)
master = DumpMaster(opts, loop=loop, with_termlog=False)
master.options.flow_detail = 0
master.addons.add(DranaInterceptorAddon(loop))
print("[Proxy] Drana Interceptor running on 127.0.0.1:8080 (HTTP / HTTPS / HTTP2)")
try:
loop.run_until_complete(master.run())
except KeyboardInterrupt:
master.shutdown()