forked from 7h30th3r0n3/Raspyjack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathraspyjack.py
More file actions
5042 lines (4413 loc) · 180 KB
/
Copy pathraspyjack.py
File metadata and controls
5042 lines (4413 loc) · 180 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
import base64
import hashlib
import hmac
import os
import secrets
import subprocess
import netifaces
from scapy.all import ARP, Ether, srp
from datetime import datetime
import threading, smbus, time, pyudev, serial, struct, json
from subprocess import STDOUT, check_output
from PIL import Image, ImageDraw, ImageFont, ImageColor, ImageSequence, ImageOps
import LCD_Config
import LCD_1in44
import gui_background # themed menu background (gradient / image / none)
import RPi.GPIO as GPIO
import socket
import ipaddress
import signal
from functools import partial
import time
import sys
import requests # For Discord webhook integration
import rj_input # Virtual input bridge (WebSocket → Unix socket)
# WiFi Integration - Add dual interface support
try:
sys.path.append('/root/Raspyjack/wifi/')
from wifi.raspyjack_integration import (
get_best_interface,
get_interface_ip,
get_interface_network,
get_nmap_target_network,
get_mitm_interface,
get_responder_interface,
get_dns_spoof_ip,
show_interface_info,
set_raspyjack_interface
)
WIFI_AVAILABLE = True
print("✅ WiFi integration loaded - dual interface support enabled")
except ImportError as e:
print(f"⚠️ WiFi integration not available: {e}")
print(" Using ethernet-only mode")
WIFI_AVAILABLE = False
# Fallback functions for ethernet-only mode
def get_best_interface():
return "eth0"
def get_interface_ip(interface):
try:
return subprocess.check_output(f"ip addr show dev {interface} | awk '/inet / {{ print $2 }}'", shell=True).decode().strip().split('/')[0]
except:
return None
def get_nmap_target_network(interface=None):
try:
iface = interface or "eth0"
return subprocess.check_output(f"ip -4 addr show {iface} | awk '/inet / {{ print $2 }}'", shell=True).decode().strip()
except:
return None
def get_mitm_interface():
return "eth0"
def get_responder_interface():
return "eth0"
def get_dns_spoof_ip(interface=None):
try:
iface = interface or "eth0"
return subprocess.check_output(f"ip -4 addr show {iface} | awk '/inet / {{split($2, a, \"/\"); print a[1]}}'", shell=True).decode().strip()
except:
return None
def set_raspyjack_interface(interface):
print(f"⚠️ WiFi integration not available - cannot switch to {interface}")
return False
_stop_evt = threading.Event()
screen_lock = threading.Event()
# Flicker control
_status_text = ""
_temp_c = 0.0
draw_lock = threading.Lock()
_last_button = None
_last_button_time = 0.0
_debounce_seconds = 0.10
_button_down_since = 0.0
_repeat_delay = 0.25
_repeat_interval = 0.08
_double_click_window = 0.6
LOCK_PIN_PBKDF2_ROUNDS = 40000
LOCK_SCREEN_STATIC_SECONDS = 1.2
LOCK_MODE_PIN = "pin"
LOCK_MODE_SEQUENCE = "sequence"
LOCK_SEQUENCE_LENGTH = 6
LOCK_SEQUENCE_ALLOWED_BUTTONS = (
"KEY_UP_PIN",
"KEY_DOWN_PIN",
"KEY_LEFT_PIN",
"KEY_RIGHT_PIN",
"KEY1_PIN",
"KEY2_PIN",
)
LOCK_SEQUENCE_LABELS = {
"KEY_UP_PIN": "UP",
"KEY_DOWN_PIN": "DOWN",
"KEY_LEFT_PIN": "LEFT",
"KEY_RIGHT_PIN": "RIGHT",
"KEY1_PIN": "KEY1",
"KEY2_PIN": "KEY2",
}
LOCK_SEQUENCE_TOKENS = {
"KEY_UP_PIN": "U",
"KEY_DOWN_PIN": "D",
"KEY_LEFT_PIN": "L",
"KEY_RIGHT_PIN": "R",
"KEY1_PIN": "1",
"KEY2_PIN": "2",
}
LOCK_SEQUENCE_DEBOUNCE = 0.06
LOCK_DEFAULTS = {
"enabled": False,
"mode": LOCK_MODE_PIN,
"pin_hash": "",
"sequence_hash": "",
"sequence_length": LOCK_SEQUENCE_LENGTH,
"auto_lock_seconds": 0,
}
LOCK_TIMEOUT_OPTIONS = [
(0, "Never"),
(15, "15 sec"),
(30, "30 sec"),
(60, "1 min"),
(300, "5 min"),
(600, "10 min"),
]
lock_config = LOCK_DEFAULTS.copy()
lock_runtime = {
"locked": False,
"last_activity": time.monotonic(),
"in_lock_flow": False,
"suspend_auto_lock": False,
"showing_screensaver": False,
}
_lock_screensaver_cache = {
"path": None,
"mtime": None,
"frames": [],
"durations": [],
}
# WebUI frame mirror (used by device_server.py)
FRAME_MIRROR_PATH = os.environ.get("RJ_FRAME_PATH", "/dev/shm/raspyjack_last.jpg")
FRAME_MIRROR_ENABLED = os.environ.get("RJ_FRAME_MIRROR", "1") != "0"
CARDPUTER_FRAME_PATH = os.environ.get("RJ_CARDPUTER_FRAME_PATH", "/dev/shm/raspyjack_cardputer.jpg")
CARDPUTER_FRAME_ENABLED = os.environ.get("RJ_CARDPUTER_FRAME_ENABLED", "1") != "0"
CARDPUTER_FRAME_MODE = str(os.environ.get("RJ_CARDPUTER_FRAME_MODE", "stretch") or "stretch").strip().lower()
CARDPUTER_FRAME_WIDTH = max(1, int(os.environ.get("RJ_CARDPUTER_FRAME_WIDTH", "240")))
CARDPUTER_FRAME_HEIGHT = max(1, int(os.environ.get("RJ_CARDPUTER_FRAME_HEIGHT", "135")))
CARDPUTER_FRAME_QUALITY = min(100, max(1, int(os.environ.get("RJ_CARDPUTER_FRAME_QUALITY", "60"))))
CARDPUTER_FRAME_SUBSAMPLING = min(2, max(0, int(os.environ.get("RJ_CARDPUTER_FRAME_SUBSAMPLING", "0"))))
try:
_frame_fps = float(os.environ.get("RJ_FRAME_FPS", "10"))
FRAME_MIRROR_INTERVAL = 1.0 / max(1.0, _frame_fps)
except Exception:
FRAME_MIRROR_INTERVAL = 0.1
try:
_cardputer_frame_fps = float(os.environ.get("RJ_CARDPUTER_FRAME_FPS", "6"))
CARDPUTER_FRAME_INTERVAL = 1.0 / max(1.0, _cardputer_frame_fps)
except Exception:
CARDPUTER_FRAME_INTERVAL = 1.0 / 6.0
try:
_resampling_lanczos = Image.Resampling.LANCZOS
except AttributeError:
_resampling_lanczos = Image.LANCZOS
def _build_cardputer_frame(src_image):
if CARDPUTER_FRAME_MODE == "stretch":
return src_image.resize((CARDPUTER_FRAME_WIDTH, CARDPUTER_FRAME_HEIGHT), _resampling_lanczos)
if CARDPUTER_FRAME_MODE == "contain":
return ImageOps.contain(src_image, (CARDPUTER_FRAME_WIDTH, CARDPUTER_FRAME_HEIGHT), _resampling_lanczos)
return ImageOps.fit(src_image, (CARDPUTER_FRAME_WIDTH, CARDPUTER_FRAME_HEIGHT), _resampling_lanczos)
def _save_cardputer_frame(src_image):
if not CARDPUTER_FRAME_ENABLED:
return
try:
cardputer_frame = _build_cardputer_frame(src_image)
if cardputer_frame.size != (CARDPUTER_FRAME_WIDTH, CARDPUTER_FRAME_HEIGHT):
canvas = Image.new("RGB", (CARDPUTER_FRAME_WIDTH, CARDPUTER_FRAME_HEIGHT), "black")
offset_x = max(0, (CARDPUTER_FRAME_WIDTH - cardputer_frame.width) // 2)
offset_y = max(0, (CARDPUTER_FRAME_HEIGHT - cardputer_frame.height) // 2)
canvas.paste(cardputer_frame, (offset_x, offset_y))
cardputer_frame = canvas
cardputer_frame.save(
CARDPUTER_FRAME_PATH,
"JPEG",
quality=CARDPUTER_FRAME_QUALITY,
subsampling=CARDPUTER_FRAME_SUBSAMPLING,
)
except Exception:
pass
def _set_last_button(name, ts):
global _last_button, _last_button_time, _button_down_since
_last_button = name
_last_button_time = ts
_button_down_since = ts
def _log_virtual_consume(stage, button):
try:
print(f"[virtual_consume] {stage}: {button}", flush=True)
except Exception:
pass
# https://www.waveshare.com/wiki/File:1.44inch-LCD-HAT-Code.7z
_wifi_connected = False
_battery_pct = -1
_battery_charging = False
_show_clock = True
def _check_battery():
global _battery_pct, _battery_charging
try:
with open("/sys/class/power_supply/bq27500-0/voltage_now") as f:
uv = int(f.read().strip())
_battery_pct = max(0, min(100, int((uv / 1_000_000 - 3.0) / 1.2 * 100)))
with open("/sys/class/power_supply/bq27500-0/status") as f:
_battery_charging = f.read().strip() == "Charging"
except Exception:
_battery_pct = -1
def _check_wifi():
"""Check if wlan0 is connected to a WiFi network."""
global _wifi_connected
try:
r = subprocess.run(["iwgetid", "-r"], capture_output=True, text=True, timeout=3)
_wifi_connected = bool(r.stdout.strip())
except Exception:
_wifi_connected = False
def _stats_loop():
global _status_text, _temp_c
_wifi_tick = 4 # starts at 4 so first iteration triggers check immediately
while not _stop_evt.is_set():
if screen_lock.is_set():
time.sleep(0.5)
continue
try:
_temp_c = temp()
_wifi_tick += 1
if _wifi_tick % 5 == 0:
_check_wifi()
_check_battery()
status = ""
if subprocess.call(['pgrep', 'nmap'], stdout=subprocess.DEVNULL) == 0:
status = "(Scan in progress)"
elif is_mitm_running():
status = "(MITM & sniff)"
elif subprocess.call(['pgrep', 'ettercap'], stdout=subprocess.DEVNULL) == 0:
status = "(DNSSpoof)"
if is_responder_running():
status = "(Responder)"
_status_text = status
if not lock_runtime.get("showing_screensaver"):
try:
draw_lock.acquire()
_draw_toolbar()
finally:
draw_lock.release()
except Exception:
pass
time.sleep(2)
_display_dirty = True # flag: image changed, needs refresh
def mark_display_dirty():
global _display_dirty
_display_dirty = True
def _display_loop():
global _display_dirty
last_frame_save = 0.0
last_cardputer_frame_save = 0.0
while not _stop_evt.is_set():
if not screen_lock.is_set() and _display_dirty:
mirror_image = None
save_webui_frame = False
save_cardputer_frame = False
try:
draw_lock.acquire()
LCD.LCD_ShowImage(image, 0, 0)
_display_dirty = False
if FRAME_MIRROR_ENABLED or CARDPUTER_FRAME_ENABLED:
now = time.monotonic()
save_webui_frame = FRAME_MIRROR_ENABLED and (now - last_frame_save) >= FRAME_MIRROR_INTERVAL
save_cardputer_frame = CARDPUTER_FRAME_ENABLED and (now - last_cardputer_frame_save) >= CARDPUTER_FRAME_INTERVAL
if save_webui_frame or save_cardputer_frame:
mirror_image = image.copy()
if save_webui_frame:
last_frame_save = now
if save_cardputer_frame:
last_cardputer_frame_save = now
finally:
draw_lock.release()
if mirror_image is not None:
if save_webui_frame:
try:
mirror_image.save(FRAME_MIRROR_PATH, "JPEG", quality=80)
except Exception:
pass
if save_cardputer_frame:
_save_cardputer_frame(mirror_image)
time.sleep(0.1)
def start_background_loops():
threading.Thread(target=_stats_loop, daemon=True).start()
threading.Thread(target=_display_loop, daemon=True).start()
if os.getuid() != 0:
print("You need a sudo to run this!")
exit()
print(" ")
print(" ------ RaspyJack Started !!! ------ ")
start_time = time.time()
####### Classes except menu #######
# Screen dimensions (read from LCD driver at import time)
_SCR_W = LCD_1in44.LCD_WIDTH
_SCR_H = LCD_1in44.LCD_HEIGHT
if _SCR_W != _SCR_H:
_SCALE = _SCR_H / 128 # widescreen: use height as constraining dimension
else:
_SCALE = _SCR_W / 128 # square: 1.0 for 128x128, 1.875 for 240x240
def S(v):
"""Scale a pixel value from 128-base to current screen resolution."""
return int(v * _SCALE)
### Global mostly static values ###
class Defaults():
start_text = [S(12), S(22)]
text_gap = S(14)
updown_center = S(52)
updown_pos = [S(15), updown_center, S(88)]
imgstart_path = "/root/"
install_path = "/root/Raspyjack/"
config_file = install_path + "gui_conf.json"
screensaver_gif = install_path + "img/screensaver/default.gif"
payload_path = install_path + "payloads/"
payload_log = install_path + "loot/payload.log"
### Themed background state (loaded from gui_conf.json "BACKGROUND" section) ###
_bg_config = gui_background.normalize(None) # defaults until LoadConfig runs
_bg_layer = None # None => stock solid background
_bg_scrim = _bg_config["scrim"]
def _rebuild_bg_layer():
"""(Re)build the cached background layer for the current panel size."""
global _bg_layer, _bg_scrim
_bg_scrim = _bg_config.get("scrim", 0.30)
try:
_bg_layer = gui_background.build_layer(
LCD.width, LCD.height, _bg_config, base_dir=default.install_path
)
except Exception as e:
print(f"[bg] failed to build background layer: {e}")
_bg_layer = None
### Color scheme class ###
class template():
# Color values
border = "#05ff00"
background = "#000000"
text = "#05ff00"
selected_text = "#00ff55"
select = "#2d0fff"
gamepad = "#141494"
gamepad_fill = "#eeeeee"
# Render the border
def DrawBorder(self):
w, h = _SCR_W, _SCR_H
bw = S(5)
by = S(12)
draw.line([(w - 1, by), (w - 1, h - 1)], fill=self.border, width=bw)
draw.line([(w - 1, h - 1), (0, h - 1)], fill=self.border, width=bw)
draw.line([(0, h - 1), (0, by)], fill=self.border, width=bw)
draw.line([(0, by), (w, by)], fill=self.border, width=bw)
# Render inside of the border
def DrawMenuBackground(self):
x0, y0, x1, y1 = S(3), S(14), _SCR_W - S(4), _SCR_H - S(4)
if _bg_layer is None:
# Stock look: solid theme background colour.
draw.rectangle((x0, y0, x1, y1), fill=self.background)
else:
# Themed background (gradient / image) rendered underneath the menu.
gui_background.paint_region(image, (x0, y0, x1, y1), _bg_layer, _bg_scrim)
mark_display_dirty()
# I don't know how to python pass 'class.variable' as reference properly
def Set(self, index, color):
if index == 0:
self.background = color
elif index == 1:
self.border = color
self.DrawBorder()
elif index == 2:
self.text = color
elif index == 3:
self.selected_text = color
elif index == 4:
self.select = color
elif index == 5:
self.gamepad = color
elif index == 6:
self.gamepad_fill = color
def Get(self, index):
if index == 0:
return self.background
elif index == 1:
return self.border
elif index == 2:
return self.text
elif index == 3:
return self.selected_text
elif index == 4:
return self.select
elif index == 5:
return self.gamepad
elif index == 6:
return self.gamepad_fill
# Methods for JSON export
def Dictonary(self):
x = {
"BORDER" : self.border,
"BACKGROUND" : self.background,
"TEXT" : self.text,
"SELECTED_TEXT" : self.selected_text,
"SELECTED_TEXT_BACKGROUND" : self.select,
"GAMEPAD" : self.gamepad,
"GAMEPAD_FILL" : self.gamepad_fill
}
return x
def LoadDictonary(self, dic):
self.Set(1,dic["BORDER"])
self.background = dic["BACKGROUND"]
self.text = dic["TEXT"]
self.selected_text = dic["SELECTED_TEXT"]
self.select = dic["SELECTED_TEXT_BACKGROUND"]
self.gamepad = dic["GAMEPAD"]
self.gamepad_fill = dic["GAMEPAD_FILL"]
# Menu search filter (CardputerZero keyboard support)
_menu_filter = ""
_menu_filter_active = False
try:
import evdev_keys as _evdev
_HAS_EVDEV = True
except ImportError:
_HAS_EVDEV = False
# Evdev keycode → character mapping for search
_KEY_CHARS = {
16:'q',17:'w',18:'e',19:'r',20:'t',21:'y',22:'u',23:'i',24:'o',25:'p',
30:'a',31:'s',32:'d',33:'f',34:'g',35:'h',36:'j',37:'k',38:'l',
44:'z',45:'x',46:'c',47:'v',48:'b',49:'n',50:'m',
2:'1',3:'2',4:'3',5:'4',6:'5',7:'6',8:'7',9:'8',10:'9',11:'0',
57:' ',
}
# Edge-triggered key state tracking (detect press, not hold)
_prev_key_state = {}
def _menu_filter_reset():
global _menu_filter, _menu_filter_active, _prev_key_state
_menu_filter = ""
_menu_filter_active = False
_prev_key_state = {}
def _menu_filter_activate():
global _menu_filter_active, _prev_key_state
_menu_filter_active = True
_prev_key_state = {}
if _HAS_EVDEV:
for code in _KEY_CHARS:
_prev_key_state[code] = _evdev.is_key_pressed(code)
def _menu_filter_add(char):
global _menu_filter
_menu_filter += char
def _menu_filter_backspace():
global _menu_filter, _menu_filter_active
_menu_filter = _menu_filter[:-1]
if not _menu_filter:
_menu_filter_active = False
def _check_search_trigger():
"""Check if S key was just pressed (edge-triggered, CardputerZero only)."""
if not _HAS_EVDEV:
return False
code = 31 # S key
now_pressed = _evdev.is_key_pressed(code)
was_pressed = _prev_key_state.get(code, False)
_prev_key_state[code] = now_pressed
return now_pressed and not was_pressed
def _check_search_key():
"""Check if a letter key was just pressed (edge-triggered). Returns char or None."""
global _prev_key_state
if not _HAS_EVDEV:
return None
for code, char in _KEY_CHARS.items():
now_pressed = _evdev.is_key_pressed(code)
was_pressed = _prev_key_state.get(code, False)
_prev_key_state[code] = now_pressed
if now_pressed and not was_pressed:
return char
return None
def _check_search_backspace():
"""Check if backspace (evdev code 14) was just pressed (edge-triggered)."""
if not _HAS_EVDEV:
return False
code = 14
now_pressed = _evdev.is_key_pressed(code)
was_pressed = _prev_key_state.get(code, False)
_prev_key_state[code] = now_pressed
return now_pressed and not was_pressed
def _check_search_escape():
"""Check if ESC (evdev code 1) was just pressed (edge-triggered)."""
if not _HAS_EVDEV:
return False
code = 1
now_pressed = _evdev.is_key_pressed(code)
was_pressed = _prev_key_state.get(code, False)
_prev_key_state[code] = now_pressed
return now_pressed and not was_pressed
def _filter_menu_items(inlist, query):
"""Filter menu items by search query. Returns filtered list."""
if not query:
return inlist
q = query.lower()
return [item for item in inlist if q in item.lower()]
# Flat payload list for global search (built lazily)
_flat_payload_list = None
_flat_payload_map = {}
def _build_flat_payload_list():
"""Build a flat list of all payload labels + exec mappings for global search."""
global _flat_payload_list, _flat_payload_map
all_payloads = list_payloads()
labels = []
_flat_payload_map.clear()
for rel_path in all_payloads:
name = os.path.splitext(os.path.basename(rel_path))[0]
label = f" {name}"
labels.append(label)
_flat_payload_map[label] = rel_path
_flat_payload_list = labels
return labels
def _get_flat_payload_list():
"""Get the flat payload list, building it if needed."""
global _flat_payload_list
if _flat_payload_list is None:
return _build_flat_payload_list()
return _flat_payload_list
def _invalidate_flat_payload_list():
"""Force rebuild on next access (call after adding/removing payloads)."""
global _flat_payload_list
_flat_payload_list = None
def _draw_search_bar():
"""Draw a search bar at the bottom of the screen when search is active."""
if not _menu_filter_active:
return
bar_h = S(14)
y = _SCR_H - bar_h
draw.rectangle((0, y, _SCR_W, _SCR_H), fill="#1a1a2e")
draw.line([(0, y), (_SCR_W, y)], fill="#00E5FF", width=1)
try:
_search_icon_font = ImageFont.truetype('/usr/share/fonts/truetype/fontawesome/fa-solid-900.ttf', S(8))
draw.text((S(3), y + S(2)), "", fill="#00E5FF", font=_search_icon_font)
except Exception:
draw.text((S(3), y + S(2)), ">", fill="#00E5FF", font=font)
query_text = _menu_filter if _menu_filter else ""
cursor = "|" if int(time.time() * 2) % 2 == 0 else " "
draw.text((S(14), y + S(2)), query_text + cursor, fill="#FFFFFF", font=font)
filtered_count = ""
if _menu_filter:
filtered_count = f"({_menu_filter_match_count})"
draw.text((_SCR_W - S(2), y + S(2)), filtered_count, fill="#888888", font=font, anchor="ra")
_menu_filter_match_count = 0
def _apply_search_filter(inlist_original):
"""Apply current search filter and return (filtered_list, total). Updates match count."""
global _menu_filter_match_count
if _menu_filter:
filtered = _filter_menu_items(inlist_original, _menu_filter)
_menu_filter_match_count = len(filtered)
return filtered if filtered else inlist_original, len(filtered) if filtered else len(inlist_original)
_menu_filter_match_count = len(inlist_original)
return list(inlist_original), len(inlist_original)
def _handle_search_input(inlist_original, use_global=False):
"""Process search keyboard input. Returns (changed, new_inlist, new_total, new_index) or None if no search input.
If use_global=True, search across ALL payloads (not just the current menu list)."""
global _menu_filter_active
if not _HAS_EVDEV:
return None
search_source = _get_flat_payload_list() if (use_global and _menu_filter_active) else inlist_original
if _menu_filter_active:
if _check_search_escape():
_menu_filter_reset()
inlist = list(inlist_original)
return True, inlist, len(inlist), 0
if _check_search_backspace():
_menu_filter_backspace()
if not _menu_filter:
inlist = list(inlist_original)
return True, inlist, len(inlist), 0
inlist, total = _apply_search_filter(search_source)
return True, inlist, total, 0
ch = _check_search_key()
if ch is not None:
_menu_filter_add(ch)
inlist, total = _apply_search_filter(search_source)
return True, inlist, total, 0
else:
if _check_search_trigger():
_menu_filter_activate()
return True, None, None, None
return None
####### Simple methods #######
### Get any button press ###
def getButton():
global _last_button, _last_button_time, _button_down_since
while 1:
if _should_auto_lock():
lock_device("Auto lock")
continue
# WebUI payload requests: launch immediately while waiting for input
if not screen_lock.is_set():
requested = _check_payload_request()
if requested:
exec_payload(requested)
continue
# 1) virtual buttons from Web UI
v = rj_input.get_virtual_button()
if v:
_log_virtual_consume("getButton", v)
_mark_user_activity()
return v
pressed = None
for item in PINS:
if GPIO.input(PINS[item]) == 0:
pressed = item
break
if pressed is None:
if _last_button is not None:
_set_last_button(None, time.time())
time.sleep(0.01)
continue
now = time.time()
if pressed != _last_button:
_set_last_button(pressed, now)
_mark_user_activity()
return pressed
# Same button still held: debounce first, then allow auto-repeat
if (now - _last_button_time) < _debounce_seconds:
time.sleep(0.01)
continue
if (now - _button_down_since) >= _repeat_delay and (now - _last_button_time) >= _repeat_interval:
_last_button_time = now
_mark_user_activity()
return pressed
time.sleep(0.01)
def temp() -> float:
with open("/sys/class/thermal/thermal_zone0/temp") as f:
return int(f.read()) / 1000
def _iface_carrier_up(name: str) -> bool:
try:
with open(f"/sys/class/net/{name}/carrier", "r") as f:
return f.read().strip() == "1"
except Exception:
return False
def get_best_interface_prefer_eth() -> str:
"""Prefer wired interface when link is up, otherwise fall back."""
eth_candidate = None
for name in ("eth0", "eth1"):
if _iface_carrier_up(name):
ip = get_interface_ip(name)
if ip:
return name
eth_candidate = eth_candidate or name
if eth_candidate:
return eth_candidate
return get_best_interface()
def Leave(poweroff: bool = False) -> None:
_stop_evt.set()
GPIO.cleanup()
if poweroff:
os.system("sync && poweroff")
print("Bye!")
sys.exit(0)
def Restart():
print("Restarting the UI!")
Dialog("Restarting!", False)
arg = ["-n","-5",os.sys.executable] + sys.argv
os.execv(os.popen("whereis nice").read().split(" ")[1], arg)
Leave()
def safe_kill(*names):
for name in names:
subprocess.run(
["pkill", "-9", "-x", name], # -x = nom exact
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
### Two threaded functions ###
# One for updating status bar and one for refreshing display #
def is_responder_running():
time.sleep(1)
ps_command = "ps aux | grep Responder.py | grep -v grep | awk '{print $2}'"
try:
output = subprocess.check_output(ps_command, shell=True)
pid = int(output.strip())
return True
except (subprocess.CalledProcessError, ValueError):
return False
def is_mitm_running():
time.sleep(1)
tcpdump_running = subprocess.call(['pgrep', 'tcpdump'], stdout=subprocess.DEVNULL) == 0
arpspoof_running = subprocess.call(['pgrep', 'arpspoof'], stdout=subprocess.DEVNULL) == 0
return tcpdump_running or arpspoof_running
def _b64url_encode(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def _normalize_lock_config(raw: dict | None) -> dict[str, object]:
cfg = raw if isinstance(raw, dict) else {}
normalized = LOCK_DEFAULTS.copy()
normalized["enabled"] = bool(cfg.get("enabled", normalized["enabled"]))
mode = str(cfg.get("mode", cfg.get("lock_type", normalized["mode"])) or normalized["mode"]).strip().lower()
if mode not in (LOCK_MODE_PIN, LOCK_MODE_SEQUENCE):
mode = LOCK_MODE_PIN
normalized["mode"] = mode
normalized["pin_hash"] = str(cfg.get("pin_hash", normalized["pin_hash"]) or "").strip()
normalized["sequence_hash"] = str(cfg.get("sequence_hash", normalized["sequence_hash"]) or "").strip()
normalized["sequence_length"] = LOCK_SEQUENCE_LENGTH
try:
auto_lock_seconds = int(cfg.get("auto_lock_seconds", normalized["auto_lock_seconds"]))
except (TypeError, ValueError):
auto_lock_seconds = int(normalized["auto_lock_seconds"])
normalized["auto_lock_seconds"] = max(0, auto_lock_seconds)
if not normalized["pin_hash"] and normalized["sequence_hash"] and "mode" not in cfg and "lock_type" not in cfg:
normalized["mode"] = LOCK_MODE_SEQUENCE
if normalized["enabled"] and not _lock_config_has_secret(normalized, str(normalized["mode"])):
normalized["enabled"] = False
return normalized
def _lock_config_has_secret(config: dict[str, object], mode: str | None = None) -> bool:
selected_mode = str(mode or config.get("mode") or LOCK_MODE_PIN)
if selected_mode == LOCK_MODE_SEQUENCE:
return bool(str(config.get("sequence_hash") or "").strip())
return bool(str(config.get("pin_hash") or "").strip())
def _lock_mode() -> str:
mode = str(lock_config.get("mode") or LOCK_MODE_PIN)
return mode if mode in (LOCK_MODE_PIN, LOCK_MODE_SEQUENCE) else LOCK_MODE_PIN
def _lock_mode_label(mode: str | None = None) -> str:
return "Sequence" if (mode or _lock_mode()) == LOCK_MODE_SEQUENCE else "PIN"
def _lock_has_pin() -> bool:
return bool(str(lock_config.get("pin_hash") or "").strip())
def _lock_has_sequence() -> bool:
return bool(str(lock_config.get("sequence_hash") or "").strip())
def _lock_has_secret(mode: str | None = None) -> bool:
return _lock_config_has_secret(lock_config, mode or _lock_mode())
def _lock_is_enabled() -> bool:
return bool(lock_config.get("enabled")) and _lock_has_secret()
def _mark_user_activity() -> None:
lock_runtime["last_activity"] = time.monotonic()
def _should_auto_lock() -> bool:
if lock_runtime["locked"] or lock_runtime["in_lock_flow"] or lock_runtime["suspend_auto_lock"]:
return False
if not _lock_is_enabled():
return False
timeout = int(lock_config.get("auto_lock_seconds") or 0)
if timeout <= 0:
return False
return (time.monotonic() - float(lock_runtime.get("last_activity") or 0.0)) >= timeout
def _lock_timeout_label(seconds: int | None = None) -> str:
value = int(lock_config.get("auto_lock_seconds") or 0) if seconds is None else int(seconds)
for candidate, label in LOCK_TIMEOUT_OPTIONS:
if candidate == value:
return label
if value <= 0:
return "Never"
return f"{value} sec"
def _handle_main_menu_key3_double_click() -> bool:
deadline = time.monotonic() + _double_click_window
key3_released = False
while time.monotonic() < deadline:
try:
if GPIO.input(PINS["KEY3_PIN"]) != 0:
key3_released = True
elif key3_released:
_mark_user_activity()
if _lock_has_secret():
lock_device("Locked")
else:
Dialog_info(f"Set {_lock_mode_label()} first", wait=False, timeout=1.0)
return True
except Exception:
pass
virtual_button = rj_input.get_virtual_button()
if virtual_button == "KEY3_PIN":
_log_virtual_consume("main_menu_key3_double_click", virtual_button)
_mark_user_activity()
if _lock_has_secret():
lock_device("Locked")
else:
Dialog_info(f"Set {_lock_mode_label()} first", wait=False, timeout=1.0)
return True
time.sleep(0.01)
return False
def _serialize_sequence(sequence: list[str]) -> str:
return "|".join(sequence)
def _hash_pin(pin: str, rounds: int = LOCK_PIN_PBKDF2_ROUNDS) -> str:
salt = secrets.token_hex(16)
dk = hashlib.pbkdf2_hmac("sha256", pin.encode("utf-8"), salt.encode("utf-8"), rounds)
return f"pbkdf2_sha256${rounds}${salt}${_b64url_encode(dk)}"
def _parse_pin_hash(encoded: str) -> tuple[str, int, str, str] | None:
try:
algo, rounds, salt, digest = encoded.split("$", 3)
return algo, int(rounds), salt, digest
except Exception:
return None
def _verify_pin(pin: str, encoded: str) -> bool:
parsed = _parse_pin_hash(encoded)
if not parsed:
return False
algo, rounds, salt, digest = parsed
if algo != "pbkdf2_sha256":
return False
try:
dk = hashlib.pbkdf2_hmac("sha256", pin.encode("utf-8"), salt.encode("utf-8"), rounds)
return hmac.compare_digest(_b64url_encode(dk), digest)
except Exception:
return False
def _hash_sequence(sequence: list[str], rounds: int = LOCK_PIN_PBKDF2_ROUNDS) -> str:
return _hash_pin(_serialize_sequence(sequence), rounds=rounds)
def _verify_sequence(sequence: list[str], encoded: str) -> bool:
return _verify_pin(_serialize_sequence(sequence), encoded)
def _should_rehash_pin(encoded: str) -> bool:
parsed = _parse_pin_hash(encoded)
if not parsed:
return False
algo, rounds, _salt, _digest = parsed
return algo == "pbkdf2_sha256" and rounds != LOCK_PIN_PBKDF2_ROUNDS
def _rehash_pin_if_needed(pin: str, encoded: str) -> None:
if not _should_rehash_pin(encoded):
return
lock_config["pin_hash"] = _hash_pin(pin)
SaveConfig()
def _rehash_sequence_if_needed(sequence: list[str], encoded: str) -> None:
if not _should_rehash_pin(encoded):
return
lock_config["sequence_hash"] = _hash_sequence(sequence)
SaveConfig()
def _wait_for_button_release(timeout: float = 1.0) -> None:
deadline = time.monotonic() + max(0.0, timeout)
while time.monotonic() < deadline:
try:
physical_released = all(GPIO.input(pin) != 0 for pin in PINS.values())
virtual_released = not rj_input.get_held_buttons()
if physical_released and virtual_released:
return
except Exception:
if not rj_input.get_held_buttons():
return
time.sleep(0.01)
def _write_config_atomic(data: dict) -> None:
os.makedirs(os.path.dirname(default.config_file), exist_ok=True)
tmp_path = default.config_file + ".tmp"
try:
with open(tmp_path, "w", encoding="utf-8") as wf:
json.dump(data, wf, indent=4, sort_keys=True)
os.replace(tmp_path, default.config_file)
try:
os.chmod(default.config_file, 0o600)
except Exception:
pass
finally:
if os.path.exists(tmp_path):
try:
os.remove(tmp_path)
except Exception:
pass
_flip_enabled = False # screen + controls flipped 180 degrees
_ORIGINAL_PINS = {
"KEY_UP_PIN": 6, "KEY_DOWN_PIN": 19,
"KEY_LEFT_PIN": 5, "KEY_RIGHT_PIN": 26,
"KEY_PRESS_PIN": 13, "KEY1_PIN": 21,
"KEY2_PIN": 20, "KEY3_PIN": 16,
}
def SaveConfig() -> None:
data = {
"DISPLAY": {
"type": getattr(LCD_1in44, '_DISPLAY_TYPE', 'ST7789_240'),
"supported_types": ["ST7735_128", "ST7789_240"],
"flip": _flip_enabled,
},