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
|
import socket
import threading
from urllib.parse import parse_qs, urlparse
from flask import Flask, request,render_template
import unicodedata
BLACKLIST_KEYWORDS = [
'write', 'eval', 'assert', 'read', 'exec', 'apply', 'locals', 'load_module', 'json.loads', 'urllib.request.urlopen', 'subprocess', 'threading', 'tempfile', 'run', 'yield', 'inspect', 'netrc', 'globals', 'os', 'urandom', 'register', 'breakpoint', 'environ', 'str.format_map', 'tarfile', 'traceback', 'open', 'listen', 'info_leak', 'vars', 'exec_hook',
'__import__', 'exec', 'eval', 'compile', 'open', 'input', 'raw_input', 'getattr', 'setattr', 'delattr', 'hasattr', 'globals', 'locals', 'vars', 'dir', 'help', 'license', 'copyright', 'credits', 'exit', 'quit', 'breakpoint', 'os', 'sys', 'subprocess', 'commands', 'popen', 'popen2', 'popen3', 'popen4', 'system',
'popen', 'spawn', 'fork', 'execve', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'startfile', 'remove', 'unlink', 'rmdir', 'mkdir', 'chdir', 'chmod', 'chown', 'rename', 'replace', 'walk', 'listdir', 'stat', 'fstat', 'lstat', 'getenv', 'putenv', 'environ', 'system',
'urandom', 'socket', 'urllib', 'urllib2', 'requests', 'http', 'ftplib', 'smtplib', 'socketserver', 'http.server', 'xmlrpc', 'jsonrpc', 'pickle', 'marshal', 'load', 'loads', 'dump', 'dumps', 'class', 'base', 'mro', '__subclasses__', '__dict__', '__globals__',
'__builtins__', '__getattribute__', '__getattr__', '__setattr__', '__delattr__', '__code__', '__closure__', '__func__', '__self__', '__module__', '__name__', '__qualname__', '__file__', '__loader__', '__spec__', '__package__', '__doc__', '__annotations__', '__kwdefaults__',
'__defaults__', '()', '[]', '{}', '.', 'lambda', 'yield', 'from', 'import', 'True.__class__', '"".__class__', '0.__class__', '().__class__', '[].__class__', '{}.__class__', 'pathlib', 'shutil', 'tempfile', 'glob', 'zipfile', 'tarfile', 'inspect', 'dis', 'types', 'imp',
'importlib', 'pkgutil', 'site', 'builtins', '__builtin__', 'main', '__main__', 'chr', 'ord', 'hex', 'oct', 'bin', 'repr', 'ascii', 'eval', 'exec', 'compile', 'memoryview', 'bytearray', 'bytes', 'str', 'int', 'float', '().__class__.__base__', '().__class__.__mro__',
'().__class__.__subclasses__', '().__class__.__init__', '().__class__.__dict__', '().__class__.__getattribute__', '().__class__.__bases__[0].__subclasses__()', 'del', 'global', 'nonlocal', 'assert', 'with', 'as', 'try', 'except', 'finally', 'raise', 'import', 'from', 'while', 'for', 'if',
'else', 'elif', 'def', 'class', 'return', 'yield', 'await', 'async', 'print', 'format', 'input', 'id', 'type', 'isinstance', 'issubclass', 'pickle.loads', 'marshal.loads', 'yaml.load', 'json.loads', 'evaljs', 'execjs', 'shell', 'run', 'call', 'check_output', 'Popen',
'check_call', 'getoutput', 'getstatusoutput', "url","config","read","sub","get",'\\x', '\\u', '\\U', '\\N', '\\', 'encode', 'decode', 'replace', 'join', 'split', 'format', 'translate', 'maketrans', 'getattr(', 'vars(', 'locals(', 'globals(', 'dir(', 'eval(', 'exec(', 'compile(', 'open(', '__import__(',
'().__', '"".__', '0.__', '().__class__(', '[].__class__(', '{}.__class__(', '_', '{', '}', '[', ']', '(', ')', '=', '<', '>', ':', ';', ',', '"', "'", '\\', '|', '`', '~', '!', '@', '#', '$', '%', '^', '&', '?',
'\n', '\r', '\t', '\f', '\v', '\x00', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\x08', '\x0b', '\x0c', '\x0e', '\x0f', '\x10', '\x11', '\x12', '\x13', '\x14', '\x15', '\x16', '\x17', '\x18', '\x19', '\x1a', '\x1b', '\x1c', '\x1d', '\x1e', '\x1f',
'\u200b', '\u200c', '\u200d', '\u200e', '\u200f', '\u202a', '\u202b', '\u202c', '\u202d', '\u202e', '\u2060', '\u2061', '\u2062', '\u2063', '\u2064', '\ufeff', '\\x', '\\u', '\\U', '\\N{', '0x', '0o', '0b', '%', 'f"', "f'", 'b"', "b'", 'r"', "r'", ' ', '.', '__',
'#', '--', '/*', '*/', '//', ';--', ';#', '\\v', '\\t', '\\r', '\\n', '\\b', '\\a', '\\f','ev', 'ex', 'ch', 'ge', 'b6', 'un', 'co', '__b', '__g', '__s', '__d', '__m', '__c'
]
def to_halfwidth(s): //全角字符规范化:防止全角绕过
s = unicodedata.normalize('NFKC', s)
result = []
for char in s:
code = ord(char)
if 0xFF21 <= code <= 0xFF3A:
result.append(chr(code - 0xFF21 + 0x41))
elif 0xFF41 <= code <= 0xFF5A:
result.append(chr(code - 0xFF41 + 0x61))
elif 0xFF10 <= code <= 0xFF19:
result.append(chr(code - 0xFF10 + 0x30))
elif code in {0xFF08, 0xFF5F}:
result.append('(')
elif code in {0xFF09, 0xFF60}:
result.append(')')
elif code == 0xFF3B:
result.append('[')
elif code == 0xFF3D:
result.append(']')
elif code == 0xFF5B:
result.append('{')
elif code == 0xFF5D:
result.append('}')
elif code == 0xFF01:
result.append('!')
elif code == 0xFF0C:
result.append(',')
elif code == 0xFF1B:
result.append(';')
elif code == 0xFF1A:
result.append(':')
elif code in {0x3002, 0xFF0E}:
result.append('.')
elif code == 0xFF1F:
result.append('?')
elif code == 0xFF0F:
result.append('/')
elif code == 0xFF02:
result.append('"')
elif code == 0xFF07:
result.append("'")
else:
result.append(char)
return ''.join(result)
def parse_headers(headers):
header_dict = {}
for line in headers:
if ':' in line:
key, value = line.split(':', 1)
header_dict[key.strip().lower()] = value.strip()
return header_dict
def check_params_for_secret(params):
for key, values in params.items():
for value in values:
value_normalized = to_halfwidth(value).lower()
for keyword in BLACKLIST_KEYWORDS:
if keyword in value_normalized:
return True
return False
def handle_client(client_socket):
TIMEOUT_SECONDS = 5
try:
client_socket.settimeout(TIMEOUT_SECONDS)
request_data = b""
header_end_idx = -1
while header_end_idx == -1:
chunk = client_socket.recv(4096)
if not chunk:
client_socket.close()
return
request_data += chunk
header_end_idx = request_data.find(b'\r\n\r\n')
try:
header_end_idx = request_data.find(b'\r\n\r\n')
if header_end_idx == -1:
raise ValueError("Malformed request")
header_bytes = request_data[:header_end_idx]
headers_raw = header_bytes.decode('utf-8', errors='ignore').split('\r\n')
request_line = headers_raw[0]
method, path, version = request_line.split(maxsplit=2)
except Exception:
client_socket.close()
return
headers = parse_headers(headers_raw[1:])
url_parts = urlparse(path)
query_params = parse_qs(url_parts.query)
has_secret = check_params_for_secret(query_params)
if method.upper() == 'POST':
content_length = int(headers.get('content-length', '0'))
transfer_encoding = headers.get('transfer-encoding', '').lower().strip()
body_start = header_end_idx + 4
body_data = request_data[body_start:] if len(request_data) > body_start else b''
if transfer_encoding:
body_buffer = b""
remaining_data = body_data
while True:
if b'\r\n' not in remaining_data:
more = client_socket.recv(4096)
if not more:
break
remaining_data += more
continue
size_line, rest = remaining_data.split(b'\r\n', 1)
try:
chunk_size = int(size_line.strip(), 16)
except ValueError:
break
if chunk_size == 0:
if rest.startswith(b'\r\n'):
break
else:
while len(rest) < 2:
more = client_socket.recv(4096)
if not more:
break
rest += more
if rest.startswith(b'\r\n'):
break
else:
break
needed = chunk_size + 2
while len(rest) < needed:
more = client_socket.recv(min(4096, needed - len(rest)))
if not more:
break
rest += more
chunk_data = rest[:chunk_size]
body_buffer += chunk_data
remaining_data = rest[chunk_size + 2:]
body_str = body_buffer.decode('utf-8', errors='ignore')
post_params = parse_qs(body_str)
has_secret = has_secret or check_params_for_secret(post_params)
elif content_length > 0:
while len(body_data) < content_length:
chunk = client_socket.recv(min(4096, content_length - len(body_data)))
if not chunk:
break
body_data += chunk
try:
body_str = body_data.decode('utf-8', errors='ignore')
post_params = parse_qs(body_str)
has_secret = has_secret or check_params_for_secret(post_params)
except Exception:
pass
if has_secret:
response = (
"HTTP/1.1 403 Forbidden\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n"
"\r\n"
"We are all just trying our best to live"
)
client_socket.send(response.encode())
client_socket.close()
return
try:
backend_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
backend_socket.settimeout(TIMEOUT_SECONDS)
backend_socket.connect(('localhost', 3001)) # 连接到Flask后端
backend_socket.sendall(request_data) # 转发原始请求
while True:
response_chunk = backend_socket.recv(4096)
if not response_chunk:
break
client_socket.sendall(response_chunk)
backend_socket.close()
except socket.timeout:
response = (
"HTTP/1.1 504 Gateway Timeout\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n"
"\r\n"
"Did not respond in time"
)
client_socket.send(response.encode())
client_socket.close()
return
except Exception:
pass
client_socket.close()
except socket.timeout:
try:
response = (
"HTTP/1.1 408 Request Timeout\r\n"
"Content-Type: text/plain\r\n"
"Connection: close\r\n"
"\r\n"
"timeout"
)
client_socket.send(response.encode())
except:
pass
finally:
client_socket.close()
return
except Exception:
try:
client_socket.close()
except:
pass
def start_flask_server():
app = Flask(__name__)
@app.route('/calc', methods=['POST'])
def index():
try:
exp = request.form.get('calc')
if(exp!=None):
result = eval(exp)
return str(result)
else:
return "no num to calc"
except:
return "I'm just a calc, I could not process this"
@app.route('/', methods=['GET'])
def home():
return render_template('index.html')
import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
app.run(host='127.0.0.1', port=3001, debug=False)
def main():
flask_thread = threading.Thread(target=start_flask_server, daemon=True)
flask_thread.start()
import time
time.sleep(1)
proxy_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
proxy_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
proxy_socket.bind(('0.0.0.0', 8000))
proxy_socket.listen(5)
while True:
client_socket, addr = proxy_socket.accept()
client_handler = threading.Thread(target=handle_client, args=(client_socket,))
client_handler.start()
if __name__ == "__main__":
main()
|