Spaces:
Running
Running
fix: authenticate public release assets
Browse filesFiles changed (9)
7 unmodified lines89101112131415167 unmodified lines verification and the adaptive campaign evidence plan.- Make the public first-kill path default to `v1.0.0` and make the support helper use the installed, root-owned zipapp shipped by the verified bundle.- Require a detached release-checksum signature from the pinned release key and reject duplicate, link, special, oversized and unsafe ZIP members before any bundled installer can reach root execution.- Keep publication, signing, tagging and external deployment as separate decisions.
62 unmodified lines636465666667686970717273747576777879808162 unmodified lines5. privileged installer attacks: hostile Python import hooks, symlinked inputs, expected-digest/manifest/version/source drift, traversal archive, partial prior installation, pre-existing-install refusal and a pathname replacement after the installer binds its artifact descriptor. after the installer binds its artifact descriptor. The public bootstrap must also reject an absent or invalid detached checksum signature, self-recomputed unsigned checksums, duplicate/normalized-duplicate members, archive links or special members and a bundle whose authenticated asset identity disagrees with the signed tag source identity.
Before publication, sign the final detached checksum list with the private keycorresponding to fingerprint`53786DEB001459956A2E1B86A3F29F7A27636DC7`, publish `SHA256SUMS.asc` beside`SHA256SUMS`, the Linux bundle and `eggcracker-release-key.asc`, and rerun thepublic first-kill asset-authentication path against those exact uploaded bytes.CI build artifacts without that detached signature are build outputs, not areleasable distribution.
The control-plane parser must also reject, without replacing the supervisor,a valid sub-32-KiB JSON request containing an integer beyond the supported105 unmodified lines10610710810911010911011111211311411511611776 unmodified lines19419519619319419519619719819920020120220320459 unmodified lines264265266262263264265267268269270271272273274275276105 unmodified linespublished-release reference is an annotated tag resolving to a commit. It makesno network request and creates no workspace, GPG home, build, installation orservice. It does not verify the tag signature, downloaded assets, functionalbuild, installation or containment; the full run verifies the signature andrequires the signed tag commit to match the release manifest.build, installation or containment. The full run verifies both the annotatedtag signature and the detached `SHA256SUMS.asc` signature with the pinnedrelease-key fingerprint, requires the downloaded bundle to match that signedchecksum list, and requires the signed tag commit to match the releasemanifest. It rejects duplicate, link, special and unsafe archive members beforeextraction.
### Probe the containment primitive
76 unmodified lines --accept-third-party-downloads```
The command checks host compatibility, downloads and verifies the signedrelease assets, installs the root-controlled supervisor, downloads the pinneddemo model only after the explicit acceptance flag, launches the real model,prints the kill receipt, and offers clean removal. Use `--remove` for aThe command checks host compatibility, authenticates the tag and detachedrelease checksums, verifies the exact downloaded bundle, installs theroot-controlled supervisor, downloads the pinned demo model only after theexplicit acceptance flag, launches the real model, prints the kill receipt,and offers clean removal. Use `--remove` for anon-interactive removal or `--keep` to inspect the installation after thedemonstration. Share a passing, refused, or confusing supported-path run throughthe [redacted result form](https://github.com/noqt/Lumi-Eggcracker/issues/new?template=first_kill_result.yml).59 unmodified lines
## Install and remove
The first-kill command is the recommended campaign path. For a controlledinstallation, use the signed Linux bundle and its `SHA256SUMS`, then run thebundled installer as root with a non-root operator. Remove every product-ownedunit, socket, account and state file with:The first-kill command is the recommended campaign path. A release is completeonly when it carries `SHA256SUMS`, its detached `SHA256SUMS.asc` signature and`eggcracker-release-key.asc`; the pinned fingerprint is`53786DEB001459956A2E1B86A3F29F7A27636DC7`. For a controlled manualinstallation, verify that signature and the Linux bundle checksum beforerunning the bundled installer as root with a non-root operator. Remove everyproduct-owned unit, socket, account and state file with:
```shsudo /usr/bin/python3 -I -S scripts/uninstall.py9 unmodified lines101112131415161718199 unmodified linesThe public first-kill helper defaults to `v1.0.0`. The packaged support helperdelegates to the installed root-owned zipapp, so the documented command worksfrom the verified Linux release bundle without importing a mutable checkout.The bootstrap now also requires a detached `SHA256SUMS.asc` signature from thepinned release key and rejects duplicate, link, special, oversized and unsafeZIP members. A replaced release bundle plus self-recomputed unsigned checksumscan therefore no longer reach root execution.
The candidate is not tagged, signed or published. Its release decision isbound to the exact commit, artifact hashes, disposable Ubuntu qualification22 unmodified lines232425262728293031323334353622 unmodified lines
Heartbeat emission is tied to recent successful discovery completion and durable post-containment detection receipts, not merely to a live worker thread. A blocked or repeatedly failing scan, or any failure to persist a detection receipt after containment, therefore makes `doctor` report `UNSUPPORTED`, stops heartbeats and lets the independent watchdog apply its bounded fail-closed recovery. Receipt-storage health remains latched false until a root operator repairs storage and restarts the supervisor. Model descriptors and executable runtime mappings are inspected in bounded stripes, and the stripe generation is reserved in root-owned state before scanning. Every executable mapping line within the bounded 8 MiB procfs read is eligible for those stripes; the observer does not silently truncate the mapping table at a line-count prefix. A process table beyond that byte bound explicitly fails discovery health rather than silently omitting its suffix. Runtime evidence is accepted only from the running executable or an executable mapping backed by a structurally loadable ELF whose complete SHA-256 matches the qualified release pin; build IDs and symbol names are prefilters, not trust anchors. An ordinary open ELF descriptor or read-only data mapping is not runtime evidence. A deleted executable mapping may use a retained descriptor only when its kernel mount/inode identity matches that mapping. A supervisor restart advances the stripe generation instead of returning every still-live process to the first descriptor window.
The public first-kill path authenticates two separate release bindings with thepinned release key: the annotated Git tag fixes the source commit, while thedetached `SHA256SUMS.asc` signature fixes the published binary assets. Thedownloaded Linux bundle must match the signed checksum and its manifest/sourceidentity must match the signed tag before any bundled installer is run.Duplicate, link, special, oversized and unsafe archive members are rejectedbefore extraction. An unsigned checksum file is not release authority.
This is not a general sandbox, universal AI detector, host intrusion detector,malware detector, host-wide network isolator, credential isolator or EDRreplacement. An unapproved workload can evade recognition by using an11 unmodified lines121314151617185 unmodified lines242526262728293018 unmodified lines49505152535455565750 unmodified lines10810911010711111211311410911511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316411816516616716837 unmodified lines206207208209210211212213214215216217218219220221222223224225226227106 unmodified lines334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392278279280281282283284285286393394395289290291292396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437299438439440441442443444445446447308448449450311312313451452453454455456457458316459460461462259 unmodified lines72272372458272572672772872973073173273373473513 unmodified lines74975075175275375475575 unmodified lines83183283383483583668483783883984084184284311 unmodified linesimport jsonimport osimport platformimport reimport secretsimport shutilimport signal5 unmodified linesimport urllib.errorimport urllib.requestimport zipfilefrom pathlib import Pathfrom pathlib import Path, PurePosixPathfrom typing import Any
try:18 unmodified lines Path("/etc/tmpfiles.d/lumi-eggcracker.conf"),)MAX_DOWNLOAD_BYTES = 2 * 1024 * 1024MAX_ARCHIVE_MEMBERS = 256MAX_ARCHIVE_MEMBER_BYTES = 16 * 1024 * 1024MAX_ARCHIVE_TOTAL_BYTES = 64 * 1024 * 1024DETECTIONS = Path("/var/lib/lumi-eggcracker/detections")DEFAULT_AI_SMOKE_WORKSPACE = Path("/opt/lumi-eggcracker-ai-smoke")QUALIFIED_LLAMA_SHA256 = "ef0b86d353638b74519079b5937b9d62b4d4c6c6cdbf68812d7898437ecc4fb5"50 unmodified lines raise FirstKillError("release SHA256SUMS is unreadable") from error for line in lines: fields = line.split(maxsplit=1) if len(fields) != 2 or len(fields[0]) != 64: if len(fields) != 2 or len(fields[0]) != 64 or any( character not in "0123456789abcdefABCDEF" for character in fields[0] ): raise FirstKillError("release SHA256SUMS contains an invalid line") values[fields[1].removeprefix("*")] = fields[0].lower() name = fields[1].removeprefix("*") if not name or name in values: raise FirstKillError("release SHA256SUMS contains a duplicate or empty name") values[name] = fields[0].lower() if not values: raise FirstKillError("release SHA256SUMS is empty") return values
def validated_zip_members(bundle: zipfile.ZipFile) -> list[zipfile.ZipInfo]: members = bundle.infolist() if not members or len(members) > MAX_ARCHIVE_MEMBERS: raise FirstKillError("release bundle has an invalid member count") seen: set[str] = set() total = 0 for member in members: name = member.filename path = PurePosixPath(name) parts = path.parts normalized = path.as_posix().rstrip("/") if ( not name or "\x00" in name or "\\" in name or path.is_absolute() or not normalized or any(part in ("", ".", "..") for part in parts) or (len(parts[0]) >= 2 and parts[0][1] == ":") ): raise FirstKillError("release bundle contains an unsafe path") if normalized in seen: raise FirstKillError("release bundle contains a duplicate path") seen.add(normalized) mode = (member.external_attr >> 16) & 0xFFFF file_type = stat.S_IFMT(mode) if member.flag_bits & 0x1 or file_type not in (0, stat.S_IFREG, stat.S_IFDIR): raise FirstKillError("release bundle contains a link or special member") if member.is_dir() != (file_type == stat.S_IFDIR) and file_type != 0: raise FirstKillError("release bundle member type is inconsistent") if member.file_size > MAX_ARCHIVE_MEMBER_BYTES: raise FirstKillError("release bundle member exceeds the extraction limit") total += member.file_size if total > MAX_ARCHIVE_TOTAL_BYTES: raise FirstKillError("release bundle exceeds the extraction limit") return members
def safe_extract(archive: Path, destination: Path) -> None: try: with zipfile.ZipFile(archive) as bundle: members = bundle.infolist() members = validated_zip_members(bundle) for member in members: candidate = (destination / member.filename).resolve() if not candidate.is_relative_to(destination.resolve()):37 unmodified lines raise FirstKillError(f"{description} must be a regular file: {path}")
def require_root_directory(path: Path, description: str, *, private: bool) -> None: try: metadata = path.lstat() except OSError as error: raise FirstKillError(f"{description} is missing: {path}") from error forbidden_mode = 0o077 if private else 0o022 if ( path.is_symlink() or not stat.S_ISDIR(metadata.st_mode) or metadata.st_uid != 0 or stat.S_IMODE(metadata.st_mode) & forbidden_mode ): access = "root-private" if private else "root-owned and not writable by group/other" raise FirstKillError(f"{description} must be a {access} directory: {path}")
def operator_name(explicit: str | None) -> str: if pwd is None: raise FirstKillError("first-kill requires the POSIX passwd database")106 unmodified lines return 0
def import_release_key(gpg_home: Path, key: Path) -> None: imported = run( ["/usr/bin/gpg", "--homedir", str(gpg_home), "--batch", "--import", str(key)], check=False, ) if imported.returncode: raise FirstKillError(imported.stderr.strip() or "release public key import failed") shown = run( [ "/usr/bin/gpg", "--homedir", str(gpg_home), "--batch", "--with-colons", "--show-keys", str(key), ] ) primary_fingerprints: list[str] = [] expect_primary_fingerprint = False for line in shown.stdout.splitlines(): fields = line.split(":") if fields[0] == "pub": expect_primary_fingerprint = True elif fields[0] == "fpr" and expect_primary_fingerprint: primary_fingerprints.append(fields[9].upper()) expect_primary_fingerprint = False if primary_fingerprints != [RELEASE_KEY_FINGERPRINT]: raise FirstKillError( "downloaded release key does not contain exactly the published primary key" )
def require_pinned_valid_signature( result: subprocess.CompletedProcess[str], description: str) -> None: if result.returncode: detail = (result.stderr or result.stdout).strip() raise FirstKillError(f"{description} verification failed: {detail}") fingerprints: set[str] = set() marker = "[GNUPG:] VALIDSIG " for line in (result.stdout + "\n" + result.stderr).splitlines(): position = line.find(marker) if position < 0: continue for value in line[position + len(marker) :].split(): if re.fullmatch(r"[0-9A-Fa-f]{40}", value): fingerprints.add(value.upper()) if RELEASE_KEY_FINGERPRINT not in fingerprints: raise FirstKillError(f"{description} was not signed by the pinned release key")
def verify_tag(root: Path, tag: str, key: Path) -> str: gpg_home = Path(tempfile.mkdtemp(prefix="eggcracker-gpg-")) os.chmod(gpg_home, 0o700) try: imported = run(["/usr/bin/gpg", "--homedir", str(gpg_home), "--batch", "--import", str(key)]) if imported.returncode: raise FirstKillError(imported.stderr.strip() or "release public key import failed") shown = run( ["/usr/bin/gpg", "--homedir", str(gpg_home), "--batch", "--with-colons", "--show-keys", str(key)] ) fingerprints = [line.split(":")[9].upper() for line in shown.stdout.splitlines() if line.startswith("fpr:")] if RELEASE_KEY_FINGERPRINT not in fingerprints: raise FirstKillError("downloaded release key fingerprint does not match the published fingerprint") import_release_key(gpg_home, key) env = os.environ.copy() env["GNUPGHOME"] = str(gpg_home) verified = run(["/usr/bin/git", "-C", str(root), "tag", "-v", tag], env=env, check=False) if verified.returncode: detail = (verified.stderr or verified.stdout).strip() raise FirstKillError(f"signed tag verification failed: {detail}") verified = run( ["/usr/bin/git", "-C", str(root), "verify-tag", "--raw", tag], env=env, check=False, ) require_pinned_valid_signature(verified, "signed tag") commit = run(["/usr/bin/git", "-C", str(root), "rev-parse", f"{tag}^{{}}"]) return commit.stdout.strip() finally: shutil.rmtree(gpg_home, ignore_errors=True)
def verify_checksum_signature(key: Path, sums: Path, signature: Path) -> None: gpg_home = Path(tempfile.mkdtemp(prefix="eggcracker-gpg-")) os.chmod(gpg_home, 0o700) try: import_release_key(gpg_home, key) verified = run( [ "/usr/bin/gpg", "--homedir", str(gpg_home), "--batch", "--status-fd", "1", "--verify", str(signature), str(sums), ], check=False, ) require_pinned_valid_signature(verified, "release checksum signature") finally: shutil.rmtree(gpg_home, ignore_errors=True)
def verify_bundle_checksum(bundle: Path, sums: Path) -> None: expected = parse_checksums(sums) if expected.get(bundle.name) != digest(bundle): raise FirstKillError("downloaded Linux bundle does not match signed SHA256SUMS")
def release_files(tag: str, workspace: Path) -> tuple[Path, Path]:def release_files(tag: str, workspace: Path) -> tuple[Path, Path, Path, Path]: version = tag.removeprefix("v") if not version.replace(".", "").isdigit() or version.count(".") != 2: raise FirstKillError("tag must look like v1.0.0") base = f"https://github.com/{REPOSITORY}/releases/download/{tag}" sums = workspace / "SHA256SUMS" signature = workspace / "SHA256SUMS.asc" bundle = workspace / f"lumi-eggcracker-{version}-linux.zip" key = workspace / "eggcracker-release-key.asc" download(f"{base}/SHA256SUMS", sums, maximum=64 * 1024) expected = parse_checksums(sums) download(f"{base}/SHA256SUMS.asc", signature, maximum=64 * 1024) download(f"{base}/{bundle.name}", bundle, maximum=8 * 1024 * 1024) download(f"{base}/{key.name}", key, maximum=64 * 1024) if expected.get(bundle.name) != digest(bundle): raise FirstKillError("downloaded Linux bundle does not match release SHA256SUMS") require_regular(key, "release public key") for path, description in ( (sums, "release SHA256SUMS"), (signature, "release checksum signature"), (key, "release public key"), ): require_regular(path, description) if b"BEGIN PGP PRIVATE KEY BLOCK" in key.read_bytes(): raise FirstKillError("release key asset unexpectedly contains private key material") return bundle, key return bundle, key, sums, signature
def extracted_release(bundle: Path, workspace: Path) -> Path:259 unmodified lines if path.exists(): if path.is_symlink() or not path.is_dir(): raise FirstKillError("--workspace must be a non-symlink directory") allowed = {"ai-smoke", "release", "SHA256SUMS", "eggcracker-release-key.asc"} require_root_directory(path, "--workspace", private=True) allowed = { "ai-smoke", "release", "SHA256SUMS", "SHA256SUMS.asc", "eggcracker-release-key.asc", } unexpected = [ item.name for item in path.iterdir()13 unmodified lines else: path.mkdir(mode=0o700, parents=True, exist_ok=True) os.chmod(path, 0o700) require_root_directory(path, "--workspace", private=True) return path
75 unmodified lines ai_workspace_preexisting = ai_workspace.exists() if ai_workspace.is_symlink() or (ai_workspace.exists() and not ai_workspace.is_dir()): raise FirstKillError("--ai-workspace must be a non-symlink directory") if ai_workspace_preexisting: require_root_directory(ai_workspace, "--ai-workspace", private=False) say(f"downloading and checking signed {args.tag} release assets") bundle, key = release_files(args.tag, workspace) bundle, key, sums, signature = release_files(args.tag, workspace) commit = verify_tag(root, args.tag, key) verify_checksum_signature(key, sums, signature) verify_bundle_checksum(bundle, sums) release_root = extracted_release(bundle, workspace) release = manifest(release_root) if release.get("source_commit") != commit:5 unmodified lines678910111212131415167 unmodified lines2425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717231323373747576777813 unmodified lines92939453545556959697989910010110210310410588 unmodified lines1941951961511971981992002015 unmodified linesimport hashlibimport jsonimport reimport statimport subprocessimport sysimport zipfilefrom pathlib import Pathfrom pathlib import Path, PurePosixPath
FORBIDDEN = ( "/mnt/" + "f/",7 unmodified lines "skylark" + " sentinel", "skylark" + "-sentinel",)MAX_ARCHIVE_MEMBERS = 256MAX_ARCHIVE_MEMBER_BYTES = 16 * 1024 * 1024MAX_ARCHIVE_TOTAL_BYTES = 64 * 1024 * 1024
def validated_members(archive: zipfile.ZipFile) -> list[zipfile.ZipInfo]: members = archive.infolist() if not members or len(members) > MAX_ARCHIVE_MEMBERS: raise SystemExit("release archive has an invalid member count") seen: set[str] = set() total = 0 for member in members: name = member.filename path = PurePosixPath(name) parts = path.parts normalized = path.as_posix().rstrip("/") if ( not name or "\x00" in name or "\\" in name or path.is_absolute() or not normalized or any(part in ("", ".", "..") for part in parts) or (len(parts[0]) >= 2 and parts[0][1] == ":") ): raise SystemExit("release archive contains an unsafe path") if normalized in seen: raise SystemExit("release archive contains a duplicate path") seen.add(normalized) mode = (member.external_attr >> 16) & 0xFFFF file_type = stat.S_IFMT(mode) if member.flag_bits & 0x1 or file_type not in (0, stat.S_IFREG, stat.S_IFDIR): raise SystemExit("release archive contains a link or special member") if member.is_dir() != (file_type == stat.S_IFDIR) and file_type != 0: raise SystemExit("release archive member type is inconsistent") if member.file_size > MAX_ARCHIVE_MEMBER_BYTES: raise SystemExit("release archive member exceeds the verification limit") total += member.file_size if total > MAX_ARCHIVE_TOTAL_BYTES: raise SystemExit("release archive exceeds the verification limit") return members
def text_from_zip(path: Path) -> str: with zipfile.ZipFile(path) as archive: return "\n".join( archive.read(name).decode("utf-8", errors="ignore").lower() for name in archive.namelist() if name.endswith((".py", ".md", ".toml", ".txt")) archive.read(member).decode("utf-8", errors="ignore").lower() for member in validated_members(archive) if member.filename.endswith((".py", ".md", ".toml", ".txt")) )
13 unmodified lines
def artifact_source_commit(path: Path) -> str: with zipfile.ZipFile(path) as archive: try: raw = archive.read("lumi_eggcracker/build_info.py") except KeyError as error: raise SystemExit("artifact source identity is missing") from error matches = [ member for member in validated_members(archive) if member.filename == "lumi_eggcracker/build_info.py" ] if len(matches) != 1: raise SystemExit("artifact source identity is missing") raw = archive.read(matches[0]) match = re.fullmatch(b'SOURCE_COMMIT = "([0-9a-f]{40})"\r?\n', raw) if match is None: raise SystemExit("artifact source identity is invalid")88 unmodified lines ) } with zipfile.ZipFile(args.release_bundle) as archive: if set(archive.namelist()) != expected: members = validated_members(archive) if {member.filename for member in members} != expected: raise SystemExit("release bundle contents are inconsistent") if ( digest_bytes(archive.read(prefix + args.artifact.name)) != manifest["sha256"]4 unmodified lines56789101112131425 unmodified lines404142434445464748498 unmodified lines585960616263646514 unmodified lines808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715873 unmodified lines2322332342352362372382392402412422432442452462472482492503 unmodified lines2542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493504 unmodified linesimport ioimport jsonimport osimport statimport tempfileimport unittestimport warningsimport zipfilefrom pathlib import Pathfrom unittest import mock25 unmodified lines mock.patch.object(first_kill, "prepare_workspace") as prepare_workspace, mock.patch.object(first_kill, "release_files") as release_files, mock.patch.object(first_kill, "verify_tag") as verify_tag, mock.patch.object( first_kill, "verify_checksum_signature" ) as verify_checksum_signature, mock.patch.object(first_kill, "verify_bundle_checksum") as verify_bundle_checksum, mock.patch.object(first_kill, "install_release") as install_release, mock.patch.object(first_kill, "run_real_smoke") as run_real_smoke, mock.patch.object(first_kill.tempfile, "mkdtemp") as make_temporary,8 unmodified lines prepare_workspace, release_files, verify_tag, verify_checksum_signature, verify_bundle_checksum, install_release, run_real_smoke, make_temporary,14 unmodified lines first_kill.main(["--operator", "tester"]) self.assertEqual(2, raised.exception.code)
def test_normal_run_authenticates_checksums_before_extraction_or_install(self) -> None: events: list[str] = [] release = { "artifact": "lumi-eggcracker-1.0.0.pyz", "sha256": "a" * 64, "source_archive": "lumi-eggcracker-1.0.0-source.zip", "source_commit": TAG_COMMIT, "version": "1.0.0", } receipt = { "result": "TERMINATED", "containment": {"surviving_pids": [], "root_populated": 0}, } with ( mock.patch.object(first_kill, "operator_name", return_value="tester"), mock.patch.object(first_kill, "compatibility"), mock.patch.object(first_kill, "repository_root", return_value=Path("/checkout")), mock.patch.object( first_kill, "prepare_workspace", return_value=Path("/private-workspace") ), mock.patch.object( first_kill, "release_files", return_value=( Path("/bundle.zip"), Path("/key.asc"), Path("/SHA256SUMS"), Path("/SHA256SUMS.asc"), ), ), mock.patch.object(first_kill, "verify_tag", return_value=TAG_COMMIT), mock.patch.object( first_kill, "verify_checksum_signature", side_effect=lambda *_: events.append("signature"), ), mock.patch.object( first_kill, "verify_bundle_checksum", side_effect=lambda *_: events.append("checksum"), ), mock.patch.object( first_kill, "extracted_release", side_effect=lambda *_: events.append("extract") or Path("/release"), ), mock.patch.object(first_kill, "manifest", return_value=release), mock.patch.object(first_kill, "run"), mock.patch.object( first_kill, "install_release", side_effect=lambda *_: events.append("install"), ), mock.patch.object( first_kill, "installed_workload_user", return_value="workload" ), mock.patch.object(first_kill, "run_real_smoke", return_value=receipt), mock.patch.object(first_kill, "remove_installation"), contextlib.redirect_stdout(io.StringIO()), ): result = first_kill.main( [ "--operator", "tester", "--workspace", "/private-workspace", "--accept-third-party-downloads", "--remove", ] ) self.assertEqual(0, result) self.assertEqual(["signature", "checksum", "extract", "install"], events)
def test_preflight_rejects_mutation_only_flags(self) -> None: with ( contextlib.redirect_stderr(io.StringIO()),73 unmodified lines path.write_text("a" * 64 + " payload.zip\n", encoding="ascii") self.assertEqual({"payload.zip": "a" * 64}, first_kill.parse_checksums(path))
def test_checksums_reject_non_hex_and_duplicate_names(self) -> None: with tempfile.TemporaryDirectory() as raw: path = Path(raw) / "SHA256SUMS" path.write_text("z" * 64 + " payload.zip\n", encoding="ascii") with self.assertRaisesRegex(first_kill.FirstKillError, "invalid line"): first_kill.parse_checksums(path) path.write_text( "a" * 64 + " payload.zip\n" + "b" * 64 + " payload.zip\n", encoding="ascii", ) with self.assertRaisesRegex(first_kill.FirstKillError, "duplicate"): first_kill.parse_checksums(path)
def test_safe_extract_rejects_path_traversal(self) -> None: with tempfile.TemporaryDirectory() as raw: root = Path(raw)3 unmodified lines with self.assertRaisesRegex(first_kill.FirstKillError, "unsafe path"): first_kill.safe_extract(archive, root / "out")
def test_safe_extract_rejects_duplicate_paths(self) -> None: with tempfile.TemporaryDirectory() as raw: root = Path(raw) archive = root / "duplicate.zip" with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) with zipfile.ZipFile(archive, "w") as bundle: bundle.writestr("release/install.py", "trusted") bundle.writestr("release/install.py", "hostile") with self.assertRaisesRegex(first_kill.FirstKillError, "duplicate path"): first_kill.safe_extract(archive, root / "out")
def test_safe_extract_rejects_symlink_members(self) -> None: with tempfile.TemporaryDirectory() as raw: root = Path(raw) archive = root / "link.zip" member = zipfile.ZipInfo("release/install.py") member.create_system = 3 member.external_attr = (stat.S_IFLNK | 0o777) << 16 with zipfile.ZipFile(archive, "w") as bundle: bundle.writestr(member, "../../outside") with self.assertRaisesRegex(first_kill.FirstKillError, "link or special"): first_kill.safe_extract(archive, root / "out")
def test_checksum_signature_requires_valid_pinned_key_signature(self) -> None: imported = mock.Mock(returncode=0, stdout="", stderr="") shown = mock.Mock( returncode=0, stdout=( "pub:::::::::\n" f"fpr:::::::::{first_kill.RELEASE_KEY_FINGERPRINT}:\n" ), stderr="", ) verified = mock.Mock( returncode=0, stdout=( "[GNUPG:] VALIDSIG " f"{first_kill.RELEASE_KEY_FINGERPRINT} 2026 0 0 4 0 1 10 00 " f"{first_kill.RELEASE_KEY_FINGERPRINT}\n" ), stderr="", ) with mock.patch.object(first_kill, "run", side_effect=[imported, shown, verified]) as run: first_kill.verify_checksum_signature( Path("/release-key.asc"), Path("/SHA256SUMS"), Path("/SHA256SUMS.asc"), ) self.assertIn("--verify", run.call_args_list[-1].args[0])
def test_checksum_signature_failure_is_fatal(self) -> None: imported = mock.Mock(returncode=0, stdout="", stderr="") shown = mock.Mock( returncode=0, stdout=( "pub:::::::::\n" f"fpr:::::::::{first_kill.RELEASE_KEY_FINGERPRINT}:\n" ), stderr="", ) rejected = mock.Mock(returncode=1, stdout="", stderr="BAD signature") with ( mock.patch.object(first_kill, "run", side_effect=[imported, shown, rejected]), self.assertRaisesRegex(first_kill.FirstKillError, "signature verification failed"), ): first_kill.verify_checksum_signature( Path("/release-key.asc"), Path("/SHA256SUMS"), Path("/SHA256SUMS.asc"), )
def test_release_key_bundle_cannot_add_an_attacker_primary_key(self) -> None: attacker = "B" * 40 imported = mock.Mock(returncode=0, stdout="", stderr="") shown = mock.Mock( returncode=0, stdout=( "pub:::::::::\n" f"fpr:::::::::{first_kill.RELEASE_KEY_FINGERPRINT}:\n" "pub:::::::::\n" f"fpr:::::::::{attacker}:\n" ), stderr="", ) with ( mock.patch.object(first_kill, "run", side_effect=[imported, shown]), self.assertRaisesRegex(first_kill.FirstKillError, "exactly the published"), ): first_kill.import_release_key(Path("/gpg-home"), Path("/release-key.asc"))
def test_public_key_fingerprint_is_pinned(self) -> None: self.assertEqual(40, len(first_kill.RELEASE_KEY_FINGERPRINT)) self.assertEqual(first_kill.RELEASE_KEY_FINGERPRINT.upper(), first_kill.RELEASE_KEY_FINGERPRINT)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152from __future__ import annotations
import importlib.utilimport statimport tempfileimport unittestimport warningsimport zipfilefrom pathlib import Path
ROOT = Path(__file__).resolve().parents[1]SPEC = importlib.util.spec_from_file_location( "verify_release", ROOT / "scripts" / "verify_release.py")if SPEC is None or SPEC.loader is None: raise RuntimeError("cannot load release verifier")verify_release = importlib.util.module_from_spec(SPEC)SPEC.loader.exec_module(verify_release)
class ReleaseArchiveTests(unittest.TestCase): def test_verifier_rejects_duplicate_members(self) -> None: with tempfile.TemporaryDirectory() as raw: archive_path = Path(raw) / "duplicate.zip" with warnings.catch_warnings(): warnings.simplefilter("ignore", UserWarning) with zipfile.ZipFile(archive_path, "w") as archive: archive.writestr("release/install.py", "trusted") archive.writestr("release/install.py", "hostile") with ( zipfile.ZipFile(archive_path) as archive, self.assertRaisesRegex(SystemExit, "duplicate path"), ): verify_release.validated_members(archive)
def test_verifier_rejects_special_members(self) -> None: with tempfile.TemporaryDirectory() as raw: archive_path = Path(raw) / "special.zip" member = zipfile.ZipInfo("release/install.py") member.create_system = 3 member.external_attr = (stat.S_IFIFO | 0o600) << 16 with zipfile.ZipFile(archive_path, "w") as archive: archive.writestr(member, "not-a-file") with ( zipfile.ZipFile(archive_path) as archive, self.assertRaisesRegex(SystemExit, "link or special"), ): verify_release.validated_members(archive)
if __name__ == "__main__": unittest.main()CHANGELOG.md+3
QUALIFICATION.md+13-1
README.md+18-10
RELEASE_NOTES.md+4
SECURITY_MODEL.md+8
scripts/first_kill.py+180-25
scripts/verify_release.py+56-9
tests/test_first_kill.py+185
tests/test_release_archive.pyAdded+52