-
Notifications
You must be signed in to change notification settings - Fork 7
/
mitm.py
69 lines (58 loc) · 2.25 KB
/
mitm.py
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
import os
import json
import base64
import urllib.parse
from mitmproxy import ctx
special_prefix_token = os.environ.get("SPECIAL_PREFIX_TOKEN", "$$")
header_split_token = os.environ.get("HEADER_SPLIT_TOKEN", ":")
header_token = f"{special_prefix_token}headers[]"
post_token = f"{special_prefix_token}post"
class FlaresolverrProxy:
def handle_headers(self, flow):
if header_token in flow.request.query:
headers = flow.request.query.get_all(header_token)
for header in headers:
if not header_split_token in header:
continue
[key, value] = header.split(header_split_token, 1)
flow.request.headers[key] = value
flow.request.query.pop(header_token, None)
def handle_post_json(self, flow):
# Parse the post data
try:
form_data = urllib.parse.parse_qs(flow.request.get_text())
except Exception as e:
ctx.log.error(f"Failed to parse form data: {e}")
return
if post_token in form_data:
# Check if the form data contains the post token
if not post_token in form_data:
return
# Try to decode the post data
try:
# Ensure the string is correctly padded
missing_padding = len(form_data[post_token][0]) % 4
if missing_padding:
form_data[post_token][0] += '=' * (4 - missing_padding)
decoded_string = base64.b64decode(
form_data[post_token][0]).decode("utf-8")
except Exception as e:
return
# Try to parse the post data as JSON
try:
post_data = json.loads(decoded_string)
except Exception as e:
return
# Change header to JSON
flow.request.headers["Content-Type"] = "application/json"
# Set the JSON data as the request body
flow.request.set_text(json.dumps(post_data))
def request(self, flow):
# Handle headers
self.handle_headers(flow)
# Handle post json if needed
if flow.request.method == "POST":
self.handle_post_json(flow)
addons = [
FlaresolverrProxy()
]