atomicshop 2.17.3__py3-none-any.whl → 2.18.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of atomicshop might be problematic. Click here for more details.
- atomicshop/__init__.py +1 -1
- atomicshop/basics/ansi_escape_codes.py +3 -1
- atomicshop/file_io/docxs.py +26 -17
- atomicshop/http_parse.py +118 -77
- atomicshop/mitm/connection_thread_worker.py +342 -257
- atomicshop/mitm/engines/__parent/parser___parent.py +2 -2
- atomicshop/mitm/engines/__parent/recorder___parent.py +83 -24
- atomicshop/mitm/engines/__reference_general/recorder___reference_general.py +2 -2
- atomicshop/mitm/message.py +40 -15
- atomicshop/mitm/mitm_main.py +3 -2
- atomicshop/mitm/recs_files.py +2 -1
- atomicshop/system_resource_monitor.py +16 -3
- atomicshop/wrappers/socketw/base.py +17 -0
- atomicshop/wrappers/socketw/receiver.py +90 -100
- atomicshop/wrappers/socketw/sender.py +5 -8
- atomicshop/wrappers/socketw/sni.py +0 -1
- atomicshop/wrappers/socketw/socket_client.py +2 -2
- atomicshop/wrappers/socketw/statistics_csv.py +12 -6
- {atomicshop-2.17.3.dist-info → atomicshop-2.18.0.dist-info}/METADATA +1 -1
- {atomicshop-2.17.3.dist-info → atomicshop-2.18.0.dist-info}/RECORD +23 -23
- {atomicshop-2.17.3.dist-info → atomicshop-2.18.0.dist-info}/LICENSE.txt +0 -0
- {atomicshop-2.17.3.dist-info → atomicshop-2.18.0.dist-info}/WHEEL +0 -0
- {atomicshop-2.17.3.dist-info → atomicshop-2.18.0.dist-info}/top_level.txt +0 -0
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
from datetime import datetime
|
|
2
|
+
import threading
|
|
3
|
+
import queue
|
|
2
4
|
|
|
3
5
|
from ..wrappers.socketw import receiver, sender, socket_client, base
|
|
4
6
|
from .. import websocket_parse
|
|
@@ -23,47 +25,45 @@ def thread_worker_main(
|
|
|
23
25
|
engines_list,
|
|
24
26
|
reference_module
|
|
25
27
|
):
|
|
26
|
-
def output_statistics_csv_row():
|
|
28
|
+
def output_statistics_csv_row(client_message: ClientMessage):
|
|
27
29
|
# If there is no '.code' attribute in HTTPResponse, this means that this is not an HTTP message, so there is no
|
|
28
30
|
# status code.
|
|
29
31
|
try:
|
|
30
|
-
http_status_code: str =
|
|
32
|
+
http_status_code: str = str(client_message.response_auto_parsed.code)
|
|
31
33
|
except AttributeError:
|
|
32
34
|
http_status_code: str = str()
|
|
33
35
|
|
|
34
36
|
# Same goes for the '.path' attribute, if it is not HTTP message then there will be no path.
|
|
35
37
|
try:
|
|
36
|
-
http_path: str = client_message.
|
|
38
|
+
http_path: str = client_message.response_auto_parsed.path
|
|
37
39
|
except AttributeError:
|
|
38
40
|
http_path: str = str()
|
|
39
41
|
|
|
40
42
|
# Same goes for the '.command' attribute, if it is not HTTP message then there will be no command.
|
|
41
43
|
try:
|
|
42
|
-
http_command: str = client_message.
|
|
44
|
+
http_command: str = client_message.response_auto_parsed.command
|
|
43
45
|
except AttributeError:
|
|
44
46
|
http_command: str = str()
|
|
45
47
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
else:
|
|
51
|
-
response_size_bytes += str(len(response))
|
|
52
|
-
|
|
53
|
-
# If it is not the last entry, add the comma.
|
|
54
|
-
if response_index + 1 != len(client_message.response_list_of_raw_bytes):
|
|
55
|
-
response_size_bytes += ','
|
|
56
|
-
|
|
57
|
-
# response_size_bytes = ','.join([str(len(x)) for x in client_message.response_list_of_raw_bytes])
|
|
48
|
+
if client_message.request_raw_bytes is None:
|
|
49
|
+
request_size_bytes = ''
|
|
50
|
+
else:
|
|
51
|
+
request_size_bytes = str(len(client_message.request_raw_bytes))
|
|
58
52
|
|
|
59
|
-
if
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
53
|
+
if client_message.response_raw_bytes is None:
|
|
54
|
+
response_size_bytes = ''
|
|
55
|
+
else:
|
|
56
|
+
response_size_bytes = str(len(client_message.response_raw_bytes))
|
|
57
|
+
|
|
58
|
+
if client_message.errors and len(client_message.errors) > 1:
|
|
59
|
+
error_string = '||'.join(client_message.errors)
|
|
60
|
+
error_string = f'Error count: {len(client_message.errors)} | Errors: {error_string}'
|
|
61
|
+
elif client_message.errors and len(client_message.errors) == 1:
|
|
62
|
+
error_string = client_message.errors[0]
|
|
63
|
+
elif not client_message.errors:
|
|
64
64
|
error_string = str()
|
|
65
65
|
else:
|
|
66
|
-
raise ValueError(f"Error in statistics error list. Values: {
|
|
66
|
+
raise ValueError(f"Error in statistics error list. Values: {client_message.errors}")
|
|
67
67
|
|
|
68
68
|
statistics_writer.write_row(
|
|
69
69
|
thread_id=str(thread_id),
|
|
@@ -71,58 +71,70 @@ def thread_worker_main(
|
|
|
71
71
|
tls_type=tls_type,
|
|
72
72
|
tls_version=tls_version,
|
|
73
73
|
protocol=client_message.protocol,
|
|
74
|
+
protocol2=client_message.protocol2,
|
|
74
75
|
path=http_path,
|
|
75
76
|
status_code=http_status_code,
|
|
76
77
|
command=http_command,
|
|
77
|
-
|
|
78
|
-
request_size_bytes=
|
|
78
|
+
timestamp=client_message.timestamp,
|
|
79
|
+
request_size_bytes=request_size_bytes,
|
|
79
80
|
response_size_bytes=response_size_bytes,
|
|
80
81
|
recorded_file_path=client_message.recorded_file_path,
|
|
81
82
|
process_cmd=process_commandline,
|
|
83
|
+
action=client_message.action,
|
|
82
84
|
error=error_string
|
|
83
85
|
)
|
|
84
86
|
|
|
85
|
-
def record_and_statistics_write():
|
|
87
|
+
def record_and_statistics_write(client_message: ClientMessage):
|
|
86
88
|
# If recorder wasn't executed before, then execute it now
|
|
87
89
|
if config_static.LogRec.enable_request_response_recordings_in_logs:
|
|
88
|
-
recorded_file = recorder(
|
|
89
|
-
class_client_message=client_message, record_path=config_static.LogRec.recordings_path).record()
|
|
90
|
+
recorded_file = recorder.record(class_client_message=client_message)
|
|
90
91
|
client_message.recorded_file_path = recorded_file
|
|
91
92
|
|
|
92
93
|
# Save statistics file.
|
|
93
|
-
output_statistics_csv_row()
|
|
94
|
+
output_statistics_csv_row(client_message)
|
|
94
95
|
|
|
95
|
-
def parse_http(
|
|
96
|
-
|
|
96
|
+
def parse_http(
|
|
97
|
+
raw_bytes: bytes,
|
|
98
|
+
client_message: ClientMessage):
|
|
97
99
|
nonlocal protocol
|
|
98
100
|
# Parsing the raw bytes as HTTP.
|
|
99
|
-
|
|
100
|
-
HTTPRequestParse(
|
|
101
|
+
request_http_parsed, is_http_request, request_parsing_error = (
|
|
102
|
+
HTTPRequestParse(raw_bytes).parse())
|
|
103
|
+
|
|
104
|
+
response_http_parsed, is_http_response, response_parsing_error = (
|
|
105
|
+
HTTPResponseParse(raw_bytes).parse())
|
|
101
106
|
|
|
102
107
|
if is_http_request:
|
|
103
108
|
if protocol == '':
|
|
104
109
|
protocol = 'HTTP'
|
|
105
110
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
111
|
+
auto_parsed = request_http_parsed
|
|
112
|
+
network_logger.info(
|
|
113
|
+
f"HTTP Request Parsed: Method: {request_http_parsed.command} | Path: {request_http_parsed.path}")
|
|
114
|
+
|
|
115
|
+
is_http_request_a_websocket(auto_parsed, client_message)
|
|
116
|
+
elif is_http_response:
|
|
117
|
+
auto_parsed = response_http_parsed
|
|
118
|
+
network_logger.info(
|
|
119
|
+
f"HTTP Response Parsed: Status: {response_http_parsed.code}")
|
|
120
|
+
elif protocol == 'Websocket':
|
|
121
|
+
client_message.protocol2 = 'Frame'
|
|
122
|
+
auto_parsed = parse_websocket(raw_bytes)
|
|
109
123
|
else:
|
|
110
|
-
|
|
111
|
-
# not to log it into statistics.
|
|
112
|
-
# statistics_error_list.append(error_message)
|
|
113
|
-
print_api(request_parsing_error, logger=network_logger, logger_method='error', color='yellow')
|
|
124
|
+
auto_parsed = None
|
|
114
125
|
|
|
115
|
-
|
|
126
|
+
return auto_parsed
|
|
116
127
|
|
|
117
|
-
def is_http_request_a_websocket(
|
|
128
|
+
def is_http_request_a_websocket(
|
|
129
|
+
auto_parsed,
|
|
130
|
+
client_message: ClientMessage):
|
|
118
131
|
nonlocal protocol
|
|
119
132
|
|
|
120
133
|
if protocol == 'HTTP':
|
|
121
|
-
if (
|
|
122
|
-
|
|
123
|
-
'Upgrade' in client_message.request_raw_decoded.headers):
|
|
124
|
-
if client_message.request_raw_decoded.headers['Upgrade'] == 'websocket':
|
|
134
|
+
if auto_parsed and hasattr(auto_parsed, 'headers') and 'Upgrade' in auto_parsed.headers:
|
|
135
|
+
if auto_parsed.headers['Upgrade'] == 'websocket':
|
|
125
136
|
protocol = 'Websocket'
|
|
137
|
+
client_message.protocol2 = 'Handshake'
|
|
126
138
|
|
|
127
139
|
network_logger.info(f'Protocol upgraded to Websocket')
|
|
128
140
|
|
|
@@ -132,72 +144,40 @@ def thread_worker_main(
|
|
|
132
144
|
def finish_thread():
|
|
133
145
|
# At this stage there could be several times that the same socket was used to the service server - we need to
|
|
134
146
|
# close this socket as well if it still opened.
|
|
135
|
-
if
|
|
147
|
+
# The first part of the condition is to check if the service socket was connected at all.
|
|
148
|
+
# If the service socket couldn't connect, then the instance will be None.
|
|
149
|
+
if service_socket_instance and service_socket_instance.fileno() != -1:
|
|
136
150
|
if service_client.socket_instance:
|
|
137
151
|
service_client.close_socket()
|
|
138
152
|
|
|
139
153
|
# If client socket is still opened - close
|
|
140
|
-
if client_socket:
|
|
154
|
+
if client_socket.fileno() != -1:
|
|
141
155
|
client_socket.close()
|
|
142
|
-
network_logger.info(f"Closed client socket [{
|
|
156
|
+
network_logger.info(f"Closed client socket [{client_ip}:{source_port}]...")
|
|
143
157
|
|
|
144
158
|
network_logger.info("Thread Finished. Will continue listening on the Main thread")
|
|
145
159
|
|
|
146
|
-
def
|
|
147
|
-
"""
|
|
148
|
-
Process the client raw data request.
|
|
149
|
-
|
|
150
|
-
:return: True if the socket should be closed, False if not.
|
|
151
|
-
"""
|
|
152
|
-
|
|
153
|
-
# If the message is empty, then the connection was closed already by the other side,
|
|
154
|
-
# so we can close the socket as well.
|
|
155
|
-
# If the received message from the client is not empty, then continue.
|
|
156
|
-
if not client_received_raw_data:
|
|
157
|
-
return True
|
|
158
|
-
|
|
159
|
-
# Putting the received message to the aggregating message class.
|
|
160
|
-
client_message.request_raw_bytes = client_received_raw_data
|
|
161
|
-
|
|
162
|
-
parse_http()
|
|
163
|
-
if protocol != '':
|
|
164
|
-
client_message.protocol = protocol
|
|
165
|
-
|
|
166
|
-
# Parse websocket frames only if it is not the first protocol upgrade request.
|
|
167
|
-
if protocol == 'Websocket' and cycle_count != 0:
|
|
168
|
-
client_message.request_raw_decoded = parse_websocket(client_message.request_raw_bytes)
|
|
169
|
-
|
|
170
|
-
# Custom parser, should parse HTTP body or the whole message if not HTTP.
|
|
171
|
-
parser_instance = parser(client_message)
|
|
172
|
-
parser_instance.parse()
|
|
173
|
-
|
|
174
|
-
# Converting body parsed to string on logging, since there is no strict rule for the parameter
|
|
175
|
-
# to be string.
|
|
176
|
-
parser_instance.logger.info(f"{str(client_message.request_body_parsed)[0: 100]}...")
|
|
177
|
-
|
|
178
|
-
return False
|
|
179
|
-
|
|
180
|
-
def create_responder_response():
|
|
160
|
+
def create_responder_response(client_message: ClientMessage) -> list[bytes]:
|
|
181
161
|
# Since we're in response mode, we'll record the request anyway, after the responder did its job.
|
|
182
162
|
client_message.info = "In Server Response Mode"
|
|
183
163
|
|
|
184
|
-
# Re-initiate the 'client_message.response_list_of_raw_bytes' list, since we'll be appending
|
|
185
|
-
# new entries for empty list.
|
|
186
|
-
client_message.response_list_of_raw_bytes = list()
|
|
187
|
-
|
|
188
164
|
# If it's the first cycle and the protocol is Websocket, then we'll create the HTTP Handshake
|
|
189
165
|
# response automatically.
|
|
190
|
-
if protocol == 'Websocket' and
|
|
191
|
-
|
|
166
|
+
if protocol == 'Websocket' and client_receive_count == 0:
|
|
167
|
+
responses: list = list()
|
|
168
|
+
responses.append(
|
|
192
169
|
websocket_parse.create_byte_http_response(client_message.request_raw_bytes))
|
|
193
|
-
|
|
194
|
-
|
|
170
|
+
else:
|
|
171
|
+
# Creating response for parsed message and printing
|
|
172
|
+
responses: list = responder.create_response(client_message)
|
|
195
173
|
|
|
196
174
|
# Output first 100 characters of all the responses in the list.
|
|
197
|
-
for response_raw_bytes_single in
|
|
175
|
+
for response_raw_bytes_single in responses:
|
|
198
176
|
responder.logger.info(f"{response_raw_bytes_single[0: 100]}...")
|
|
199
177
|
|
|
200
|
-
|
|
178
|
+
return responses
|
|
179
|
+
|
|
180
|
+
def create_client_socket(client_message: ClientMessage):
|
|
201
181
|
# If there is a custom certificate for the client for this domain, then we'll use it.
|
|
202
182
|
# noinspection PyTypeChecker
|
|
203
183
|
custom_client_pem_certificate_path: str = None
|
|
@@ -234,57 +214,232 @@ def thread_worker_main(
|
|
|
234
214
|
|
|
235
215
|
return service_client_instance
|
|
236
216
|
|
|
237
|
-
def
|
|
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
|
-
|
|
217
|
+
def process_client_raw_data(
|
|
218
|
+
client_received_raw_data: bytes,
|
|
219
|
+
error_string: str,
|
|
220
|
+
client_message: ClientMessage):
|
|
221
|
+
"""
|
|
222
|
+
Process the client raw data request.
|
|
223
|
+
"""
|
|
224
|
+
nonlocal protocol
|
|
225
|
+
|
|
226
|
+
client_message.request_raw_bytes = client_received_raw_data
|
|
227
|
+
|
|
228
|
+
if error_string:
|
|
229
|
+
client_message.errors.append(error_string)
|
|
230
|
+
|
|
231
|
+
if client_received_raw_data == b'':
|
|
232
|
+
return
|
|
233
|
+
|
|
234
|
+
client_message.response_auto_parsed = parse_http(client_message.request_raw_bytes, client_message)
|
|
235
|
+
if protocol != '':
|
|
236
|
+
client_message.protocol = protocol
|
|
237
|
+
|
|
238
|
+
# Parse websocket frames only if it is not the first protocol upgrade request.
|
|
239
|
+
if protocol == 'Websocket' and client_receive_count != 0:
|
|
240
|
+
client_message.request_auto_parsed = parse_websocket(client_message.request_raw_bytes)
|
|
241
|
+
|
|
242
|
+
# Custom parser, should parse HTTP body or the whole message if not HTTP.
|
|
243
|
+
parser_instance = parser(client_message)
|
|
244
|
+
parser_instance.parse()
|
|
245
|
+
|
|
246
|
+
# Converting body parsed to string on logging, there is no strict rule for the parameter to be string.
|
|
247
|
+
parser_instance.logger.info(f"{str(client_message.request_custom_parsed)[0: 100]}...")
|
|
248
|
+
|
|
249
|
+
def process_server_raw_data(
|
|
250
|
+
service_received_raw_data: bytes,
|
|
251
|
+
error_string: str,
|
|
252
|
+
client_message: ClientMessage
|
|
253
|
+
):
|
|
254
|
+
nonlocal protocol
|
|
255
|
+
|
|
256
|
+
client_message.response_raw_bytes = service_received_raw_data
|
|
257
|
+
|
|
258
|
+
if error_string:
|
|
259
|
+
client_message.errors.append(error_string)
|
|
260
|
+
|
|
261
|
+
if service_received_raw_data == b'':
|
|
262
|
+
return
|
|
263
|
+
|
|
264
|
+
client_message.response_auto_parsed = parse_http(client_message.response_raw_bytes, client_message)
|
|
265
|
+
if protocol != '':
|
|
266
|
+
client_message.protocol = protocol
|
|
267
|
+
|
|
268
|
+
def client_message_first_start() -> ClientMessage:
|
|
269
|
+
client_message: ClientMessage = ClientMessage()
|
|
270
|
+
client_message.client_ip = client_ip
|
|
271
|
+
client_message.source_port = source_port
|
|
272
|
+
client_message.destination_port = destination_port
|
|
273
|
+
client_message.server_name = server_name
|
|
274
|
+
client_message.thread_id = thread_id
|
|
275
|
+
client_message.process_name = process_commandline
|
|
276
|
+
|
|
277
|
+
return client_message
|
|
278
|
+
|
|
279
|
+
def receive_send_start(
|
|
280
|
+
receiving_socket,
|
|
281
|
+
sending_socket = None,
|
|
282
|
+
exception_queue: queue.Queue = None
|
|
283
|
+
):
|
|
284
|
+
nonlocal client_receive_count
|
|
285
|
+
nonlocal server_receive_count
|
|
286
|
+
nonlocal exception_or_close_in_receiving_thread
|
|
287
|
+
|
|
288
|
+
# Set the thread name to the custom name for logging
|
|
289
|
+
# threading.current_thread().name = thread_name
|
|
290
|
+
|
|
291
|
+
# Initialize the client message object with current thread's data.
|
|
292
|
+
client_message: ClientMessage = client_message_first_start()
|
|
293
|
+
|
|
294
|
+
try:
|
|
295
|
+
if receiving_socket is client_socket:
|
|
296
|
+
side: str = 'Client'
|
|
297
|
+
elif receiving_socket is service_socket_instance:
|
|
298
|
+
side: str = 'Service'
|
|
299
|
+
else:
|
|
300
|
+
raise ValueError(f"Unknown side of the socket: {receiving_socket}")
|
|
301
|
+
|
|
302
|
+
while True:
|
|
303
|
+
client_message.reinitialize_dynamic_vars()
|
|
304
|
+
|
|
305
|
+
if side == 'Client':
|
|
306
|
+
client_receive_count += 1
|
|
307
|
+
current_count = client_receive_count
|
|
308
|
+
else:
|
|
309
|
+
server_receive_count += 1
|
|
310
|
+
current_count = server_receive_count
|
|
311
|
+
|
|
312
|
+
network_logger.info(
|
|
313
|
+
f"Initializing Receiver for {side} cycle: {str(current_count)}")
|
|
314
|
+
|
|
315
|
+
# Getting message from the client over the socket using specific class.
|
|
316
|
+
received_raw_data, is_socket_closed, error_message = receiver.Receiver(
|
|
317
|
+
ssl_socket=receiving_socket, logger=network_logger).receive()
|
|
318
|
+
|
|
319
|
+
# Getting current time of message received, either from client or service.
|
|
320
|
+
client_message.timestamp = datetime.now()
|
|
321
|
+
|
|
322
|
+
# In case of client socket, we'll process the raw data specifically for the client.
|
|
323
|
+
if side == 'Client':
|
|
324
|
+
process_client_raw_data(received_raw_data, error_message, client_message)
|
|
325
|
+
client_message.action = 'client_receive'
|
|
326
|
+
# In case of service socket, we'll process the raw data specifically for the service.
|
|
327
|
+
else:
|
|
328
|
+
process_server_raw_data(received_raw_data, error_message, client_message)
|
|
329
|
+
client_message.action = 'service_receive'
|
|
330
|
+
|
|
331
|
+
# If there was an exception in the service thread, then receiving empty bytes doesn't mean that
|
|
332
|
+
# the socket was closed by the other side, it means that the service thread closed the socket.
|
|
333
|
+
if (received_raw_data == b'' or error_message) and exception_or_close_in_receiving_thread:
|
|
334
|
+
print_api("Both sockets are closed, breaking the loop", logger=network_logger,
|
|
335
|
+
logger_method='info')
|
|
336
|
+
return
|
|
337
|
+
|
|
338
|
+
# We will record only if there was no closing signal, because if there was, it means that we initiated
|
|
339
|
+
# the close on the opposite socket.
|
|
340
|
+
record_and_statistics_write(client_message)
|
|
341
|
+
|
|
342
|
+
if is_socket_closed:
|
|
343
|
+
exception_or_close_in_receiving_thread = True
|
|
344
|
+
finish_thread()
|
|
345
|
+
return
|
|
346
|
+
|
|
347
|
+
# If we're in response mode, execute responder.
|
|
348
|
+
if config_static.TCPServer.server_response_mode:
|
|
349
|
+
raw_responses: list[bytes] = create_responder_response(client_message)
|
|
350
|
+
|
|
351
|
+
is_socket_closed: bool = False
|
|
352
|
+
for response_raw_bytes in raw_responses:
|
|
353
|
+
client_message.reinitialize_dynamic_vars()
|
|
354
|
+
client_message.timestamp = datetime.now()
|
|
355
|
+
client_message.response_raw_bytes = response_raw_bytes
|
|
356
|
+
error_on_send: str = sender.Sender(
|
|
357
|
+
ssl_socket=client_socket, class_message=client_message.response_raw_bytes,
|
|
358
|
+
logger=network_logger).send()
|
|
359
|
+
|
|
360
|
+
# If there was problem with sending data, we'll break the main while loop.
|
|
361
|
+
if error_on_send:
|
|
362
|
+
client_message.errors.append(error_on_send)
|
|
363
|
+
record_and_statistics_write(client_message)
|
|
364
|
+
is_socket_closed = True
|
|
365
|
+
|
|
366
|
+
if is_socket_closed:
|
|
367
|
+
# exception_or_close_in_receiving_thread = True
|
|
368
|
+
return
|
|
369
|
+
else:
|
|
370
|
+
# if side == 'Client':
|
|
371
|
+
# raise NotImplementedError
|
|
372
|
+
client_message.reinitialize_dynamic_vars()
|
|
373
|
+
error_on_send: str = sender.Sender(
|
|
374
|
+
ssl_socket=sending_socket, class_message=received_raw_data,
|
|
375
|
+
logger=network_logger).send()
|
|
376
|
+
|
|
377
|
+
if error_on_send:
|
|
378
|
+
client_message.reinitialize_dynamic_vars()
|
|
379
|
+
client_message.errors.append(error_on_send)
|
|
380
|
+
client_message.timestamp = datetime.now()
|
|
381
|
+
if side == 'Client':
|
|
382
|
+
client_message.action = 'service_send'
|
|
383
|
+
else:
|
|
384
|
+
client_message.action = 'client_send'
|
|
385
|
+
|
|
386
|
+
record_and_statistics_write(client_message)
|
|
387
|
+
|
|
388
|
+
# If the socket was closed, then we'll break the loop.
|
|
389
|
+
if is_socket_closed or error_on_send:
|
|
390
|
+
exception_or_close_in_receiving_thread = True
|
|
391
|
+
finish_thread()
|
|
392
|
+
return
|
|
393
|
+
except Exception as exc:
|
|
394
|
+
# If the sockets were already closed, then there is nothing to do here besides log.
|
|
395
|
+
# if (isinstance(exc, OSError) and exc.errno == 10038 and
|
|
396
|
+
# client_socket.fileno() == -1 and service_socket_instance.fileno() == -1):
|
|
397
|
+
if isinstance(exc, OSError) and exc.errno == 10038:
|
|
398
|
+
print_api("Both sockets are closed, breaking the loop", logger=network_logger, logger_method='info')
|
|
266
399
|
else:
|
|
267
|
-
|
|
400
|
+
exception_or_close_in_receiving_thread = True
|
|
401
|
+
# handle_exceptions(exc, client_message, recorded)
|
|
402
|
+
exception_message = tracebacks.get_as_string(one_line=True)
|
|
403
|
+
error_message = f'Socket Thread [{str(thread_id)}] Exception: {exception_message}'
|
|
404
|
+
print_api("Exception in a thread, forwarding to parent thread.", logger_method='info', logger=network_logger)
|
|
405
|
+
client_message.errors.append(error_message)
|
|
406
|
+
|
|
407
|
+
# if not recorded:
|
|
408
|
+
# record_and_statistics_write(client_message)
|
|
409
|
+
|
|
410
|
+
finish_thread()
|
|
411
|
+
exception_queue.put(exc)
|
|
412
|
+
|
|
413
|
+
def handle_exceptions(
|
|
414
|
+
exc: Exception,
|
|
415
|
+
client_message: ClientMessage
|
|
416
|
+
):
|
|
417
|
+
exception_message = tracebacks.get_as_string(one_line=True)
|
|
418
|
+
error_message = f'Socket Thread [{str(thread_id)}] Exception: {exception_message}'
|
|
419
|
+
print_api(error_message, logger_method='critical', logger=network_logger)
|
|
420
|
+
client_message.errors.append(error_message)
|
|
268
421
|
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
422
|
+
# === At this point while loop of 'client_connection_boolean' was broken =======================================
|
|
423
|
+
# If recorder wasn't executed before, then execute it now
|
|
424
|
+
record_and_statistics_write(client_message)
|
|
425
|
+
|
|
426
|
+
finish_thread()
|
|
427
|
+
|
|
428
|
+
# After the socket clean up, we will still raise the exception to the main thread.
|
|
429
|
+
raise exc
|
|
430
|
+
|
|
431
|
+
# ================================================================================================================
|
|
432
|
+
# This is the start of the thread_worker_main function
|
|
275
433
|
|
|
276
434
|
# Only protocols that are encrypted with TLS have the server name attribute.
|
|
277
435
|
if is_tls:
|
|
278
436
|
# Get current destination domain
|
|
279
437
|
server_name = client_socket.server_hostname
|
|
280
|
-
# client_message.server_name = domain_from_dns
|
|
281
438
|
# If the protocol is not TLS, then we'll use the domain from the DNS.
|
|
282
439
|
else:
|
|
283
440
|
server_name = domain_from_dns
|
|
284
|
-
client_message.server_name = server_name
|
|
285
441
|
|
|
286
442
|
thread_id = threads.current_thread_id()
|
|
287
|
-
client_message.thread_id = thread_id
|
|
288
443
|
|
|
289
444
|
protocol: str = str()
|
|
290
445
|
# # This is Client Masked Frame Parser.
|
|
@@ -295,7 +450,7 @@ def thread_worker_main(
|
|
|
295
450
|
|
|
296
451
|
# Loading parser by domain, if there is no parser for current domain - general reference parser is loaded.
|
|
297
452
|
# These should be outside any loop and initialized only once entering the thread.
|
|
298
|
-
parser, responder,
|
|
453
|
+
parser, responder, recorder_no_init, mtls_dict = assign_class_by_domain(
|
|
299
454
|
engines_usage=config_static.TCPServer.engines_usage,
|
|
300
455
|
engines_list=engines_list,
|
|
301
456
|
message_domain_name=server_name,
|
|
@@ -303,140 +458,70 @@ def thread_worker_main(
|
|
|
303
458
|
logger=network_logger
|
|
304
459
|
)
|
|
305
460
|
|
|
461
|
+
recorder = recorder_no_init(record_path=config_static.LogRec.recordings_path)
|
|
462
|
+
|
|
463
|
+
# Initializing the client message object with current thread's data.
|
|
464
|
+
# This is needed only to skip error alerts after 'try'.
|
|
465
|
+
client_message_connection: ClientMessage = ClientMessage()
|
|
466
|
+
# This is needed to indicate if there was an exception or socket was closed in any of the receiving thread.
|
|
467
|
+
exception_or_close_in_receiving_thread: bool = False
|
|
468
|
+
|
|
306
469
|
try:
|
|
307
470
|
client_ip, source_port = client_socket.getpeername()
|
|
308
|
-
client_message.client_ip = client_ip
|
|
309
|
-
client_message.source_port = source_port
|
|
310
|
-
|
|
311
471
|
destination_port = client_socket.getsockname()[1]
|
|
312
|
-
client_message.destination_port = destination_port
|
|
313
472
|
|
|
314
473
|
network_logger.info(f"Thread Created - Client [{client_ip}:{source_port}] | "
|
|
315
474
|
f"Destination service: [{server_name}:{destination_port}]")
|
|
316
475
|
|
|
317
|
-
end_socket: bool = False
|
|
318
476
|
service_client = None
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
while True:
|
|
323
|
-
# If cycle count is None, then it's the first cycle, else it's not.
|
|
324
|
-
# The cycle_count should be added 1 in the beginning of each cycle, and not in the end, since not always
|
|
325
|
-
# the cycle will be executed till the end.
|
|
326
|
-
if cycle_count is None:
|
|
327
|
-
cycle_count = 0
|
|
328
|
-
else:
|
|
329
|
-
cycle_count += 1
|
|
330
|
-
|
|
331
|
-
recorded: bool = False
|
|
332
|
-
statistics_error_list: list[str] = list()
|
|
333
|
-
|
|
334
|
-
client_message = ClientMessage()
|
|
335
|
-
client_message.thread_id = thread_id
|
|
336
|
-
client_message.client_ip = client_ip
|
|
337
|
-
client_message.source_port = source_port
|
|
338
|
-
client_message.destination_port = destination_port
|
|
339
|
-
client_message.process_name = process_commandline
|
|
340
|
-
client_message.server_name = server_name
|
|
341
|
-
# Getting current time of message received from client.
|
|
342
|
-
client_message.request_time_received = datetime.now()
|
|
343
|
-
|
|
344
|
-
# Peek if there is some data in the socket.
|
|
345
|
-
# This is needed to check if the client just connects without sending data, if so we need to try and
|
|
346
|
-
# receive data from the server and send it to the client.
|
|
347
|
-
# We will do it only on the first cycle, after that the connection should work as usual.
|
|
348
|
-
# Sometimes the client will execute connection without sending data, just for the server to send response.
|
|
349
|
-
is_socket_ready: bool = True
|
|
350
|
-
if cycle_count == 0:
|
|
351
|
-
is_socket_ready = receiver.is_socket_ready_for_read(client_socket)
|
|
352
|
-
|
|
353
|
-
if is_socket_ready:
|
|
354
|
-
network_logger.info(f"Initializing Receiver on cycle: {str(cycle_count+1)}")
|
|
355
|
-
# Getting message from the client over the socket using specific class.
|
|
356
|
-
client_received_raw_data = receiver.Receiver(
|
|
357
|
-
ssl_socket=client_socket, logger=network_logger).receive()
|
|
358
|
-
|
|
359
|
-
end_socket = process_client_raw_data_request()
|
|
477
|
+
client_receive_count: int = 0
|
|
478
|
+
server_receive_count: int = 0
|
|
479
|
+
client_message_connection = client_message_first_start()
|
|
360
480
|
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
# If there was problem with sending data, we'll break current loop.
|
|
402
|
-
if error_on_send:
|
|
403
|
-
statistics_error_list.append(error_on_send)
|
|
404
|
-
break
|
|
405
|
-
# If response from server came back empty, then the server has closed the connection,
|
|
406
|
-
# we will do the same.
|
|
407
|
-
else:
|
|
408
|
-
network_logger.info(f"Response empty, nothing to send to client.")
|
|
409
|
-
break
|
|
410
|
-
|
|
411
|
-
record_and_statistics_write()
|
|
412
|
-
recorded = True
|
|
413
|
-
|
|
414
|
-
# If the message is empty, then the connection was closed already by the other side, also if there will
|
|
415
|
-
# be empty response from the server, so we can close the socket as well and exceptions will be raised.
|
|
416
|
-
if end_socket:
|
|
417
|
-
# If it's the first cycle we will record the message from the client if it came empty.
|
|
418
|
-
if cycle_count == 0:
|
|
419
|
-
record_and_statistics_write()
|
|
420
|
-
|
|
421
|
-
# In other cases, we'll just break the loop, since empty message means that the other side closed the
|
|
422
|
-
# connection.
|
|
423
|
-
recorded = True
|
|
424
|
-
|
|
425
|
-
break
|
|
481
|
+
# If we're not in response mode, then we'll create the client socket to the service.
|
|
482
|
+
# noinspection PyTypeChecker
|
|
483
|
+
connection_error: str = None
|
|
484
|
+
service_socket_instance = None
|
|
485
|
+
if not config_static.TCPServer.server_response_mode:
|
|
486
|
+
# If "service_client" object is not defined, we'll define it.
|
|
487
|
+
# If it's defined, then there's still active "ssl_socket" with connection to the service domain.
|
|
488
|
+
if not service_client:
|
|
489
|
+
service_client = create_client_socket(client_message_connection)
|
|
490
|
+
service_socket_instance, connection_error = service_client.service_connection()
|
|
491
|
+
|
|
492
|
+
if connection_error:
|
|
493
|
+
client_message_connection.timestamp = datetime.now()
|
|
494
|
+
client_message_connection.errors.append(connection_error)
|
|
495
|
+
client_message_connection.action = 'service_connect'
|
|
496
|
+
record_and_statistics_write(client_message_connection)
|
|
497
|
+
else:
|
|
498
|
+
client_exception_queue: queue.Queue = queue.Queue()
|
|
499
|
+
service_exception_queue: queue.Queue = queue.Queue()
|
|
500
|
+
|
|
501
|
+
client_thread = threading.Thread(
|
|
502
|
+
target=receive_send_start, args=(client_socket, service_socket_instance, client_exception_queue),
|
|
503
|
+
name=f"Thread-{thread_id}-Client")
|
|
504
|
+
client_thread.daemon = True
|
|
505
|
+
client_thread.start()
|
|
506
|
+
|
|
507
|
+
service_thread = threading.Thread(
|
|
508
|
+
target=receive_send_start, args=(service_socket_instance, client_socket, service_exception_queue),
|
|
509
|
+
name=f"Thread-{thread_id}-Service")
|
|
510
|
+
service_thread.daemon = True
|
|
511
|
+
service_thread.start()
|
|
512
|
+
|
|
513
|
+
client_thread.join()
|
|
514
|
+
service_thread.join()
|
|
515
|
+
|
|
516
|
+
# If there was an exception in any of the threads, then we'll raise it here.
|
|
517
|
+
if not client_exception_queue.empty():
|
|
518
|
+
raise client_exception_queue.get()
|
|
519
|
+
if not service_exception_queue.empty():
|
|
520
|
+
raise service_exception_queue.get()
|
|
426
521
|
|
|
427
522
|
finish_thread()
|
|
428
523
|
except Exception as e:
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
print_api(error_message, logger_method='critical', logger=network_logger)
|
|
432
|
-
statistics_error_list.append(error_message)
|
|
433
|
-
|
|
434
|
-
# === At this point while loop of 'client_connection_boolean' was broken =======================================
|
|
435
|
-
# If recorder wasn't executed before, then execute it now
|
|
436
|
-
if not recorded:
|
|
437
|
-
record_and_statistics_write()
|
|
438
|
-
|
|
439
|
-
finish_thread()
|
|
524
|
+
if not client_message_connection.timestamp:
|
|
525
|
+
client_message_connection.timestamp = datetime.now()
|
|
440
526
|
|
|
441
|
-
|
|
442
|
-
raise e
|
|
527
|
+
handle_exceptions(e, client_message_connection)
|