-
Notifications
You must be signed in to change notification settings - Fork 2
/
proxy_setup.py
215 lines (188 loc) · 7.89 KB
/
proxy_setup.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
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
"""Script to set up proxy as a cache.
Author:
Jacinta Hu
About:
This script intercepts requests and responses to act as a local cache.
It alters the index.html file of webpages on the fly based on the request URL
to easily enable and disable scripts.
"""
import os
import hashlib
import binascii
import pickle
import mysql.connector
from mitmproxy import http
from bs4 import BeautifulSoup
from config import config
class LocalCache:
"""The local client-side cache."""
def __init__(self):
self.path = os.getcwd()
self.cnx = mysql.connector.connect(**config["mysql"])
cursor = self.cnx.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS js_analyzer;")
cursor.execute("USE js_analyzer;")
cursor.execute(
"CREATE TABLE IF NOT EXISTS `resource_location` ("
" `hashed_url` CHAR(64) NOT NULL PRIMARY KEY,"
" `full_url` VARCHAR(2000) NOT NULL,"
" `file_name` CHAR(32) NOT NULL,"
" `datetime` DATETIME NOT NULL"
")"
)
self.cnx.commit()
cursor.close()
def __del__(self):
self.cnx.close()
def random_filename(self):
"""Generate a new unique random filename for the cache."""
file_name = binascii.b2a_hex(os.urandom(15)).decode("utf-8")
while os.path.exists(self.path + "/cache/" + file_name + ".c"):
file_name = binascii.b2a_hex(os.urandom(15)).decode("utf-8")
return file_name
def request(self, flow: http.HTTPFlow):
"""Handle HTTP Request."""
js_tool = False
full_url = flow.request.pretty_url.split("?")[0]
if "?JSTool=" in flow.request.pretty_url:
full_url += "?JSTool"
js_tool = True
hashed_url = hashlib.sha256(full_url.encode()).hexdigest()
cursor = self.cnx.cursor()
cursor.execute(
"SELECT `file_name` FROM resource_location "
"WHERE `hashed_url` LIKE '%s'" %
(hashed_url)
)
result = cursor.fetchone()
if result:
# found in db
file_name = str(result[0])
file_path = self.path + "/cache/" + file_name
if js_tool:
# headers
with open(file_path + '.h', 'rb') as temp_file:
temp_headers = pickle.load(temp_file)
headers_dict = {}
for attr in list(temp_headers):
headers_dict[attr] = temp_headers[attr]
# make simplification
with open(file_path + '.c', 'rb') as temp_file:
temp_content = pickle.load(temp_file)
html = str(BeautifulSoup(temp_content, 'html.parser'))
active = flow.request.pretty_url.split(
"?JSTool=")[-1].split("_")
active = active[1:]
for num in active:
index = html.find("<!--script" + str(num) + "\n")
html = html.replace(
"<!--script" + str(num) + "\n", "<script")
html = html[0:index] + \
html[index:].replace("-->\n", "</script>", 1)
# return response
flow.response = http.HTTPResponse.make(
200, # (optional) status code
html, # (optional) content
headers_dict)
print("*" * 30)
print(full_url, "served from cache file", file_name)
else:
# delete existing entries
cursor.execute(
"DELETE FROM resource_location "
"WHERE `hashed_url` LIKE '%s'" %
(hashed_url)
)
try:
os.remove(file_path + '.h')
os.remove(file_path + '.c')
except FileNotFoundError:
pass
elif js_tool:
full_url = flow.request.pretty_url.split("?")[0]
hashed_url = hashlib.sha256(full_url.encode()).hexdigest()
cursor.execute(
"SELECT `file_name` FROM resource_location "
"WHERE `hashed_url` LIKE '%s'" %
(hashed_url)
)
result = cursor.fetchone()
if result:
# Add version with scripts removed to cache
file_name = str(result[0])
file_path = self.path + "/cache/" + file_name
with open(file_path + '.h', 'rb') as temp_file:
temp_headers = pickle.load(temp_file)
headers_dict = {}
for attr in list(temp_headers):
headers_dict[attr] = temp_headers[attr]
with open(file_path + '.c', 'rb') as temp_file:
temp_content = pickle.load(temp_file)
html = str(BeautifulSoup(temp_content, 'html.parser'))
# Remove comments
while "<!--" in html:
start_index = html.find("<!--")
end_index = html.find("-->") + 3
html = html.replace(html[start_index:end_index], "")
cnt = 1
while "<script" in html:
html = html.replace(
"<script", "\n<!--script" + str(cnt) + "\n", 1)
html = html.replace("</script>", "\n-->\n", 1)
print("cnt =", cnt)
cnt += 1
# return response
flow.response = http.HTTPResponse.make(
200, # (optional) status code
html, # (optional) content
headers_dict)
# add to database
full_url += "?JSTool"
hashed_url = hashlib.sha256(full_url.encode()).hexdigest()
file_name = self.random_filename()
file_path = self.path + "/cache/" + file_name
cursor.execute(
"INSERT INTO resource_location "
"(`hashed_url`, `full_url`, `file_name`, datetime) "
"VALUES ('%s', '%s', '%s', NOW())" %
(hashed_url, full_url, file_name)
)
self.cnx.commit()
# write to file
with open(file_path + '.h', 'wb') as temp_file:
pickle.dump(flow.response.headers, temp_file)
with open(file_path + '.c', 'wb') as temp_file:
pickle.dump(flow.response.content, temp_file)
cursor.close()
def response(self, flow: http.HTTPFlow):
"""Handle HTTP response."""
full_url = flow.request.pretty_url.split("?")[0]
if "?JSTool=" in flow.request.pretty_url:
full_url += "?JSTool=" + \
flow.request.pretty_url.split("?JSTool=")[-1]
hashed_url = hashlib.sha256(full_url.encode()).hexdigest()
cursor = self.cnx.cursor()
cursor.execute(
"SELECT `file_name` FROM resource_location "
"WHERE `hashed_url` LIKE '%s'" %
(hashed_url)
)
result = cursor.fetchone()
if not result:
# not yet in db
file_name = self.random_filename()
file_path = self.path + "/cache/" + file_name
cursor.execute(
"INSERT INTO resource_location "
"(`hashed_url`, `full_url`, `file_name`, datetime) "
"VALUES ('%s', '%s', '%s', NOW())" %
(hashed_url, full_url, file_name)
)
self.cnx.commit()
with open(file_path + '.h', 'wb') as temp_file:
pickle.dump(flow.response.headers, temp_file)
with open(file_path + '.c', 'wb') as temp_file:
pickle.dump(flow.response.content, temp_file)
cursor.close()
# pylint: disable=invalid-name
addons = [LocalCache()]