Repository navigation
Expand file tree
/
Copy pathdisplay.py
More file actions
executable file
·4932 lines (4431 loc) · 227 KB
/
Copy pathdisplay.py
File metadata and controls
executable file
·4932 lines (4431 loc) · 227 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
#display.py
# Description:
# This file, display.py, is responsible for managing the e-ink display of the Ragnar project, updating it with relevant data and statuses.
# It initializes the display, manages multiple threads for updating shared data and vulnerability counts, and handles the rendering of information
# and images on the display.
#
# Key functionalities include:
# - Initializing the e-ink display (EPD) and handling any errors during initialization.
# - Creating and managing threads to periodically update shared data and vulnerability counts.
# - Rendering various statistics, status icons, and images on the e-ink display.
# - Handling updates to shared data from various sources, including CSV files and system commands.
# - Checking and displaying the status of Bluetooth, Wi-Fi, PAN, and USB connections.
# - Providing methods to update the display with comments from an AI (Commentaireia) and generating images dynamically.
import threading
import time
import os
import re
import signal
import glob
import logging
import random
import sys
import csv
import math
from PIL import Image, ImageDraw, ImageFont
from init_shared import shared_data
from comment import Commentaireia
from logger import Logger
import subprocess
from shared import detect_wifi_interface
def _short_scan_error(err):
"""Squeeze a BT/Zigbee scanner error into the ~10 chars the net-diag card's
value column has. The scanners return sentence-length diagnostics (great in
the web UI, unreadable on a 128 px panel), so map the ones a field tester
actually hits to a short reason and clip anything unrecognised."""
e = str(err or '').lower()
if 'pyserial' in e:
return 'no pyserial'
# The radio check comes first: "this Huginn has no 802.15.4 radio" names a
# board that IS present, so it must not be reported as a missing one.
if '802.15.4' in e or 'not compiled' in e:
return 'no 15.4 rx'
if 'huginn' in e or 'companion' in e:
return 'no Huginn'
if 'busy' in e or 'in use' in e or 'permission' in e or 'cannot open' in e:
return 'port busy'
if 'controller' in e or 'adapter' in e or 'bluetoothd' in e or 'rfkill' in e:
return 'no adapter'
return str(err or 'failed')[:11]
def _fmt_wd_speed(speed_kmh, unit, decimals=1):
"""Format a km/h speed for the wardriving display in the configured unit.
Recorded data is always stored in km/h; ``unit`` ('kmh' or 'mph') only
controls presentation. Returns e.g. '12.3km/h' or '7.6mph'.
"""
if speed_kmh is None:
return None
if unit == 'mph':
return f"{speed_kmh * 0.621371:.{decimals}f}mph"
return f"{speed_kmh:.{decimals}f}km/h"
# Map rotation angle → PIL transpose operation
_ROTATION_TRANSPOSE = {
90: Image.Transpose.ROTATE_90,
180: Image.Transpose.ROTATE_180,
270: Image.Transpose.ROTATE_270,
}
def _render_dimensions(width, height, rotation):
"""Return (render_w, render_h) for the given rotation.
For 90°/270° the render canvas is portrait (swapped) so that the
e-paper getbuffer 'Vertical' path maps it correctly to the landscape
display buffer. For 0°/180° dimensions stay as-is.
"""
if rotation in (90, 270):
return height, width
return width, height
def _apply_epd_rotation(image, rotation):
"""Apply rotation for the EPD hardware path.
* 0° – no-op
* 180° – PIL ROTATE_180 (same dims, horizontal getbuffer path)
* 90° – no-op (image is already portrait, getbuffer vertical handles it)
* 270° – PIL ROTATE_180 (flips the portrait image, getbuffer vertical gives opposite orientation)
"""
if rotation == 180:
return image.transpose(Image.Transpose.ROTATE_180)
if rotation == 270:
return image.transpose(Image.Transpose.ROTATE_180)
return image
def _apply_web_rotation(image, rotation):
"""Apply rotation for the web preview PNG.
The web preview should match what the user physically sees on the display.
* 0° – landscape, show as-is
* 90° – portrait, show as-is (getbuffer + physical mount cancel)
* 180° – landscape upside-down
* 270° – portrait upside-down (getbuffer + physical mount cancel, image was flipped)
"""
if rotation in (180, 270):
return image.transpose(Image.Transpose.ROTATE_180)
return image
logger = Logger(name="display.py", level=logging.DEBUG)
# Import button listener (only functional on Pi with GPIO)
try:
from epd_button import EPDButtonListener, PAGE_MAIN, PAGE_NETWORK, PAGE_VULN, PAGE_DISCOVERED, PAGE_ADVANCED, PAGE_TRAFFIC
from epd_button import (NETDIAG_CARD_FUNCS, NETDIAG_CARD_NAMES,
netdiag_card_funcs, netdiag_iface_choices,
netdiag_auto_iface)
except ImportError:
EPDButtonListener = None
PAGE_MAIN, PAGE_NETWORK, PAGE_VULN, PAGE_DISCOVERED, PAGE_ADVANCED, PAGE_TRAFFIC = 0, 1, 2, 3, 4, 5
NETDIAG_CARD_NAMES = ["LINK", "IP", "SWITCH", "DHCP", "WIFI", "SIGNAL",
"SPECTRUM", "IFACE", "BT", "ZIGBEE"]
NETDIAG_CARD_FUNCS = {}
netdiag_card_funcs = (lambda page: [])
netdiag_iface_choices = (lambda: [])
netdiag_auto_iface = (lambda require_egress=False: None)
# Network Diagnostic mode: number of auto-cycling sub-pages
# (0=LINK, 1=IP, 2=SWITCH, 3=DHCP, 4=WIFI, 5=SIGNAL, 6=SPECTRUM, 7=IFACE,
# 8=BT, 9=ZIGBEE). See Display._render_netdiag_page.
NETDIAG_PAGE_COUNT = 10
NETDIAG_CYCLE_SECONDS = 5
# Wardriving screens on the 1.44" ST7735S LCD HAT (128x128), paged with the
# joystick while wardriving runs. Mirrored by lcdhat_input.WARDRIVE_PAGE_COUNT.
# 0=STATS 1=MAP 2=GPS 3=SKY 4=SESSION 5=VIKING
# The 2.7" e-paper HAT is unaffected — it keeps its KEY3 stats/map toggle.
WARDRIVE_PAGE_COUNT = 6
(WD_PAGE_STATS, WD_PAGE_MAP, WD_PAGE_GPS, WD_PAGE_SKY,
WD_PAGE_SESSION, WD_PAGE_VIKING) = range(6)
# Display types that manage their own driver in a dedicated _run_* method and
# legitimately leave epd_helper as None. For every other type, a None helper
# means EPD init failed and we must not call methods on it in the render loop.
_SELF_MANAGED_DISPLAYS = ("gc9a01", "ssd1306", "lcd1602", "max7219_4panel", "max7219_8panel")
class _NullEPDHelper:
"""No-op stand-in for an EPD helper that failed to initialise.
When a real SPI/EPD panel can't be driven (for example the kernel fbtft
driver already owns it for a framebuffer kiosk), the render loop would
otherwise call methods on ``None`` and raise on every frame — freezing the
web ``screen.png`` mirror and pegging a CPU core. Returning a no-op for any
attribute access lets the loop keep running and updating screen.png.
"""
def __getattr__(self, _name):
return lambda *args, **kwargs: None
# --------------------------------------------------------------------------
# nl80211-aware WiFi state
# --------------------------------------------------------------------------
# `iwgetid`/`iwconfig` speak the old Wireless Extensions. Several modern
# drivers - the Allwinner aicwf_sdio onboard radio among them - implement
# only nl80211, so those tools exit 255 and every check reports "not
# connected" against a live association. wpa_cli and iw use nl80211.
def nl80211_ssids():
"""Return {iface: ssid} for every associated station interface."""
out = {}
try:
import os as _os
ifaces = [n for n in sorted(_os.listdir("/sys/class/net"))
if n.startswith(("wlan", "wlx", "wlp", "wls"))]
except Exception:
ifaces = []
for iface in ifaces:
ssid = ""
try:
r = subprocess.run(["wpa_cli", "-i", iface, "status"],
capture_output=True, text=True, timeout=5)
if r.returncode == 0:
state = ""
for line in (r.stdout or "").splitlines():
if line.startswith("ssid="):
ssid = line.split("=", 1)[1].strip()
elif line.startswith("wpa_state="):
state = line.split("=", 1)[1].strip()
if state and state != "COMPLETED":
ssid = ""
except Exception:
pass
if not ssid:
try:
r = subprocess.run(["iw", "dev", iface, "link"],
capture_output=True, text=True, timeout=5)
if r.returncode == 0:
for line in (r.stdout or "").splitlines():
if line.strip().startswith("SSID:"):
ssid = line.split(":", 1)[1].strip()
break
except Exception:
pass
if ssid:
out[iface] = ssid
return out
def nl80211_any_connected():
return bool(nl80211_ssids())
def nl80211_current_ssid():
for iface in sorted(nl80211_ssids()):
return nl80211_ssids()[iface]
return ""
class Display:
def __init__(self, shared_data):
"""Initialize the display and start the main image and shared data update threads."""
self.shared_data = shared_data
self.config = self.shared_data.config
self.shared_data.ragnarstatustext2 = "Awakening..."
self.commentaire_ia = Commentaireia()
self.semaphore = threading.Semaphore(10)
self.screen_reversed = self.shared_data.screen_reversed
self.web_screen_reversed = self.shared_data.web_screen_reversed
self.main_image = None # Initialize main_image variable
# Resolve WiFi interface name once (cached in detect_wifi_interface)
self._wifi_iface = detect_wifi_interface(self.config.get('wifi_default_interface', 'auto'))
# Frise position (x=0 since frise is resized to full display width)
self.frise_positions = {
"default": {
"x": 0,
"y": 160
}
}
try:
self.epd_helper = self.shared_data.epd_helper
# A configured EPD panel whose helper is None means init failed
# (e.g. the SPI panel is owned by the kernel fbtft driver). Fall back
# to a no-op helper so the render loop keeps writing screen.png
# headlessly instead of crash-looping on None. Self-managed display
# types legitimately use None and are handled by their _run_* method.
if self.epd_helper is None and self.config.get("epd_type") not in _SELF_MANAGED_DISPLAYS:
logger.warning(f"EPD helper for '{self.config.get('epd_type')}' unavailable; rendering headlessly (screen.png only).")
self.epd_helper = _NullEPDHelper()
# MAX7219, LCD1602 and other non-EPD displays set epd_helper to None;
# skip EPD-specific init — their _run_* method handles setup.
if self.epd_helper is not None:
self.epd_helper.init_partial_update()
logger.info("Display initialization complete.")
except Exception as e:
logger.error(f"Error during display initialization: {e}")
raise
self.main_image_thread = threading.Thread(target=self.update_main_image)
self.main_image_thread.daemon = True
self.main_image_thread.start()
self.update_shared_data_thread = threading.Thread(target=self.schedule_update_shared_data)
self.update_shared_data_thread.daemon = True
self.update_shared_data_thread.start()
self.update_vuln_count_thread = threading.Thread(target=self.schedule_update_vuln_count)
self.update_vuln_count_thread.daemon = True
self.update_vuln_count_thread.start()
self.scale_factor_x = self.shared_data.scale_factor_x
self.scale_factor_y = self.shared_data.scale_factor_y
# Wide display detection (e.g. 2.7" at 176x264 vs reference 122x250)
self.is_wide = self.scale_factor_x > 1.2
# y_stretch is no longer needed — scale_factor_y handles vertical spacing
self.y_stretch = 1.0
# Hardware button support.
# * 1.44" LCD HAT (ST7735S): 3 keys + 5-way joystick (own pin set)
# * 2.7" e-Paper HAT: KEY1-KEY4 (only when the panel is "wide")
# Both drive the same page/net-diag state the render loop reads.
self.button_listener = None
if self.config.get("epd_type") == "st7735s":
try:
from lcdhat_input import LCDHATInputListener
self.button_listener = LCDHATInputListener(shared_data)
self.button_listener.start()
except Exception as e:
logger.warning(f"LCD HAT input listener unavailable: {e}")
elif self.is_wide and EPDButtonListener is not None:
self.button_listener = EPDButtonListener(shared_data)
self.button_listener.start()
def get_frise_position(self):
"""Get the frise position based on the display type."""
display_type = self.config.get("epd_type", "default")
position = self.frise_positions.get(display_type, self.frise_positions["default"])
return (
int(position["x"] * self.scale_factor_x),
int(position["y"] * self.scale_factor_y)
)
def schedule_update_shared_data(self):
"""Periodically update the shared data with the latest system information."""
while not self.shared_data.display_should_exit:
self.update_shared_data()
time.sleep(5) # Check every 5 seconds for faster WiFi/SSH status updates
def schedule_update_vuln_count(self):
"""Periodically update the vulnerability count on the display."""
while not self.shared_data.display_should_exit:
self.update_vuln_count()
time.sleep(300)
def update_main_image(self):
"""Update the main image on the display with the latest immagegen data."""
while not self.shared_data.display_should_exit:
try:
self.shared_data.update_image_randomizer()
if self.shared_data.imagegen:
self.main_image = self.shared_data.imagegen
else:
logger.error("No image generated for current status.")
time.sleep(random.uniform(self.shared_data.image_display_delaymin, self.shared_data.image_display_delaymax))
except Exception as e:
logger.error(f"An error occurred in update_main_image: {e}")
def get_open_files(self):
"""Get the number of open FD files on the system."""
try:
open_files = len(glob.glob('/proc/*/fd/*'))
logger.debug(f"FD : {open_files}")
return open_files
except Exception as e:
logger.error(f"Error getting open files: {e}")
return None
def update_vuln_count(self):
"""Update the vulnerability count on the display."""
import pandas as pd
with self.semaphore:
try:
if not os.path.exists(self.shared_data.vuln_summary_file):
df = pd.DataFrame(columns=["IP", "Hostname", "MAC Address", "Port", "Vulnerabilities"])
df.to_csv(self.shared_data.vuln_summary_file, index=False)
self.shared_data.vulnnbr = 0
logger.info("Vulnerability summary file created.")
else:
# Get alive hosts from SQLite database instead of CSV
try:
db_stats = self.shared_data.db.get_stats()
alive_hosts = self.shared_data.db.get_all_hosts()
alive_macs = {
h['mac'] for h in alive_hosts
if h.get('status') == 'alive' and h.get('mac') != 'STANDALONE'
}
logger.debug(f"Loaded {len(alive_macs)} alive MACs from database")
except Exception as e:
logger.warning(f"Could not get alive MACs from database: {e}")
alive_macs = set()
try:
# Check if file is not empty and has content
if os.path.getsize(self.shared_data.vuln_summary_file) > 0:
with open(self.shared_data.vuln_summary_file, 'r') as file:
df = pd.read_csv(file)
else:
logger.debug("vuln_summary file is empty, initializing with empty DataFrame")
df = pd.DataFrame(columns=["IP", "Hostname", "MAC Address", "Port", "Vulnerabilities"])
except (pd.errors.EmptyDataError, pd.errors.ParserError) as e:
logger.warning(f"Could not parse vuln_summary file: {e}, creating new one")
df = pd.DataFrame(columns=["IP", "Hostname", "MAC Address", "Port", "Vulnerabilities"])
all_vulnerabilities = set()
for index, row in df.iterrows():
mac_address = row["MAC Address"]
if mac_address in alive_macs and mac_address != "STANDALONE":
vulnerabilities = row["Vulnerabilities"]
if pd.isna(vulnerabilities) or not isinstance(vulnerabilities, str):
continue
if vulnerabilities and isinstance(vulnerabilities, str):
all_vulnerabilities.update(vulnerabilities.split("; "))
self.shared_data.vulnnbr = len(all_vulnerabilities)
logger.debug(f"Updated vulnerabilities count: {self.shared_data.vulnnbr}")
if os.path.exists(self.shared_data.livestatusfile):
try:
# Check if file is not empty and has content
if os.path.getsize(self.shared_data.livestatusfile) > 0:
with open(self.shared_data.livestatusfile, 'r+') as livestatus_file:
livestatus_df = pd.read_csv(livestatus_file)
if not livestatus_df.empty:
livestatus_df.loc[0, 'Vulnerabilities Count'] = self.shared_data.vulnnbr
try:
from actions.exploit_engine import get_stats
livestatus_df.loc[0, 'Exploit Count'] = int(get_stats().get('vulnerable', 0))
except Exception:
pass
livestatus_df.to_csv(self.shared_data.livestatusfile, index=False)
logger.debug(f"Updated livestatusfile with vulnerability count: {self.shared_data.vulnnbr}")
else:
logger.debug("livestatus file is empty, skipping update")
except (pd.errors.EmptyDataError, pd.errors.ParserError) as e:
logger.warning(f"Could not parse livestatus file: {e}")
else:
logger.error(f"Livestatusfile {self.shared_data.livestatusfile} does not exist.")
except Exception as e:
logger.error(f"An error occurred in update_vuln_count: {e}")
def update_shared_data(self):
"""Update the shared data with the latest system information."""
import pandas as pd
with self.semaphore:
try:
# Create livestatus file if it doesn't exist
if not os.path.exists(self.shared_data.livestatusfile):
logger.info(f"Creating missing livestatus file: {self.shared_data.livestatusfile}")
self.shared_data.create_livestatusfile()
try:
# Check if file is not empty and has content
if os.path.getsize(self.shared_data.livestatusfile) > 0:
with open(self.shared_data.livestatusfile, 'r') as file:
livestatus_df = pd.read_csv(file)
else:
logger.warning("Livestatus file is empty, recreating it")
self.shared_data.create_livestatusfile()
with open(self.shared_data.livestatusfile, 'r') as file:
livestatus_df = pd.read_csv(file)
except (pd.errors.EmptyDataError, pd.errors.ParserError) as e:
logger.warning(f"Could not parse livestatus file: {e}, recreating it")
self.shared_data.create_livestatusfile()
with open(self.shared_data.livestatusfile, 'r') as file:
livestatus_df = pd.read_csv(file)
# Check if DataFrame is empty or has the expected columns
if livestatus_df.empty:
logger.warning("Livestatus file is empty, skipping data update")
return
# Ensure required columns exist; add them with default 0 if missing
required_columns = ['Total Open Ports', 'Alive Hosts Count', 'All Known Hosts Count', 'Vulnerabilities Count', 'Exploit Count']
for column in required_columns:
if column not in livestatus_df.columns:
logger.warning(f"Column '{column}' missing in livestatus file, initializing with 0")
livestatus_df[column] = 0
# Check if there's at least one row
if len(livestatus_df) == 0:
logger.warning("Livestatus file has no data rows, skipping data update")
return
def _safe_int_from_df(df, column_name):
try:
value = pd.to_numeric(df[column_name].iloc[0], errors='coerce')
if pd.isna(value):
return 0
return int(value)
except Exception as e:
logger.debug(f"Could not parse column '{column_name}' from livestatus file: {e}")
return 0
self.shared_data.portnbr = _safe_int_from_df(livestatus_df, 'Total Open Ports')
self.shared_data.targetnbr = _safe_int_from_df(livestatus_df, 'Alive Hosts Count')
self.shared_data.networkkbnbr = _safe_int_from_df(livestatus_df, 'All Known Hosts Count')
self.shared_data.vulnnbr = _safe_int_from_df(livestatus_df, 'Vulnerabilities Count')
# Persist any columns we added so other components stay in sync
try:
livestatus_df.to_csv(self.shared_data.livestatusfile, index=False)
except Exception as e:
logger.debug(f"Unable to persist normalized livestatus columns: {e}")
crackedpw_files = glob.glob(f"{self.shared_data.crackedpwddir}/*.csv")
total_passwords = 0
for file in crackedpw_files:
try:
# Check if file is not empty and has content
if os.path.getsize(file) > 0:
with open(file, 'r') as f:
df = pd.read_csv(f, usecols=[0])
if not df.empty:
total_passwords += len(df)
else:
logger.debug(f"Password file {file} is empty, skipping")
except (pd.errors.EmptyDataError, pd.errors.ParserError) as e:
logger.debug(f"Could not parse password file {file}: {e}")
continue
except Exception as e:
logger.warning(f"Error reading password file {file}: {e}")
continue
self.shared_data.crednbr = total_passwords
total_data = sum([len(files) for r, d, files in os.walk(self.shared_data.datastolendir)])
self.shared_data.datanbr = total_data
total_zombies = sum([len(files) for r, d, files in os.walk(self.shared_data.zombiesdir)])
self.shared_data.zombiesnbr = total_zombies
total_attacks = sum([len(files) for r, d, files in os.walk(self.shared_data.actions_dir) if not r.endswith("__pycache__")]) - 2
self.shared_data.attacksnbr = total_attacks
self.shared_data.update_stats()
self.shared_data.manual_mode = self.is_manual_mode()
if self.shared_data.manual_mode:
self.manual_mode_txt = "M"
else:
self.manual_mode_txt = "A"
# Check WiFi connectivity with detailed logging
wifi_connected = self.is_wifi_connected()
self.shared_data.wifi_connected = wifi_connected
logger.debug(f"[DISPLAY] WiFi status check: connected={wifi_connected}")
signal_dbm, signal_quality = self.get_wifi_signal_strength() if wifi_connected else (None, None)
self.shared_data.wifi_signal_dbm = signal_dbm
self.shared_data.wifi_signal_quality = signal_quality
if signal_dbm is not None:
logger.debug(f"[DISPLAY] WiFi RSSI: {signal_dbm} dBm, quality={self.shared_data.wifi_signal_quality}%")
self.shared_data.ap_mode_active = self.is_ap_mode_active()
self.shared_data.ap_client_count = self.get_ap_client_count() if self.shared_data.ap_mode_active else 0
self.shared_data.usb_active = self.is_usb_connected()
# Update Wi-Fi/AP status text for display
wifi_status_text = self.get_wifi_status_text()
self.shared_data.ragnarstatustext2 = wifi_status_text
# Per-tick: the display loop re-renders every few seconds.
# Only surface a change at INFO.
# Class-level cache: the display object is rebuilt on refresh,
# so a per-instance cache resets every tick and the line
# repeats forever.
prev = getattr(Display, "_last_wifi_status_text", None)
if wifi_status_text != prev:
Display._last_wifi_status_text = wifi_status_text
logger.info(f"[DISPLAY] WiFi status text: '{wifi_status_text}'")
else:
logger.debug(f"[DISPLAY] WiFi status text: '{wifi_status_text}'")
self.get_open_files()
except (FileNotFoundError, pd.errors.EmptyDataError) as e:
logger.error(f"Error: {e}")
except Exception as e:
logger.error(f"Error updating shared data: {e}")
def display_comment(self, status):
"""Display the comment based on the status of the ragnarorch."""
comment = self.commentaire_ia.get_commentaire(status)
if comment:
self.shared_data.ragnarsays = comment
# Surface exploit summary in the status line the e-ink "current status"
# and web console both read.
try:
ex_line = self._exploit_stat_line()
if ex_line and ex_line != "n/a":
self.shared_data.ragnarstatustext = f"{self.shared_data.ragnarorch_status} | EX:{ex_line}"
else:
self.shared_data.ragnarstatustext = self.shared_data.ragnarorch_status
except Exception:
pass
# # # def is_bluetooth_connected(self):
# # # """
# # # Check if any device is connected to the Bluetooth (pan0) interface by checking the output of 'ip neigh show dev pan0'.
# # # """
# # # try:
# # # result = subprocess.Popen(['ip', 'neigh', 'show', 'dev', 'pan0'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# # # output, error = result.communicate()
# # # if result.returncode != 0:
# # # logger.error(f"Error executing 'ip neigh show dev pan0': {error}")
# # # return False
# # # return bool(output.strip())
# # # except Exception as e:
# # # logger.error(f"Error checking Bluetooth connection status: {e}")
# # # return False
def is_wifi_connected(self):
"""Check if WiFi is connected by checking the current SSID and network connectivity."""
try:
# Method 0: nl80211 (wpa_cli / iw) first. iwgetid is WEXT-only and
# exits 255 on drivers like the Allwinner aicwf_sdio onboard radio.
if nl80211_any_connected():
self._log_wifi_state(True, "nl80211", nl80211_ssids())
return True
# Method 1: Try iwgetid first
result = subprocess.Popen(['iwgetid', '-r'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
ssid, error = result.communicate()
if result.returncode == 0 and ssid.strip():
self._log_wifi_state(True, "iwgetid", ssid.strip())
return True
# Method 2: Check if we have an active network interface with IP
result = subprocess.Popen(['ip', 'route', 'get', '8.8.8.8'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
route_output, error = result.communicate()
if result.returncode == 0 and 'via' in route_output:
self._log_wifi_state(True, "ip route", "")
return True
# Method 3: Check for wlan interface with IP
result = subprocess.Popen(['ip', 'addr', 'show'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
addr_output, error = result.communicate()
if result.returncode == 0:
# Look for wlan interfaces with inet addresses
for line in addr_output.split('\n'):
if ('wlan' in line and 'state UP' in line) or ('inet ' in line and 'scope global' in line and ('wlan' in addr_output)):
logger.debug(f"WiFi connected via interface check")
return True
self._log_wifi_state(False, "none", "")
return False
except Exception as e:
logger.error(f"Error checking WiFi status: {e}")
return False
_wifi_state_cache = {"last": None}
def _log_wifi_state(self, connected, method, detail):
"""Log the WiFi state only when it CHANGES.
The display refresh loop calls is_wifi_connected() every few seconds.
Logging each pass produced four identical lines every 5s - hundreds of
lines an hour of pure noise. Now it logs on transitions only.
"""
state = (connected, method, str(detail))
if state == Display._wifi_state_cache["last"]:
return
Display._wifi_state_cache["last"] = state
if connected:
logger.info(f"[DISPLAY] WiFi connected via {method}: {detail}")
else:
logger.info("[DISPLAY] WiFi not connected")
def _dbm_to_quality(self, signal_dbm):
"""Convert RSSI (dBm) to an approximate 0-100 quality percentage."""
if signal_dbm is None:
return None
quality = int((signal_dbm - (-90)) * 100 / (-30 - (-90)))
return max(0, min(100, quality))
def get_wifi_signal_strength(self):
"""Return a tuple (signal_dbm, quality_percent) if available."""
# Primary method: use `iw dev wlan0 link`
try:
result = subprocess.run(['iw', 'dev', self._wifi_iface, 'link'], capture_output=True, text=True, timeout=2)
if result.returncode == 0:
for line in result.stdout.split('\n'):
if 'signal:' in line:
try:
raw_value = line.split('signal:')[1].split('dBm')[0].strip()
signal_dbm = float(raw_value)
return signal_dbm, self._dbm_to_quality(signal_dbm)
except (ValueError, IndexError):
logger.debug(f"Failed to parse iw signal line: {line.strip()}")
break
except FileNotFoundError:
logger.debug("`iw` command not available for wifi strength measurement")
except subprocess.TimeoutExpired:
logger.debug("Timeout while fetching wifi strength via iw")
except Exception as e:
logger.debug(f"Unexpected error while using iw for wifi strength: {e}")
# Fallback: use `iwconfig`
try:
result = subprocess.run(['iwconfig', self._wifi_iface], capture_output=True, text=True, timeout=2)
if result.returncode == 0:
quality = None
signal_dbm = None
for line in result.stdout.split('\n'):
if 'Link Quality' in line:
try:
quality_part = line.split('Link Quality=')[1].split(' ')[0]
if '/' in quality_part:
numerator, denominator = quality_part.split('/')
quality = int(float(numerator) / float(denominator) * 100)
except (ValueError, IndexError):
logger.debug(f"Failed to parse Link Quality line: {line.strip()}")
if 'Signal level' in line:
try:
signal_part = line.split('Signal level=')[1].split(' ')[0]
if '/' in signal_part:
signal_part = signal_part.split('/')[0]
signal_dbm = float(signal_part.replace('dBm', ''))
except (ValueError, IndexError):
logger.debug(f"Failed to parse Signal level line: {line.strip()}")
if signal_dbm is not None or quality is not None:
if quality is None:
quality = self._dbm_to_quality(signal_dbm)
if signal_dbm is None and quality is not None:
# approximate dbm from quality if needed
signal_dbm = (quality / 100) * (-30 - (-90)) + (-90)
return signal_dbm, quality
except FileNotFoundError:
logger.debug("`iwconfig` command not available for wifi strength measurement")
except subprocess.TimeoutExpired:
logger.debug("Timeout while fetching wifi strength via iwconfig")
except Exception as e:
logger.debug(f"Unexpected error while using iwconfig for wifi strength: {e}")
return None, None
def get_wifi_wave_count(self, quality):
"""Translate a 0-100 quality value into 0-4 wave arcs."""
if quality is None:
return 0
thresholds = [8, 28, 52, 70]
waves = 0
for threshold in thresholds:
if quality >= threshold:
waves += 1
return waves
def render_wifi_wave_indicator(self, image, draw):
"""Render a live Wi-Fi indicator using wave arcs with no dBm text."""
_sx = getattr(self, 'render_sx', self.scale_factor_x)
_sy = getattr(self, 'render_sy', self.scale_factor_y)
base_x = int(3 * _sx)
base_y = int(8 * _sy)
scale = min(_sx, _sy)
signal_dbm = getattr(self.shared_data, 'wifi_signal_dbm', None)
raw_quality = getattr(self.shared_data, 'wifi_signal_quality', None)
effective_quality = raw_quality if raw_quality is not None else self._dbm_to_quality(signal_dbm)
ip_last_octet = self.get_wifi_ip_last_octet()
waves = self.get_wifi_wave_count(effective_quality)
if waves <= 0:
waves = 1 # Always show at least one wave when connected
base_radius = max(2, int(1.5 * scale))
wave_spacing = max(2, int(2.5 * scale) + 2)
line_width = max(1, int(scale) + 1)
center_x = base_x + base_radius + wave_spacing * 2
center_y = base_y + base_radius + wave_spacing * 2
# Draw expanding arcs to mimic Wi-Fi waves
for i in range(waves):
radius = max(2, base_radius + (i + 1) * wave_spacing - 4)
bbox = (
center_x - radius,
center_y - radius,
center_x + radius,
center_y + radius
)
draw.arc(bbox, start=225, end=315, fill=0, width=line_width)
if ip_last_octet:
text_x = center_x + wave_spacing + base_radius
text_y = center_y - base_radius - max(1, int(6 * _sy))
draw.text((text_x, text_y), ip_last_octet, font=self.shared_data.font_arial9, fill=0)
def get_wifi_ip_last_octet(self):
"""Get the last octet of the WiFi IP address (e.g., '.211' from '192.168.1.211')."""
try:
# Get IP address of wlan0 interface
result = subprocess.run(['ip', '-4', 'addr', 'show', self._wifi_iface],
capture_output=True, text=True, timeout=2)
if result.returncode == 0:
# Parse the output to find the IP address
for line in result.stdout.split('\n'):
if 'inet ' in line:
# Extract IP address (format: "inet 192.168.1.211/24 ...")
parts = line.strip().split()
if len(parts) >= 2:
ip_with_mask = parts[1]
ip_address = ip_with_mask.split('/')[0]
# Get the last octet
octets = ip_address.split('.')
if len(octets) == 4:
return f".{octets[3]}"
return None
except Exception as e:
logger.error(f"Error getting WiFi IP address: {e}")
return None
def is_ap_mode_active(self):
"""Check if AP mode is currently active."""
try:
# Check if hostapd is running
result = subprocess.run(['pgrep', 'hostapd'], capture_output=True, text=True)
if result.returncode == 0:
return True
# Alternative check: see if we're listening on AP interface
result = subprocess.run(['ip', 'addr', 'show', self._wifi_iface], capture_output=True, text=True)
if result.returncode == 0 and '192.168.4.1' in result.stdout:
return True
return False
except Exception as e:
logger.error(f"Error checking AP mode status: {e}")
return False
def get_ap_client_count(self):
"""Get the number of clients connected to AP mode."""
try:
# Try to get from WiFi manager first
if (hasattr(self.shared_data, 'ragnar_instance') and
self.shared_data.ragnar_instance and
hasattr(self.shared_data.ragnar_instance, 'wifi_manager')):
wifi_mgr = self.shared_data.ragnar_instance.wifi_manager
if hasattr(wifi_mgr, 'ap_clients_count'):
return wifi_mgr.ap_clients_count
# Fallback to hostapd_cli
result = subprocess.run(['hostapd_cli', '-i', self._wifi_iface, 'list_sta'],
capture_output=True, text=True, timeout=2)
if result.returncode == 0:
clients = [line.strip() for line in result.stdout.strip().split('\n') if line.strip()]
return len(clients)
return 0
except Exception as e:
logger.error(f"Error getting AP client count: {e}")
return 0
def get_wifi_status_text(self):
"""Get descriptive text for current Wi-Fi status."""
try:
# FIRST: Try system-level WiFi detection (most reliable)
# Method 1: Try iwgetid first (get SSID if available)
try:
result = subprocess.run(['iwgetid', '-r'], capture_output=True, text=True, timeout=2)
if result.returncode == 0 and result.stdout.strip():
ssid = result.stdout.strip()
logger.debug(f"[STATUS] WiFi connected via iwgetid: SSID={ssid}")
return f"WiFi: {ssid}"
except:
pass
# Method 2: Check if we have network connectivity (WiFi without SSID)
try:
result = subprocess.run(['ip', 'route', 'get', '8.8.8.8'],
capture_output=True, text=True, timeout=2)
if result.returncode == 0 and 'via' in result.stdout:
logger.debug(f"[STATUS] WiFi connected via ip route check")
return "WiFi: Connected"
except:
pass
# Method 3: Check for wlan interface with IP
try:
result = subprocess.run(['ip', 'addr', 'show'],
capture_output=True, text=True, timeout=2)
if result.returncode == 0:
# Look for wlan interfaces with inet addresses
for line in result.stdout.split('\n'):
if ('wlan' in line and 'state UP' in line) or ('inet ' in line and 'scope global' in line and ('wlan' in result.stdout)):
logger.debug(f"[STATUS] WiFi connected via interface check")
return "WiFi: Connected"
except:
pass
# SECONDARY: Try to get status from WiFi manager (if available in same process)
if (hasattr(self.shared_data, 'ragnar_instance') and
self.shared_data.ragnar_instance and
hasattr(self.shared_data.ragnar_instance, 'wifi_manager')):
wifi_mgr = self.shared_data.ragnar_instance.wifi_manager
# Check AP mode status first
if hasattr(wifi_mgr, 'ap_mode_active') and wifi_mgr.ap_mode_active:
# Try to get client count
client_count = 0
if hasattr(wifi_mgr, 'ap_clients_count'):
client_count = wifi_mgr.ap_clients_count
if client_count > 0:
return f"AP: {client_count} client{'s' if client_count != 1 else ''}"
else:
return "AP: No clients"
# Check Wi-Fi connection status
if hasattr(wifi_mgr, 'wifi_connected') and wifi_mgr.wifi_connected:
if hasattr(wifi_mgr, 'current_ssid') and wifi_mgr.current_ssid:
return f"WiFi: {wifi_mgr.current_ssid}"
else:
return "WiFi: Connected"
# Check if cycling mode is active
if hasattr(wifi_mgr, 'cycling_mode') and wifi_mgr.cycling_mode:
return "WiFi: Cycling"
# TERTIARY: Check if we're in AP mode at system level
if self.is_ap_mode_active():
# Try to get AP client count
try:
result = subprocess.run(['hostapd_cli', '-i', self._wifi_iface, 'list_sta'],
capture_output=True, text=True, timeout=2)
if result.returncode == 0:
clients = [line.strip() for line in result.stdout.strip().split('\n') if line.strip()]
client_count = len(clients)
if client_count > 0:
return f"AP: {client_count} client{'s' if client_count != 1 else ''}"
else:
return "AP: No clients"
else:
return "AP: Active"
except:
return "AP: Active"
logger.debug(f"[STATUS] WiFi not detected by any method")
return "WiFi: Disconnected"
except Exception as e:
logger.error(f"Error getting WiFi status text: {e}")
return "WiFi: Unknown"
def is_manual_mode(self):
"""Check if the ragnarorch is in manual mode."""
return self.shared_data.manual_mode
def is_interface_connected(self, interface):
"""Check if any device is connected to the specified interface.
A missing interface is a normal condition (e.g. ``usb0`` when the box is
not set up as a USB-ethernet gadget), so treat it as "not connected"
quietly instead of logging an error on every poll — ``ip neigh show dev
usb0`` otherwise fails with ``Cannot find device "usb0"`` every cycle.
"""
if not os.path.exists(f'/sys/class/net/{interface}'):
return False
try:
result = subprocess.Popen(['ip', 'neigh', 'show', 'dev', interface], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
output, error = result.communicate()
if result.returncode != 0:
logger.error(f"Error executing 'ip neigh show dev {interface}': {error}")
return False
return bool(output.strip())
except Exception as e:
logger.error(f"Error checking connection status on {interface}: {e}")
return False
def is_usb_connected(self):
"""Check if any device is connected to the USB (usb0) interface.
usb0 only exists when the box is a USB-ethernet gadget; on Wi-Fi /
Ethernet-HAT / dongle setups it is absent, which is not an error.
"""
return self.is_interface_connected('usb0')
def _sleep_interruptible(self, current_page):
"""Sleep for screen_delay but wake early if button changes the page.
Also watches the wardriving sub-page so the LCD HAT's joystick paging
through the wardriving screens redraws promptly instead of waiting out
the full screen_delay.
"""
wd_active0 = self._wardriving_active_cheap()
if not self.button_listener:
# Still poll so a wardriving start/stop flips the panel promptly
# instead of waiting out the full screen_delay.
steps = max(1, int(self.shared_data.screen_delay / 0.1))
for _ in range(steps):
if self._wardriving_active_cheap() != wd_active0:
return # Wardriving started/stopped — redraw now
time.sleep(0.1)
return
wd_page = getattr(self.button_listener, 'wardrive_page', 0)
# Check every 0.1s if page changed, otherwise do full sleep
steps = max(1, int(self.shared_data.screen_delay / 0.1))
for _ in range(steps):
if self.button_listener.current_page != current_page:
return # Page changed, skip remaining sleep
if getattr(self.button_listener, 'wardrive_page', 0) != wd_page:
return # Wardriving sub-page changed (joystick)
if self._wardriving_active_cheap() != wd_active0:
return # Wardriving started/stopped — redraw now
time.sleep(0.1)
def _wardriving_active_cheap(self):
"""True if wardriving is running or in its start-up window.
Cheap enough to poll at 10 Hz from the sleep loop: reads the engine's
_running/_starting flags directly instead of the full get_status()
(which walks sysfs/GPS/DB). Never creates an engine — if none exists
yet, wardriving can't be active.
"""
try: