forked from 7h30th3r0n3/Raspyjack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_server.py
More file actions
1890 lines (1685 loc) · 69.4 KB
/
Copy pathweb_server.py
File metadata and controls
1890 lines (1685 loc) · 69.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
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
"""
RaspyJack WebUI HTTP server
---------------------------
Serves the static WebUI and exposes a small, read-only API to browse loot/.
Routes:
/ -> static WebUI (web/)
/api/loot/list -> JSON directory listing (read-only)
/api/loot/download -> file download (read-only)
/api/loot/view -> text preview (read-only)
/api/loot/nmap -> normalized Nmap XML (read-only)
/api/system/status -> live system monitor metrics
/api/settings/discord_webhook -> get/save Discord webhook
/api/auth/* -> bootstrap/login/session endpoints
Environment:
RJ_WEB_HOST Host to bind (default: 0.0.0.0)
RJ_WEB_PORT Port to bind (default: 8080)
RJ_WS_TOKEN Optional shared token for API access (Bearer header)
RJ_WS_TOKEN_FILE Optional token file (default: <repo>/.webui_token)
RJ_WEB_AUTH_FILE Auth user storage file (default: /root/Raspyjack/.webui_auth.json)
RJ_WEB_AUTH_SECRET_FILE Session signing secret file (default: /root/Raspyjack/.webui_session_secret)
RJ_WEB_SESSION_TTL Session lifetime seconds (default: 28800)
RJ_WEB_WS_TICKET_TTL WS ticket lifetime seconds (default: 120)
"""
from __future__ import annotations
import json
import base64
import hmac
import hashlib
import mimetypes
import os
import secrets
import shutil
import socket
import subprocess
import threading
import time
from http import HTTPStatus
from http.cookies import SimpleCookie
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlparse, unquote
from nmap_parser import parse_nmap_xml_file
ROOT_DIR = Path(__file__).resolve().parent
WEB_DIR = ROOT_DIR / "web"
LOOT_DIR = ROOT_DIR / "loot"
PAYLOADS_DIR = ROOT_DIR / "payloads"
PAYLOAD_STATE_PATH = Path("/dev/shm/rj_payload_state.json")
DISCORD_WEBHOOK_PATH = ROOT_DIR / "discord_webhook.txt"
WIGLE_CREDENTIALS_PATH = ROOT_DIR / ".wigle_credentials.json"
TOKEN_FILE = Path(os.environ.get("RJ_WS_TOKEN_FILE", str(ROOT_DIR / ".webui_token")))
AUTH_FILE = Path(os.environ.get("RJ_WEB_AUTH_FILE", "/root/Raspyjack/.webui_auth.json"))
AUTH_SECRET_FILE = Path(os.environ.get("RJ_WEB_AUTH_SECRET_FILE", "/root/Raspyjack/.webui_session_secret"))
SESSION_COOKIE_NAME = "rj_session"
SESSION_TTL_SECONDS = int(os.environ.get("RJ_WEB_SESSION_TTL", str(8 * 60 * 60)))
WS_TICKET_TTL_SECONDS = int(os.environ.get("RJ_WEB_WS_TICKET_TTL", "120"))
TAILSCALE_KEY_PATH = ROOT_DIR / ".tailscale_auth_key"
TAILSCALE_STATUS_PATH = Path("/dev/shm/rj_tailscale_status.json")
def _load_shared_token() -> str | None:
"""Load auth token from env first, then token file."""
env_token = str(os.environ.get("RJ_WS_TOKEN", "")).strip()
if env_token:
return env_token
try:
if TOKEN_FILE.exists():
for line in TOKEN_FILE.read_text(encoding="utf-8").splitlines():
value = line.strip()
if value and not value.startswith("#"):
return value
except Exception:
pass
return None
def _load_line_secret(path: Path) -> str | None:
try:
if not path.exists():
return None
for line in path.read_text(encoding="utf-8").splitlines():
value = line.strip()
if value and not value.startswith("#"):
return value
except Exception:
pass
return None
def _load_or_create_auth_secret() -> str:
existing = _load_line_secret(AUTH_SECRET_FILE)
if existing:
return existing
generated = secrets.token_urlsafe(48)
try:
AUTH_SECRET_FILE.parent.mkdir(parents=True, exist_ok=True)
AUTH_SECRET_FILE.write_text(generated + "\n", encoding="utf-8")
os.chmod(AUTH_SECRET_FILE, 0o600)
except Exception:
# Fallback for environments where file creation is not possible.
pass
return generated
HOST = os.environ.get("RJ_WEB_HOST", "0.0.0.0")
PORT = int(os.environ.get("RJ_WEB_PORT", "8080"))
TOKEN = _load_shared_token()
AUTH_SECRET = _load_or_create_auth_secret()
# WebUI only listens on these interfaces — wlan1+ are for attacks/monitor mode
WEBUI_INTERFACES = ["eth0", "eth1", "wlan0", "tailscale0"]
def _get_interface_ip(interface: str) -> str | None:
"""Get the IPv4 address of a network interface."""
try:
result = subprocess.run(
["ip", "-4", "addr", "show", interface],
capture_output=True, text=True, timeout=3,
)
if result.returncode == 0:
for line in result.stdout.split("\n"):
if "inet " in line:
return line.split("inet ")[1].split("/")[0]
except Exception:
pass
return None
def _get_webui_bind_addrs() -> list[tuple[str, str]]:
"""Return (ip, iface_label) pairs the WebUI should bind to."""
addrs: list[tuple[str, str]] = []
for iface in WEBUI_INTERFACES:
ip = _get_interface_ip(iface)
if ip:
addrs.append((ip, iface))
# Always include localhost for local access
addrs.append(("127.0.0.1", "lo"))
return addrs
PREVIEW_MAX_BYTES = int(os.environ.get("RJ_LOOT_PREVIEW_MAX", str(200 * 1024)))
PAYLOAD_MAX_BYTES = int(os.environ.get("RJ_PAYLOAD_MAX", str(512 * 1024)))
TEXT_EXTS = {
".txt", ".log", ".md", ".json", ".csv", ".conf", ".ini", ".yaml", ".yml",
".pcapng.txt", ".xml", ".sqlite", ".db", ".out", ".py", ".sh"
}
_CPU_SNAPSHOT = None
_LOGIN_FAILS: dict[str, list[float]] = {}
def _is_valid_discord_webhook(url: str) -> bool:
return url.startswith("https://discord.com/api/webhooks/")
def _read_discord_webhook_url() -> str:
"""Read the configured Discord webhook URL from file."""
try:
if not DISCORD_WEBHOOK_PATH.exists():
return ""
for line in DISCORD_WEBHOOK_PATH.read_text(encoding="utf-8").splitlines():
value = line.strip()
if not value or value.startswith("#"):
continue
if _is_valid_discord_webhook(value):
return value
return ""
except Exception:
return ""
def _write_discord_webhook_url(url: str) -> tuple[bool, str]:
"""Write or clear Discord webhook URL in file."""
value = str(url or "").strip()
try:
if not value:
if DISCORD_WEBHOOK_PATH.exists():
DISCORD_WEBHOOK_PATH.unlink()
return True, "cleared"
if not _is_valid_discord_webhook(value):
return False, "invalid webhook url"
DISCORD_WEBHOOK_PATH.write_text(value + "\n", encoding="utf-8")
return True, "saved"
except Exception as exc:
return False, f"write error: {exc}"
def _read_wigle_credentials() -> dict[str, str]:
try:
if not WIGLE_CREDENTIALS_PATH.exists():
return {"api_name": "", "api_token": ""}
raw = WIGLE_CREDENTIALS_PATH.read_text(encoding="utf-8")
data = json.loads(raw) if raw else {}
if not isinstance(data, dict):
return {"api_name": "", "api_token": ""}
return {
"api_name": str(data.get("api_name") or "").strip(),
"api_token": str(data.get("api_token") or "").strip(),
}
except Exception:
return {"api_name": "", "api_token": ""}
def _write_wigle_credentials(api_name: str, api_token: str) -> tuple[bool, str]:
clean_name = str(api_name or "").strip()
clean_token = str(api_token or "").strip()
try:
if not clean_name and not clean_token:
if WIGLE_CREDENTIALS_PATH.exists():
WIGLE_CREDENTIALS_PATH.unlink()
return True, "cleared"
if not clean_name or not clean_token:
return False, "api name and api token are required"
WIGLE_CREDENTIALS_PATH.write_text(
json.dumps({"api_name": clean_name, "api_token": clean_token}) + "\n",
encoding="utf-8",
)
try:
os.chmod(WIGLE_CREDENTIALS_PATH, 0o600)
except Exception:
pass
return True, "saved"
except Exception as exc:
return False, f"write error: {exc}"
def _mask_secret(value: str, keep_start: int = 3, keep_end: int = 2) -> str:
secret = str(value or "")
if not secret:
return ""
if len(secret) <= (keep_start + keep_end):
return "*" * len(secret)
return secret[:keep_start] + ("*" * (len(secret) - keep_start - keep_end)) + secret[-keep_end:]
def _tailscale_write_status(payload: dict) -> None:
"""Persist last Tailscale install/bootstrap status for the WebUI."""
try:
TAILSCALE_STATUS_PATH.write_text(json.dumps(payload), encoding="utf-8")
except Exception:
pass
def _tailscale_read_status() -> dict:
try:
if not TAILSCALE_STATUS_PATH.exists():
return {}
raw = TAILSCALE_STATUS_PATH.read_text(encoding="utf-8")
data = json.loads(raw) if raw else {}
return data if isinstance(data, dict) else {}
except Exception:
return {}
def _tailscale_installed() -> bool:
"""Return True if the tailscale CLI appears to be installed."""
try:
return shutil.which("tailscale") is not None
except Exception:
return False
def _tailscale_status() -> dict:
"""
Best-effort snapshot of the Tailscale daemon.
Returns {"backend_state": str|None, "ip": str|None}.
"""
summary: dict[str, str | None] = {"backend_state": None, "ip": None}
if not _tailscale_installed():
return summary
try:
res = subprocess.run(
["tailscale", "status", "--json"],
capture_output=True,
text=True,
timeout=5,
)
if res.returncode != 0 or not res.stdout:
return summary
data = json.loads(res.stdout)
if not isinstance(data, dict):
return summary
summary["backend_state"] = str(data.get("BackendState") or "") or None
self_info = data.get("Self") or {}
if isinstance(self_info, dict):
ips = self_info.get("TailscaleIPs") or []
if isinstance(ips, list) and ips:
summary["ip"] = str(ips[0])
except Exception:
pass
return summary
def _tailscale_write_key(key: str) -> tuple[bool, str]:
"""Store the auth key in a root-only file so tailscale can read it."""
value = str(key or "").strip()
if not value:
return False, "missing auth key"
try:
TAILSCALE_KEY_PATH.write_text(value + "\n", encoding="utf-8")
try:
os.chmod(TAILSCALE_KEY_PATH, 0o600)
except Exception:
# On some platforms chmod may fail; do not treat as fatal.
pass
return True, "ok"
except Exception as exc:
return False, f"write error: {exc}"
def _regenerate_caddyfile_and_reload() -> None:
"""
Regenerate /etc/caddy/Caddyfile with current IPs (eth0, wlan0, tailscale0)
and reload Caddy. Same logic as install_raspyjack.sh so that installing
Tailscale from the WebUI updates HTTPS to listen on the Tailscale IP
without re-running the install script.
"""
hosts: list[str] = []
for iface in ("eth0", "wlan0", "tailscale0"):
try:
res = subprocess.run(
["ip", "-4", "-o", "addr", "show", iface],
capture_output=True,
text=True,
timeout=5,
)
if res.returncode != 0 or not res.stdout:
continue
# First line: "2: eth0 inet 192.168.1.100/24 ..." -> take 4th field, strip /suffix
line = res.stdout.strip().split("\n")[0]
parts = line.split()
if len(parts) >= 4:
addr = parts[3].split("/")[0].strip()
if addr and addr not in hosts:
hosts.append(addr)
except Exception:
continue
hosts.append("localhost")
if not hosts:
return
caddy_site_addrs = ", ".join(hosts)
caddyfile_content = f"""{{
# RaspyJack self-signed internal CA (local trust only)
auto_https disable_redirects
}}
{caddy_site_addrs} {{
tls internal
@ws path /ws*
reverse_proxy @ws 127.0.0.1:8765 {{
header_up X-Forwarded-Proto {{scheme}}
header_up X-Forwarded-Host {{host}}
}}
reverse_proxy 127.0.0.1:8080 {{
header_up X-Forwarded-Proto {{scheme}}
header_up X-Forwarded-Host {{host}}
}}
}}
"""
tmp = Path("/dev/shm/rj_caddyfile_tmp")
try:
tmp.write_text(caddyfile_content, encoding="utf-8")
subprocess.run(
["sudo", "cp", str(tmp), "/etc/caddy/Caddyfile"],
check=True,
timeout=10,
)
subprocess.run(
["sudo", "systemctl", "reload", "caddy"],
check=True,
timeout=15,
)
except Exception:
pass
finally:
try:
if tmp.exists():
tmp.unlink()
except Exception:
pass
def _tailscale_run_install_and_up() -> None:
"""
Run the official install script and bring Tailscale up using the stored auth key.
This is executed in a background thread so HTTP handlers can return quickly.
"""
_tailscale_write_status({"installing": True, "ok": False, "error": None})
try:
if not TAILSCALE_KEY_PATH.exists():
_tailscale_write_status({
"installing": False,
"ok": False,
"error": "auth key not found",
})
return
except Exception:
_tailscale_write_status({
"installing": False,
"ok": False,
"error": "auth key not found",
})
return
# 1) Install Tailscale using the official script.
try:
install_res = subprocess.run(
["sh", "-c", "curl -fsSL https://tailscale.com/install.sh | sh"],
capture_output=True,
text=True,
timeout=600,
)
except subprocess.TimeoutExpired:
_tailscale_write_status({
"installing": False,
"ok": False,
"error": "tailscale install timeout",
})
return
except Exception as exc:
_tailscale_write_status({
"installing": False,
"ok": False,
"error": str(exc),
})
return
if install_res.returncode != 0:
msg = (install_res.stderr or install_res.stdout or "").strip()
if not msg:
msg = f"tailscale install failed (code {install_res.returncode})"
_tailscale_write_status({
"installing": False,
"ok": False,
"error": msg[:200],
})
return
# 2) Bring the daemon up using the stored auth key (non-interactive).
try:
auth_arg = f"--auth-key=file:{TAILSCALE_KEY_PATH}"
up_res = subprocess.run(
["tailscale", "up", auth_arg, "--ssh"],
capture_output=True,
text=True,
timeout=120,
)
except subprocess.TimeoutExpired:
_tailscale_write_status({
"installing": False,
"ok": False,
"error": "tailscale up timeout",
})
return
except Exception as exc:
_tailscale_write_status({
"installing": False,
"ok": False,
"error": str(exc),
})
return
if up_res.returncode != 0:
msg = (up_res.stderr or up_res.stdout or "").strip()
if not msg:
msg = f"tailscale up failed (code {up_res.returncode})"
_tailscale_write_status({
"installing": False,
"ok": False,
"error": msg[:200],
})
return
# Regenerate Caddyfile with tailscale0 IP and reload Caddy so HTTPS works over Tailscale.
_regenerate_caddyfile_and_reload()
_tailscale_write_status({
"installing": False,
"ok": True,
"error": None,
})
def _tailscale_run_reauth() -> None:
"""
Re-authenticate an existing Tailscale install using the stored auth key.
Does not re-run the install script, only `tailscale up --reset --auth-key=... --ssh`.
"""
_tailscale_write_status({"installing": True, "ok": False, "error": None})
try:
if not TAILSCALE_KEY_PATH.exists():
_tailscale_write_status({
"installing": False,
"ok": False,
"error": "auth key not found",
})
return
except Exception:
_tailscale_write_status({
"installing": False,
"ok": False,
"error": "auth key not found",
})
return
try:
auth_arg = f"--auth-key=file:{TAILSCALE_KEY_PATH}"
up_res = subprocess.run(
["tailscale", "up", "--reset", auth_arg, "--ssh"],
capture_output=True,
text=True,
timeout=120,
)
except subprocess.TimeoutExpired:
_tailscale_write_status({
"installing": False,
"ok": False,
"error": "tailscale up timeout",
})
return
except Exception as exc:
_tailscale_write_status({
"installing": False,
"ok": False,
"error": str(exc),
})
return
if up_res.returncode != 0:
msg = (up_res.stderr or up_res.stdout or "").strip()
if not msg:
msg = f"tailscale up failed (code {up_res.returncode})"
_tailscale_write_status({
"installing": False,
"ok": False,
"error": msg[:200],
})
return
_regenerate_caddyfile_and_reload()
_tailscale_write_status({
"installing": False,
"ok": True,
"error": None,
})
def _read_cpu_percent() -> float:
"""Best-effort CPU usage based on /proc/stat delta."""
global _CPU_SNAPSHOT
try:
with open("/proc/stat", "r", encoding="utf-8") as f:
line = f.readline().strip()
if not line.startswith("cpu "):
return 0.0
parts = [int(x) for x in line.split()[1:]]
idle = parts[3] + (parts[4] if len(parts) > 4 else 0)
total = sum(parts)
if _CPU_SNAPSHOT is None:
_CPU_SNAPSHOT = (idle, total)
return 0.0
prev_idle, prev_total = _CPU_SNAPSHOT
_CPU_SNAPSHOT = (idle, total)
idle_delta = idle - prev_idle
total_delta = total - prev_total
if total_delta <= 0:
return 0.0
pct = 100.0 * (1.0 - (idle_delta / total_delta))
return max(0.0, min(100.0, pct))
except Exception:
return 0.0
def _read_meminfo() -> tuple[int, int]:
"""Return used_bytes, total_bytes from /proc/meminfo."""
try:
vals = {}
with open("/proc/meminfo", "r", encoding="utf-8") as f:
for line in f:
key, rest = line.split(":", 1)
vals[key.strip()] = int(rest.strip().split()[0]) * 1024
total = int(vals.get("MemTotal", 0))
available = int(vals.get("MemAvailable", vals.get("MemFree", 0)))
used = max(0, total - available)
return used, total
except Exception:
return 0, 0
def _read_temp_c() -> float | None:
try:
raw = Path("/sys/class/thermal/thermal_zone0/temp").read_text(encoding="utf-8").strip()
val = float(raw)
return val / 1000.0 if val > 1000 else val
except Exception:
return None
def _read_uptime_seconds() -> int:
try:
with open("/proc/uptime", "r", encoding="utf-8") as f:
return int(float(f.read().split()[0]))
except Exception:
return 0
def _read_ipv4_interfaces() -> list[dict]:
out = []
try:
res = subprocess.run(
["ip", "-o", "-4", "addr", "show", "up"],
capture_output=True, text=True, timeout=3,
)
if res.returncode != 0:
return out
for line in res.stdout.splitlines():
parts = line.split()
if len(parts) < 4:
continue
iface = parts[1]
if iface == "lo":
continue
try:
inet_idx = parts.index("inet")
addr = parts[inet_idx + 1].split("/")[0]
except Exception:
addr = "-"
out.append({"name": iface, "ipv4": addr, "up": True})
except Exception:
pass
return out
def _b64url_encode(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def _b64url_decode(text: str) -> bytes:
padding = "=" * (-len(text) % 4)
return base64.urlsafe_b64decode(text + padding)
def _hmac_sign(payload: str) -> str:
mac = hmac.new(AUTH_SECRET.encode("utf-8"), payload.encode("utf-8"), hashlib.sha256).digest()
return _b64url_encode(mac)
def _issue_signed_token(claims: dict) -> str:
payload = _b64url_encode(json.dumps(claims, separators=(",", ":")).encode("utf-8"))
sig = _hmac_sign(payload)
return f"{payload}.{sig}"
def _read_signed_token(token: str) -> dict | None:
try:
payload, sig = token.split(".", 1)
except ValueError:
return None
if not hmac.compare_digest(_hmac_sign(payload), sig):
return None
try:
raw = _b64url_decode(payload)
data = json.loads(raw.decode("utf-8"))
return data if isinstance(data, dict) else None
except Exception:
return None
def _read_auth_config() -> dict | None:
try:
if not AUTH_FILE.exists():
return None
data = json.loads(AUTH_FILE.read_text(encoding="utf-8"))
if not isinstance(data, dict):
return None
if not data.get("username") or not data.get("password_hash"):
return None
return data
except Exception:
return None
def _auth_initialized() -> bool:
return _read_auth_config() is not None
def _hash_password(password: str, salt: str | None = None) -> str:
salt = salt or secrets.token_hex(16)
rounds = 210000
dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt.encode("utf-8"), rounds)
return f"pbkdf2_sha256${rounds}${salt}${_b64url_encode(dk)}"
def _verify_password(password: str, encoded: str) -> bool:
try:
algo, rounds, salt, digest = encoded.split("$", 3)
if algo != "pbkdf2_sha256":
return False
dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt.encode("utf-8"), int(rounds))
return hmac.compare_digest(_b64url_encode(dk), digest)
except Exception:
return False
def _write_auth_config(username: str, password: str) -> tuple[bool, str]:
user = str(username or "").strip()
pwd = str(password or "")
if len(user) < 3:
return False, "username must be at least 3 characters"
if len(user) > 32:
return False, "username too long"
if len(pwd) < 8:
return False, "password must be at least 8 characters"
rec = {
"username": user,
"password_hash": _hash_password(pwd),
"created_at": int(time.time()),
}
try:
AUTH_FILE.parent.mkdir(parents=True, exist_ok=True)
AUTH_FILE.write_text(json.dumps(rec), encoding="utf-8")
os.chmod(AUTH_FILE, 0o600)
return True, "ok"
except Exception as exc:
return False, f"write error: {exc}"
def _session_from_cookie(handler: SimpleHTTPRequestHandler) -> dict | None:
raw = str(handler.headers.get("Cookie", "") or "")
if not raw:
return None
c = SimpleCookie()
try:
c.load(raw)
except Exception:
return None
morsel = c.get(SESSION_COOKIE_NAME)
if not morsel:
return None
claims = _read_signed_token(morsel.value)
if not claims:
return None
if claims.get("typ") != "session":
return None
if int(claims.get("exp", 0)) < int(time.time()):
return None
if not claims.get("usr"):
return None
return claims
def _bearer_token_from_request(handler: SimpleHTTPRequestHandler, query: dict) -> str:
try:
authz = str(handler.headers.get("Authorization", "")).strip()
if authz.lower().startswith("bearer "):
return authz[7:].strip()
except Exception:
pass
# Legacy fallback for older links.
return str(query.get("token", [""])[0] or "").strip()
def _auth_context(handler: SimpleHTTPRequestHandler, query: dict) -> dict | None:
sess = _session_from_cookie(handler)
if sess:
return {"method": "session", "user": str(sess.get("usr")), "claims": sess}
bearer = _bearer_token_from_request(handler, query)
if TOKEN and bearer and hmac.compare_digest(bearer, TOKEN):
return {"method": "token", "user": "token-admin", "claims": None}
if not _auth_initialized():
return {"method": "bootstrap", "user": "bootstrap", "claims": None}
return None
def _auth_ok(handler: SimpleHTTPRequestHandler, query: dict) -> bool:
ctx = _auth_context(handler, query)
return ctx is not None and ctx.get("method") != "bootstrap"
def _request_is_https(handler: SimpleHTTPRequestHandler) -> bool:
"""Return True for direct TLS or trusted local reverse proxy TLS."""
if getattr(handler, "request_version", "").startswith("HTTPS/"):
return True
proto = str(handler.headers.get("X-Forwarded-Proto", "") or "").strip().lower()
if proto != "https":
return False
try:
ip = str(handler.client_address[0])
except Exception:
ip = ""
# Trust forwarded scheme only from local proxy hops.
return ip in ("127.0.0.1", "::1")
def _session_cookie_header(username: str, secure: bool = False, ttl_seconds: int = SESSION_TTL_SECONDS) -> tuple[str, str]:
now = int(time.time())
claims = {"typ": "session", "usr": username, "iat": now, "exp": now + int(ttl_seconds)}
token = _issue_signed_token(claims)
secure_attr = "; Secure" if secure else ""
cookie = f"{SESSION_COOKIE_NAME}={token}; Path=/; HttpOnly; SameSite=Strict; Max-Age={int(ttl_seconds)}{secure_attr}"
return ("Set-Cookie", cookie)
def _clear_session_cookie_header(secure: bool = False) -> tuple[str, str]:
secure_attr = "; Secure" if secure else ""
return ("Set-Cookie", f"{SESSION_COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0{secure_attr}")
def _safe_loot_path(raw_path: str) -> Path | None:
raw_path = raw_path.strip().lstrip("/")
target = (LOOT_DIR / raw_path).resolve()
try:
loot_root = LOOT_DIR.resolve()
except FileNotFoundError:
loot_root = LOOT_DIR
if loot_root in target.parents or target == loot_root:
return target
return None
def _safe_payload_path(raw_path: str) -> Path | None:
raw_path = raw_path.strip().lstrip("/")
target = (PAYLOADS_DIR / raw_path).resolve()
try:
payload_root = PAYLOADS_DIR.resolve()
except FileNotFoundError:
payload_root = PAYLOADS_DIR
if payload_root in target.parents or target == payload_root:
return target
return None
def _json_response(
handler: SimpleHTTPRequestHandler,
payload: dict,
status: int = 200,
extra_headers: list[tuple[str, str]] | None = None,
) -> None:
body = json.dumps(payload).encode("utf-8")
handler.send_response(status)
if extra_headers:
for key, value in extra_headers:
handler.send_header(key, value)
handler.send_header("Content-Type", "application/json; charset=utf-8")
handler.send_header("Content-Length", str(len(body)))
handler.end_headers()
handler.wfile.write(body)
def _read_json(handler: SimpleHTTPRequestHandler) -> dict | None:
try:
length = int(handler.headers.get("Content-Length", "0") or "0")
except Exception:
length = 0
try:
raw = handler.rfile.read(length) if length > 0 else b"{}"
return json.loads(raw.decode("utf-8", "ignore")) if raw else {}
except Exception:
return None
def _is_text_file(path: Path) -> bool:
ctype, _ = mimetypes.guess_type(str(path))
if ctype and ctype.startswith("text/"):
return True
ext = "".join(path.suffixes).lower() or path.suffix.lower()
if ext in TEXT_EXTS:
return True
return False
class RaspyJackHandler(SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=str(WEB_DIR), **kwargs)
def do_GET(self):
parsed = urlparse(self.path)
if parsed.path == "/ide":
self.path = "/ide.html" + (f"?{parsed.query}" if parsed.query else "")
super().do_GET()
return
if (
parsed.path.startswith("/api/loot/")
or parsed.path.startswith("/api/payloads/")
or parsed.path.startswith("/api/system/")
or parsed.path.startswith("/api/settings/")
or parsed.path.startswith("/api/auth/")
or parsed.path.startswith("/api/wardriving/")
):
query = parse_qs(parsed.query or "")
if parsed.path == "/api/auth/bootstrap-status":
self._handle_auth_bootstrap_status()
return
if parsed.path == "/api/auth/me":
self._handle_auth_me(query)
return
if not _auth_ok(self, query):
_json_response(self, {"error": "unauthorized"}, status=HTTPStatus.UNAUTHORIZED)
return
if parsed.path == "/api/payloads/list":
self._handle_payloads_list()
return
if parsed.path == "/api/payloads/status":
self._handle_payloads_status()
return
if parsed.path == "/api/payloads/tree":
self._handle_payloads_tree()
return
if parsed.path == "/api/payloads/file":
self._handle_payloads_file_get(query)
return
if parsed.path == "/api/loot/list":
self._handle_loot_list(query)
return
if parsed.path == "/api/loot/download":
self._handle_loot_download(query)
return
if parsed.path == "/api/loot/view":
self._handle_loot_view(query)
return
if parsed.path == "/api/loot/nmap":
self._handle_loot_nmap(query)
return
if parsed.path == "/api/wardriving/sessions":
self._handle_wardriving_sessions()
return
if parsed.path == "/api/wardriving/live":
self._handle_wardriving_live()
return
if parsed.path == "/api/wardriving/session":
self._handle_wardriving_session(query)
return
if parsed.path == "/api/system/status":
self._handle_system_status()
return
if parsed.path == "/api/settings/discord_webhook":
if not _auth_ok(self, query):
_json_response(self, {"error": "unauthorized"}, status=HTTPStatus.UNAUTHORIZED)
return
self._handle_settings_webhook_get()
return
if parsed.path == "/api/settings/wigle":
if not _auth_ok(self, query):
_json_response(self, {"error": "unauthorized"}, status=HTTPStatus.UNAUTHORIZED)
return
self._handle_settings_wigle_get()
return
if parsed.path == "/api/settings/tailscale":
if not _auth_ok(self, query):
_json_response(self, {"error": "unauthorized"}, status=HTTPStatus.UNAUTHORIZED)
return
self._handle_settings_tailscale_get()
return
_json_response(self, {"error": "not found"}, status=HTTPStatus.NOT_FOUND)
return
super().do_GET()
def do_POST(self):
parsed = urlparse(self.path)
if parsed.path == "/api/auth/bootstrap":
self._handle_auth_bootstrap()
return
if parsed.path == "/api/auth/login":
self._handle_auth_login()
return
if parsed.path == "/api/auth/logout":
self._handle_auth_logout()
return
if parsed.path == "/api/auth/ws-ticket":
query = parse_qs(parsed.query or "")
self._handle_auth_ws_ticket(query)
return
if parsed.path == "/api/system/restart-ui":
query = parse_qs(parsed.query or "")
if not _auth_ok(self, query):
_json_response(self, {"error": "unauthorized"}, status=HTTPStatus.UNAUTHORIZED)
return
self._handle_system_restart_ui()
return