-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathwebapp_modern.py
More file actions
executable file
·14933 lines (12677 loc) · 625 KB
/
webapp_modern.py
File metadata and controls
executable file
·14933 lines (12677 loc) · 625 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
#webapp_modern.py
"""
Modern Flask-based web application for Ragnar
Features:
- Fast Flask backend with proper routing
- RESTful API endpoints
- WebSocket support for real-time updates
- Static file caching
- Better performance than SimpleHTTPRequestHandler
"""
import os
import sys
import json
import csv
import glob
import signal
import logging
import threading
import time
import subprocess
import re
import io
import base64
import shutil
import importlib
import hashlib
import ipaddress
import socket
import traceback
from datetime import datetime, timedelta, timezone
from typing import Optional, Dict, List, Tuple
from contextlib import contextmanager
from email.utils import format_datetime
from flask import Flask, render_template, jsonify, request, send_from_directory, Response, make_response, g, session, redirect
from flask_socketio import SocketIO, emit, disconnect
try:
from flask_cors import CORS # type: ignore
flask_cors_available = True
except ImportError:
flask_cors_available = False
try:
import psutil
psutil_available = True
except ImportError:
psutil_available = False
try:
import pandas as pd
pandas_available = True
except ImportError:
pandas_available = False
from init_shared import shared_data
from wifi_interfaces import gather_wifi_interfaces, gather_ethernet_interfaces, is_ethernet_available, get_active_ethernet_interface
from utils import WebUtils
from logger import Logger
from threat_intelligence import ThreatIntelligenceFusion
from lynis_parser import parse_lynis_dat
from actions.lynis_pentest_ssh import LynisPentestSSH
from actions.connector_utils import CredentialChecker
from db_manager import get_db, DatabaseManager
from auth_manager import AuthManager
# Initialize logger
logger = Logger(name="webapp_modern.py", level=logging.DEBUG)
# Initialize auth manager
auth_mgr = AuthManager(shared_data)
# Initialize Flask app
app = Flask(__name__,
static_folder='web',
template_folder='web')
app.config['SECRET_KEY'] = auth_mgr.get_or_create_secret_key()
app.config['JSON_SORT_KEYS'] = False
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=24)
# Set up CORS if available
if flask_cors_available:
CORS(app)
# Initialize SocketIO for real-time updates
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='threading')
# ============================================================================
# AUTHENTICATION MIDDLEWARE
# ============================================================================
@app.before_request
def check_authentication():
"""Enforce authentication on all endpoints when auth is configured."""
if not auth_mgr.is_configured():
return # No auth set up yet, allow everything
# Whitelist: paths that must be accessible without authentication
path = request.path
whitelist_prefixes = ['/login', '/api/auth/', '/api/kill']
if any(path.startswith(p) for p in whitelist_prefixes):
return
# Static assets needed for login page (CSS, JS, images, fonts)
static_prefixes = ['/css/', '/images/', '/scripts/', '/fonts/']
if any(path.startswith(p) for p in static_prefixes):
return
# Check if user is authenticated via Flask session
if not session.get('authenticated'):
if path.startswith('/api/'):
return jsonify({'error': 'Unauthorized', 'auth_required': True}), 401
return redirect('/login')
# Initialize web utilities
web_utils = WebUtils(shared_data, logger)
# Initialize threat intelligence system
try:
threat_intelligence = ThreatIntelligenceFusion(shared_data)
shared_data.threat_intelligence = threat_intelligence # type: ignore
logger.info("Threat intelligence system initialized")
except Exception as exc:
logger.error(f"Failed to initialize threat intelligence: {exc}")
threat_intelligence = None
shared_data.threat_intelligence = None # type: ignore
# Global state
clients_connected = 0
# Synchronization helpers for keeping dashboard and e-paper data fresh
sync_lock = threading.Lock()
last_sync_time = 0.0
SYNC_BACKGROUND_INTERVAL = 15 # seconds between automatic synchronizations (increased from 5s to reduce CPU load)
# Scan results caching to avoid reprocessing files every sync
scan_results_cache = {}
processed_scan_files = {} # Track which files we've already processed: {filename: mtime}
DEFAULT_ARP_SCAN_INTERFACE = 'wlan0'
SEP_SCAN_COMMAND = ['sudo', 'sep-scan']
MAC_REGEX = re.compile(r'^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$')
PWN_INSTALL_SCRIPT = os.path.join(shared_data.currentdir, 'scripts', 'install_pwnagotchi.sh')
PWN_SERVICE_FILE = '/etc/systemd/system/pwnagotchi.service'
PWN_SWAP_DELAY_SECONDS = 1
PWN_INSTALL_STALE_SECONDS = 600 # Treat installer as stale after 10 minutes
PWN_SWITCH_STALE_SECONDS = 60 # Consider switch stuck after 60 seconds
RELEASE_GATE_DEFAULT_MESSAGE = (
"A controlled release is rolling out. Proceeding with a manual update may cause instability."
)
def _normalize_value(value, default='Unknown'):
"""Normalize a value, handling nan, None, empty strings, etc."""
if value is None:
return default
str_value = str(value).strip()
if not str_value or str_value.lower() in ['nan', 'none', 'null', '']:
return default
return str_value
def _is_valid_ipv4(value):
try:
ipaddress.ip_address(value)
return True
except ValueError:
return False
def _normalize_mac(mac):
return mac.lower() if mac else ''
def _parse_attack_timestamp(value):
if value is None:
return None
if isinstance(value, (int, float)):
try:
return datetime.fromtimestamp(float(value), tz=timezone.utc)
except (ValueError, OSError):
return None
if isinstance(value, str):
cleaned = value.strip()
if cleaned.endswith('Z') and '+' not in cleaned:
cleaned = cleaned[:-1] + '+00:00'
parsers = (
lambda v: datetime.fromisoformat(v),
lambda v: datetime.strptime(v, '%Y-%m-%d %H:%M:%S'),
lambda v: datetime.strptime(v, '%Y-%m-%dT%H:%M:%S'),
)
for parser in parsers:
try:
return parser(cleaned)
except ValueError:
continue
return None
def _parse_arp_scan_output(output):
hosts = {}
if not output:
return hosts
for line in output.splitlines():
line = line.strip()
if not line or line.startswith('Interface:') or line.startswith('Starting') or line.startswith('Ending'):
continue
parts = re.split(r'\s+', line)
if len(parts) < 2:
continue
ip_candidate, mac_candidate = parts[0], parts[1]
if not (_is_valid_ipv4(ip_candidate) and MAC_REGEX.match(mac_candidate)):
continue
vendor = ' '.join(parts[2:]).strip() if len(parts) > 2 else ''
hosts[ip_candidate] = {
'mac': _normalize_mac(mac_candidate),
'vendor': vendor
}
return hosts
def build_pseudo_mac_from_ip(ip):
try:
octets = [int(part) for part in ip.split('.')]
if len(octets) == 4:
return f"00:00:{octets[0]:02x}:{octets[1]:02x}:{octets[2]:02x}:{octets[3]:02x}"
except Exception:
pass
return "00:00:00:00:00:00"
def _extract_requested_network_identifier() -> Optional[str]:
"""Read a requested network identifier from common query params."""
if not request:
return None
for key in ('network', 'ssid', 'slug'):
value = request.args.get(key)
if value:
value = value.strip()
if value:
return value
return None
def _normalize_network_slug(identifier: Optional[str]) -> Optional[str]:
"""Normalize a requested network identifier to a storage slug."""
if not identifier:
return None
candidate = identifier.strip()
if not candidate:
return None
manager = getattr(shared_data, 'storage_manager', None)
slugify = getattr(manager, '_slugify', None) if manager else None
if callable(slugify):
try:
return slugify(candidate)
except Exception as exc:
logger.debug(f"Failed to slugify network identifier '{candidate}': {exc}")
simplified = re.sub(r'[^a-z0-9]+', '_', candidate.lower()).strip('_')
return simplified or candidate.lower()
@contextmanager
def _network_context_from_request():
"""Temporarily switch shared data to the network requested by the client."""
identifier = _extract_requested_network_identifier()
slug = _normalize_network_slug(identifier)
registry = getattr(shared_data, 'context_registry', None)
if slug and registry:
try:
with registry.activate(slug):
g.requested_network_slug = slug
yield slug
return
except Exception as exc:
logger.warning(f"Unable to activate network context '{slug}': {exc}")
finally:
try:
g.pop('requested_network_slug', None)
except Exception:
pass
yield None
def run_targeted_arp_scan(ip, interface=DEFAULT_ARP_SCAN_INTERFACE):
command = ['sudo', 'arp-scan', f'--interface={interface}', ip]
logger.info(f"Running targeted arp-scan for {ip}: {' '.join(command)}")
try:
result = subprocess.run(command, capture_output=True, text=True, check=False, timeout=60)
hosts = _parse_arp_scan_output(result.stdout)
entry = hosts.get(ip)
return entry.get('mac', '') if entry else ''
except FileNotFoundError:
logger.warning(f"arp-scan command not found when resolving MAC for {ip}")
return ''
except subprocess.TimeoutExpired as e:
logger.warning(f"arp-scan timed out for {ip}: {e}")
hosts = _parse_arp_scan_output(e.stdout or '')
entry = hosts.get(ip)
return entry.get('mac', '') if entry else ''
except Exception as e:
logger.error(f"Error running targeted arp-scan for {ip}: {e}")
return ''
def _update_pwn_config(updates: dict) -> None:
if not updates:
return
changed = False
for key, value in updates.items():
if shared_data.config.get(key) != value:
shared_data.config[key] = value
setattr(shared_data, key, value)
changed = True
if changed:
try:
shared_data.save_config()
except Exception as exc:
logger.error(f"Failed to persist Pwnagotchi config updates: {exc}")
def _read_pwn_status_file() -> dict:
status_path = getattr(shared_data, 'pwnagotchi_status_file', os.path.join(shared_data.datadir, 'pwnagotchi_status.json'))
if not os.path.exists(status_path):
return {}
try:
with open(status_path, 'r', encoding='utf-8') as handle:
return json.load(handle)
except json.JSONDecodeError as exc:
logger.warning(f"Malformed Pwnagotchi status file: {exc}")
except Exception as exc:
logger.debug(f"Unable to read Pwnagotchi status file: {exc}")
return {}
def _parse_iso_timestamp(value: Optional[str]) -> Optional[datetime]:
if not value:
return None
try:
normalized = value.replace('Z', '+00:00')
parsed = datetime.fromisoformat(normalized)
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed
except Exception as exc:
logger.debug(f"Failed to parse Pwnagotchi status timestamp '{value}': {exc}")
return None
def _write_pwn_status_file(state: str, message: str, phase: str = 'dashboard', extra: Optional[dict] = None) -> dict:
payload = _read_pwn_status_file()
payload.update(extra or {})
payload.update({
'state': state,
'message': message,
'phase': phase,
'timestamp': datetime.utcnow().isoformat() + 'Z'
})
status_path = getattr(shared_data, 'pwnagotchi_status_file', os.path.join(shared_data.datadir, 'pwnagotchi_status.json'))
os.makedirs(os.path.dirname(status_path), exist_ok=True)
try:
with open(status_path, 'w', encoding='utf-8') as handle:
json.dump(payload, handle, indent=2)
except Exception as exc:
logger.error(f"Failed to update Pwnagotchi status file: {exc}")
return payload
def _systemctl_check(command: list[str]) -> bool:
try:
result = subprocess.run(command, capture_output=True, text=True)
return result.returncode == 0
except FileNotFoundError:
logger.warning(f"systemctl not available when running: {' '.join(command)}")
except Exception as exc:
logger.debug(f"systemctl check failed for {' '.join(command)}: {exc}")
return False
def _systemctl_state_label(service_name: str) -> str:
try:
result = subprocess.run(
['systemctl', 'is-active', service_name],
capture_output=True,
text=True
)
label = result.stdout.strip() or result.stderr.strip() or 'unknown'
return label
except FileNotFoundError:
logger.warning(f"systemctl not available while querying {service_name}")
except Exception as exc:
logger.debug(f"systemctl state query failed for {service_name}: {exc}")
return 'unknown'
_pwn_discovery_cache: Dict = {'data': None, 'timestamp': 0.0, 'dir_mtimes': {}}
_PWN_DISCOVERY_CACHE_TTL = 30
def _parse_pwnagotchi_filename(basename: str) -> Tuple[Optional[str], Optional[str], str]:
"""Parse a Pwnagotchi capture filename into (ssid, bssid, extension).
Pwnagotchi names files as SSID_BSSID.ext where BSSID may use hex-only,
underscores, or colons. Returns (ssid, bssid_colon_format, ext).
"""
ext = ''
name = basename
for compound in ('.gps.json', '.hc22000', '.pcapng', '.netjson'):
if name.lower().endswith(compound):
ext = compound
name = name[:-len(compound)]
break
if not ext:
dot_pos = name.rfind('.')
if dot_pos > 0:
ext = name[dot_pos:]
name = name[:dot_pos]
if not name:
return None, None, ext
# Case 1: BSSID with colons e.g. SSID_aa:bb:cc:dd:ee:ff
m = re.search(r'_([0-9a-fA-F]{2}(?::[0-9a-fA-F]{2}){5})$', name)
if m:
return name[:m.start()] or None, m.group(1).lower(), ext
# Case 2: BSSID as 12 contiguous hex chars e.g. SSID_aabbccddeeff
m = re.search(r'_([0-9a-fA-F]{12})$', name)
if m:
raw = m.group(1).lower()
bssid = ':'.join(raw[i:i + 2] for i in range(0, 12, 2))
return name[:m.start()] or None, bssid, ext
# Case 3: BSSID with underscores e.g. SSID_aa_bb_cc_dd_ee_ff
m = re.search(
r'_([0-9a-fA-F]{2})_([0-9a-fA-F]{2})_([0-9a-fA-F]{2})'
r'_([0-9a-fA-F]{2})_([0-9a-fA-F]{2})_([0-9a-fA-F]{2})$', name)
if m:
bssid = ':'.join(m.group(i).lower() for i in range(1, 7))
return name[:m.start()] or None, bssid, ext
return name, None, ext
def _read_gps_json_safe(filepath: str) -> Optional[dict]:
"""Read a Pwnagotchi .gps.json file. Returns dict with lat/lng or None."""
try:
with open(filepath, 'r', encoding='utf-8') as fh:
data = json.load(fh)
lat = data.get('Latitude') or data.get('latitude')
lng = data.get('Longitude') or data.get('longitude')
if lat is None or lng is None:
return None
lat, lng = float(lat), float(lng)
if lat == 0.0 and lng == 0.0:
return None
return {
'latitude': lat,
'longitude': lng,
'altitude': data.get('Altitude') or data.get('altitude'),
'accuracy': data.get('Accuracy') or data.get('accuracy'),
'updated': data.get('Updated') or data.get('updated'),
}
except (OSError, json.JSONDecodeError, ValueError, TypeError):
return None
def _collect_pwnagotchi_discovery_summary() -> dict:
"""Parse Pwnagotchi handshake/discovery files into grouped network data."""
global _pwn_discovery_cache
handshake_dirs = ['/root/handshakes', '/home/pi/handshakes']
current_mtimes: Dict[str, float] = {}
for d in handshake_dirs:
try:
current_mtimes[d] = os.path.getmtime(d)
except OSError:
pass
now = time.time()
if (_pwn_discovery_cache['data'] is not None
and (now - _pwn_discovery_cache['timestamp']) < _PWN_DISCOVERY_CACHE_TTL
and current_mtimes == _pwn_discovery_cache['dir_mtimes']):
return _pwn_discovery_cache['data']
handshake_exts = ('*.pcap', '*.pcapng', '*.22000', '*.hc22000')
discovery_exts = ('*.gps.json', '*.netjson', '*.json')
handshake_files: List[str] = []
discovery_files: List[str] = []
for d in handshake_dirs:
for ext in handshake_exts:
handshake_files.extend(glob.glob(os.path.join(d, ext)))
for ext in discovery_exts:
discovery_files.extend(glob.glob(os.path.join(d, ext)))
handshake_files = sorted(set(p for p in handshake_files if os.path.isfile(p)))
discovery_files = sorted(set(p for p in discovery_files if os.path.isfile(p)))
networks: Dict[Tuple[str, str], dict] = {}
def _get_or_create(ssid: Optional[str], bssid: Optional[str]) -> dict:
key = (ssid or 'Unknown', bssid or 'unknown')
if key not in networks:
networks[key] = {
'ssid': key[0], 'bssid': key[1],
'has_handshake': False, 'handshake_types': [],
'has_gps': False, 'gps': None, 'has_netjson': False,
'first_seen': None, 'last_seen': None,
'files': [],
}
return networks[key]
def _touch_ts(net: dict, fpath: str) -> None:
try:
ts = datetime.fromtimestamp(os.path.getmtime(fpath), tz=timezone.utc).isoformat()
except OSError:
return
if net['first_seen'] is None or ts < net['first_seen']:
net['first_seen'] = ts
if net['last_seen'] is None or ts > net['last_seen']:
net['last_seen'] = ts
def _file_entry(fpath: str) -> dict:
basename = os.path.basename(fpath)
try:
size = os.path.getsize(fpath)
except OSError:
size = 0
return {'name': basename, 'path': fpath, 'size': size}
for fpath in handshake_files:
ssid, bssid, ext = _parse_pwnagotchi_filename(os.path.basename(fpath))
net = _get_or_create(ssid, bssid)
net['has_handshake'] = True
label = ext.lstrip('.').upper() if ext else 'UNKNOWN'
if label not in net['handshake_types']:
net['handshake_types'].append(label)
net['files'].append(_file_entry(fpath))
_touch_ts(net, fpath)
for fpath in discovery_files:
ssid, bssid, ext = _parse_pwnagotchi_filename(os.path.basename(fpath))
net = _get_or_create(ssid, bssid)
net['files'].append(_file_entry(fpath))
_touch_ts(net, fpath)
if os.path.basename(fpath).lower().endswith('.gps.json'):
gps = _read_gps_json_safe(fpath)
if gps:
net['has_gps'] = True
net['gps'] = gps
elif os.path.basename(fpath).lower().endswith('.netjson'):
net['has_netjson'] = True
network_list = sorted(networks.values(), key=lambda n: n['last_seen'] or '', reverse=True)
combined = handshake_files + discovery_files
last_discovery = None
if combined:
try:
newest = max(combined, key=os.path.getmtime)
last_discovery = datetime.fromtimestamp(os.path.getmtime(newest), tz=timezone.utc).isoformat()
except OSError:
pass
def _recent_items(paths: List[str], limit: int = 5) -> List[dict]:
items: List[dict] = []
for fp in sorted(paths, key=lambda p: os.path.getmtime(p), reverse=True)[:limit]:
try:
items.append({
'name': os.path.basename(fp),
'modified': datetime.fromtimestamp(os.path.getmtime(fp), tz=timezone.utc).isoformat(),
})
except OSError:
continue
return items
result = {
'handshake_count': len(handshake_files),
'discovery_count': len(discovery_files),
'last_discovery': last_discovery,
'recent_handshakes': _recent_items(handshake_files),
'recent_discoveries': _recent_items(discovery_files),
'networks': network_list,
'network_count': len(network_list),
'networks_with_handshake': sum(1 for n in network_list if n['has_handshake']),
'networks_with_gps': sum(1 for n in network_list if n['has_gps']),
}
_pwn_discovery_cache = {'data': result, 'timestamp': now, 'dir_mtimes': current_mtimes}
return result
def _build_pwnagotchi_status(persist: bool = True) -> dict:
status = {
'state': 'not_installed',
'message': 'Pwnagotchi is not installed',
'phase': 'idle',
'installed': os.path.isdir('/opt/pwnagotchi') and os.path.exists(PWN_SERVICE_FILE),
'installing': False,
'mode': shared_data.config.get('pwnagotchi_mode', 'ragnar'),
'last_switch': shared_data.config.get('pwnagotchi_last_switch', ''),
'service_active': False,
'service_enabled': False,
'log_file': None,
'config_file': None,
'target_mode': shared_data.config.get('pwnagotchi_mode', 'ragnar'),
'timestamp': datetime.utcnow().isoformat() + 'Z',
'discoveries': {
'handshake_count': 0,
'discovery_count': 0,
'last_discovery': None,
'recent_handshakes': [],
'recent_discoveries': []
}
}
file_data = _read_pwn_status_file()
if file_data:
for key, value in file_data.items():
# Only update known keys to avoid leaking arbitrary data
if key in {'state', 'message', 'phase', 'log_file', 'config_file', 'repo_dir', 'target_mode', 'timestamp'}:
status[key] = value
state = status.get('state', 'not_installed')
status['installing'] = state in {'preflight', 'dependencies', 'python', 'installing'}
if status['installing'] and not _pwn_install_process_running() and _is_pwn_install_stale(file_data):
stale_message = 'Pwnagotchi installer stopped unexpectedly. Press Install again to retry.'
status['installing'] = False
status['state'] = 'error'
status['phase'] = 'error'
status['message'] = stale_message
_write_pwn_status_file('error', stale_message, 'error', {
'log_file': status.get('log_file'),
'target_mode': status.get('target_mode', 'ragnar')
})
pwn_service_state = _systemctl_state_label('pwnagotchi')
status['service_state'] = pwn_service_state
status['service_active'] = pwn_service_state == 'active'
status['service_enabled'] = _systemctl_check(['systemctl', 'is-enabled', 'pwnagotchi'])
ragnar_service_state = _systemctl_state_label('ragnar')
status['ragnar_service_state'] = ragnar_service_state
ragnar_service_active = ragnar_service_state == 'active'
service_file_exists = os.path.exists(PWN_SERVICE_FILE)
status['service_file_exists'] = service_file_exists
if service_file_exists and not status.get('service_file'):
status['service_file'] = PWN_SERVICE_FILE
if status['service_active']:
status['state'] = 'running'
status['message'] = 'Pwnagotchi service is running'
status['mode'] = 'pwnagotchi'
elif ragnar_service_active:
status['mode'] = 'ragnar'
if status['state'] not in {'error', 'installing'}:
status['state'] = 'running'
status['message'] = 'Ragnar service is running'
else:
status['mode'] = status.get('mode', shared_data.config.get('pwnagotchi_mode', 'ragnar'))
state = status.get('state', state)
stale_switch = False
if state == 'switching' and not status['installing']:
timestamp_obj = _parse_iso_timestamp(status.get('timestamp'))
if not timestamp_obj:
stale_switch = True
else:
age = datetime.now(timezone.utc) - timestamp_obj
stale_switch = age.total_seconds() >= PWN_SWITCH_STALE_SECONDS
if stale_switch:
target_mode = (status.get('target_mode') or shared_data.config.get('pwnagotchi_mode', 'ragnar')).lower()
if target_mode not in {'pwnagotchi', 'ragnar'}:
target_mode = 'ragnar'
if target_mode == 'pwnagotchi':
if status['service_active']:
status['state'] = 'running'
status['phase'] = 'active'
status['message'] = 'Pwnagotchi service is running'
status['mode'] = 'pwnagotchi'
status['target_mode'] = 'pwnagotchi'
else:
status['state'] = 'error'
status['phase'] = 'error'
status['mode'] = 'ragnar' if ragnar_service_active else 'ragnar'
status['target_mode'] = 'ragnar'
status['message'] = (
f"Switch to Pwnagotchi failed: pwnagotchi.service is {pwn_service_state}. "
f"Ragnar service is {ragnar_service_state}."
)
else: # target_mode == 'ragnar'
if ragnar_service_active:
status['state'] = 'running'
status['phase'] = 'idle'
status['message'] = 'Ragnar service is running'
status['mode'] = 'ragnar'
status['target_mode'] = 'ragnar'
else:
status['state'] = 'error'
status['phase'] = 'error'
status['mode'] = 'pwnagotchi' if status['service_active'] else 'ragnar'
status['target_mode'] = 'pwnagotchi'
status['message'] = (
f"Switch to Ragnar failed: ragnar.service is {ragnar_service_state}. "
f"Pwnagotchi service is {pwn_service_state}."
)
updated_payload = _write_pwn_status_file(
status['state'],
status['message'],
status.get('phase', 'dashboard'),
{
'target_mode': status.get('target_mode'),
'log_file': status.get('log_file'),
'config_file': status.get('config_file'),
'service_state': status.get('service_state')
}
)
for key in ('state', 'message', 'phase', 'timestamp', 'target_mode'):
if key in updated_payload:
status[key] = updated_payload[key]
state = status['state']
status['installed'] = (
status['installed']
or state == 'installed'
or status['service_active']
or status['service_enabled']
or service_file_exists
)
config_updates = {}
if status['installed'] != bool(shared_data.config.get('pwnagotchi_installed', False)):
config_updates['pwnagotchi_installed'] = status['installed']
if status.get('mode') and status['mode'] != shared_data.config.get('pwnagotchi_mode'):
config_updates['pwnagotchi_mode'] = status['mode']
if status.get('message') and status['message'] != shared_data.config.get('pwnagotchi_last_status'):
config_updates['pwnagotchi_last_status'] = status['message']
if persist and config_updates:
_update_pwn_config(config_updates)
status['discoveries'] = _collect_pwnagotchi_discovery_summary()
return status
def _emit_pwn_status_update(status: Optional[dict] = None) -> dict:
payload = status or _build_pwnagotchi_status()
try:
socketio.emit('pwnagotchi_status', payload)
except Exception as exc:
logger.debug(f"Failed to emit pwnagotchi_status event: {exc}")
return payload
def _pwn_install_process_running() -> bool:
script_name = os.path.basename(PWN_INSTALL_SCRIPT)
try:
result = subprocess.run(['pgrep', '-f', script_name], capture_output=True, text=True)
return result.returncode == 0
except FileNotFoundError:
logger.debug('pgrep not available to verify Pwnagotchi installer state')
except Exception as exc:
logger.debug(f"Unable to determine installer process state: {exc}")
return False
def _is_pwn_install_stale(status: Optional[dict], max_age_seconds: int = PWN_INSTALL_STALE_SECONDS) -> bool:
if not status:
return True
timestamp = status.get('timestamp')
if not timestamp:
return True
normalized = timestamp.replace('Z', '+00:00')
try:
parsed = datetime.fromisoformat(normalized)
except ValueError:
logger.debug(f"Unable to parse Pwnagotchi installer timestamp: {timestamp}")
return True
age = datetime.now(timezone.utc) - parsed
return age.total_seconds() > max_age_seconds
def _read_pwn_log_chunk(cursor: Optional[int] = None, tail_bytes: int = 4096, max_bytes: int = 8192):
"""Return a slice of the installer log starting at cursor or tail bytes from end."""
status = _build_pwnagotchi_status(persist=False)
log_file = status.get('log_file')
if not log_file or not os.path.exists(log_file):
return status, None, 0, []
try:
file_size = os.path.getsize(log_file)
except OSError:
return status, None, 0, []
if cursor is None or cursor < 0:
tail_bytes = max(0, min(tail_bytes, 65536))
start = max(file_size - tail_bytes, 0)
else:
start = max(0, min(cursor, file_size))
max_bytes = max(1024, min(max_bytes, 65536))
entries: list[str] = []
new_cursor = start
try:
with open(log_file, 'r', encoding='utf-8', errors='replace') as handle:
handle.seek(start)
chunk = handle.read(max_bytes)
new_cursor = handle.tell()
except Exception as exc:
logger.debug(f"Failed reading Pwnagotchi installer log: {exc}")
return status, log_file, new_cursor, []
if chunk:
entries = chunk.splitlines()
return status, log_file, new_cursor, entries
def _schedule_pwn_mode_switch(target_mode: str) -> None:
if target_mode not in {'pwnagotchi', 'ragnar'}:
logger.warning(f"Invalid Pwnagotchi target mode requested: {target_mode}")
return
def _thread_target():
try:
_execute_pwn_mode_switch(target_mode)
except Exception as exc: # pragma: no cover - defensive guard
logger.error(f"Unhandled error during Pwnagotchi handoff to {target_mode}: {exc}")
thread = threading.Thread(
target=_thread_target,
name=f"pwn-switch-{target_mode}",
daemon=True,
)
thread.start()
def _run_systemctl(args: list[str], *, timeout: int = 60) -> subprocess.CompletedProcess:
"""Execute systemctl with sudo and capture output."""
return subprocess.run(
['sudo', 'systemctl', *args],
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
def _summarize_status_output(output: str, limit: int = 600) -> str:
"""Condense systemctl status output into a single readable line."""
if not output:
return ''
collapsed = ' | '.join(line.strip() for line in output.splitlines() if line.strip())
return (collapsed[:limit].rstrip() + ('…' if len(collapsed) > limit else ''))
def _collect_service_status(service_name: str) -> str:
try:
status_proc = _run_systemctl(['status', service_name, '--no-pager'], timeout=10)
status_output = status_proc.stdout.strip() or status_proc.stderr.strip()
return _summarize_status_output(status_output)
except Exception as exc: # pragma: no cover - best effort
return f"Unable to collect status for {service_name}: {exc}"
def _ensure_pwn_launcher() -> None:
"""Ensure /usr/bin/pwnagotchi-launcher exists and is executable."""
launcher_path = '/usr/bin/pwnagotchi-launcher'
try:
if os.path.exists(launcher_path):
if os.access(launcher_path, os.X_OK):
return
os.chmod(launcher_path, 0o755)
logger.info(f"Repaired permissions for {launcher_path}")
return
candidates = [
shutil.which('pwnagotchi'),
shutil.which('pwnagotchi-launcher'),
'/usr/local/bin/pwnagotchi',
'/usr/local/bin/pwnagotchi-launcher'
]
target = next((c for c in candidates if c and os.path.exists(c)), None)
if not target:
logger.warning("Unable to locate pwnagotchi binary; launcher shim not created")
return
script = f"#!/bin/bash\nexec {target} \"$@\"\n"
with open(launcher_path, 'w', encoding='utf-8') as handle:
handle.write(script)
os.chmod(launcher_path, 0o755)
logger.info(f"Created pwnagotchi launcher shim at {launcher_path} → {target}")
except PermissionError as exc:
logger.error(f"Permission error while ensuring pwnagotchi launcher: {exc}")
except Exception as exc: # pragma: no cover - defensive guard
logger.error(f"Failed to prepare pwnagotchi launcher: {exc}")
def _unit_name(service_name: str) -> str:
unit = service_name.strip()
if unit.endswith('.service'):
unit = unit[:-8]
return unit or service_name
def _format_service_failure_message(service_name: str) -> str:
unit = _unit_name(service_name)
readable = unit.replace('_', ' ').replace('-', ' ').title()
return f"Failed to start {readable} service. Review journalctl -u {unit} -f for details."
def _wait_for_service_active(service_name: str, timeout: int = 30, poll_interval: int = 1) -> tuple[bool, str]:
deadline = time.monotonic() + timeout
last_state = ''
while time.monotonic() < deadline:
state_proc = _run_systemctl(['is-active', service_name], timeout=10)
state = state_proc.stdout.strip() or state_proc.stderr.strip()
last_state = state or last_state or 'unknown'
if state == 'active':
return True, 'active'
if state in {'failed', 'inactive'}:
return False, _collect_service_status(service_name) or f"{service_name} reported state {state}"
time.sleep(poll_interval)
return False, _collect_service_status(service_name) or f"{service_name} did not become active within {timeout}s (last state: {last_state})"
def _start_service_with_monitor(service_name: str, timeout: int = 30) -> tuple[bool, str]:
start_proc = _run_systemctl(['start', service_name])
if start_proc.returncode != 0:
detail = start_proc.stderr.strip() or start_proc.stdout.strip() or f"systemctl start {service_name} failed with {start_proc.returncode}"
status_excerpt = _collect_service_status(service_name)
summary = status_excerpt or detail
return False, summary
return _wait_for_service_active(service_name, timeout=timeout)
def _stop_service(service_name: str) -> tuple[bool, str]:
stop_proc = _run_systemctl(['stop', service_name])
if stop_proc.returncode != 0:
detail = stop_proc.stderr.strip() or stop_proc.stdout.strip() or f"systemctl stop {service_name} failed with {stop_proc.returncode}"
logger.warning(detail)
return False, detail
return True, 'stopped'
def _deferred_self_stop(delay: int = 1) -> None:
"""Stop the ragnar.service via a systemd-run transient unit.
Because Ragnar is stopping *itself*, a direct systemctl stop kills the
thread before status files and config can be persisted. We use
systemd-run so the stop command runs in its own cgroup — completely
outside ragnar.service — and survives ragnar's cgroup teardown.
subprocess.Popen with start_new_session=True is NOT sufficient: it
creates a new session but inherits the same cgroup, so systemd kills
it when tearing down ragnar.service.
"""
try:
subprocess.Popen(
['systemd-run', '--no-block', '--collect',
'--unit=ragnar-deferred-stop',
'bash', '-c', f'sleep {delay} && systemctl stop ragnar.service'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)