Repository navigation
Expand file tree
/
Copy pathphp2shell-audit.py
More file actions
1964 lines (1770 loc) · 103 KB
/
Copy pathphp2shell-audit.py
File metadata and controls
1964 lines (1770 loc) · 103 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
"""PHP2Shell audit: Linux/macOS/Windows discovery, file checks and remote inspection."""
import argparse
import base64
import bz2
import ctypes
import errno
import gzip
import hashlib
import html
import http.client
import json
import lzma
import ntpath
import os
import platform
import re
import secrets
import shlex
import sqlite3
import stat
import subprocess
import sys
import tarfile
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
import zlib
from contextlib import ExitStack
from dataclasses import dataclass
from datetime import datetime, timezone
from html.parser import HTMLParser
from pathlib import Path, PurePosixPath, PureWindowsPath
CVES = ("CVE-2026-109618", "CVE-2026-109619")
BASELINES = {(8, 2): 35, (8, 3): 36, (8, 4): 27, (8, 5): 12}
KINDS = {"fpm", "mod_php", "cgi", "lsphp", "frankenphp", "php", "embedded"}
MAX_CONFIG = 1024 * 1024
MAX_ARCHIVE = 512 * 1024 * 1024
# Both Ubuntu CVE pages confirmed these package revisions on 2026-10-22.
UBUNTU_FIXES = {
("14.04", "php5"): "5.5.9+dfsg-1ubuntu4.29+esm18",
("16.04", "php7.0"): "7.0.33-0ubuntu0.16.04.16+esm22",
("18.04", "php7.2"): "7.2.24-0ubuntu0.18.04.17+esm14",
("20.04", "php7.4"): "7.4.3-4ubuntu2.29+esm5",
("22.04", "php8.1"): "8.1.2-1ubuntu2.28",
("24.04", "php8.3"): "8.3.6-0ubuntu0.24.04.13",
("26.04", "php8.5"): "8.5.4-0ubuntu1.5",
("26.10", "php8.5"): "8.5.9-0ubuntu2.1",
}
UBUNTU_SOURCES = ["https://ubuntu.com/security/" + cve for cve in CVES]
# Debian's trackers for both CVEs, checked 2026-10-22. Derivatives need their own rules.
DEBIAN_FIXES = {("12", "php8.2"): "8.2.35-1~deb12u1",
("13", "php8.4"): "8.4.27-1~deb13u1"}
DEBIAN_SOURCES = ["https://security-tracker.debian.org/tracker/" + cve for cve in CVES]
MANAGERS = {"dpkg", "rpm", "apk", "pacman"}
# Both CVEs in Alpine's release-scoped community secdb, verified 2026-10-23.
ALPINE_FIXES = {"php83": "8.3.36-r0", "php84": "8.4.27-r0", "php85": "8.5.12-r0"}
# Exact Arch binary-package advisories, verified 2026-10-23.
ARCH_FIXES = {"php": ("8.5.12-1", "AVG-2909"), "php-legacy": ("8.3.36-1", "AVG-2910")}
TOOL_VERSION = "1.1.0"
GUIDANCE = {
"ubuntu": "https://ubuntu.com/server/docs/how-to/software/package-management/",
"debian": "https://www.debian.org/doc/manuals/debian-handbook/sect.regular-upgrades.en.html",
"rhel": "https://access.redhat.com/solutions/10021",
"rocky": "https://docs.rockylinux.org/guides/package_management/dnf_package_manager/",
"almalinux": "https://wiki.almalinux.org/documentation/errata.html",
"alpine": "https://docs.alpinelinux.org/user-handbook/0.1a/Working/apk.html#_upgrading_packages",
"arch": "https://wiki.archlinux.org/title/System_maintenance",
"homebrew": "https://docs.brew.sh/FAQ#how-do-i-update-my-local-packages",
"macports": "https://guide.macports.org/#using.port.upgrade",
"win32": "https://www.php.net/manual/en/install.windows.manual.php",
}
NEXT_STEPS = {
"ACCESS_DENIED": "Obtain read access to the reported process/file and rerun the audit.",
"FILE_MISSING": "Check the inventory path and deployment; inspect inactive artifacts separately.",
"FILE_CHANGED": "Recheck the deployed artifact and restart affected workers as appropriate, then re-audit.",
"PROCESS_CHANGED": "Rerun after the worker stops exiting or changing during inspection.",
"EVIDENCE_MISSING": "Supply trusted SHA-256 build evidence or a matching verified package archive.",
"EVIDENCE_MISMATCH": "Investigate the file/evidence mismatch; obtain evidence for the actual artifact.",
"VENDOR_RULE_MISSING": "Supply a vendor rule for this exact release/package covering both CVEs.",
"VERSION_UNSUPPORTED": "Supply verified backport evidence for both CVEs or use a supported fixed build.",
"LOADED_IMAGE_UNVERIFIED": "Assess installed files with --files; that result cannot clear Windows running images.",
"RESTART_REQUIRED": "Restart or replace the affected deployment using its normal procedure, then re-audit.",
"AFFECTED": "Apply a vendor/build update fixing both CVEs, restart affected workers, and re-audit.",
"INVENTORY_UNCONFIRMED": "Review discovered and inactive deployments, then supply a confirmed inventory.",
"EXPECTED_RUNTIME_MISSING": "Check the expected service/namespace; assess inactive files separately.",
"UNEXPECTED_RUNTIME": "Identify the runtime and include it in the reviewed deployment inventory.",
"DISCOVERY_INCOMPLETE": "Resolve process access or namespace restrictions and rerun within the deployment.",
"NO_RUNTIME_FOUND": "Confirm the target namespace and inventory; use --files for inactive deployments.",
"TRANSPORT_FAILED": "Check SSH/container access, the target Python path, and the reported transport error.",
"OBSERVATION_ONLY": "Run a local or remote artifact audit with confirmed inventory and trusted evidence.",
"INSPECTION_FAILED": "Resolve the reported inspection error and rerun; do not clear this deployment.",
}
class AuditError(Exception):
"""Audit failure with a stable diagnostic code."""
def __init__(self, message, code="INSPECTION_FAILED"):
"""Initialize an audit failure.
Args:
message (str): Human-readable failure detail.
code (str): Key in NEXT_STEPS identifying the unresolved condition.
"""
super().__init__(message)
self.code = code
def command(argv, timeout=15, data=None):
"""Fixed system utilities, or a binary explicitly selected with --probe-php."""
environment = {"PATH": "/usr/sbin:/usr/bin:/sbin:/bin", "LC_ALL": "C"}
if sys.platform == "win32":
directory = windows_system_directory()
environment = {"SystemRoot": str(directory.parent), "PATH": str(directory),
"TEMP": os.environ.get("TEMP", str(directory.parent / "Temp"))}
if Path(argv[0]).name.lower() == "ssh.exe":
for key in ("USERPROFILE", "HOMEDRIVE", "HOMEPATH"):
if key in os.environ:
environment[key] = os.environ[key]
if Path(argv[0]).name == "ssh" and "SSH_AUTH_SOCK" in os.environ:
environment["SSH_AUTH_SOCK"] = os.environ["SSH_AUTH_SOCK"]
if Path(argv[0]).name in ("docker", "podman"):
environment["HOME"] = str(Path.home())
for key in ("DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_CONFIG", "DOCKER_TLS_VERIFY",
"DOCKER_CERT_PATH", "CONTAINER_HOST", "CONTAINER_CONNECTION", "XDG_RUNTIME_DIR"):
if key in os.environ:
environment[key] = os.environ[key]
try:
return subprocess.run(argv, input=data, text=True, capture_output=True,
timeout=timeout, check=False,
env=environment, encoding="utf-8", errors="replace")
except (OSError, subprocess.TimeoutExpired) as exc:
raise AuditError("Command failed or timed out: " + argv[0]) from exc
def windows_system_directory():
import ctypes
buffer = ctypes.create_unicode_buffer(32768)
size = ctypes.windll.kernel32.GetSystemDirectoryW(buffer, len(buffer))
require(0 < size < len(buffer), "Cannot locate Windows system directory")
return Path(buffer.value)
def system_tool(name):
if sys.platform == "win32":
relative = {"powershell": "WindowsPowerShell/v1.0/powershell.exe",
"ssh": "OpenSSH/ssh.exe"}.get(name)
require(relative is not None, "Unsupported Windows utility: " + name)
path = windows_system_directory() / relative
require(path.is_file(), "Missing Windows system utility: " + name)
return str(path)
directories = ("/usr/bin", "/bin", "/usr/sbin", "/sbin")
if name in ("docker", "podman"):
directories += ("/usr/local/bin", "/opt/homebrew/bin")
owners = {0}
if name in ("docker", "podman") and os.getuid() == os.geteuid():
owners.add(os.getuid())
for directory in directories:
path = Path(directory) / name
try:
info = path.stat()
if (stat.S_ISREG(info.st_mode) and info.st_uid in owners
and not info.st_mode & 0o022 and os.access(path, os.X_OK)):
return str(path)
except OSError:
continue
raise AuditError("Missing trusted system utility: " + name)
def load_json(path):
with open(path, "rb") as stream:
data = stream.read(MAX_CONFIG + 1)
if len(data) > MAX_CONFIG:
raise AuditError("Configuration exceeds 1 MiB")
return json.loads(data)
def require(condition, message, code="INSPECTION_FAILED"):
"""Enforce an audit precondition.
Args:
condition (bool): Whether the required invariant holds.
message (str): Failure detail.
code (str): Stable diagnostic code.
Raises:
AuditError: The condition is false.
"""
if not condition:
raise AuditError(message, code)
def diagnostic(code, detail, distro=None, manager=None):
"""Describe a finding without changing its patch verdict.
Args:
code (str): Stable NEXT_STEPS key.
detail (str): Finding detail; treated as data in text and JSON output.
distro (tuple[str, str] | None): Audited OS ID and release.
manager (str | None): Artifact package manager, when known.
Returns:
dict: Code, detail, next step and applicable update guidance URLs.
"""
guide = GUIDANCE.get(manager) or GUIDANCE.get(distro[0] if distro else sys.platform)
return {"code": code, "detail": detail, "next_step": NEXT_STEPS[code],
"guidance": [guide] if guide else ["https://github.com/beardedeagle/php2shell-patch-audit#patching-guidance"]}
def error_diagnostic(error, distro=None, manager=None):
"""Convert an inspection error into an actionable diagnostic.
Args:
error (Exception): Inspection or validation error.
distro (tuple[str, str] | None): Audited OS ID and release.
manager (str | None): Package manager already identified for the artifact.
Returns:
dict: Diagnostic retaining the original error detail.
"""
code = error.code if isinstance(error, AuditError) else "INSPECTION_FAILED"
if isinstance(error, PermissionError):
code = "ACCESS_DENIED"
elif isinstance(error, FileNotFoundError):
code = "FILE_MISSING"
return diagnostic(code, str(error), distro, manager)
def explain_record(record, distro):
"""Attach unresolved conditions and restart guidance to an artifact record.
Args:
record (dict): Artifact assessment, updated in place.
distro (tuple[str, str] | None): Audited OS ID and release.
Returns:
dict: The record with additive diagnostics; status remains unchanged.
"""
findings = record.setdefault("diagnostics", [])
if not findings and record["status"] != "PATCHED":
code = "AFFECTED" if record["status"] == "AFFECTED" else (
"VERSION_UNSUPPORTED" if "php_version" in record else "INSPECTION_FAILED")
findings.append(diagnostic(code, record.get("detail", ""), distro, record.get("manager")))
if record.get("restart_needed"):
findings.append(diagnostic("RESTART_REQUIRED", "Running file was removed or replaced", distro, record.get("manager")))
return record
def report_metadata(inventory=None, evidence=None):
"""Record the audited host and fingerprints of the supplied JSON documents.
Args:
inventory (dict | None): Parsed inventory, including its scope assertion.
evidence (dict | None): Parsed evidence, including imported advisory rows.
Returns:
dict: UTC report time, tool identity, target OS/architecture and SHA-256
fingerprints of canonical JSON; raw inputs are not retained.
"""
def fingerprint(value):
return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"),
allow_nan=False).encode()).hexdigest() if value is not None else None
try:
distro = os_release()
except (OSError, AuditError):
distro = None
source_hash = globals().get("AUDIT_SOURCE_SHA256")
if source_hash is None and "__file__" in globals():
try:
source_hash = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
except OSError:
source_hash = None
return {"timestamp_utc": datetime.now(timezone.utc).isoformat(),
"tool_version": TOOL_VERSION, "tool_sha256": source_hash,
"target": {"platform": sys.platform, "os_release": list(distro) if distro else None,
"os_version": platform.mac_ver()[0] if sys.platform == "darwin" else platform.version(),
"architecture": platform.machine()},
"inventory_sha256": fingerprint(inventory), "evidence_sha256": fingerprint(evidence)}
def absolute_path(value):
return bool(isinstance(value, str) and not any(ord(c) < 32 for c in value)
and not value.startswith(("//", "\\\\"))
and (value.startswith("/") or
(PureWindowsPath(value).is_absolute() and re.match(r"^[A-Za-z]:", value)
and ":" not in value[2:])))
def path_key(value):
return ntpath.normcase(ntpath.normpath(value)) if re.match(r"^[A-Za-z]:", value) else value
def validate_config(inventory, evidence):
if inventory is not None:
require(isinstance(inventory, dict) and inventory.get("schema") == 1,
"Inventory must have schema=1")
require(inventory.get("coverage_confirmed") is True and
isinstance(inventory.get("scope"), str) and inventory["scope"].strip(),
"Inventory needs scope and an explicit coverage_confirmed=true assertion", "INVENTORY_UNCONFIRMED")
require(isinstance(inventory.get("runtimes"), list) and inventory["runtimes"],
"Inventory must contain expected runtimes")
keys = set()
for item in inventory["runtimes"]:
require(isinstance(item, dict), "Invalid inventory entry")
require(isinstance(item.get("label"), str) and item["label"].strip(),
"Inventory entry needs a label")
require(isinstance(item.get("kind"), str) and item["kind"] in KINDS
and absolute_path(item.get("path")),
"Inventory entry needs a supported kind and absolute runtime path")
key = (item["kind"], path_key(item["path"]))
require(key not in keys, "Duplicate inventory runtime")
keys.add(key)
require(isinstance(evidence, dict) and evidence.get("schema") == 1,
"Evidence must have schema=1")
for field in ("vendor_fixes", "builds", "rpm_advisories", "package_archives"):
require(isinstance(evidence.get(field, []), list), "Invalid evidence list: " + field)
seen = set()
for row in evidence.get("vendor_fixes", []):
require(isinstance(row, dict), "Invalid vendor rule")
for key in ("os_id", "os_version", "package", "fixed_version"):
require(isinstance(row.get(key), str) and
re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.+:~^_-]*", row[key]),
"Invalid vendor rule field: " + key)
require(isinstance(row.get("manager"), str) and row["manager"] in MANAGERS and
sorted(row.get("cves", [])) == sorted(CVES),
"Each vendor rule must cover both CVEs and name dpkg, rpm, apk or pacman")
require(isinstance(row.get("sources"), list) and row["sources"] and
all(isinstance(url, str) and url.startswith("https://")
for url in row["sources"]), "Vendor rule needs advisory sources")
key = tuple(row[k] for k in ("os_id", "os_version", "manager", "package"))
require(key not in seen, "Duplicate vendor rule")
seen.add(key)
seen = set()
for row in evidence.get("builds", []):
require(isinstance(row, dict) and isinstance(row.get("sha256"), str) and
re.fullmatch(r"[0-9a-f]{64}", row["sha256"]), "Invalid build SHA-256")
require(isinstance(row.get("php_version"), str) and
isinstance(row.get("source"), str) and row["source"].strip(),
"Build evidence needs php_version and trusted build provenance")
require(row["sha256"] not in seen, "Duplicate build SHA-256")
if "fixed_cves" in row:
require(isinstance(row["fixed_cves"], list) and sorted(row["fixed_cves"]) == sorted(CVES),
"Build fixed_cves must establish fixes for both CVEs")
seen.add(row["sha256"])
seen = set()
for row in evidence.get("package_archives", []):
require(isinstance(row, dict) and row.get("manager") in ("homebrew", "macports"),
"Package archive needs manager homebrew or macports")
for field in ("package", "version", "php_version", "source"):
require(isinstance(row.get(field), str) and row[field].strip(),
"Package archive needs " + field)
require(absolute_path(row.get("path")) and isinstance(row.get("sha256"), str)
and re.fullmatch(r"[0-9a-f]{64}", row["sha256"]),
"Package archive needs an absolute path and SHA-256")
if "fixed_cves" in row:
require(isinstance(row["fixed_cves"], list) and sorted(row["fixed_cves"]) == sorted(CVES),
"Package archive fixed_cves must cover both CVEs")
key = row["manager"], row["package"], row["version"]
require(key not in seen, "Duplicate package archive")
seen.add(key)
for row in evidence.get("rpm_advisories", []):
require(isinstance(row, dict), "Invalid imported RPM advisory")
for key in ("os_id", "os_version", "package", "version", "arch"):
require(isinstance(row.get(key), str) and
re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.+:~^_-]*", row[key]),
"Invalid RPM advisory field: " + key)
require(isinstance(row.get("module"), str) and
re.fullmatch(r"[A-Za-z0-9.+:_-]*", row["module"]) and
isinstance(row.get("cves"), list) and row["cves"] and
all(cve in CVES for cve in row["cves"]) and
isinstance(row.get("source"), str) and row["source"], "Invalid RPM advisory scope")
def load_updateinfo(path, distro):
opener = gzip.open if str(path).endswith(".gz") else open
with opener(path, "rb") as stream:
data = stream.read(32 * MAX_CONFIG + 1)
require(len(data) <= 32 * MAX_CONFIG, "Updateinfo exceeds 32 MiB decompressed")
text = data.decode("utf-8-sig")
require("<!DOCTYPE" not in text and "<!ENTITY" not in text, "XML declarations are not allowed")
try:
root = ET.fromstring(text)
except ET.ParseError as exc:
raise AuditError("Invalid updateinfo XML") from exc
for element in root.iter():
element.tag = element.tag.rsplit("}", 1)[-1]
require(root.tag == "updates", "Expected updateinfo updates document")
records = []
for update in root.findall("update"):
cves = sorted({ref.get("id") for ref in update.findall("references/reference")
if ref.get("type", "").lower() == "cve" and ref.get("id") in CVES})
if not cves:
continue
for collection in update.findall("pkglist/collection"):
module = collection.find("module")
stream = ":".join(module.get(key, "") for key in ("name", "stream", "context")) if module is not None else ""
for package in collection.findall("package"):
records.append({"os_id": distro[0], "os_version": distro[1],
"package": package.get("name"), "arch": package.get("arch"),
"version": package.get("epoch", "0") + ":" + package.get("version", "") + "-" + package.get("release", ""),
"module": stream, "cves": cves,
"source": str(path) + "#" + (update.findtext("id") or "unnamed")})
validate_config(None, {"schema": 1, "rpm_advisories": records})
require(records, "Updateinfo has no package records for these CVEs")
return records
def updateinfo_rule(package, distro, evidence):
if package["manager"] != "rpm" or not evidence.get("rpm_advisories"):
return None
if package.get("module") is None:
return None
module = package["module"].split(":")
stream = ":".join((module[0], module[1], module[3])) if len(module) >= 4 else ""
branch = re.match(r"[0-9]+:([0-9]+\.[0-9]+)\.", package["version"])
if not branch or (package.get("module") and not stream):
return None
matches = [r for r in evidence.get("rpm_advisories", [])
if (r["os_id"], r["os_version"]) == distro and
r["package"] == package["package"] and r["arch"] == package.get("arch")
and r["module"] == stream and
re.match(r"[0-9]+:" + re.escape(branch[1]) + r"\.", r["version"])]
minima, sources = [], set()
for cve in CVES:
candidates = [row for row in matches if cve in row["cves"]]
if not candidates:
return None
minimum = candidates[0]["version"]
for row in candidates:
if package_status({"manager": "rpm", "version": row["version"]}, minimum) == "AFFECTED":
minimum = row["version"]
sources.add(row["source"])
minima.append(minimum)
fixed = minima[0]
for version in minima[1:]:
if package_status({"manager": "rpm", "version": version}, fixed) == "PATCHED":
fixed = version
return {"fixed_version": fixed, "sources": sorted(sources)}
def upstream_status(version):
match = re.fullmatch(r"(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)", version)
if not match:
return "UNKNOWN"
major, minor, patch = map(int, match.groups())
minimum = BASELINES.get((major, minor))
if minimum is None:
return "UNKNOWN"
return "PATCHED" if patch >= minimum else "AFFECTED"
def os_release():
# Parse the two simple fields without sourcing a shell file.
values = {}
path = Path("/etc/os-release")
if not path.is_file():
path = Path("/usr/lib/os-release")
for line in path.read_text().splitlines():
match = re.fullmatch(r'(ID|VERSION_ID|VERSION_CODENAME)=["\']?([A-Za-z0-9._-]+)["\']?', line)
if match:
values[match[1]] = match[2]
require("ID" in values, "Cannot determine OS release")
return values["ID"], values.get("VERSION_ID", values.get("VERSION_CODENAME", "rolling"))
def start_time(pid):
return Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[19]
def same_namespace(pid):
remote = os.stat(f"/proc/{pid}/ns/mnt")
local = os.stat("/proc/self/ns/mnt")
return ((remote.st_dev, remote.st_ino) == (local.st_dev, local.st_ino) and
os.stat(f"/proc/{pid}/root").st_ino == os.stat("/").st_ino and
os.stat(f"/proc/{pid}/root").st_dev == os.stat("/").st_dev)
def executable_kind(path):
name = Path(path).name.lower()
patterns = ((r"php-fpm[0-9.-]*", "fpm"), (r"php-cgi[0-9.-]*", "cgi"),
(r"lsphp[0-9.-]*", "lsphp"), (r"frankenphp", "frankenphp"),
(r"php[0-9.-]*", "php"), (r"caddy", "embedded"))
return next((kind for pattern, kind in patterns if re.fullmatch(pattern, name)), None)
def proc_path(raw):
deleted = raw.endswith(" (deleted)")
if deleted:
raw = raw[:-10]
return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m[1], 8)), raw), deleted
@dataclass
class Runtime:
pid: int
kind: str
path: str
live_path: str
start: str
deleted: bool = False
device: int = 0
inode: int = 0
def discover(inventory):
if sys.platform == "win32":
return discover_windows(inventory)
if sys.platform == "darwin":
return discover_macos(inventory)
require(sys.platform.startswith("linux"),
"Process inspection supports Linux, macOS and Windows; use --files for other systems")
expected = {row["path"]: row["kind"] for row in (inventory or {}).get("runtimes", [])
if row["kind"] != "mod_php"}
runtimes, issues = [], []
try:
pids = sorted(int(p.name) for p in Path("/proc").iterdir() if p.name.isdigit())
except OSError as exc:
raise AuditError("Cannot enumerate /proc") from exc
require(pids, "No processes visible in /proc")
for pid in pids:
try:
started = start_time(pid)
try:
raw_exe = os.readlink(f"/proc/{pid}/exe")
except FileNotFoundError:
if not Path(f"/proc/{pid}/cmdline").read_bytes():
continue # Kernel thread or zombie; no executing userspace image.
raise
exe, deleted = proc_path(raw_exe)
kind = expected.get(exe) or executable_kind(exe)
found = []
if kind:
found.append(Runtime(pid, kind, exe, f"/proc/{pid}/exe", started, deleted))
# Inspect modules even for renamed Apache/embedded-server executables.
for line in Path(f"/proc/{pid}/maps").read_text().splitlines():
fields = line.split(None, 5)
if len(fields) != 6:
continue
path, removed = proc_path(fields[5])
is_module = re.search(r"(?:^|/)libphp[^/]*\.so(?:\.[0-9]+)*$", path)
is_expected = any(row["kind"] == "mod_php" and row["path"] == path
for row in (inventory or {}).get("runtimes", []))
if not is_module and not is_expected:
continue
device = os.makedev(*(int(part, 16) for part in fields[3].split(":")))
if not any(r.path == path and r.kind == "mod_php" for r in found):
found.append(Runtime(pid, "mod_php", path,
f"/proc/{pid}/map_files/{fields[0]}", started,
removed, device, int(fields[4])))
if found and not same_namespace(pid):
issues.append(f"PID {pid}: different mount/root namespace; audit inside it")
continue
if found and start_time(pid) != started:
issues.append(f"PID {pid}: process identity changed during discovery")
continue
runtimes.extend(found)
except FileNotFoundError:
if Path(f"/proc/{pid}").exists():
issues.append(f"PID {pid}: runtime inspection was incomplete")
except (OSError, ValueError, IndexError):
issues.append(f"PID {pid}: cannot inspect executable/modules; coverage incomplete")
return runtimes, issues
WINDOWS_DISCOVERY = r'''
$ErrorActionPreference = 'Stop'
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
# Windows PowerShell 5.1 already returns the JSON array as one object.
$expected = [Console]::In.ReadToEnd() | ConvertFrom-Json
$processes = @()
$issues = @()
foreach ($process in @(Get-Process)) {
if ($process.Id -in @(0, 4, $PID)) { continue }
try {
$started = $process.StartTime.ToUniversalTime().Ticks.ToString()
$path = $process.MainModule.FileName
if (-not $path) { throw 'Executable path unavailable' }
$modules = @()
foreach ($module in @($process.Modules)) {
if ($module.ModuleName -match '^(php[0-9].*|libphp.*)\.(dll|so)$' -or
$module.FileName -in $expected) {
$modules += @{path=$module.FileName; version=$module.FileVersionInfo.ProductVersion}
}
}
$current = Get-Process -Id $process.Id
if ($current.StartTime.ToUniversalTime().Ticks.ToString() -ne $started) {
throw 'Process identity changed'
}
$processes += @{pid=$process.Id; start=$started; path=$path; modules=$modules}
} catch {
$issues += "PID $($process.Id): cannot inspect executable/modules: $($_.Exception.Message)"
}
}
@{processes=$processes; issues=$issues} | ConvertTo-Json -Depth 6 -Compress
'''
def powershell_json(script, data):
encoded = base64.b64encode(script.encode("utf-16le")).decode("ascii")
result = command([system_tool("powershell"), "-NoLogo", "-NoProfile", "-NonInteractive",
"-EncodedCommand", encoded], timeout=120, data=json.dumps(data))
require(result.returncode == 0, "Windows inspection failed: " + result.stderr[:1000])
return json.loads(result.stdout.lstrip("\ufeff"))
def discover_windows(inventory):
expected = {path_key(row["path"]): row["kind"]
for row in (inventory or {}).get("runtimes", [])}
snapshot = powershell_json(WINDOWS_DISCOVERY, list(expected))
require(isinstance(snapshot, dict) and isinstance(snapshot.get("processes"), list)
and isinstance(snapshot.get("issues"), list)
and all(isinstance(issue, str) for issue in snapshot["issues"]),
"Malformed Windows process snapshot")
runtimes = []
for process in snapshot["processes"]:
require(isinstance(process, dict) and type(process.get("pid")) is int
and process["pid"] > 0 and absolute_path(process.get("path"))
and isinstance(process.get("start"), str)
and isinstance(process.get("modules"), list), "Malformed Windows process")
path = process["path"]
name = ntpath.basename(path).lower()
kind = expected.get(path_key(path)) or executable_kind("/" + name.removesuffix(".exe"))
if kind:
runtimes.append(Runtime(process["pid"], kind, path, path, process["start"]))
for module in process["modules"]:
require(isinstance(module, dict) and absolute_path(module.get("path")),
"Malformed Windows module")
path = module["path"]
if (path_key(path) in expected or
re.fullmatch(r"(?:php[0-9].*|libphp.*)\.(?:dll|so)", ntpath.basename(path), re.I)):
kind = expected.get(path_key(path), "mod_php")
if not any(r.pid == process["pid"] and path_key(r.path) == path_key(path) for r in runtimes):
runtimes.append(Runtime(process["pid"], kind, path, path, process["start"]))
return runtimes, snapshot["issues"]
class MacOSProcesses:
"""Read process identities and mapped vnodes through libproc."""
class BSDInfo(ctypes.Structure):
_fields_ = [(name, ctypes.c_uint32) for name in (
"flags", "status", "xstatus", "pid", "ppid", "uid", "gid", "ruid",
"rgid", "svuid", "svgid", "reserved")]
_fields_ += [("comm", ctypes.c_char * 16), ("name", ctypes.c_char * 32)]
_fields_ += [(name, ctypes.c_uint32) for name in ("nfiles", "pgid", "jobc", "tdev", "tpgid")]
_fields_ += [("nice", ctypes.c_int32), ("seconds", ctypes.c_uint64), ("microseconds", ctypes.c_uint64)]
class RegionInfo(ctypes.Structure):
_fields_ = [(name, ctypes.c_uint32) for name in ("protection", "max_protection", "inheritance", "flags")]
_fields_ += [("offset", ctypes.c_uint64)]
_fields_ += [(name, ctypes.c_uint32) for name in (
"behavior", "wired", "tag", "resident", "private_shared", "swapped", "dirty",
"references", "shadow_depth", "share_mode", "private", "shared", "object_id", "depth")]
_fields_ += [("address", ctypes.c_uint64), ("size", ctypes.c_uint64)]
class VnodeStat(ctypes.Structure):
_fields_ = [("device", ctypes.c_uint32), ("mode", ctypes.c_uint16), ("nlink", ctypes.c_uint16),
("inode", ctypes.c_uint64), ("uid", ctypes.c_uint32), ("gid", ctypes.c_uint32)]
_fields_ += [(name, ctypes.c_int64) for name in (
"atime", "atime_ns", "mtime", "mtime_ns", "ctime", "ctime_ns",
"birthtime", "birthtime_ns", "size", "blocks")]
_fields_ += [("blocksize", ctypes.c_int32), ("flags", ctypes.c_uint32),
("generation", ctypes.c_uint32), ("rdevice", ctypes.c_uint32),
("reserved", ctypes.c_int64 * 2)]
def __init__(self):
class RegionPath(ctypes.Structure):
_fields_ = [("region", MacOSProcesses.RegionInfo), ("stat", MacOSProcesses.VnodeStat),
("type", ctypes.c_int), ("padding", ctypes.c_int),
("fsid", ctypes.c_int32 * 2), ("path", ctypes.c_char * 1024)]
self.region_type = RegionPath
self.lib = ctypes.CDLL("/usr/lib/libproc.dylib", use_errno=True)
self.lib.proc_listallpids.argtypes = [ctypes.c_void_p, ctypes.c_int]
self.lib.proc_listallpids.restype = ctypes.c_int
self.lib.proc_pidinfo.argtypes = [ctypes.c_int, ctypes.c_int, ctypes.c_uint64, ctypes.c_void_p, ctypes.c_int]
self.lib.proc_pidinfo.restype = ctypes.c_int
self.lib.proc_pidpath.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32]
self.lib.proc_pidpath.restype = ctypes.c_int
def pids(self):
for _ in range(3):
count = self.lib.proc_listallpids(None, 0)
require(0 < count < 1000000, "Cannot enumerate macOS processes")
buffer = (ctypes.c_int * (count + 128))()
used = self.lib.proc_listallpids(buffer, ctypes.sizeof(buffer))
require(used > 0, "Cannot enumerate macOS processes")
if used < len(buffer):
return sorted(set(pid for pid in buffer[:used] if pid > 0))
raise AuditError("macOS process list kept growing during enumeration")
def info(self, pid, flavor, data, address=0):
ctypes.set_errno(0)
size = self.lib.proc_pidinfo(pid, flavor, address, ctypes.byref(data), ctypes.sizeof(data))
if size <= 0:
code = ctypes.get_errno() or errno.EIO
raise OSError(code, os.strerror(code))
require(size == ctypes.sizeof(data), "Incomplete macOS process information")
return data
def identity(self, pid):
data = self.info(pid, 3, self.BSDInfo()) # PROC_PIDTBSDINFO
require(data.pid == pid, "macOS process identity mismatch")
if data.status == 5: # SZOMB
raise ProcessLookupError(errno.ESRCH, "Process is a zombie")
return f"{data.seconds}:{data.microseconds}"
def executable(self, pid):
buffer = ctypes.create_string_buffer(4096)
ctypes.set_errno(0)
size = self.lib.proc_pidpath(pid, buffer, len(buffer))
if size <= 0:
code = ctypes.get_errno() or errno.EIO
raise OSError(code, os.strerror(code))
path = os.fsdecode(buffer.value)
require(absolute_path(path), "Invalid macOS executable path")
return path
def mappings(self, pid):
address, mappings = 0, {}
for index in range(100000):
try:
data = self.info(pid, 8, self.region_type(), address) # PROC_PIDREGIONPATHINFO
except OSError as exc:
if exc.errno == errno.EINVAL and index:
return list(mappings.values())
raise
end = data.region.address + data.region.size
require(data.region.address >= address and end > address and end < 2 ** 64,
"Invalid macOS memory region")
address = end
path = os.fsdecode(data.path)
if path:
require(absolute_path(path), "Invalid macOS mapped-file path")
row = {"path": path, "device": data.stat.device, "inode": data.stat.inode,
"nlink": data.stat.nlink}
key = path, row["device"], row["inode"]
mappings[key] = row
raise AuditError("macOS memory-region limit exceeded")
def discover_macos(inventory):
api = MacOSProcesses()
expected = {os.path.realpath(row["path"]): row["kind"] for row in (inventory or {}).get("runtimes", [])}
runtimes, issues = [], []
for pid in api.pids():
try:
started = api.identity(pid)
exe = api.executable(pid)
kind = expected.get(os.path.realpath(exe)) or executable_kind(exe)
try:
mappings = api.mappings(pid)
except (OSError, AuditError) as exc:
if kind:
runtimes.append(Runtime(pid, kind, exe, exe, started))
raise AuditError("cannot inspect mapped files: " + str(exc)) from exc
found = []
for item in mappings:
path = item["path"]
module = re.fullmatch(r"(?:libphp|mod_php)[^/]*\.(?:so|dylib)(?:\.[0-9]+)*", Path(path).name, re.I)
item_kind = expected.get(os.path.realpath(path)) or (kind if path == exe else None)
if item_kind or module:
found.append(Runtime(pid, item_kind or "mod_php", path, path, started,
item["nlink"] == 0, item["device"], item["inode"]))
if kind and not any(r.kind == kind and r.path == exe for r in found):
found.append(Runtime(pid, kind, exe, exe, started))
issues.append(f"PID {pid}: executable mapping not available")
require(api.identity(pid) == started, "Process identity changed during discovery")
runtimes.extend(found)
except ProcessLookupError:
continue
except (OSError, AuditError) as exc:
issues.append(f"PID {pid}: macOS inspection incomplete: {exc}")
return runtimes, issues
def hash_macos_runtime(runtime):
api = MacOSProcesses()
require(api.identity(runtime.pid) == runtime.start, "Process exited or PID was reused", "PROCESS_CHANGED")
require(runtime.inode > 0 and not runtime.deleted, "Running macOS file has no readable vnode identity")
with open(runtime.live_path, "rb") as stream:
before = os.fstat(stream.fileno())
require((before.st_dev, before.st_ino) == (runtime.device, runtime.inode),
"macOS pathname no longer identifies the running mapping; restart and re-audit", "FILE_CHANGED")
hashes, info = hash_stream(stream)
mappings = api.mappings(runtime.pid)
require(any((row["device"], row["inode"]) == (info.st_dev, info.st_ino) for row in mappings),
"macOS mapping changed during inspection", "PROCESS_CHANGED")
require(api.identity(runtime.pid) == runtime.start, "Process exited or PID was reused", "PROCESS_CHANGED")
after = os.fstat(stream.fileno())
require((info.st_size, info.st_mtime_ns, info.st_ctime_ns) ==
(after.st_size, after.st_mtime_ns, after.st_ctime_ns), "Running file changed during inspection", "FILE_CHANGED")
try:
current = os.stat(runtime.path)
restart = (current.st_dev, current.st_ino) != (info.st_dev, info.st_ino)
except FileNotFoundError:
restart = True
return hashes, restart
def hash_stream(stream):
info = os.fstat(stream.fileno())
require(stat.S_ISREG(info.st_mode), "Image is not a regular file")
hashes = {name: hashlib.new(name, usedforsecurity=False)
for name in ("md5", "sha1", "sha256", "sha384", "sha512")}
for block in iter(lambda: stream.read(1024 * 1024), b""):
for digest in hashes.values():
digest.update(block)
after = os.fstat(stream.fileno())
require((info.st_size, info.st_mtime_ns, info.st_ctime_ns) ==
(after.st_size, after.st_mtime_ns, after.st_ctime_ns), "File changed while hashing", "FILE_CHANGED")
return {name: digest.hexdigest() for name, digest in hashes.items()}, info
def hash_file(path):
"""Hash a stable installed file without executing it.
Args:
path (str): Absolute path on this host.
Returns:
dict[str, str]: File digests keyed by algorithm name.
Raises:
AuditError: The path is invalid, non-regular or changes while hashing.
OSError: The file is missing or cannot be inspected.
"""
require(absolute_path(path) and Path(path).is_absolute(), "File path must be absolute on this host")
require(stat.S_ISREG(os.stat(path).st_mode), "File is not a regular file: " + path)
with open(path, "rb") as stream:
hashes, info = hash_stream(stream)
# Windows stat/fstat can disagree on ctime semantics; compare open handles.
with open(path, "rb") as current_stream:
current = os.fstat(current_stream.fileno())
require((info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns) ==
(current.st_dev, current.st_ino, current.st_size, current.st_mtime_ns, current.st_ctime_ns),
"File pathname changed while hashing", "FILE_CHANGED")
return hashes
def hash_runtime(runtime):
if sys.platform == "darwin":
return hash_macos_runtime(runtime)
require(start_time(runtime.pid) == runtime.start, "Process exited or PID was reused", "PROCESS_CHANGED")
with ExitStack() as stack:
try:
stream = stack.enter_context(open(runtime.live_path, "rb"))
except OSError as exc:
# map_files may need extra capabilities. A pathname is acceptable only
# when its device/inode proves it is the file in the inspected mapping.
require(runtime.kind == "mod_php" and not runtime.deleted,
"Cannot read the running file", error_diagnostic(exc)["code"])
stream = stack.enter_context(open(runtime.path, "rb"))
info = os.fstat(stream.fileno())
require(stat.S_ISREG(info.st_mode), "Running image is not a regular file")
if runtime.kind == "mod_php":
require((info.st_dev, info.st_ino) == (runtime.device, runtime.inode),
"Module pathname no longer identifies the running mapping", "FILE_CHANGED")
hashes, info = hash_stream(stream)
require(start_time(runtime.pid) == runtime.start, "Process exited or PID was reused", "PROCESS_CHANGED")
if runtime.kind == "mod_php":
mapped = False
for line in Path(f"/proc/{runtime.pid}/maps").read_text().splitlines():
fields = line.split(None, 5)
if len(fields) == 6:
device = os.makedev(*(int(part, 16) for part in fields[3].split(":")))
if (device, int(fields[4])) == (info.st_dev, info.st_ino):
mapped = True
require(mapped, "PHP module mapping changed during inspection", "PROCESS_CHANGED")
else:
current = os.stat(runtime.live_path)
require((current.st_dev, current.st_ino) == (info.st_dev, info.st_ino),
"Process executable changed during inspection", "PROCESS_CHANGED")
restart = runtime.deleted
try:
disk = os.stat(runtime.path)
restart |= (disk.st_dev, disk.st_ino) != (info.st_dev, info.st_ino)
except FileNotFoundError:
restart = True
return hashes, restart
def dpkg_metadata(path):
tool = system_tool("dpkg-query")
result = command([tool, "-S", "--", path])
owners = set()
for line in result.stdout.splitlines():
owner, sep, owned_path = line.partition(": ")
if sep and owned_path == path:
owners.add(owner)
require(result.returncode == 0 and len(owners) == 1, "No unique dpkg owner for runtime")
owner = owners.pop()
require(re.fullmatch(r"[a-z0-9][a-z0-9+.-]*(?::[a-z0-9]+)?", owner), "Invalid package owner")
result = command([tool, "-W", "-f=${binary:Package}\t${Version}\t${db:Status-Status}\n", "--", owner])
fields = result.stdout.strip().split("\t")
require(result.returncode == 0 and len(fields) == 3 and fields[2] == "installed",
"Package is not fully installed")
package, version, _ = fields
require(re.fullmatch(r"[a-z0-9][a-z0-9+.-]*(?::[a-z0-9]+)?", package), "Invalid package name")
checksum = None
for name in dict.fromkeys((package, owner, package.split(":")[0])):
manifest = Path("/var/lib/dpkg/info") / (name + ".md5sums")
if not manifest.is_file():
continue
for line in manifest.read_text().splitlines():
parts = line.split(None, 1)
if len(parts) == 2 and "/" + parts[1].lstrip("./") == path:
require(re.fullmatch(r"[0-9a-f]{32}", parts[0]), "Invalid package checksum")
checksum = parts[0]
require(checksum is not None, "Package has no checksum for the running file")
return {"manager": "dpkg", "package": package.split(":")[0], "version": version,
"algorithm": "md5", "digest": checksum}
def rpm_metadata(path):
tool = system_tool("rpm")
result = command([tool, "-qf", "--qf",
"%{NAME}\t%{EPOCHNUM}\t%{VERSION}\t%{RELEASE}\t%{FILEDIGESTALGO}\n", "--", path])
fields = result.stdout.strip().split("\t")
require(result.returncode == 0 and len(fields) == 5, "No unique RPM owner for runtime")
package, epoch, version, release, algorithm = fields
require(re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9+._-]*", package), "Invalid RPM name")
require(epoch.isdigit(), "Cannot determine RPM epoch")
algorithm = {"1": "md5", "2": "sha1", "8": "sha256", "9": "sha384", "10": "sha512"}.get(algorithm)
require(algorithm is not None, "Unsupported RPM file digest algorithm")
result = command([tool, "-qf", "--qf", "[%{FILENAMES}\t%{FILEDIGESTS}\n]", "--", path])
digests = [line.split("\t")[1] for line in result.stdout.splitlines()
if line.startswith(path + "\t") and len(line.split("\t")) == 2]
require(result.returncode == 0 and len(digests) == 1 and
re.fullmatch(r"[0-9a-f]+", digests[0]), "No unique RPM file checksum")
identity = command([tool, "-qf", "--qf", "%{ARCH}\t%{VENDOR}\n", "--", path])
identity_fields = identity.stdout.strip().split("\t")
require(identity.returncode == 0 and len(identity_fields) == 2, "Cannot determine RPM architecture/vendor")
arch, vendor = identity_fields
module_query = command([tool, "-qf", "--qf", "%{MODULARITYLABEL}", "--", path])
module = module_query.stdout.strip() if module_query.returncode == 0 else None
return {"manager": "rpm", "package": package, "version": f"{epoch}:{version}-{release}",
"algorithm": algorithm, "digest": digests[0], "arch": arch,
"module": "" if module == "(none)" else module, "vendor": vendor}
def apk_metadata(path):
matches = []
with Path("/lib/apk/db/installed").open() as stream:
name = version = directory = filename = None
for line in stream:
line = line.rstrip("\r\n")
if not line:
name = version = directory = filename = None
continue
key, sep, value = line.partition(":")
if not sep:
continue
if key == "P":
name = value
elif key == "V":
version = value
elif key == "F":
directory, filename = value, None
elif key == "R":
filename = value
elif key == "Z" and directory is not None and filename is not None:
if "/" + "/".join(filter(None, (directory, filename))) != path:
continue
require(value.startswith("Q1"), "Unsupported APK checksum encoding")
digest = base64.b64decode(value[2:], validate=True)
require(len(digest) == 20 and name and version, "Invalid APK file checksum")
matches.append({"manager": "apk", "package": name, "version": version,
"algorithm": "sha1", "digest": digest.hex()})
require(len(matches) == 1, "No unique APK file checksum; use build evidence")
return matches[0]
def pacman_metadata(path):
result = command([system_tool("pacman"), "-Qoq", "--", path])
owners = result.stdout.splitlines()
require(result.returncode == 0 and len(owners) == 1
and re.fullmatch(r"[A-Za-z0-9@_+][A-Za-z0-9@_.+-]*", owners[0]),
"No unique pacman owner for file")
package = owners[0]
result = command([system_tool("pacman"), "-Q", "--", package])
parts = result.stdout.split()
require(result.returncode == 0 and len(parts) == 2 and parts[0] == package
and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.+:~^_-]*", parts[1]),
"Cannot determine pacman package version")
version = parts[1]
manifest = Path("/var/lib/pacman/local") / (package + "-" + version) / "mtree"
matches = []
with gzip.open(manifest, "rt") as stream:
for line in stream:
fields = line.split()
if not fields or not fields[0].startswith("./"):
continue
name = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m[1], 8)), fields[0][1:])
if name == path:
digests = [v[len("sha256digest="):] for v in fields[1:] if v.startswith("sha256digest=")]
require(len(digests) == 1 and re.fullmatch(r"[0-9a-f]{64}", digests[0]),