-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathJanOS_app.py
More file actions
4228 lines (3675 loc) · 189 KB
/
JanOS_app.py
File metadata and controls
4228 lines (3675 loc) · 189 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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
JanOS App - ESP32-C5 Controller
Usage: ./JanOS_app.py
Optional: ./JanOS_app.py <device>
Example: ./JanOS_app.py /dev/ttyUSB0
"""
import sys
import os
import time
import serial
from serial.tools import list_ports
import threading
import select
import termios
import fcntl
import tempfile
import re
import readline # For better input handling
import unicodedata
from datetime import datetime
from typing import List, Dict, Tuple, Optional, Any
# ============================================================================
# Configuration
# ============================================================================
BAUD_RATE = 115200
SCAN_TIMEOUT = 15
READ_TIMEOUT = 2
SNIFFER_UPDATE_INTERVAL = 1 # seconds
PORTAL_UPDATE_INTERVAL = 2 # seconds for portal monitoring
EVIL_TWIN_UPDATE_INTERVAL = 2 # seconds for evil twin monitoring
# ============================================================================
# Colors and Styling
# ============================================================================
class Colors:
RED = '\033[0;31m'
GREEN = '\033[0;32m'
YELLOW = '\033[0;33m'
BLUE = '\033[0;34m'
MAGENTA = '\033[0;35m'
CYAN = '\033[0;36m'
WHITE = '\033[1;37m'
GRAY = '\033[0;90m'
NC = '\033[0m' # No Color
BOLD = '\033[1m'
DIM = '\033[2m'
# Box drawing characters
BOX_TL = '╔'
BOX_TR = '╗'
BOX_BL = '╚'
BOX_BR = '╝'
BOX_H = '═'
BOX_V = '║'
BOX_LT = '╠'
BOX_RT = '╣'
# ============================================================================
# Utility Functions
# ============================================================================
def detect_os() -> str:
"""Detect the operating system."""
if sys.platform.startswith('linux'):
return 'linux'
elif sys.platform.startswith('darwin'):
return 'macos'
else:
return 'unknown'
def get_terminal_width() -> int:
"""Get terminal width."""
try:
import shutil
return shutil.get_terminal_size().columns
except:
return 80
def center_text(text: str) -> str:
"""Center text in terminal."""
width = get_terminal_width()
text_len = len(strip_ansi(text))
padding = max(0, (width - text_len) // 2)
return " " * padding + text
def strip_ansi(text: str) -> str:
"""Remove ANSI color codes from text."""
ansi_escape = re.compile(r'\x1b\[[0-9;]*m')
return ansi_escape.sub('', text)
def char_display_width(ch: str) -> int:
"""Estimate display width of one character in terminal."""
if not ch:
return 0
if unicodedata.combining(ch):
return 0
if unicodedata.east_asian_width(ch) in ("W", "F"):
return 2
return 1
def display_width(text: str) -> int:
"""Compute visual width of text (ANSI ignored)."""
clean = strip_ansi(text)
return sum(char_display_width(ch) for ch in clean)
def fit_ansi_text(text: str, width: int) -> str:
"""Trim/pad ANSI-colored text to exact display width."""
if width <= 0:
return ""
ansi_re = re.compile(r'(\x1b\[[0-9;]*m)')
tokens = ansi_re.split(text)
out = []
used = 0
for token in tokens:
if not token:
continue
if ansi_re.fullmatch(token):
out.append(token)
continue
for ch in token:
w = char_display_width(ch)
if used + w > width:
break
out.append(ch)
used += w
if used >= width:
break
if used < width:
out.append(" " * (width - used))
return "".join(out)
def print_line(char: str = '═') -> None:
"""Print a horizontal line."""
width = get_terminal_width()
print(char * width)
def clear_screen() -> None:
"""Clear the terminal screen."""
os.system('clear' if os.name != 'nt' else 'cls')
def is_probable_esp32(port) -> bool:
"""Heuristic check to guess ESP32 serial adapters."""
haystack = " ".join(filter(None, [port.description, port.manufacturer, port.hwid])).lower()
keywords = ["esp32", "cp210", "ch340", "silicon labs", "uart"]
return any(keyword in haystack for keyword in keywords)
def list_serial_devices() -> List:
"""Return a list of available serial devices."""
return list(list_ports.comports())
def print_usage() -> None:
"""Print CLI usage."""
print(f"{Colors.CYAN}JanOS Controller{Colors.NC} - ESP32-C5 Wireless Controller")
print()
print("Usage: ./JanOS_app.py")
print("Optional: ./JanOS_app.py <device>")
print()
print("Arguments:")
print(" device Serial device path (e.g., /dev/ttyUSB0, /dev/cu.usbserial-*)")
print()
print("Examples:")
print(" ./JanOS_app.py # Interactive selector")
print(" ./JanOS_app.py /dev/ttyUSB0 # Linux")
print(" ./JanOS_app.py /dev/cu.usbserial-0001 # macOS")
print()
# ============================================================================
# UI Components
# ============================================================================
COMPACT_BOX_WIDTH = 60
class UI:
@staticmethod
def print_box_top() -> None:
width = get_terminal_width()
inner_width = max(0, width - 2)
print(f"{Colors.CYAN}{BOX_TL}{BOX_H * inner_width}{BOX_TR}{Colors.NC}")
@staticmethod
def print_box_bottom() -> None:
width = get_terminal_width()
inner_width = max(0, width - 2)
print(f"{Colors.CYAN}{BOX_BL}{BOX_H * inner_width}{BOX_BR}{Colors.NC}")
@staticmethod
def print_box_separator() -> None:
width = get_terminal_width()
inner_width = max(0, width - 2)
print(f"{Colors.CYAN}{BOX_LT}{BOX_H * inner_width}{BOX_RT}{Colors.NC}")
@staticmethod
def print_box_line() -> None:
width = get_terminal_width()
inner_width = max(0, width - 2)
print(f"{Colors.CYAN}{BOX_V}{Colors.NC}{' ' * inner_width}{Colors.CYAN}{BOX_V}{Colors.NC}")
@staticmethod
def print_box_text(text: str, color: str = Colors.NC) -> None:
width = get_terminal_width()
inner_width = max(0, width - 4)
text_clean = strip_ansi(text)
text_len = len(text_clean)
padding = max(0, inner_width - text_len)
print(f"{Colors.CYAN}{BOX_V}{Colors.NC} {color}{text}{Colors.NC}{' ' * padding}{Colors.CYAN}{BOX_V}{Colors.NC}")
@staticmethod
def print_box_text_centered(text: str, color: str = Colors.NC) -> None:
width = get_terminal_width()
inner_width = max(0, width - 4)
text_clean = strip_ansi(text)
text_len = len(text_clean)
left_pad = max(0, (inner_width - text_len) // 2)
right_pad = max(0, inner_width - text_len - left_pad)
print(f"{Colors.CYAN}{BOX_V}{Colors.NC}{' ' * left_pad}{color}{text}{Colors.NC}{' ' * right_pad}{Colors.CYAN}{BOX_V}{Colors.NC}")
@staticmethod
def print_banner(device: str, attack_running: bool = False, blackout_running: bool = False,
sniffer_running: bool = False, sae_overflow_running: bool = False,
handshake_running: bool = False, portal_running: bool = False,
evil_twin_running: bool = False) -> None:
banner = f"""{Colors.CYAN}
██╗ █████╗ ███╗ ██╗ ██████╗ ███████╗
██║██╔══██╗████╗ ██║██╔═══██╗██╔════╝
██║███████║██╔██╗ ██║██║ ██║███████╗
██ ██║██╔══██║██║╚██╗██║██║ ██║╚════██║
╚█████╔╝██║ ██║██║ ╚████║╚██████╔╝███████║
╚════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝
{Colors.NC}"""
print(banner)
print(f"{Colors.GRAY} for /LAB5/ devices{Colors.NC}")
print(f"{Colors.GRAY} Device: {Colors.WHITE}{device}{Colors.NC}")
if attack_running:
print(f"{Colors.RED} ⚠ DEAUTH ATTACK RUNNING ⚠{Colors.NC}")
if blackout_running:
print(f"{Colors.RED} ⚠ BLACKOUT ATTACK RUNNING ⚠{Colors.NC}")
if sniffer_running:
print(f"{Colors.CYAN} 📡 SNIFFER RUNNING 📡{Colors.NC}")
if sae_overflow_running:
print(f"{Colors.MAGENTA} ⚠ WPA3 SAE OVERFLOW RUNNING ⚠{Colors.NC}")
if handshake_running:
print(f"{Colors.YELLOW} ⚠ HANDSHAKE CAPTURE RUNNING ⚠{Colors.NC}")
if portal_running:
print(f"{Colors.BLUE} 🌐 CAPTIVE PORTAL RUNNING 🌐{Colors.NC}")
if evil_twin_running:
print(f"{Colors.MAGENTA} 👥 EVIL TWIN ATTACK RUNNING 👥{Colors.NC}")
@staticmethod
def print_main_menu() -> None:
"""Print the main menu with categories."""
lines = [
"",
f"{Colors.GREEN}1){Colors.NC} Scan",
f"{Colors.GREEN}2){Colors.NC} Sniffer",
f"{Colors.GREEN}3){Colors.NC} Attacks",
f"{Colors.GREEN}4){Colors.NC} Wardrive",
f"{Colors.GREEN}5){Colors.NC} SD data",
"",
f"{Colors.GRAY}0){Colors.NC} Exit",
]
UI.print_compact_box("MAIN MENU", lines, Colors.CYAN)
@staticmethod
def print_scan_menu(network_count: int, selected_networks: str) -> None:
"""Print the scan submenu."""
lines = [
"",
f"{Colors.GREEN}1){Colors.NC} Scan networks",
f"{Colors.GREEN}2){Colors.NC} Show scan results",
f"{Colors.GREEN}3){Colors.NC} Select networks",
"",
f"{Colors.GRAY}0){Colors.NC} Back to main menu",
]
UI.print_compact_box("SCAN", lines, Colors.CYAN)
# Status line
if network_count > 0:
print(f"{Colors.GREEN}[+] Networks found: {network_count}{Colors.NC}")
else:
print(f"{Colors.GRAY}[-] No networks scanned{Colors.NC}")
if selected_networks:
print(f"{Colors.GREEN}[+] Selected: {selected_networks}{Colors.NC}")
print()
@staticmethod
def print_sniffer_menu(sniffer_running: bool, packets_captured: int = 0) -> None:
"""Print the sniffer submenu."""
lines = [
"",
f"{Colors.GREEN}1){Colors.NC} Start sniffer",
f"{Colors.GREEN}2){Colors.NC} Show results",
f"{Colors.GREEN}3){Colors.NC} Show probes",
"",
f"{Colors.GRAY}0){Colors.NC} Back to main menu",
]
UI.print_compact_box("SNIFFER", lines, Colors.CYAN)
# Status line
if sniffer_running:
print(f"{Colors.CYAN}[📡] Sniffer is RUNNING{Colors.NC}")
print(f"{Colors.CYAN}[+] Packets captured: {packets_captured}{Colors.NC}")
else:
print(f"{Colors.GRAY}[-] Sniffer not running{Colors.NC}")
print()
@staticmethod
def print_attacks_menu(selected_networks: str, attack_running: bool, blackout_running: bool,
sae_overflow_running: bool, handshake_running: bool, portal_running: bool,
evil_twin_running: bool, beacon_spam_running: bool = False,
arp_running: bool = False, mitm_running: bool = False) -> None:
"""Print the attacks submenu."""
lines = [
"",
f"{Colors.GRAY}global WiFi attacks{Colors.NC}",
f"{Colors.GREEN}1){Colors.NC} Deauth",
f"{Colors.GREEN}2){Colors.NC} Blackout",
f"{Colors.GREEN}3){Colors.NC} WPA3 SAE Overflow",
f"{Colors.GREEN}4){Colors.NC} Handshaker",
f"{Colors.GREEN}5){Colors.NC} Portal",
f"{Colors.GREEN}6){Colors.NC} Evil Twin",
f"{Colors.GREEN}7){Colors.NC} Beacon spam",
"",
f"{Colors.GRAY}inside network attacks{Colors.NC}",
f"{Colors.GREEN}8){Colors.NC} ARP",
f"{Colors.GREEN}9){Colors.NC} MITM",
"",
f"{Colors.RED}10){Colors.NC} Stop ALL actions",
f"{Colors.GRAY}0){Colors.NC} Back to main menu",
]
UI.print_compact_box("ATTACKS", lines, Colors.CYAN)
# Status line
if selected_networks:
print(f"{Colors.GREEN}[+] Selected: {selected_networks}{Colors.NC}")
else:
print(f"{Colors.YELLOW}[!] No networks selected{Colors.NC}")
if attack_running:
print(f"{Colors.RED}[!] Deauth Attack is RUNNING{Colors.NC}")
if blackout_running:
print(f"{Colors.RED}[!] Blackout Attack is RUNNING{Colors.NC}")
if sae_overflow_running:
print(f"{Colors.MAGENTA}[!] WPA3 SAE Overflow is RUNNING{Colors.NC}")
if handshake_running:
print(f"{Colors.YELLOW}[!] Handshake Capture is RUNNING{Colors.NC}")
if portal_running:
print(f"{Colors.BLUE}[!] Captive Portal is RUNNING{Colors.NC}")
if evil_twin_running:
print(f"{Colors.MAGENTA}[!] Evil Twin Attack is RUNNING{Colors.NC}")
if beacon_spam_running:
print(f"{Colors.YELLOW}[!] Beacon spam is RUNNING{Colors.NC}")
if arp_running:
print(f"{Colors.YELLOW}[!] ARP attack is RUNNING{Colors.NC}")
if mitm_running:
print(f"{Colors.CYAN}[!] MITM attack is RUNNING{Colors.NC}")
if not attack_running and not blackout_running and not sae_overflow_running and not handshake_running and not portal_running and not evil_twin_running and not beacon_spam_running and not arp_running and not mitm_running:
print(f"{Colors.GRAY}[-] No attacks running{Colors.NC}")
print()
@staticmethod
def print_portal_menu() -> None:
"""Print the portal setup submenu."""
lines = [
"",
f"{Colors.GREEN}1){Colors.NC} Setup and start captive portal",
f"{Colors.GREEN}2){Colors.NC} Show captured data",
"",
f"{Colors.GRAY}0){Colors.NC} Back to attacks",
]
UI.print_compact_box("PORTAL", lines, Colors.CYAN)
@staticmethod
def print_evil_twin_menu() -> None:
"""Print the evil twin setup submenu."""
lines = [
"",
f"{Colors.GREEN}1){Colors.NC} Setup and start evil twin",
f"{Colors.GREEN}2){Colors.NC} Show captured data",
"",
f"{Colors.GRAY}0){Colors.NC} Back to attacks",
]
UI.print_compact_box("EVIL TWIN", lines, Colors.CYAN)
@staticmethod
def print_system_menu() -> None:
"""Print the system submenu."""
lines = [
"",
f"{Colors.GREEN}1){Colors.NC} Reboot device",
f"{Colors.GREEN}2){Colors.NC} Ping host",
f"{Colors.GREEN}3){Colors.NC} List SD card",
"",
f"{Colors.GRAY}0){Colors.NC} Back to main menu",
]
UI.print_compact_box("SYSTEM", lines, Colors.CYAN)
@staticmethod
def print_wardrive_menu() -> None:
"""Print the wardrive submenu."""
lines = [
"",
f"{Colors.GREEN}1){Colors.NC} Start wardrive",
f"{Colors.GREEN}2){Colors.NC} GPS setup",
"",
f"{Colors.GRAY}0){Colors.NC} Back to main menu",
]
UI.print_compact_box("WARDRIVE", lines, Colors.CYAN)
@staticmethod
def print_gps_setup_menu() -> None:
"""Print GPS setup submenu."""
lines = [
"",
f"{Colors.GREEN}1){Colors.NC} Read current GPS module",
f"{Colors.GREEN}2){Colors.NC} Set GPS module: m5",
f"{Colors.GREEN}3){Colors.NC} Set GPS module: atgm",
f"{Colors.GREEN}4){Colors.NC} Set GPS module: tab5",
f"{Colors.GREEN}5){Colors.NC} Set GPS module: cap",
f"{Colors.GREEN}6){Colors.NC} Start GPS raw monitor",
"",
f"{Colors.GRAY}0){Colors.NC} Back to wardrive menu",
]
UI.print_compact_box("GPS SETUP", lines, Colors.CYAN)
@staticmethod
def print_sd_data_menu() -> None:
"""Print SD data submenu."""
lines = [
"",
f"{Colors.GREEN}1){Colors.NC} htmls",
f"{Colors.GREEN}2){Colors.NC} evil twin & portal",
f"{Colors.GREEN}3){Colors.NC} warlogs",
f"{Colors.GREEN}4){Colors.NC} handshakes",
f"{Colors.GREEN}5){Colors.NC} pcap",
"",
f"{Colors.GRAY}0){Colors.NC} Back to main menu",
]
UI.print_compact_box("SD DATA", lines, Colors.CYAN)
@staticmethod
def print_beacon_spam_menu() -> None:
"""Print beacon spam submenu."""
lines = [
"",
f"{Colors.GREEN}1){Colors.NC} Start",
f"{Colors.GREEN}2){Colors.NC} SSID list",
"",
f"{Colors.GRAY}0){Colors.NC} Back to attacks",
]
UI.print_compact_box("BEACON SPAM", lines, Colors.CYAN)
@staticmethod
def print_compact_box(title: str, lines: List[str], color: str = Colors.CYAN,
width: int = COMPACT_BOX_WIDTH) -> None:
"""Print a compact fixed-width box with centered title."""
width = max(30, width)
inner = width - 2
print(f"{color}╔{'═' * inner}╗{Colors.NC}")
title_text = f" {title} "
title_len = display_width(title_text)
if title_len > inner:
title_text = fit_ansi_text(title_text, inner)
title_len = display_width(title_text)
left_pad = max(0, (inner - title_len) // 2)
right_pad = max(0, inner - title_len - left_pad)
print(f"{color}║{Colors.NC}{' ' * left_pad}{Colors.WHITE}{Colors.BOLD}{title_text}{Colors.NC}{' ' * right_pad}{color}║{Colors.NC}")
print(f"{color}╠{'═' * inner}╣{Colors.NC}")
for line in lines:
fitted = fit_ansi_text(line, inner - 2)
print(f"{color}║{Colors.NC} {fitted} {color}║{Colors.NC}")
print(f"{color}╚{'═' * inner}╝{Colors.NC}")
print()
def select_device_interactive() -> str:
"""Interactive ESP32-C5 device selector."""
while True:
clear_screen()
UI.print_banner("Device setup", False, False, False, False, False, False, False)
print(f"{Colors.GRAY}Select the ESP32-C5 device to connect{Colors.NC}")
print()
ports = list_serial_devices()
if not ports:
print(f"{Colors.RED}[!] No serial devices found{Colors.NC}")
print("Options: [r] rescan, [m] manual path, [q] quit")
choice = input("Select option: ").strip().lower()
if choice == 'r':
continue
if choice == 'm':
manual = input("Enter device path: ").strip()
if manual:
return manual
continue
if choice == 'q':
sys.exit(0)
continue
print(f"{Colors.CYAN}Available USB/UART devices:{Colors.NC}")
for idx, port in enumerate(ports, 1):
mark = (
f"{Colors.GREEN}ESP32-C5 candidate{Colors.NC}"
if is_probable_esp32(port)
else f"{Colors.GRAY}other USB/UART{Colors.NC}"
)
desc = port.description or "Unknown"
manuf = port.manufacturer or ""
hwid = port.hwid or ""
extra = f" - {manuf}" if manuf else ""
print(f" {idx}) {port.device} {Colors.GRAY}{desc}{extra}{Colors.NC} [{mark}]")
if hwid:
print(f" {Colors.DIM}{hwid}{Colors.NC}")
print()
choice = input("Select device number, [r] rescan, [m] manual, [q] quit: ").strip().lower()
if choice == 'r':
continue
if choice == 'm':
manual = input("Enter device path: ").strip()
if manual:
return manual
continue
if choice == 'q':
sys.exit(0)
if not choice.isdigit():
print(f"{Colors.RED}Invalid selection{Colors.NC}")
time.sleep(1)
continue
index = int(choice) - 1
if index < 0 or index >= len(ports):
print(f"{Colors.RED}Selection out of range{Colors.NC}")
time.sleep(1)
continue
selected = ports[index]
desc = selected.description or "Unknown"
confirm = input(f"Use {selected.device} ({desc})? [Y/n]: ").strip().lower()
if confirm in ['', 'y', 'yes']:
return selected.device
# ============================================================================
# Serial Communication
# ============================================================================
class SerialManager:
def __init__(self, device: str):
self.device = device
self.serial_conn = None
self.baud_rate = BAUD_RATE
self.os_type = detect_os()
self.setup_serial()
def setup_serial(self) -> None:
"""Setup serial connection."""
if not os.path.exists(self.device):
print(f"{Colors.RED}Error: Device {self.device} does not exist{Colors.NC}")
sys.exit(1)
# Check permissions
if not os.access(self.device, os.R_OK | os.W_OK):
print(f"{Colors.RED}Error: No read/write access to '{self.device}'{Colors.NC}")
print()
print("Try running with sudo or add your user to the dialout group:")
print(" sudo usermod -a -G dialout $USER # Linux")
print(" # Then log out and log back in")
sys.exit(1)
try:
# Use Python's serial library for better cross-platform support
self.serial_conn = serial.Serial(
port=self.device,
baudrate=self.baud_rate,
bytesize=serial.EIGHTBITS,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=READ_TIMEOUT,
write_timeout=2
)
# Clear any existing data
self.serial_conn.reset_input_buffer()
self.serial_conn.reset_output_buffer()
except Exception as e:
print(f"{Colors.RED}Error opening serial port: {e}{Colors.NC}")
sys.exit(1)
def send_command(self, command: str) -> None:
"""Send command to ESP32."""
if not self.serial_conn:
print(f"{Colors.RED}Serial connection not established{Colors.NC}")
return
try:
full_command = command + "\r\n"
self.serial_conn.write(full_command.encode('utf-8'))
self.serial_conn.flush()
time.sleep(0.1)
except Exception as e:
print(f"{Colors.RED}Error sending command: {e}{Colors.NC}")
def clear_input(self) -> None:
"""Drop stale UART input so next read belongs to next command."""
if not self.serial_conn:
return
try:
self.serial_conn.reset_input_buffer()
except Exception:
pass
def read_response(self, timeout: float = SCAN_TIMEOUT) -> List[str]:
"""Read response from ESP32 with timeout."""
if not self.serial_conn:
return []
lines = []
start_time = time.time()
while time.time() - start_time < timeout:
if self.serial_conn.in_waiting:
try:
line = self.serial_conn.readline().decode('utf-8', errors='replace').strip()
if line:
lines.append(line)
except Exception as e:
print(f"{Colors.YELLOW}Read error: {e}{Colors.NC}")
continue
else:
# Small sleep to prevent CPU spinning
time.sleep(0.1)
return lines
def read_until_silence(self, max_wait: float = 8.0, idle_timeout: float = 1.2) -> List[str]:
"""Read lines until no new data appears for idle_timeout seconds."""
if not self.serial_conn:
return []
lines = []
start_time = time.time()
last_data_time = start_time
while time.time() - start_time < max_wait:
if self.serial_conn.in_waiting:
try:
line = self.serial_conn.readline().decode('utf-8', errors='replace').strip()
if line:
lines.append(line)
last_data_time = time.time()
except Exception:
continue
else:
if lines and (time.time() - last_data_time) >= idle_timeout:
break
time.sleep(0.05)
return lines
def read_sniffer_data(self, update_callback, stop_event) -> None:
"""Read sniffer data with dynamic update."""
if not self.serial_conn:
return
while not stop_event.is_set():
if self.serial_conn.in_waiting:
try:
line = self.serial_conn.readline().decode('utf-8', errors='replace').strip()
if line:
update_callback(line)
except Exception:
pass
time.sleep(0.1)
def read_portal_data(self, update_callback, stop_event) -> None:
"""Read portal data with real-time updates."""
if not self.serial_conn:
return
while not stop_event.is_set():
if self.serial_conn.in_waiting:
try:
line = self.serial_conn.readline().decode('utf-8', errors='replace').strip()
if line:
update_callback(line)
except Exception:
pass
time.sleep(0.1)
def read_evil_twin_data(self, update_callback, stop_event) -> None:
"""Read evil twin data with real-time updates."""
if not self.serial_conn:
return
while not stop_event.is_set():
if self.serial_conn.in_waiting:
try:
line = self.serial_conn.readline().decode('utf-8', errors='replace').strip()
if line:
update_callback(line)
except Exception:
pass
time.sleep(0.1)
def close(self) -> None:
"""Close serial connection."""
if self.serial_conn:
self.serial_conn.close()
# ============================================================================
# Network Management
# ============================================================================
class NetworkManager:
def __init__(self):
self.networks: List[Dict[str, str]] = []
self.network_count = 0
self.selected_networks = ""
self.scan_done = False
def parse_network_line(self, line: str) -> Optional[Dict[str, str]]:
"""Parse a network line from ESP32 output."""
# Expected format: "index","ssid","vendor","bssid","channel","auth","rssi","band"
if not line.startswith('"'):
return None
try:
# Simple CSV parsing
parts = [p.strip('"') for p in line.split('","')]
if len(parts) < 8:
return None
network = {
'index': parts[0],
'ssid': parts[1] if parts[1] else "<hidden>",
'vendor': parts[2],
'bssid': parts[3],
'channel': parts[4],
'auth': parts[5],
'rssi': parts[6],
'band': parts[7]
}
return network
except:
return None
def add_network(self, line: str) -> None:
"""Add a network from parsed line."""
network = self.parse_network_line(line)
if network:
self.networks.append(network)
self.network_count += 1
def clear_networks(self) -> None:
"""Clear all networks."""
self.networks.clear()
self.network_count = 0
self.scan_done = False
def set_selected_networks(self, selection: str) -> None:
"""Set selected networks."""
self.selected_networks = selection
def get_rssi_color(self, rssi_str: str) -> str:
"""Get color code for RSSI value."""
if not rssi_str:
return Colors.GRAY
try:
# Extract numeric value
rssi_num = int(rssi_str.replace('dBm', '').strip())
if rssi_num < -70:
return Colors.RED
elif rssi_num < -50:
return Colors.YELLOW
else:
return Colors.GREEN
except:
return Colors.GRAY
def display_networks(self) -> None:
"""Display networks in a table."""
if self.network_count == 0:
print(f"{Colors.YELLOW}[!] No networks scanned yet. Run a scan first.{Colors.NC}")
print()
input("Press Enter to continue...")
return
clear_screen()
terminal_width = get_terminal_width()
table_width = max(40, min(terminal_width - 4, 110))
lines = [
f"{Colors.WHITE}# SSID BSSID CH RSSI Auth{Colors.NC}",
""
]
for network in self.networks:
idx = network.get('index', '?')
ssid = network.get('ssid', '?')
bssid = network.get('bssid', '?')
channel = network.get('channel', '?')
auth = network.get('auth', '?')
rssi = network.get('rssi', '?')
# Truncate SSID if too long
if len(ssid) > 24:
ssid = ssid[:21] + "..."
# Truncate auth if too long
if len(auth) > 12:
auth = auth[:10] + ".."
rssi_color = self.get_rssi_color(rssi)
row = (
f"{Colors.GREEN}{idx:<3}{Colors.NC} "
f"{ssid:<25} "
f"{Colors.GRAY}{bssid:<17}{Colors.NC} "
f"{channel:<3} "
f"{rssi_color}{rssi:<6}{Colors.NC} "
f"{auth:<12}"
)
lines.append(row)
UI.print_compact_box("SCAN RESULTS", lines, Colors.CYAN, width=table_width)
if self.selected_networks:
print(f"{Colors.GREEN}[+] Selected networks: {Colors.WHITE}{self.selected_networks}{Colors.NC}")
print()
input("Press Enter to continue...")
# ============================================================================
# Main Application
# ============================================================================
class JanOS:
def __init__(self, device: str):
self.device = device
self.serial_mgr = SerialManager(device)
self.network_mgr = NetworkManager()
self.attack_running = False
self.blackout_running = False
self.sniffer_running = False
self.sae_overflow_running = False
self.handshake_running = False
self.portal_running = False
self.evil_twin_running = False
self.wardrive_running = False
self.beacon_spam_running = False
self.arp_running = False
self.mitm_running = False
self.wifi_connected = False
self.connected_ssid = ""
self.sniffer_packets = 0
self.sniffer_thread = None
self.stop_sniffer_event = threading.Event()
self.portal_thread = None
self.stop_portal_event = threading.Event()
self.evil_twin_thread = None
self.stop_evil_twin_event = threading.Event()
self.wardrive_thread = None
self.stop_wardrive_event = threading.Event()
self.portal_html_files = []
self.selected_html_index = -1
self.selected_html_name = ""
self.portal_ssid = ""
self.submitted_forms = 0
self.last_submitted_data = ""
self.client_count = 0
self.evil_twin_ssid = ""
self.evil_twin_captured_data = []
self.evil_twin_client_count = 0
self.wardrive_logged_networks = 0
self.wardrive_last_file = ""
self.handshake_capture_count = 0
self.handshake_last_file = ""
self.handshake_last_ssid = ""
self.last_handshake_line = ""
self.wardrive_last_lat = ""
self.wardrive_last_lon = ""
self.wardrive_last_alt = ""
self.wardrive_last_acc = ""
self.wardrive_waiting_for_fix = False
self.last_wardrive_line = ""
self.os_type = detect_os()
self.last_sniffer_line = ""
if self.os_type == 'unknown':
print(f"{Colors.RED}Error: Unsupported operating system{Colors.NC}")
sys.exit(1)
def _mark_all_actions_stopped(self) -> None:
"""Reset local state flags after sending global stop to ESP."""
self.attack_running = False
self.blackout_running = False
self.sniffer_running = False
self.sae_overflow_running = False
self.handshake_running = False
self.portal_running = False
self.evil_twin_running = False
self.wardrive_running = False
self.beacon_spam_running = False
self.arp_running = False
self.mitm_running = False
def show_usage(self) -> None:
"""Show usage information."""
print_usage()
def update_sniffer_display(self, data: str) -> None:
"""Update sniffer packet count from received data."""
# Try to extract packet count from various formats
import re
if not data or data == self.last_sniffer_line:
return
self.last_sniffer_line = data
match = re.search(r'(?:packets?|pkts?)\s*[:=]\s*(\d+)', data, re.IGNORECASE)
if not match:
match = re.search(r'(?:captured|capture)\s*[:=]?\s*(\d+)', data, re.IGNORECASE)
if not match:
match = re.search(r'(\d+)\s*(?:packets?|pkts?)', data, re.IGNORECASE)
if match:
self.sniffer_packets = int(match.group(1))
return
# Fallback: count lines that look like packet data
if re.search(r'([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})', data):
self.sniffer_packets += 1
return
lower = data.lower()
ignore_prefixes = (
"sniffer", "total", "starting", "stopping", "scan",
"wifi", "channel", "packets", "probe", "error", "failed"
)
if lower.startswith(ignore_prefixes) or data.startswith(">"):
return
if data.strip():
self.sniffer_packets += 1
def update_portal_display(self, data: str) -> None:
"""Update portal display with real-time data."""
# Check for client connections
if "Client connected" in data:
self.client_count += 1
print(f"\n{Colors.GREEN}[+] {data}{Colors.NC}")
# Check for client count updates
elif "Client count" in data:
match = re.search(r'Client count = (\d+)', data)
if match:
self.client_count = int(match.group(1))
print(f"{Colors.BLUE}[*] Connected clients: {self.client_count}{Colors.NC}")
# Check for password submissions
elif "Password:" in data:
self.submitted_forms += 1
# Extract password from the line
password_match = re.search(r'Password:\s*(.+)$', data)
if password_match:
password = password_match.group(1)
self.last_submitted_data = f"Password: {password}"
print(f"\n{Colors.GREEN}[+] Form submitted!{Colors.NC}")
print(f"{Colors.GREEN}[+] Password captured: {password}{Colors.NC}")
# Check for form data with other fields
elif "Form data:" in data or "username:" in data.lower() or "email:" in data.lower():
self.submitted_forms += 1
self.last_submitted_data = data
print(f"\n{Colors.GREEN}[+] Form submitted!{Colors.NC}")
print(f"{Colors.GREEN}[+] {data}{Colors.NC}")
# Check for data saved to file
elif "Portal data saved" in data:
print(f"{Colors.BLUE}[*] {data}{Colors.NC}")
# Check for portal errors or status
elif "error" in data.lower() or "failed" in data.lower():
print(f"{Colors.RED}[!] {data}{Colors.NC}")
elif "started successfully" in data or "enabled" in data:
print(f"{Colors.GREEN}[+] {data}{Colors.NC}")
def update_evil_twin_display(self, data: str) -> None:
"""Update evil twin display with real-time data."""
# Check for client connections
if "Client connected" in data:
self.evil_twin_client_count += 1
print(f"\n{Colors.GREEN}[+] {data}{Colors.NC}")
# Check for client trying to connect to evil twin
elif "trying to connect" in data.lower() or "association" in data.lower():
print(f"{Colors.MAGENTA}[*] {data}{Colors.NC}")