-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsyscheck.py
More file actions
executable file
·9229 lines (8503 loc) · 361 KB
/
Copy pathsyscheck.py
File metadata and controls
executable file
·9229 lines (8503 loc) · 361 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
"""
Linux Diagnostic Engine (LDE) — kompleksowa, tylko do odczytu diagnostyka
systemu Linux.
Licencja: MIT
Wersja produktu: 0.6.0
Kompatybilność raportów/snapshotów: 2.1.0
Architektura trójfazowego potoku diagnostycznego:
Stage 1: RAW — zbiór surowych wyników poleceń (CmdResult).
Stage 2: OBS — strukturalne obserwacje wyprowadzone z RAW (Observation).
Stage 3: INT — interpretacje + rekomendacje (Finding).
Interpretacje nigdy nie konsumują RAW bezpośrednio — zależą tylko od
Observation. To separacja upraszcza testowanie i redukuje false positives.
Zasady:
- Wyłącznie operacje tylko do odczytu.
- Bez sudo (chyba że odczyt jest niemożliwy – wtedy pomijane i oznaczane).
- Bez modyfikacji konfiguracji, pakietów, usług.
- Raport zapisywany do pliku .md; wyświetlenie na konsoli jest opcjonalne.
- Wspiera Arch/CachyOS, Debian/Ubuntu, RHEL/Fedora (pakiety).
Użycie:
lde [--version]
lde run [--output-dir DIRECTORY] [--quiet] [--full] [--print-report] [--verbose]
lde explain FINDING-ID [--snapshot SNAPSHOT] [--json]
"""
from __future__ import annotations
import os
import subprocess
import argparse
import datetime
import ipaddress
import json
import re
import shlex
import shutil
import sys
import threading
from urllib.parse import quote
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import Any, ClassVar, Dict, Iterable, List, NoReturn, Optional, Tuple
# ── Stałe ────────────────────────────────────────────────────────
from constants import ( # type: ignore[import-untyped]
DISTRO_CONFIG,
MAX_RECOMMENDED_KERNELS,
get_default_reports_dir,
PRODUCT_NAME,
PRODUCT_SHORT_NAME,
PRODUCT_VERSION,
REPORT_COMPATIBILITY_VERSION,
RE_AUTH_FAIL,
RE_FIRMWARE,
RE_GFX_ERROR,
RE_KERNEL_ERROR,
RE_KERNEL_TAINT,
RE_AMDGPU_RESET_FAIL,
RE_FILESYSTEM_IO_ERROR,
RE_GPU_I915_HANG,
RE_HARDWARE_MCE_EDAC,
RE_HARDWARE_THERMAL_THROTTLE,
RE_KERNEL_HARD_LOCKUP,
RE_KERNEL_HUNG_TASK,
RE_KERNEL_OOPS_BUG,
RE_KERNEL_OOPS_PANIC,
RE_KERNEL_PANIC,
RE_KERNEL_RCU_STALL,
RE_KERNEL_SOFT_LOCKUP,
RE_KERNEL_STALL_RELIABILITY,
RE_PLATFORM_ACPI_FIRMWARE_ERROR,
RE_KERNEL_FIRMWARE_LOAD_FAIL,
RE_USB_ENUMERATION_FAIL,
RE_IOMMU_FAULT,
RE_PLATFORM_DEVICE_RELIABILITY,
RE_NVIDIA_XID_79,
RE_NVME_CONTROLLER_RELIABILITY,
RE_OOM,
RE_PCIE_AER,
RE_NETWORK_DEVICE_WATCHDOG,
RE_NETWORK_MANAGER_ACTIVATION_FAILURE,
RE_SEGFAULT,
SEGFAULT_ALERT_THRESHOLD,
TIMEOUT_LONG,
TIMEOUT_MEDIUM,
TIMEOUT_SHORT,
TRUNCATE_FOREIGN_PKGS,
TRUNCATE_IP_ADDR,
TRUNCATE_LSPCI,
TRUNCATE_NFT,
TRUNCATE_NORMAL,
TRUNCATE_RESOLVECTL,
INVALID_TEMPERATURE_CELSIUS,
STORAGE_WARNING_PERCENT,
STORAGE_CRITICAL_PERCENT,
KERNEL_NON_BOOTABLE_SUFFIXES,
)
# ──────────────────────────────────────────────────────────────────
# Narzędzia pomocnicze
# ──────────────────────────────────────────────────────────────────
MAX_WORKERS = 8 # maksymalna liczba równoległych wątków
_SYSTEMD_DURATION_COMPONENT_RE = re.compile(
r"(?P<value>(?:\d+(?:\.\d*)?|\.\d+))\s*"
r"(?P<unit>usec|us|µs|ms|seconds?|sec|s|minutes?|mins?|min|m|"
r"hours?|hrs?|hr|h|days?|d|weeks?|w)",
re.IGNORECASE,
)
_SYSTEMD_DURATION_FACTORS = {
"usec": 1e-6,
"us": 1e-6,
"µs": 1e-6,
"ms": 1e-3,
"second": 1.0,
"seconds": 1.0,
"sec": 1.0,
"s": 1.0,
"minute": 60.0,
"minutes": 60.0,
"mins": 60.0,
"min": 60.0,
"m": 60.0,
"hour": 3600.0,
"hours": 3600.0,
"hrs": 3600.0,
"hr": 3600.0,
"h": 3600.0,
"day": 86400.0,
"days": 86400.0,
"d": 86400.0,
"week": 604800.0,
"weeks": 604800.0,
"w": 604800.0,
}
_SYSTEMD_DURATION_EXPRESSION = (
r"(?:\d+(?:\.\d*)?|\.\d+)\s*"
r"(?:usec|us|µs|ms|seconds?|sec|s|minutes?|mins?|min|m|"
r"hours?|hrs?|hr|h|days?|d|weeks?|w)"
r"(?:\s+(?:\d+(?:\.\d*)?|\.\d+)\s*"
r"(?:usec|us|µs|ms|seconds?|sec|s|minutes?|mins?|min|m|"
r"hours?|hrs?|hr|h|days?|d|weeks?|w))*"
)
def _parse_systemd_duration(text: str) -> Optional[float]:
"""Parse a systemd duration expression into seconds.
The parser accepts the fixed-length units emitted by systemd-analyze,
including compound values such as ``1min 31.345s``. Invalid or partial
expressions return None instead of silently accepting a numeric suffix.
"""
value = text.strip()
if value.endswith("."):
value = value[:-1].rstrip()
if not value:
return None
matches = list(_SYSTEMD_DURATION_COMPONENT_RE.finditer(value))
if not matches:
return None
seconds = 0.0
cursor = 0
for match in matches:
if value[cursor : match.start()].strip():
return None
unit = match.group("unit").lower()
seconds += float(match.group("value")) * _SYSTEMD_DURATION_FACTORS[unit]
cursor = match.end()
if value[cursor:].strip():
return None
return seconds
@dataclass
class CmdResult:
"""Strukturalny wynik wykonania polecenia."""
command: str
stdout: str
stderr: str
return_code: int
execution_status: str # ok | not_found | timeout | permission_denied | error
privilege_required: bool = False
optional_dependency: bool = False
collected_at: str = ""
truncated: bool = False
def is_ok(self) -> bool:
return self.execution_status == "ok"
def to_fallback_text(self) -> str:
"""Zwraca opis statusu do raportu."""
def with_capture_marker(text: str) -> str:
markers = []
if self.truncated:
markers.append("[... wynik polecenia obcięty ...]")
if self.execution_status == "timeout" and (
self.stdout or (self.stderr and not self.stderr.startswith("Timeout"))
):
markers.append("[... wynik niepełny po timeout ...]")
return text if not markers else f"{text}\n" + "\n".join(markers)
if self.execution_status == "ok":
return with_capture_marker(self.stdout)
if self.execution_status == "not_found":
return f"(nie znaleziono: {self.command})"
if self.execution_status == "timeout":
partial_stderr = (
self.stderr if not self.stderr.startswith("Timeout") else ""
)
return with_capture_marker(self.stdout or partial_stderr or "(timeout)")
if self.execution_status == "permission_denied":
if self.stdout:
return with_capture_marker(self.stdout) + "\n(wymaga sudo — pominięto)"
return "(wymaga sudo — pominięto)"
if self.execution_status == "empty_ok":
return with_capture_marker(self.stdout if self.stdout else "(brak wyników)")
if self.stdout or self.stderr:
captured = "\n".join(part for part in (self.stdout, self.stderr) if part)
return with_capture_marker(captured) + f"\n(błąd rc={self.return_code})"
return f"(błąd rc={self.return_code})"
@dataclass
class DiagnosticDomain(str, Enum):
SYSTEMD = "systemd"
STORAGE = "storage"
FILESYSTEM = "filesystem"
KERNEL = "kernel"
BOOT = "boot"
AUDIO = "audio"
HARDWARE = "hardware"
NETWORK = "network"
POWER = "power"
SECURITY = "security"
PACKAGES = "packages"
ENVIRONMENT = "environment"
OTHER = "other"
__hash__ = str.__hash__ # type: ignore[assignment]
class FindingKind(str, Enum):
FAILED_UNIT = "failed_unit"
SOURCE_FAILURE = "source_failure"
STORAGE_USAGE = "storage_usage"
SCRUB_STATUS = "scrub_status"
DEVICE_ERROR = "device_error"
SEGFAULT = "segfault"
KERNEL_COUNT = "kernel_count"
KERNEL_TAINT = "kernel_taint"
OOM_EVENT = "oom_event"
GPU_I915_HANG = "gpu_i915_hang"
AMDGPU_RESET_FAIL = "amdgpu_reset_fail"
GPU_NVIDIA_XID_79 = "gpu_nvidia_xid_79"
PCIE_AER_ERROR = "pcie_aer_error"
NVME_CONTROLLER_RELIABILITY = "nvme_controller_reliability"
HARDWARE_MCE_EDAC_ERROR = "hardware_mce_edac_error"
FILESYSTEM_IO_ERROR = "filesystem_io_error"
HARDWARE_THERMAL_THROTTLING = "hardware_thermal_throttling"
KERNEL_OOPS_PANIC = "kernel_oops_panic"
KERNEL_SOFT_LOCKUP = "kernel_soft_lockup"
KERNEL_HARD_LOCKUP = "kernel_hard_lockup"
KERNEL_HUNG_TASK = "kernel_hung_task"
KERNEL_RCU_STALL = "kernel_rcu_stall"
PLATFORM_ACPI_FIRMWARE_ERROR = "platform_acpi_firmware_error"
KERNEL_FIRMWARE_LOAD_FAIL = "kernel_firmware_load_fail"
USB_ENUMERATION_FAIL = "usb_enumeration_fail"
IOMMU_FAULT = "iommu_fault"
NETWORK_RELIABILITY = "network_reliability"
POWER_BATTERY_RELIABILITY = "power_battery_reliability"
BOOT_DELAY = "boot_delay"
GENERAL = "general"
__hash__ = str.__hash__ # type: ignore[assignment]
class Actionability(str, Enum):
ACTIONABLE = "actionable"
CONDITIONAL = "conditional"
INFORMATIONAL = "informational"
__hash__ = str.__hash__ # type: ignore[assignment]
class RecommendationIntent(str, Enum):
INVESTIGATE = "investigate"
VERIFY = "verify"
REMEDIATE = "remediate"
MONITOR = "monitor"
INFORMATIONAL = "informational"
@dataclass
class Finding:
"""Pojedyncze ustalenie diagnostyczne ze strukturą (Stage 3: INT)."""
finding_id: str
title: str
severity: str # "P0" | "P1" | "P2" | "P3" | "Info"
confidence: str # "Certain" | "Likely" | "Guessing"
evidence: str = ""
interpretation: str = ""
recommended_diagnostics: str = ""
remediation: str = ""
verification: str = ""
risk_level: str = ""
domain: DiagnosticDomain = field(default_factory=lambda: DiagnosticDomain.OTHER)
kind: FindingKind = field(default_factory=lambda: FindingKind.GENERAL)
actionability: Actionability = field(
default_factory=lambda: Actionability.CONDITIONAL
)
recommendation_intent: RecommendationIntent = field(
default_factory=lambda: RecommendationIntent.VERIFY
)
source_observation_ids: tuple = ()
evidence_ids: tuple = ()
# Klucz sortowania: P0=0, P1=1, P2=2, P3=3, Info=4
_severity_order: ClassVar[dict] = {"P0": 0, "P1": 1, "P2": 2, "P3": 3, "Info": 4}
@dataclass
class Observation:
"""Pojedyncza obserwacja diagnostyczna (Stage 2: OBS).
Wyprowadzana wyłącznie z danych RAW (RawDiagnostic).
Nie zawiera interpretacji ani rekomendacji — tylko fakty.
"""
obs_id: str
category: str
details: Dict[str, Any] = field(default_factory=dict)
data_complete: bool = True
contradictory_evidence: bool = False
direct_measurement: bool = True
inference_required: bool = False
independent_sources: int = 1
source_raw_ids: tuple = ()
@dataclass(frozen=True)
class RawDiagnostic:
"""Surowy rekord diagnostyczny (Stage 1: RAW output).
Produkowany przez collect_*(), konsumowany przez _derive_observations().
Nie zawiera interpretacji, severity, confidence, ani rekomendacji. Metadane
pochodzenia są przechowywane osobno od payloadu diagnostycznego.
"""
source_id: str
category: str
payload: dict
collected_at: str = ""
provenance: dict = field(default_factory=dict)
def to_dict(self) -> dict:
return {
"source_id": self.source_id,
"category": self.category,
"payload": dict(self.payload),
"collected_at": self.collected_at,
"provenance": dict(self.provenance),
}
@classmethod
def from_dict(cls, data: dict) -> "RawDiagnostic":
return cls(
source_id=str(data.get("source_id", "")),
category=str(data.get("category", "")),
payload=dict(data.get("payload", {})),
collected_at=str(data.get("collected_at", "")),
provenance=dict(data.get("provenance", {})),
)
# ── Confidence derivation ────────────────────────────────────────
def derive_confidence(
*,
direct_measurement: bool,
data_complete: bool,
contradictory_evidence: bool,
inference_required: bool,
independent_sources: int,
) -> str:
"""Deterministycznie wyznacza poziom pewności na podstawie metadanych."""
if contradictory_evidence:
return "Guessing"
if not data_complete:
return "Guessing"
if independent_sources < 1:
return "Guessing"
if direct_measurement and not inference_required:
return "Certain"
if not direct_measurement and inference_required and independent_sources >= 1:
return "Likely"
return "Likely"
def run_cmd(
cmd: List[str],
timeout: int = TIMEOUT_SHORT,
env: Optional[Dict[str, str]] = None,
optional_dependency: bool = False,
) -> CmdResult:
"""
Uruchamia polecenie. Zwraca CmdResult ze szczegółowym statusem.
Bezpiecznie – bez powłoki, bez sudo.
"""
merged_env = os.environ.copy()
if env:
merged_env.update(env)
cmd_str = " ".join(cmd)
collected_at = datetime.datetime.now().isoformat(timespec="seconds")
def drain(stream: Any) -> Tuple[bytes, bool]:
chunks: List[bytes] = []
retained = 0
truncated = False
while True:
chunk = stream.read(65536)
if not chunk:
break
if retained < TRUNCATE_NORMAL:
keep = chunk[: TRUNCATE_NORMAL - retained]
chunks.append(keep)
retained += len(keep)
if len(keep) < len(chunk):
truncated = True
else:
truncated = True
return b"".join(chunks), truncated
try:
proc = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=merged_env,
start_new_session=True,
)
assert proc.stdout is not None
assert proc.stderr is not None
stdout_holder: List[Tuple[bytes, bool]] = []
stderr_holder: List[Tuple[bytes, bool]] = []
stdout_thread = threading.Thread(
target=lambda: stdout_holder.append(drain(proc.stdout)), daemon=True
)
stderr_thread = threading.Thread(
target=lambda: stderr_holder.append(drain(proc.stderr)), daemon=True
)
stdout_thread.start()
stderr_thread.start()
timed_out = False
try:
proc.wait(timeout=timeout)
except subprocess.TimeoutExpired:
timed_out = True
try:
os.killpg(proc.pid, 9)
except ProcessLookupError:
pass
proc.wait()
stdout_thread.join(timeout=2)
stderr_thread.join(timeout=2)
stdout_bytes, stdout_truncated = (
stdout_holder[0] if stdout_holder else (b"", True)
)
stderr_bytes, stderr_truncated = (
stderr_holder[0] if stderr_holder else (b"", True)
)
stdout = stdout_bytes.decode("utf-8", errors="replace").strip()
stderr = stderr_bytes.decode("utf-8", errors="replace").strip()
truncated = stdout_truncated or stderr_truncated
if timed_out:
timeout_text = f"Timeout ({timeout}s): {cmd_str}"
stderr = f"{stderr}\n{timeout_text}".strip()
status = "timeout"
return_code = -2
else:
return_code = proc.returncode
status = "ok" if return_code == 0 else "error"
return CmdResult(
command=cmd_str,
stdout=stdout,
stderr=stderr,
return_code=return_code,
execution_status=status,
optional_dependency=optional_dependency,
collected_at=collected_at,
truncated=truncated,
)
except FileNotFoundError:
return CmdResult(
command=cmd_str,
stdout="",
stderr=f"Polecenie nie znalezione: {cmd[0]}",
return_code=-1,
execution_status="not_found",
optional_dependency=optional_dependency,
collected_at=collected_at,
truncated=False,
)
except PermissionError:
return CmdResult(
command=cmd_str,
stdout="",
stderr=f"Brak uprawnień (bez sudo): {cmd_str}",
return_code=-3,
execution_status="permission_denied",
privilege_required=True,
optional_dependency=optional_dependency,
collected_at=collected_at,
truncated=False,
)
except Exception as exc:
return CmdResult(
command=cmd_str,
stdout="",
stderr=str(exc),
return_code=-4,
execution_status="error",
optional_dependency=optional_dependency,
collected_at=collected_at,
truncated=False,
)
def safestr(text: str, max_len: int = TRUNCATE_NORMAL, *, full: bool = False) -> str:
"""Przycina długi string, chyba że full=True."""
if full or len(text) <= max_len:
return text
return text[:max_len] + f"\n\n[... obcięto, pełna długość: {len(text)} znaków]"
def _capture_payload(result: CmdResult, payload: dict) -> dict:
"""Preserve bounded-capture metadata through the RAW diagnostic stage."""
if result.truncated:
payload["capture_truncated"] = True
return payload
def _cmd_result_provenance(result: CmdResult) -> dict:
"""Return non-sensitive execution metadata for a raw diagnostic."""
return {
"command": result.command,
"return_code": result.return_code,
"execution_status": result.execution_status,
"privilege_required": result.privilege_required,
"optional_dependency": result.optional_dependency,
"truncated": result.truncated,
"collected_at": result.collected_at,
}
def _raw_from_result(
result: CmdResult, *, source_id: str, category: str, payload: dict
) -> RawDiagnostic:
"""Build a RAW record without dropping command capture metadata."""
return RawDiagnostic(
source_id=source_id,
category=category,
payload=_capture_payload(result, payload),
collected_at=result.collected_at,
provenance=_cmd_result_provenance(result),
)
def _storage_diagnostic_id(threshold_state: str, mountpoint: str) -> str:
"""Return a deterministic, mount-specific storage diagnostic ID.
Keep the historical root IDs stable while encoding every other mountpoint
injectively so two qualifying mounts cannot share an Observation/Finding ID.
"""
base = (
"STORAGE-USAGE-CRITICAL"
if threshold_state == "critical"
else "STORAGE-USAGE-WARNING"
)
if mountpoint == "/":
return base
return f"{base}-MOUNT-{quote(mountpoint, safe='')}"
def _write_new_text(path: str | Path, text: str) -> None:
"""Create a new text file without following or replacing a destination."""
destination = Path(path)
if destination.is_symlink():
raise FileExistsError(f"Destination {destination} is a symlink")
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
if hasattr(os, "O_NOFOLLOW"):
flags |= os.O_NOFOLLOW
try:
fd = os.open(destination, flags, 0o644)
except FileExistsError:
raise FileExistsError(f"Destination {destination} already exists") from None
try:
handle = os.fdopen(fd, "w", encoding="utf-8")
except BaseException:
os.close(fd)
raise
try:
handle.write(text)
except BaseException:
try:
current = os.stat(destination, follow_symlinks=False)
opened = os.fstat(fd)
if (current.st_dev, current.st_ino) == (opened.st_dev, opened.st_ino):
destination.unlink()
except OSError:
pass
raise
finally:
handle.close()
def _cli_error(message: str) -> NoReturn:
"""Render an expected command-line failure without a traceback."""
print(f"Error: {message}", file=sys.stderr)
raise SystemExit(1)
# ── Public source capability surface ──────────────────────────────
CAPABILITY_AVAILABLE = "AVAILABLE"
CAPABILITY_LIMITED = "LIMITED"
CAPABILITY_NOT_APPLICABLE = "NOT_APPLICABLE"
CAPABILITY_UNAVAILABLE = "UNAVAILABLE"
CAPABILITY_FAILED = "FAILED"
CAPABILITY_STATES = frozenset(
{
CAPABILITY_AVAILABLE,
CAPABILITY_LIMITED,
CAPABILITY_NOT_APPLICABLE,
CAPABILITY_UNAVAILABLE,
CAPABILITY_FAILED,
}
)
@dataclass(frozen=True)
class SourceCapability:
"""Stable, non-diagnostic description of one source family."""
family: str
status: str
detail: str
def __post_init__(self) -> None:
if self.status not in CAPABILITY_STATES:
raise ValueError(f"Unsupported capability status: {self.status}")
def to_dict(self) -> dict:
return {
"family": self.family,
"status": self.status,
"detail": self.detail,
}
@dataclass(frozen=True)
class CapabilityProbeSpec:
"""One existing read-only source query exposed by ``lde capabilities``."""
family: str
command: Tuple[str, ...]
timeout: int = TIMEOUT_SHORT
optional_dependency: bool = False
empty_means_not_applicable: bool = False
mode: str = "generic"
CAPABILITY_PROBES = (
CapabilityProbeSpec("system_journal", ("journalctl", "-b", "--no-pager")),
CapabilityProbeSpec("kernel_journal", ("journalctl", "-b", "-k", "--no-pager")),
CapabilityProbeSpec(
"kernel_dmesg",
("cat", "/proc/sys/kernel/dmesg_restrict"),
mode="dmesg_restrict",
),
CapabilityProbeSpec(
"systemd_system",
("systemctl", "--failed", "--no-pager"),
mode="systemd_system",
),
CapabilityProbeSpec(
"systemd_user",
("systemctl", "--user", "--failed", "--no-pager"),
mode="systemd_user",
),
CapabilityProbeSpec(
"network_manager",
("systemctl", "status", "NetworkManager", "--no-pager"),
),
CapabilityProbeSpec("upower", ("upower", "-d"), optional_dependency=True),
CapabilityProbeSpec(
"btrfs",
("btrfs", "filesystem", "show", "/"),
optional_dependency=True,
),
CapabilityProbeSpec(
"nvme",
("nvme", "list"),
optional_dependency=True,
empty_means_not_applicable=True,
),
CapabilityProbeSpec(
"pci",
("lspci", "-k"),
optional_dependency=True,
empty_means_not_applicable=True,
),
CapabilityProbeSpec(
"usb", ("lsusb",), optional_dependency=True, empty_means_not_applicable=True
),
CapabilityProbeSpec(
"sensors",
("sensors",),
optional_dependency=True,
empty_means_not_applicable=True,
),
)
def _capability_detail(status: str) -> str:
return {
CAPABILITY_AVAILABLE: "authoritative source query succeeded",
CAPABILITY_LIMITED: "source is available but collection is limited",
CAPABILITY_NOT_APPLICABLE: "source does not apply on this workstation",
CAPABILITY_UNAVAILABLE: "command or source is unavailable",
CAPABILITY_FAILED: "source query failed; state is unknown",
}[status]
def _stderr_contains(text: str, markers: tuple[str, ...]) -> bool:
lowered = text.lower()
return any(marker in lowered for marker in markers)
def _capability_from_result(
spec: CapabilityProbeSpec, result: CmdResult
) -> SourceCapability:
"""Map an existing source query to a capability state only.
Capability states never become Findings and no state is described as
healthy. The classifier deliberately uses fixed public wording instead
of exposing command output that may contain workstation identifiers.
"""
if result.execution_status == "not_found":
status = CAPABILITY_UNAVAILABLE
elif result.execution_status == "permission_denied":
status = CAPABILITY_LIMITED
elif result.execution_status == "timeout" or result.truncated:
status = CAPABILITY_LIMITED
elif result.execution_status != "ok":
captured = f"{result.stdout}\n{result.stderr}"
if _stderr_contains(
captured,
(
"permission denied",
"operation not permitted",
"access denied",
"not permitted",
),
):
status = CAPABILITY_LIMITED
elif spec.mode == "systemd_user" and _stderr_contains(
captured,
(
"failed to connect to bus",
"no medium found",
"no data available",
"user scope bus",
"local transport",
"no such file or directory",
"not running systemd",
),
):
status = CAPABILITY_LIMITED
elif _stderr_contains(
captured,
(
"not a btrfs filesystem",
"unit networkmanager.service could not be found",
"unit networkmanager.service not found",
"no sensors found",
"no nvme controllers",
),
):
status = CAPABILITY_NOT_APPLICABLE
elif spec.mode == "systemd_system" and _stderr_contains(
captured,
("not booted with systemd",),
):
status = CAPABILITY_NOT_APPLICABLE
elif spec.family in {
"systemd_system",
"systemd_user",
"network_manager",
} and _stderr_contains(
captured,
("failed to connect to bus", "no data available", "local transport"),
):
status = CAPABILITY_LIMITED
else:
status = CAPABILITY_FAILED
elif spec.mode == "dmesg_restrict":
value = result.stdout.strip()
if value == "1":
status = CAPABILITY_LIMITED
elif value == "0":
status = CAPABILITY_AVAILABLE
else:
status = CAPABILITY_FAILED
elif spec.empty_means_not_applicable and not result.stdout.strip():
status = CAPABILITY_NOT_APPLICABLE
else:
status = CAPABILITY_AVAILABLE
return SourceCapability(spec.family, status, _capability_detail(status))
def _session_display_capability() -> SourceCapability:
if os.environ.get("WAYLAND_DISPLAY") or os.environ.get("DISPLAY"):
status = CAPABILITY_AVAILABLE
else:
status = CAPABILITY_NOT_APPLICABLE
detail = (
"session environment is available"
if status == CAPABILITY_AVAILABLE
else _capability_detail(status)
)
return SourceCapability("session_display", status, detail)
def probe_source_capabilities() -> tuple[SourceCapability, ...]:
"""Probe only source availability already used by the diagnostic run."""
capabilities = [
_capability_from_result(
spec,
run_cmd(
list(spec.command),
timeout=spec.timeout,
optional_dependency=spec.optional_dependency,
),
)
for spec in CAPABILITY_PROBES
]
capabilities.append(_session_display_capability())
return tuple(capabilities)
def format_capabilities(
capabilities: Iterable[SourceCapability], *, json_output: bool = False
) -> str:
"""Format source capabilities with stable ordering and no terminal state."""
ordered = tuple(capabilities)
if json_output:
return (
json.dumps(
{
"product": PRODUCT_NAME,
"version": PRODUCT_VERSION,
"capabilities": [capability.to_dict() for capability in ordered],
},
ensure_ascii=False,
indent=2,
sort_keys=True,
)
+ "\n"
)
lines = [
f"{PRODUCT_NAME} {PRODUCT_VERSION}",
"Source capabilities",
"FAMILY STATUS DETAIL",
]
lines.extend(
f"{capability.family:<22} {capability.status:<15} {capability.detail}"
for capability in ordered
)
return "\n".join(lines) + "\n"
# ── Deterministic report/snapshot sanitization ─────────────────────
SANITIZATION_NOTICE = (
"Known host, user, network, and explicitly owned hardware identifiers "
"were replaced. This artifact is not guaranteed anonymous; inspect it "
"before sharing."
)
_UUID_RE = re.compile(
r"(?<![0-9A-Fa-f])"
r"[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-"
r"[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}"
r"(?![0-9A-Fa-f])"
)
_MAC_RE = re.compile(
r"(?<![0-9A-Fa-f])(?:[0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}(?![0-9A-Fa-f])"
)
_IPV4_RE = re.compile(r"(?<![0-9.])(?:[0-9]{1,3}\.){3}[0-9]{1,3}(?![0-9.])")
_IPV6_CANDIDATE_RE = re.compile(
r"(?<![0-9A-Fa-f:])[0-9A-Fa-f:.]+(?:%[0-9A-Za-z_.-]+)?(?![0-9A-Fa-f:])"
)
_HOME_PATH_RE = re.compile(r"(?<![A-Za-z0-9._-])/home/[A-Za-z0-9._-]+")
_ROOT_PATH_RE = re.compile(r"(?<![A-Za-z0-9._-])/root(?=$|[/\s:])")
_RUNTIME_USER_PATH_RE = re.compile(r"(?<![A-Za-z0-9._-])/run/user/[0-9]+")
_MEDIA_PATH_RE = re.compile(r"(?<![A-Za-z0-9._-])/run/media/[^\n`]+")
_PS_USER_COLUMN_RE = re.compile(
r"(?m)^(?P<user>[A-Za-z_][A-Za-z0-9_.-]{0,31})(?P<spacing>\s+)"
r"(?P<pid>[0-9]+)(?=\s+[0-9.]+\s+[0-9.]+)"
)
def _replace_ip_literals(text: str) -> str:
def replace_ipv6(match: re.Match[str]) -> str:
candidate = match.group(0)
if ":" not in candidate:
return candidate
address = candidate.split("%", 1)[0]
try:
ipaddress.IPv6Address(address)
except ValueError:
return candidate
return "<IP>"
text = _IPV6_CANDIDATE_RE.sub(replace_ipv6, text)
def replace_ipv4(match: re.Match[str]) -> str:
candidate = match.group(0)
try:
ipaddress.IPv4Address(candidate)
except ipaddress.AddressValueError:
return candidate
return "<IP>"
return _IPV4_RE.sub(replace_ipv4, text)
def _sanitize_text(text: str, *, hostname: str = "") -> str:
if hostname and hostname not in {"unknown", "?"}:
hostname_pattern = re.compile(
rf"(?<![A-Za-z0-9._-]){re.escape(hostname)}(?![A-Za-z0-9._-])"
)
text = hostname_pattern.sub("<HOST>", text)
text = _UUID_RE.sub("<UUID>", text)
text = _MAC_RE.sub("<MAC>", text)
text = _replace_ip_literals(text)
text = _HOME_PATH_RE.sub("<HOME>", text)
text = _ROOT_PATH_RE.sub("<HOME>", text)
text = _RUNTIME_USER_PATH_RE.sub("/run/user/<USER>", text)
text = _MEDIA_PATH_RE.sub("<MEDIA>", text)
return _PS_USER_COLUMN_RE.sub(r"<USER>\g<spacing>\g<pid>", text)
_SANITIZE_ID_KEYS = frozenset(
{
"source_id",
"obs_id",
"observation_id",
"finding_id",
"evidence_id",
"raw_id",
"source_observation_ids",
"source_raw_ids",
"evidence_ids",
"rule_id",
}
)
_SANITIZE_HOST_KEYS = frozenset({"hostname", "host_name"})
_SANITIZE_USER_KEYS = frozenset({"username", "user_name"})
_SANITIZE_HOME_KEYS = frozenset({"home", "home_path"})
_SANITIZE_SERIAL_KEYS = frozenset({"serial", "serial_number", "device_serial"})
_SANITIZE_LABEL_KEYS = frozenset({"filesystem_label", "volume_label"})
def _sanitize_json_value(value: Any, *, key: str = "", hostname: str = "") -> Any:
lowered_key = key.lower()
if isinstance(value, dict):
return {
child_key: _sanitize_json_value(
child_value, key=child_key, hostname=hostname
)
for child_key, child_value in value.items()
}
if isinstance(value, list):
return [
_sanitize_json_value(item, key=key, hostname=hostname) for item in value
]