-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWSerial.py
More file actions
409 lines (346 loc) · 13.4 KB
/
Copy pathWSerial.py
File metadata and controls
409 lines (346 loc) · 13.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
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
402
403
404
405
406
407
408
409
can you give add an option that use can select its port? import threading
import serial
import colorama
from colorama import Fore, Back, Style
import time
import sys
import os
import datetime
import readline
import atexit
import uuid
import argparse
import shutil
import subprocess
from cryptography.fernet import Fernet
TIMEOUT_DURATION = 15 # seconds
# colorama.init(autoreset=True)
CYAN = Style.BRIGHT + Fore.CYAN
GREEN = Style.BRIGHT + Fore.GREEN
BLUE = Style.BRIGHT + Fore.BLUE
RED = Style.BRIGHT + Fore.RED
YELLOW = Style.BRIGHT + Fore.YELLOW
MAGENTA = Style.BRIGHT + Fore.MAGENTA
RESET = Fore.RESET
# === CONFIGURATION ===
PORT = "COM3"
BAUD = 115200
# === ENCRYPTION SETUP ===
KEY_FILE = "serial_log.key"
encryption_key = None
cipher = None
LOG_FILE = None
SESSION_ID = None
should_exit = False
is_reconnecting = False
exit_pressed = False
# === COMMAND LINE ARGUMENTS ===
parser = argparse.ArgumentParser(description='Serial Terminal with Logging')
parser.add_argument('--output', '-o', type=str, nargs='?', const='auto', help='Save encrypted log output')
parser.add_argument('--output-key', '-k', type=str, help='Specify custom key file for encryption')
parser.add_argument('--port', '-p', type=str, help=f'Serial port (default: {PORT})')
parser.add_argument('--baud', '-b', type=int, help=f'Baud rate (default: {BAUD})')
args = parser.parse_args()
if args.port:
PORT = args.port
if args.baud:
BAUD = args.baud
if args.output_key:
KEY_FILE = args.output_key
if not KEY_FILE.endswith('.key'):
KEY_FILE += '.key'
output_filename = None
if args.output:
if args.output == 'auto':
output_filename = None
else:
output_filename = args.output
# === COMMAND HISTORY SETUP ===
histfile = os.path.join(os.path.expanduser("~"), ".serial_terminal_history")
try:
readline.read_history_file(histfile)
except FileNotFoundError:
pass
atexit.register(readline.write_history_file, histfile)
# === SYSTEM COMMAND CHECK FUNCTION ===
def is_command_executable(command):
"""Check if a command exists on the system"""
cmd_parts = command.strip().split()
if not cmd_parts:
return False
executable = cmd_parts[0]
# Check if it's in PATH
if shutil.which(executable):
return True
# Check for Windows extensions
if sys.platform == 'win32':
for ext in ['.exe', '.bat', '.cmd', '.ps1']:
if shutil.which(executable + ext):
return True
return False
def execute_system_command(command):
"""Execute a system command and display output"""
try:
print(YELLOW + f"\n[*] Executing: {command}" + RESET)
print("-" * 50)
# Set timeout for command execution
timeout = 30
try:
result = subprocess.run(
command,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=timeout
)
# Print stdout
if result.stdout:
print(result.stdout, end='')
# Print stderr
if result.stderr:
print(RED + result.stderr + RESET, end='')
# Print return code if non-zero
if result.returncode != 0 and result.returncode != 1:
print(YELLOW + f"[!] Command exited with code: {result.returncode}" + RESET)
except subprocess.TimeoutExpired:
print(RED + f"[!] Command timed out after {timeout} seconds" + RESET)
print("-" * 50)
return True
except Exception as e:
print(RED + f"[!] Failed to execute: {e}" + RESET)
print("-" * 50)
return False
# === ENCRYPTION FUNCTIONS ===
def generate_key():
key = Fernet.generate_key()
with open(KEY_FILE, 'wb') as key_file:
key_file.write(key)
return key
def load_or_create_key():
if os.path.exists(KEY_FILE):
with open(KEY_FILE, 'rb') as key_file:
return key_file.read()
else:
return generate_key()
def encrypt_data(data, cipher):
if cipher:
return cipher.encrypt(data.encode())
return data.encode()
def save_encrypted_log(data_buffer, log_file_path, cipher):
if data_buffer and log_file_path:
encrypted_data = encrypt_data(''.join(data_buffer), cipher)
with open(log_file_path, 'wb') as f:
f.write(encrypted_data)
print(GREEN + f"[+] Encrypted log saved to: {log_file_path}" + RESET)
print(YELLOW + f"[!] Key file: {KEY_FILE} (KEEP THIS SAFE!)" + RESET)
def get_timestamp():
return datetime.datetime.now().strftime("[%H:%M:%S]")
def ascii():
ASCII = """⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⣤⡾⠿⢿⡀⠀⠀⠀⠀⣠⣶⣿⣷⠀⠀⠀⠀
⠀⠀⠀⠀⠀⠀⠀⢀⣴⣦⣴⣿⡋⠀⠀⠈⢳⡄⠀⢠⣾⣿⠁⠈⣿⡆⠀⠀⠀
⠀⠀⠀⠀⠀⠀⣰⣿⣿⠿⠛⠉⠉⠁⠀⠀⠀⠹⡄⣿⣿⣿⠀⠀⢹⡇⠀⠀⠀
⠀⠀⠀⠀⣠⣾⡿⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⣰⣏⢻⣿⣿⡆⠀⠸⣿⠀⠀⠀
⠀⠀⢀⣴⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣾⣿⣿⣆⠹⣿⣷⠀⢘⣿⠀⠀⠀
⠀⢀⡾⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢰⣿⣿⠋⠉⠛⠂⠹⠿⣲⣿⣿⣧⠀⠀
⢠⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣤⣿⣿⣿⣷⣾⣿⡇⢀⠀⣼⣿⣿⣿⣧⠀
⠰⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⡘⢿⣿⣿⣿⠀@wrait8
⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⣷⡈⠿⢿⣿⡆VoidRecon
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⠛⠁⢙⠛⣿⣿⣿⣿⡟⠀⡿⠀⠀⢀⣿⡇
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣶⣤⣉⣛⠻⠇⢠⣿⣾⣿⡄⢻⡇
⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⣿⣿⣿⣿⣦⣤⣾⣿⣿⣿⣿⣆⠁"""
print(ASCII)
def initial_boot_message_logic():
global should_exit
try:
print(YELLOW + "\r[?] " + RESET + "Consuming first boot messages . . .", end='', flush=True)
initial_data = ""
start_time = time.time()
timeout = 1
while time.time() - start_time < timeout and not should_exit:
try:
if ser and ser.is_open and ser.in_waiting > 0:
data = ser.read(ser.in_waiting).decode(errors='ignore')
initial_data += data
start_time = time.time()
except:
pass
time.sleep(0.01)
print('\r' + ' ' * 50 + '\r', end='', flush=True)
except:
print('\r' + ' ' * 50 + '\r', end='', flush=True)
def serial_reconnection():
global ser, is_reconnecting, should_exit, exit_pressed
if is_reconnecting or should_exit:
return
is_reconnecting = True
try:
if ser and ser.is_open:
ser.close()
except:
pass
start_time = time.time()
while time.time() - start_time < TIMEOUT_DURATION and not should_exit and not exit_pressed:
try:
print(YELLOW + "\r[?] " + RESET + f"Reconnection timeout {int(TIMEOUT_DURATION - (time.time() - start_time))} [PRESS ENTER TO EXIT] . . .", end='', flush=True)
ser = serial.Serial(PORT, BAUD, timeout=0.1)
print("\r" + " " * 80 + "\r", end="", flush=True)
print(BLUE + "\r[*] " + RESET + f"Reconnected [{PORT}, {BAUD}]", flush=True)
time.sleep(0.5)
initial_boot_message_logic()
is_reconnecting = False
return True
except serial.SerialException:
time.sleep(0.5)
except:
time.sleep(0.5)
if not should_exit:
print("\r" + " " * 80 + "\r", end="", flush=True)
print(RED + "\r[!] " + RESET + f"Failed to reconnect after {TIMEOUT_DURATION}s")
should_exit = True
is_reconnecting = False
exit_pressed = True
return False
def read_from_serial(log_buffer):
global should_exit, is_reconnecting
initial_boot_message_logic()
while not should_exit:
try:
if ser and ser.is_open and ser.in_waiting > 0:
data = ser.read(ser.in_waiting).decode(errors='ignore')
if data:
print(data, end='', flush=True)
if log_buffer is not None:
log_buffer.append(data)
time.sleep(0.01)
except (serial.SerialException, AttributeError, OSError, PermissionError):
if not should_exit and not is_reconnecting:
print(MAGENTA + "\n[^] " + RESET + "Serial connection lost.")
serial_reconnection()
time.sleep(0.5)
except:
break
def write_to_serial():
global should_exit, exit_pressed, log_buffer
while not should_exit and not exit_pressed:
try:
if sys.platform == 'win32':
import msvcrt
if msvcrt.kbhit():
line = sys.stdin.readline()
else:
time.sleep(0.1)
continue
else:
line = sys.stdin.readline()
if not line:
break
if line == "\n":
if is_reconnecting:
exit_pressed = True
should_exit = True
break
else:
continue
# Terminal commands
if line.strip() == "clear":
os.system("clear||cls")
continue
elif line.strip() == "banner":
ascii()
continue
elif line.strip() == "quit":
should_exit = True
exit_pressed = True
break
elif line.strip() == "session":
print(f"{MAGENTA}[^]{RESET} Session ID: {BLUE}{SESSION_ID}{RESET}")
continue
elif line.strip() == "help":
# Send to serial device
if ser and ser.is_open:
ser.write(line.encode())
if log_buffer is not None:
timestamp = get_timestamp()
log_entry = f"{timestamp} >>> {line.strip()}"
log_buffer.append(log_entry)
else:
cmd = line.strip()
# Check if the command exists on the system
if is_command_executable(cmd):
# Execute system command
execute_system_command(cmd)
# Log the command with timestamp
if log_buffer is not None:
timestamp = get_timestamp()
log_entry = f"{timestamp} >>> [SYSTEM] {cmd}"
log_buffer.append(log_entry)
else:
# Send to serial device
if ser and ser.is_open:
ser.write(line.encode())
if log_buffer is not None:
timestamp = get_timestamp()
log_entry = f"{timestamp} >>> {line.strip()}"
log_buffer.append(log_entry)
else:
print(YELLOW + "[!] Not connected to serial device" + RESET)
except KeyboardInterrupt:
should_exit = True
exit_pressed = True
break
except (serial.serialutil.PortNotOpenError, ValueError, AttributeError):
if not should_exit:
print(YELLOW + "\n[!] Not connected. Type 'quit' to exit." + RESET)
continue
except Exception as e:
if not should_exit:
print(YELLOW + f"\n[!] Error: {e}" + RESET)
continue
def save_log_automatically(log_buffer):
if not log_buffer:
return
encryption_key = load_or_create_key()
cipher = Fernet(encryption_key)
global output_filename
if output_filename:
log_file_path = output_filename
if not log_file_path.endswith('.enc'):
log_file_path += '.enc'
else:
log_file_path = f"serial_log_{datetime.datetime.now().strftime('%Y%m%d_%H%M%S')}_{SESSION_ID}.enc"
save_encrypted_log(log_buffer, log_file_path, cipher)
# === START BANNER ===
os.system("clear||cls")
ascii()
SESSION_ID = f"{uuid.uuid4().hex[:4]}-{uuid.uuid4().hex[:4]}-{uuid.uuid4().hex[:4]}"
print(f"{MAGENTA}[^]{RESET} Session ID: {BLUE}{SESSION_ID}{RESET}")
print()
print(YELLOW + "\r[?] " + RESET + f"Connecting to [{PORT}, {BAUD}] . . .", end='', flush=True)
try:
ser = serial.Serial(PORT, BAUD, timeout=0.1)
print("\r" + " " * 50 + "\r", end="", flush=True)
except serial.SerialException:
print("\r" + " " * 80 + "\r", end="", flush=True)
print(RED + "[!] " + RESET + f"Port {PORT} hasn't been found.")
exit()
log_buffer = []
t1 = threading.Thread(target=read_from_serial, args=(log_buffer,), daemon=True)
t2 = threading.Thread(target=write_to_serial, daemon=False)
t1.start()
t2.start()
try:
t2.join()
except KeyboardInterrupt:
should_exit = True
exit_pressed = True
pass
try:
if ser and ser.is_open:
ser.close()
except:
pass
time.sleep(0.5)
if args.output:
save_log_automatically(log_buffer)