#!/usr/bin/env python3 # SPDX-License-Identifier: GPL-3.0-or-later """Validate Phase-1.0S official shsrv/hbldr provenance and safety gates.""" from __future__ import annotations import argparse import hashlib import json from pathlib import Path import subprocess from typing import Any PHASE = "PHASE_1_0S_LAUNCHER_PROVENANCE" STATUS = "BIGAPP_CONTEXT_SOURCE_PROVEN_DEPLOYED_IDENTITY_UNPROVEN_DEVICE_PATH_BLOCKED" CURRENT_COMMIT = "6f320637d56d344a0e7797753099e33238bbf146" CURRENT_TREE = "c26ce02b6c3ca4202993e039b3db7c28c353dee4" V07_COMMIT = "74287f5db6b20320efd7892d7b29cf438fe7cb98" V07_TREE = "7184968c702afe038551bf3228cc25f455388bb6" PACBREW_COMMIT = "c2abcfcb60f569128abd0e8e70ad03a67bee5ea7" AUTHORIZATION_FIELDS = ( "target_build_authorized", "ps5_connection_authorized", "device_request_authorized", "device_transfer_authorized", "device_execution_authorized", "result_receive_authorized", "installation_authorized", "autoload_authorized", "device_write_authorized", "app_termination_authorized", "system_remount_authorized", "automatic_retry", ) def load_json(path: Path) -> dict[str, Any]: value = json.loads(path.read_text(encoding="utf-8")) if not isinstance(value, dict): raise ValueError("launcher provenance manifest is not an object") return value def sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def git(root: Path, *args: str) -> str: result = subprocess.run( ["git", *args], cwd=root, capture_output=True, text=True, check=False) if result.returncode: raise RuntimeError(result.stderr.strip() or "git failed") return result.stdout def all_false(record: dict[str, Any], fields: tuple[str, ...]) -> bool: return all(record.get(field) is False for field in fields) def acquisition_is_bounded(record: dict[str, Any]) -> bool: return record == { "official_repository": "https://github.com/ps5-payload-dev/shsrv.git", "official_github_only": True, "arbitrary_mirrors_used": False, "dependencies_installed": False, "downloaded_code_built": False, "downloaded_code_executed": False, "target_artifact_downloaded": False, "ps5_address_used": False, "ps5_connected": False, } def deployed_identity_is_unproven(record: dict[str, Any]) -> bool: return record == { "local_shsrv_binary_found": False, "device_version_observed": False, "device_hash_observed": False, "package_receipt_found": False, "classification": "UNPROVEN", } def context_difference_is_source_only(record: dict[str, Any]) -> bool: return record == { "raw_elfldr_process_basis": "SCE_SP_ZERO_CONF", "hbldr_process_basis": "SYSTEM_SERVICE_BIGAPP", "different_from_raw_elfldr": True, "bigapp_launch_source_proven": True, "foreground_user_context_source_proven": True, "process_image_replacement_source_proven": True, "videoout_permission_proven": False, "firmware_9_60_runtime_proven": False, "root_cause_classification": "STRONG_SOURCE_CANDIDATE_NOT_PROVEN_ROOT_CAUSE", } def effects_block_device_use(record: dict[str, Any]) -> bool: return record == { "target_elf_must_exist_on_device": True, "direct_host_to_memory_target_input": False, "running_bigapp_may_be_killed": True, "kernel_or_ptrace_runtime_writes": True, "v019_system_ex_remount_possible": True, "v019_persistent_fakeapp_creation_possible": True, "autoload_change_found": False, "hard_deadline_present": False, "automatic_retry_present": False, "atomic_persistent_write_protocol_present": False, "rollback_protocol_present": False, "power_loss_safe": False, } def decision_is_blocked(record: dict[str, Any]) -> bool: return ( record.get("root_cause_resolved") is False and record.get("existing_hbldr_route_safe_for_device_test") is False and record.get("existing_hbldr_route_reuse_allowed") is False and record.get("launcher_code_copy_allowed") is False and record.get("target_source_change_allowed") is False and record.get("target_build_allowed") is False and record.get("device_fact_collection_allowed") is False and record.get("device_action_allowed") is False and record.get("safe_next_steps") == [ "OFFLINE_DEPLOYED_SHSRV_IDENTITY_COLLECTION_DESIGN", "HOST_OR_SOFTWARE_ONLY_INTEGRATION", ] ) def callgraph_is_exact(record: Any) -> bool: return record == [ "HOST_TELNET_TO_PORT_2323", "SHSRV_ACCEPT", "ELFLDR_SPAWN_EMBEDDED_SHELL", "SHELL_BUILTIN_HBLDR", "ELFLDR_SPAWN_EMBEDDED_HBLDR", "READ_TARGET_ELF_FROM_DEVICE_PATH", "PREPARE_OR_SELECT_BIGAPP", "KILL_RUNNING_BIGAPP_IF_PRESENT", "SYSTEM_SERVICE_LAUNCH_BIGAPP", "FOLLOW_FORK_AND_EXEC", "SET_TARGET_ROOT_AND_JAIL", "REPLACE_BIGAPP_PROCESS_WITH_ELF", "DETACH_TARGET", ] def file_identity_is_exact(path: Path, record: dict[str, Any]) -> bool: return path.stat().st_size == record.get("size") and \ sha256(path) == record.get("sha256") def validate( root: Path, shsrv_root: Path, shsrv_v07_root: Path, pacbrew_root: Path, ) -> list[str]: errors: list[str] = [] try: record = load_json( root / "manifests/retroarch/phase-1.0s-launcher-provenance.json") except (OSError, ValueError, json.JSONDecodeError) as error: return [str(error)] if record.get("phase") != PHASE or record.get("status") != STATUS: errors.append("phase/status mismatch") if record.get("start_commit") != "189a4afdf4b6bb6d76b8a5fa7b5ce79cd4f82243": errors.append("start commit mismatch") if not all_false(record.get("authorizations", {}), AUTHORIZATION_FIELDS): errors.append("authorization remains active") if not acquisition_is_bounded(record.get("source_acquisition", {})): errors.append("source acquisition scope is broadened") if not deployed_identity_is_unproven(record.get("deployed_identity", {})): errors.append("deployed identity was promoted") if not callgraph_is_exact(record.get("launch_callgraph")): errors.append("launch callgraph mismatch") if not context_difference_is_source_only(record.get("launch_context", {})): errors.append("source context was promoted to runtime proof") if not effects_block_device_use(record.get("effects", {})): errors.append("hbldr side effects were relaxed") if not decision_is_blocked(record.get("decision", {})): errors.append("target or device decision is not blocked") performed = record.get("performed_actions", {}) if set(performed) != { "target_source_changed", "target_artifact_created", "ps5_connected", "device_request_performed", "device_transfer_performed", "target_execution_performed", "device_file_created", "device_app_terminated", "device_remounted", } or not all(value is False for value in performed.values()): errors.append("performed-action boundary mismatch") if record.get("robustness_findings") != [ "UNBOUNDED_WHOLE_ELF_ALLOCATION", "UNBOUNDED_PROCESS_WAITS", "UNAUTHENTICATED_ALL_INTERFACE_LISTENER", "SPLITSTRING_POINTER_ALLOCATION_UNDERSIZED", "UNBOUNDED_PATH_COPY_AND_FORMAT", "NO_TARGET_HASH_OR_SIZE_POLICY", "INCOMPLETE_GLOBAL_CLEANUP_PROOF", ]: errors.append("robustness inventory mismatch") tests = record.get("tests", {}) if not ( tests.get("chimera_gfx_ctest") == "66_OF_66_PASS" and tests.get("phase10s_guardrails") == 20 and tests.get("safety_audit") == "PASS" and tests.get("secret_scan") == "PASS" and tests.get("network_required_by_tests") is False and tests.get("hardware_claim_from_host_test") is False ): errors.append("test evidence mismatch") try: if git(shsrv_root, "rev-parse", "HEAD").strip() != CURRENT_COMMIT: errors.append("current shsrv commit mismatch") if git(shsrv_root, "rev-parse", "HEAD^{tree}").strip() != CURRENT_TREE: errors.append("current shsrv tree mismatch") if git(shsrv_v07_root, "rev-parse", "HEAD").strip() != V07_COMMIT: errors.append("shsrv v0.7 commit mismatch") if git(shsrv_v07_root, "rev-parse", "HEAD^{tree}").strip() != V07_TREE: errors.append("shsrv v0.7 tree mismatch") if git(pacbrew_root, "rev-parse", "HEAD").strip() != PACBREW_COMMIT: errors.append("PacBrew commit mismatch") for repository, name in ( (shsrv_root, "current shsrv"), (shsrv_v07_root, "shsrv v0.7"), (pacbrew_root, "PacBrew")): if git(repository, "status", "--porcelain"): errors.append(f"{name} worktree is dirty") if git(shsrv_root, "remote", "get-url", "origin").strip() != \ "https://github.com/ps5-payload-dev/shsrv.git": errors.append("shsrv origin is not official") for key, base, files in ( ("official_current", shsrv_root, record["official_current"]["files"]), ("historical_reference", shsrv_v07_root, record["historical_reference"]["files"]), ): for relative, identity in files.items(): if not file_identity_is_exact(base / relative, identity): errors.append(f"{key} file identity mismatch: {relative}") current = (shsrv_root / "bundles/hbldr/hbldr.c").read_text( encoding="utf-8") for token in ( '#define FAKE_PATH "/system_ex/app/FAKE00000"', "remount_system_ex(void)", "nmount(iov, IOVEC_SIZE(iov), MNT_UPDATE)", 'sceSystemServiceLaunchApp("FAKE00000", ctx->argv, ctx)', "sceSystemServiceKillApp(app_id, -1, 0, 0)", "kernel_set_proc_rootdir(pid, kernel_get_root_vnode())", "kernel_set_proc_jaildir(pid, 0)", "char **tokens = calloc(bufsize, sizeof(char))", 'sprintf(path, "%s/%s", paths[i], name)', ): if token not in current: errors.append(f"current hbldr source token missing: {token}") historical = (shsrv_v07_root / "bundles/hbldr/main.c").read_text( encoding="utf-8") for token in ( 'sceSystemServiceLaunchApp("PPSA01659", argv, &ctx)', "sceSystemServiceKillApp(app_id, -1, 0, 0)", "kernel_set_proc_rootdir(pid, kernel_get_root_vnode())", "kernel_set_proc_jaildir(pid, 0)", ): if token not in historical: errors.append(f"v0.7 hbldr source token missing: {token}") if "FAKE00000" in historical or "remount_system_ex" in historical: errors.append("v0.7 was incorrectly given the later fake-app path") server = (shsrv_root / "shsrv.c").read_text(encoding="utf-8") shell = (shsrv_root / "sh.c").read_text(encoding="utf-8") wrapper = (shsrv_root / "bundles/hbldr/main.c").read_text( encoding="utf-8") if "int port = 2323" not in server or \ "server_addr.sin_addr.s_addr = htonl(INADDR_ANY)" not in server: errors.append("shsrv listener contract mismatch") if "builtin_cmd_run(argv[0], argc, argv)" not in shell: errors.append("shell builtin dispatch mismatch") if 'builtin_cmd_define("hbldr"' not in wrapper or \ "elfldr_spawn(STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO" \ not in wrapper: errors.append("embedded hbldr wrapper mismatch") recipe = (pacbrew_root / "shsrv/PKGBUILD").read_text(encoding="utf-8") if 'source=("git+https://github.com/ps5-payload-dev/shsrv.git")' \ not in recipe or "sha256sums=('SKIP')" not in recipe: errors.append("PacBrew shsrv provenance boundary mismatch") tracked = git(root, "ls-files").splitlines() if any(path.lower().endswith((".elf", ".self", ".sprx", ".pkg")) for path in tracked): errors.append("target artifact is tracked") except (OSError, RuntimeError, KeyError) as error: errors.append(str(error)) return errors def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--root", type=Path, required=True) parser.add_argument("--shsrv-root", type=Path, required=True) parser.add_argument("--shsrv-v07-root", type=Path, required=True) parser.add_argument("--pacbrew-root", type=Path, required=True) args = parser.parse_args() errors = validate( args.root.resolve(), args.shsrv_root.resolve(), args.shsrv_v07_root.resolve(), args.pacbrew_root.resolve()) if errors: for error in errors: print(f"ERROR: {error}") return 1 print("Phase-1.0S shsrv/hbldr provenance validation passed") return 0 if __name__ == "__main__": raise SystemExit(main())