Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/patches/b96d9932c5f1d50f # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers ## GitHub aien-dev/aienux#326 (code only) closed derived `b96d9932c5f1d50f` #326 Imported from GitHub aien-dev/aienux#326 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `22157e1f4c7d55dcc667625209f98f80912dcab2` · Head `bc7202d57c3e8fc4e7dfd69f71e34208324e996e` github-advanced-security[bot] commented on `native/kernel/tools/ck_slot_tool.c` line 1089 on 2026-10-12 15:53 UTC ## CodeQL / Potentially overflowing call to snprintf The size argument of this snprintf call is derived from its return value, which may exceed the size of the buffer and overflow. Show more details github-advanced-security[bot] commented on `native/kernel/tools/ck_slot_tool.c` line 1091 on 2026-10-12 15:53 UTC ## CodeQL / Potentially overflowing call to snprintf The size argument of this snprintf call is derived from its return value, which may exceed the size of the buffer and overflow. Show more details github-advanced-security[bot] commented on `native/kernel/tools/ck_slot_tool.c` line 1092 on 2026-10-12 15:53 UTC ## CodeQL / Potentially overflowing call to snprintf The size argument of this snprintf call is derived from its return value, which may exceed the size of the buffer and overflow. Show more details github-advanced-security[bot] reviewed (COMMENTED) on 2026-10-12 15:53 UTC ### Apply it ``` git checkout -b patch-b96d9932c5f1d50f 22157e1f4c7d55dcc667625209f98f80912dcab2 curl -fsSL https://interplane.io/drakestapleton/aienux/patches/b96d9932c5f1d50f.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aienux 326 bc7202d57c3e8fc4e7dfd69f71e34208324e996e ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aienux","number":326,"url":"https://github.com/aien-dev/aienux/pull/326","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:13Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/.crumb b/.crumb index 6fd3b83b..e55da201 100644 --- a/.crumb +++ b/.crumb @@ -27,33 +27,33 @@ "purpose": "Directory crates. Purpose not yet described by a human." }, { - "digest": "eacfb39a65dc3a385a6a374b74e883f52ddb3d50e30ebc6d69288ab7562fa1b3", - "last_commit": "8d90cbb", + "digest": "ac5354ec8aed2e3d31d4c528d1277c3019bebd593ef7fc3648b4017f37ee9504", + "last_commit": "4900d1f", "name": "docs", "purpose": "Directory docs. Purpose not yet described by a human." }, { - "digest": "794b6a712e50e0a7c597a70aa144ceba0f456e75800d580e85cb0900bf6a1f11", - "last_commit": "12e17f6", + "digest": "c426ad5c19f8a955eec686eb38a6b4110782931a238c9f85d24bcc8278f7fdad", + "last_commit": "d7c6c9c", "name": "native", "purpose": "Directory native. Purpose not yet described by a human." }, { - "digest": "654df809529c9ef3d80af6141a30543a957e3ebde6010d9726519f7fa2a24138", - "last_commit": "12e17f6", + "digest": "472997503f5d637af1f91e8eab7ecfe10ddee01e79bd42fb46ba245f061c3607", + "last_commit": "6813d62", "name": "scripts", "purpose": "Directory scripts. Purpose not yet described by a human." } ], - "children_root": "sha256:f27e93a7256a34e2c4d84c451ed2f64fc682176d37d5076c91a69b78abf8df78", - "compiled_at": "2026-10-12T16:50:19Z", + "children_root": "sha256:3f23e1bc11c583943fec01ea5e8c05e81f09ea30eb40de3261d35e0ac3a117a7", + "compiled_at": "2026-10-12T17:02:49Z", "compiler": "crumb-compile/1", - "digest": "sha256:b3dd12a5934d05f00620ba1d3f4e7aa51a9d77d4a400ac6b209c88640c53086c", + "digest": "sha256:1f89952d8d9efbbab43565a6117c6b8648963662f9d97df357ae8aa358a1101f", "evidence_files": 155, "evidence_root": "sha256:d59c0cef4e7dd5172923754a95b411ca54b01f35baca4587f792f1b259f1eaf7", - "files": 3102, - "generated_at_commit": "8d90cbbc8bc9b1b33dac2060a69bfb6b9d8e4063", - "source_tree": "sha256:fdf05689e2e428e3cdc4041cefec802bfe82d6af4f4254106cce542d768d83a0" + "files": 3104, + "generated_at_commit": "d7c6c9c90f6711626732bcb168f95cbf45671685", + "source_tree": "sha256:479eab5581119f0dbab41f828cfd2680553baec0e4c4e7eb36db3ca9cca64ad1" }, "owner_lane": "", "provenance": { diff --git a/docs/.crumb b/docs/.crumb index 6915d245..2d101e05 100644 --- a/docs/.crumb +++ b/docs/.crumb @@ -30,14 +30,14 @@ } ], "children_root": "sha256:baea130f2c52779b57d90139beb66ac01b21ab499d113471a334be5500f3e369", - "compiled_at": "2026-10-12T16:50:19Z", + "compiled_at": "2026-10-12T17:02:49Z", "compiler": "crumb-compile/1", - "digest": "sha256:eacfb39a65dc3a385a6a374b74e883f52ddb3d50e30ebc6d69288ab7562fa1b3", + "digest": "sha256:ac5354ec8aed2e3d31d4c528d1277c3019bebd593ef7fc3648b4017f37ee9504", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 74, - "generated_at_commit": "8d90cbbc8bc9b1b33dac2060a69bfb6b9d8e4063", - "source_tree": "sha256:f5be4d57dd153cfa4876cc955b4159a2f82f3543092ead657c49b2a2a6779745" + "generated_at_commit": "d7c6c9c90f6711626732bcb168f95cbf45671685", + "source_tree": "sha256:2a74ca0a64b7964f84a6827626631cdb85db7844d31490d34ba9ded1532828f1" }, "owner_lane": "", "provenance": { diff --git a/docs/BOOT_HANDOFF_CONTRACT.md b/docs/BOOT_HANDOFF_CONTRACT.md index 75f95095..157258b1 100644 --- a/docs/BOOT_HANDOFF_CONTRACT.md +++ b/docs/BOOT_HANDOFF_CONTRACT.md @@ -210,6 +210,21 @@ is handed out) and after the vectors are installed, so a refusal can print. ## 7. Rollback without A/B slots +**Update 2026-10-12 (P11 cut 2a, owner decision):** Drake approved a slot +loader, narrowly scoped to signed A/B image selection, boot-success tracking +and rollback. The slots live in a separate UEFI application, +`SLOTLDR.EFI` (`native/boot/slot_loader.c`), placed in front of the +unchanged stub + kernel image; this loader (the stub) still has no slots and +the rules below still hold for the image itself. SLOTLDR.EFI picks a +verified slot from the slots partition, consumes one candidate try before +the jump, and chain-loads the slot image with `LoadImage` + `StartImage`; it +never touches UEFI variables, so a BootNext stager in front of it works as +before. If the chained image returns to the firmware (the three paths in +item 3), it returns to SLOTLDR.EFI, which prints +`slot_loader: slot X returned status=...` and returns that status to the +firmware. Format, rules and gate: `docs/NATIVE_IMAGE_SLOTS.md` sections 5 +and 7, `native/kernel/GATES.md` `SLOT_LOADER`. + There are no slots and, per Q3, none will be added to this loader. Rollback is the firmware's **one-time BootNext** rule, already the subject of `docs/NATIVE_BOOT_ROLLBACK_CONTRACT.md` (section 2 invariant: "A candidate may diff --git a/docs/NATIVE_IMAGE_SLOTS.md b/docs/NATIVE_IMAGE_SLOTS.md index 9aab17c2..7097fb85 100644 --- a/docs/NATIVE_IMAGE_SLOTS.md +++ b/docs/NATIVE_IMAGE_SLOTS.md @@ -1,9 +1,13 @@ -# Native image slots: install, update and recovery without Linux (P11 cut 1) +# Native image slots: install, update and recovery without Linux (P11 cuts 1 and 2a) -STATUS: PROPOSED (design note plus host tooling; no loader or kernel image -code changed in this cut; nothing here has run on hardware). +STATUS: cut 1 (format, rules, host tool) and cut 2a (SLOTLDR.EFI, a separate +slot loader in front of the unchanged image, QEMU gate PASS) done; the owner +approved the loader on 2026-10-12 (section 2). Nothing here has run on +hardware (hardware NOT_RUN). The kernel image and its stub are unchanged. SECURITY_IMPACT: PERSISTENT_FORMAT + RECOVERY (a new on-disk format and a new -recovery rule are specified; neither is written to any machine by this cut). +recovery rule are specified; from cut 2a SLOTLDR.EFI writes the control +region of the slots partition, and nothing else, before a candidate try; +nothing has been written to a physical machine). Program: AIEN native v1 (aien-architecture CURRENT_EXECUTION_PLAN, addendum 2026-10-12), work package P11, gate N7: "Install, update and recovery work @@ -52,7 +56,20 @@ built by our own tools), which is a later cut. Dual-invalid cannot happen by update alone under the rules below (the active slot is never written while it is active), only by media failure or a deliberate wipe. -## 2. Decision needed from the owner (Drake) +## 2. Owner decision (Drake): approved 2026-10-12, narrow scope + +**Decision recorded 2026-10-12.** Drake: "Slot loader APPROVED, narrowly +scoped: the frozen boot stub may change only for signed A/B image selection, +boot-success tracking, and rollback. Emulator tests required before hardware: +successful update, invalid signature, interrupted update, unsuccessful boot." +Cut 2a meets that without changing the stub at all: the slot logic is a +separate UEFI application, `SLOTLDR.EFI`, in front of the unchanged stub + +kernel image (section 7). The four required emulator tests are rows 2 +(a staged update boots, one counted try per boot; it is not yet made +permanent, that is the kernel promote of cut 2b; after three unsuccessful +boots the loader goes back to A), 3 and 4 (invalid signature, untrusted key) +and 6 (interrupted update) of its QEMU gate; rows 5, 7 and 8 add a tampered +image, both slots invalid and the generation floor. The text below is the request as it was asked. The loader is frozen: `docs/BOOT_HANDOFF_CONTRACT.md` section 7 says "There are no slots and, per Q3, none will be added to this loader", and @@ -167,8 +184,10 @@ nothing and to re-release anything. 10 control mutations, 16 selection scenarios including the bounded tries and the floor, the transitions, and torn-slot commit/recover with a simulated torn write) and the freestanding proof (`slot-free`). The - signing path is offline: `ck_slot_tool tbs` emits the 448 signed bytes, - the owner signs them on the air-gapped machine with OpenSSL + signing path is offline: `ck_slot_tool tbs M --pubkey HEX64 --out F` + emits the 448 signed bytes (the owner public key is required because + `signer_id`, its SHA-256, lies inside the signed bytes; aienos#324), the + owner signs them on the air-gapped machine with OpenSSL (`pkeyutl -sign -rawin`), `attach-sig` verifies and attaches. No private key ever touches the Spark. The TEST signer exists for tests only. **Cut 1b (merged with this note's follow-up): the package.** @@ -178,7 +197,10 @@ nothing and to re-release anything. firmware digests) and `SHA256SUMS`, and sets the slot manifest's provenance to the SHA-256 of `SHA256SUMS`, so the owner's one signature over the manifest binds the whole package. `docs/NATIVE_PACKAGE.md`. -2. **Stub reads a slot (after the owner's yes).** The stub locates the +2. **Cut 2a (done, QEMU): a slot loader in front of the stub.** Built as a + separate loader, `SLOTLDR.EFI`, not inside the stub (section 7), so the + qualified image stays byte-identical and its own stub never recurses into + slot selection. As first planned: the stub locates the slots partition on the boot disk, reads C, reads both manifests and images, calls `ck_slot_select`, commits the try if asked, and chain-loads the chosen image with `LoadImage(SourceBuffer)` + `StartImage`. A QEMU @@ -193,5 +215,68 @@ nothing and to re-release anything. recovery media built by our tools, for the dual-invalid case. Then N7 is run on the physical candidate inside an attended window. -Until cut 2 is approved and merged, the boot path is unchanged and the -statements in BOOT_HANDOFF_CONTRACT section 7 and native/boot/README.md hold. + **Cut 2b (next): kernel-side promote.** After its health milestone the + kernel writes the control record over its own NVMe path (promote the + candidate, or mark it failed), so a good update becomes the active slot + instead of only being tried three times. + +The stub itself is unchanged: the statements in BOOT_HANDOFF_CONTRACT +section 7 and native/boot/README.md hold for it; slots live only in +SLOTLDR.EFI. + +## 7. SLOTLDR.EFI and its gate (cut 2a) + +`native/boot/slot_loader.c` builds `$(OUT)/SLOTLDR.EFI` +(`make -C native/kernel slot-loader`). Why a separate loader and not the +stub: if the stub chose a slot and chain-loaded an image, that image's own +stub would choose again; a front loader keeps the qualified image +byte-identical and keeps the stub frozen. The boot volume's +`EFI/BOOT/BOOTAA64.EFI` becomes SLOTLDR.EFI; the slot images are the +unchanged stub + kernel image. + +What it does, in order: + +1. Finds whole disks (Block I/O), checks each primary GPT (header and entry + array CRC32, usable range) and takes the one partition with the slots type + GUID (`slot_format.h`). None, or more than one across all disks: + recovery required. The backup GPT is not read; a bad primary fails closed. +2. Reads the control region (units 0-3) and recovers the newest committed + record with the torn-slot rules (`native/store/torn_slot.c`), read only. +3. Reads both manifests and images (bounded by the slot capacity, read in + pieces of at most 8 MiB) and verifies each with `ck_slot_verify` against + the keys baked in at build time. +4. Applies `ck_slot_select`. A candidate try commits the control record with + tries reduced by one, then reads it back and compares; if that fails the + candidate is treated as invalid and the selection runs again. This is the + only write, and it lands only in the control region. +5. Prints `slot_loader: boot= reason= gen= tries= floor=` + and chain-loads the verified bytes with `LoadImage(SourceBuffer)` and its + own device path (so the chained stub still sees the boot volume) and + `StartImage`. +6. Both slots invalid: prints `slot_loader: recovery_required (A: ; B: + )` and returns `EFI_LOAD_ERROR` to the firmware. + +Never: UEFI variables, runtime services, `ExitBootServices` (the chained +stub leaves boot services itself), `SetWatchdogTimer`, kernel objects (all +checked at build time). + +Keys: `CK_SLOT_KEYS=` bakes the owner's public keys in (same file +format as `ck_slot_tool --keys`, generated by `ck_slot_tool keys-c`). +`CK_TEST_SLOT_KEY=1` bakes the RFC 8032 TEST 1 key and the loader prints +`slot_loader: TEST-ONLY key`; it is refused with `CK_HARDWARE_STAGING=1`, +and the two options together are refused. + +Boot-success tracking in cut 2a is the tries counter: a candidate that is +never promoted is tried three times and then left; the active slot boots. +Promotion after a kernel health milestone is cut 2b. + +Gate: `scripts/qemu_ck_slot_loader_test.sh` (`AIENOS_CK_SLOT_LOADER`, child +`slots` of `scripts/ck_gates.sh`), rows 186-193 of `native/kernel/GATES.md`, +plus the build check row 194 (`make test` runs `slot-loader-check`). Run on +2026-10-12 at code commit bff20a1: PASS, 8 rows, 11 boots, 76 checks, 126 s +under QEMU TCG. Hardware NOT_RUN. + +Host tool additions for the gate: `ck_slot_tool slots-image` (writes the +control record and both slots into a slots partition of a disk image), +`ck_slot_tool keys-c`, `ck_slot_tool sign-test --test2` (a second, +untrusted TEST key), and `ck_gpt_image` layout `slots`. diff --git a/docs/NATIVE_PACKAGE.md b/docs/NATIVE_PACKAGE.md index d4980824..0e613eec 100644 --- a/docs/NATIVE_PACKAGE.md +++ b/docs/NATIVE_PACKAGE.md @@ -137,6 +137,10 @@ About 40 s, nothing booted. ## What is still missing for N7 The package is the input to the updater (slots cut 3) and to the known-good -recovery image (slots cut 4). Neither exists yet. Install today is still +recovery image (slots cut 4). Neither exists yet. The owner approved the +slot loader on 2026-10-12 (`docs/NATIVE_IMAGE_SLOTS.md` section 2); its first +cut, `SLOTLDR.EFI` (slots cut 2a, QEMU only), exists but is not in the package +yet: a follow-up adds `SLOTLDR.EFI` and its SHA-256 to `PACKAGE.txt` and +`SHA256SUMS`, built with the owner's `CK_SLOT_KEYS`. Install today is still the one-time BootNext procedure of `docs/NATIVE_BOOT_ONE_TIME.md`, which N7 rejects as the supported path. diff --git a/native/.crumb b/native/.crumb index 1487c2bc..3d8952ae 100644 --- a/native/.crumb +++ b/native/.crumb @@ -55,8 +55,8 @@ "purpose": "Directory native/argus. Purpose not yet described by a human." }, { - "digest": "c1bc8c4dbdd87843adfef62a310e31290b17c16d6251212eca6be9ea6fe1963d", - "last_commit": "6e3c492", + "digest": "ac53ad497e153b30849f7064154f0dccedafe1af34a5b6de118327ee0e5c39d3", + "last_commit": "21e0473", "name": "boot", "purpose": "Directory native/boot. Purpose not yet described by a human." }, @@ -79,8 +79,8 @@ "purpose": "Directory native/disk. Purpose not yet described by a human." }, { - "digest": "45f810f4c2482700ded9443113f28d6d36c4817b79c3b3e4b4620e8f7c85f687", - "last_commit": "f56f72b", + "digest": "e67a5cfded2e60d58d49917a9807e23b1d5d71be32548f900c36a577f3d0c151", + "last_commit": "d7c6c9c", "name": "kernel", "purpose": "Directory native/kernel. Purpose not yet described by a human." }, @@ -109,15 +109,15 @@ "purpose": "Directory native/store. Purpose not yet described by a human." } ], - "children_root": "sha256:26313f317f00d90e99c5cbbace065401cab67e6c2fa3aeeb2e57396830e2c637", - "compiled_at": "2026-10-12T16:07:30Z", + "children_root": "sha256:a6ba30bd8c3b3fb4095890cdaa90571d7bc8cc4cadbd65a83e141755631abe35", + "compiled_at": "2026-10-12T17:02:49Z", "compiler": "crumb-compile/1", - "digest": "sha256:794b6a712e50e0a7c597a70aa144ceba0f456e75800d580e85cb0900bf6a1f11", + "digest": "sha256:c426ad5c19f8a955eec686eb38a6b4110782931a238c9f85d24bcc8278f7fdad", "evidence_files": 4, "evidence_root": "sha256:e410b845507e00568e15b51a5797af32a97e0e4b8ab4e8487bb7c98e7e0cf335", - "files": 477, - "generated_at_commit": "f56f72b2bdf52b7f2347c6548e42459e465558a0", - "source_tree": "sha256:5622e30e243bcdd5b3625de6aeb0a654621194f380387166ac204bcc3f46e416" + "files": 478, + "generated_at_commit": "d7c6c9c90f6711626732bcb168f95cbf45671685", + "source_tree": "sha256:c75aa7d409696ef48f3477a61e8309d5d843e09aee3224a3ac9adfb64e4f7db6" }, "owner_lane": "", "provenance": { diff --git a/native/boot/.crumb b/native/boot/.crumb index 7115a2af..3418f814 100644 --- a/native/boot/.crumb +++ b/native/boot/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-12T14:03:50Z", + "compiled_at": "2026-10-12T17:02:49Z", "compiler": "crumb-compile/1", - "digest": "sha256:c1bc8c4dbdd87843adfef62a310e31290b17c16d6251212eca6be9ea6fe1963d", + "digest": "sha256:ac53ad497e153b30849f7064154f0dccedafe1af34a5b6de118327ee0e5c39d3", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 11, - "generated_at_commit": "c30b15e75373d0357956d8b46e81d0b007839d54", - "source_tree": "sha256:f3578698cc2ea2cfe3c01795d86954d83dc8f540fc1b40aa57225d631c17b686" + "files": 12, + "generated_at_commit": "d7c6c9c90f6711626732bcb168f95cbf45671685", + "source_tree": "sha256:a48e5625c27ed0138e01d42ca77c73f130946524729e8ec9470f8ba0379a4a54" }, "owner_lane": "", "provenance": { diff --git a/native/boot/README.md b/native/boot/README.md index 2ebd9179..7516e1ca 100644 --- a/native/boot/README.md +++ b/native/boot/README.md @@ -15,12 +15,21 @@ This is the C path's UEFI entry (Lane 18). It is deliberately small: `ck_kernel_entry` with a `struct ck_handoff` (`handoff.h`): memory-map copy, RSDP, firmware EL, firmware TTBR0/SCTLR, counter, commit. -**Proposed, not wired (P11 cut 1, gate N7):** `slot_format.h` and -`slot_select.c` pin an A/B image-slot format and the loader's selection rules -(bounded candidate tries, generation floor, never a boot loop), checked by -`make -C native/kernel slot-test slot-free`. The stub does not read them yet; -whether it ever does is the owner's call recorded in -`docs/NATIVE_IMAGE_SLOTS.md` section 2. The paragraph below stays true. +**A/B slots live in a separate loader, `slot_loader.c` -> `SLOTLDR.EFI` (P11 +cut 2a, gate N7, QEMU only; owner decision 2026-10-12: narrowly scoped to +signed A/B image selection, boot-success tracking and rollback).** It sits in +front of this stub as the boot volume's `EFI/BOOT/BOOTAA64.EFI`, reads the +slots partition (`slot_format.h`), verifies both slots against owner keys +baked in at build time, applies `slot_select.c` (bounded candidate tries, +generation floor, never a boot loop), commits a candidate try before the jump, +and chain-loads the chosen image (this stub + kernel, unchanged and +byte-identical) with `LoadImage` + `StartImage`. Both slots invalid: it prints +`slot_loader: recovery_required (...)` and returns to the firmware. It never +touches UEFI variables, runtime services or `ExitBootServices`. Build: +`make -C native/kernel slot-loader CK_SLOT_KEYS=` (or the TEST-ONLY +`CK_TEST_SLOT_KEY=1`, refused with `CK_HARDWARE_STAGING`); gate +`scripts/qemu_ck_slot_loader_test.sh`; `docs/NATIVE_IMAGE_SLOTS.md`. This stub +itself still has no slot logic, so the paragraph below stays true for it. **Parked, not here:** signature checks, BootNext staging, rollback and the boot-report file. The Rust `aienos-boot` crate has BootNext staging and a QEMU diff --git a/native/boot/slot_format.h b/native/boot/slot_format.h index 6843a1a8..70eaa453 100644 --- a/native/boot/slot_format.h +++ b/native/boot/slot_format.h @@ -2,12 +2,14 @@ * reads to choose which native image boots, and a kernel writes to install, * update and roll back WITHOUT Linux (native v1 plan P11, gate N7). * - * STATUS: PROPOSED format (docs/NATIVE_IMAGE_SLOTS.md). Nothing writes it yet - * and no image reads it: native/boot/efi_main.c is unchanged (loader - * expansion is frozen, BOOT_HANDOFF_CONTRACT.md; the owner decides whether - * the loader grows slot selection). This header, slot_select.c and the host - * tool native/kernel/tools/ck_slot_tool.c pin the format and the decision - * rules so they can be reviewed and mutation-tested before any loader change. + * STATUS (docs/NATIVE_IMAGE_SLOTS.md): format v1. Read by SLOTLDR.EFI + * (native/boot/slot_loader.c, P11 cut 2a, owner decision 2026-10-12), a + * separate chain loader in FRONT of the unchanged stub + kernel image + * (native/boot/efi_main.c is not modified). The loader writes the control + * record only to consume a candidate try. The kernel-side writer (stage, + * promote, abandon from the native NVMe path) is cut 2b. This header, + * slot_select.c and the host tool native/kernel/tools/ck_slot_tool.c pin + * the format and the decision rules (mutation-tested in make slot-test). * * Accepted design this follows: ADR 0006 (transactional A/B slots, health * milestones before promotion) and TRUST-1 Q19 (A = known-good, B = @@ -63,6 +65,19 @@ #define CK_SLOT_MAX_TRIES 3u /* bounded candidate boot attempts */ #define CK_SLOT_MIN_CAP_UNITS 2u /* manifest + at least one image unit */ +/* Geometry from the partition size alone (U = whole 4096-byte units in the + * partition): CAP = (U - 4) / 2 units per slot; slot s starts at unit + * 4 + s * CAP (its manifest), its image at the next unit, at most + * (CAP - 1) * 4096 bytes. Shared by SLOTLDR.EFI and ck_slot_tool. */ +static inline uint64_t ck_slot_cap_units(uint64_t part_units) +{ + return part_units < CK_SLOT_FIRST_UNIT ? 0 : (part_units - CK_SLOT_FIRST_UNIT) / CK_SLOT_COUNT; +} +static inline uint64_t ck_slot_manifest_unit(unsigned slot, uint64_t cap_units) +{ + return CK_SLOT_FIRST_UNIT + (uint64_t)slot * cap_units; +} + /* 8B1096CD-7928-4E08-B5E4-C19B6B532760: AIENOS image slots partition type. */ #define CK_SLOT_PART_TYPE_TEXT "8B1096CD-7928-4E08-B5E4-C19B6B532760" #define CK_SLOT_PART_TYPE_BYTES \ diff --git a/native/boot/slot_loader.c b/native/boot/slot_loader.c new file mode 100644 index 00000000..2e9296c2 --- /dev/null +++ b/native/boot/slot_loader.c @@ -0,0 +1,478 @@ +/* slot_loader.c -- SLOTLDR.EFI: the AIENOS signed A/B image slot loader + * (native v1 plan P11 cut 2a, gate N7; docs/NATIVE_IMAGE_SLOTS.md). + * + * A separate UEFI application that runs IN FRONT of the unchanged native + * image (stub native/boot/efi_main.c + kernel, one PE). The owner approved a + * narrowly scoped slot loader on 2026-10-12: signed A/B image selection, + * boot-success tracking (bounded candidate tries) and rollback, nothing else. + * Putting it in its own PE keeps the qualified stub + kernel byte-identical + * (BOOT_HANDOFF_CONTRACT.md section 7) and avoids recursion: a stub that + * chain-loaded itself would select slots again inside the chained copy. + * + * Flow (UEFI 2.10 boot services only; edk2 BlockIo.h, LoadedImage.h): + * 1. LocateHandleBuffer(ByProtocol, BlockIo): on every whole disk + * (LogicalPartition == 0, block size 512 or 4096) read the primary GPT + * (header CRC32, entry array CRC32, usable range) and find entries with + * the slots partition type CK_SLOT_PART_TYPE_BYTES. Exactly one across + * all disks, or recovery is required (no fallback guess). + * 2. Control record: torn-slot recover over partition units 0..3 + * (native/store/torn_slot.c, the same object the host tool links). + * 3. Each slot: read the manifest unit, read image_len bytes of the image + * (bounded by the slot capacity, <= 8 MiB ReadBlocks pieces), then + * ck_slot_verify against the owner keys baked in at build time + * (CK_SLOT_KEYS, or the TEST 1 key with CK_TEST_SLOT_KEY=1, which the + * Makefile refuses with CK_HARDWARE_STAGING). + * 4. ck_slot_select (slot_select.c, mutation-tested in make slot-test). + * CK_SLOT_R_CANDIDATE_TRY: commit ctl_out (tries - 1) with ts_commit, + * FlushBlocks, read it back, and only then boot the candidate. That is + * what bounds attempts when a candidate hangs or never promotes. If the + * commit fails the candidate is treated as invalid and selection reruns. + * 5. One decision line, then LoadImage(SourceBuffer = the verified bytes, + * DevicePath = this loader's own LoadedImageDevicePath, so the chained + * stub's LoadedImage->DeviceHandle is still the boot volume and its + * MODEL.MAP still loads) and StartImage. + * Recovery required: print why for both slots and return EFI_LOAD_ERROR to + * the firmware, which goes on to its next boot option. + * + * Never: UEFI variables, runtime services, ExitBootServices (the chained + * stub leaves boot services itself), any write other than the control + * region, any write when the control record is missing or corrupt. + * Freestanding C with the kernel's flags; no kernel objects are linked. */ +#include +#include "efi.h" +#include "slot_format.h" +#include "../store/torn_slot.h" +#include "../kernel/core/fmt.h" + +#ifndef AIENOS_COMMIT +#define AIENOS_COMMIT "unknown" +#endif + +void *memcpy(void *dst, const void *src, size_t n); +void *memset(void *dst, int c, size_t n); +int memcmp(const void *a, const void *b, size_t n); + +/* Generated at build time (native/kernel/Makefile, ck_slot_tool keys-c). */ +extern const uint8_t ck_slot_loader_keys[][32]; +extern const unsigned ck_slot_loader_nkeys; +extern const char ck_slot_loader_key_note[]; + +#define EFI_LOAD_ERROR EFI_ERR(1) +#define READ_CHUNK (8ull << 20) +#define PAGE 4096ull +#define GPT_ENT_MAX (128u * 1024u) + +/* Boot-services members efi.h keeps as placeholders (UEFI 2.10 sections 7.4 + * and 13.9; r-efi system.rs BootLoadImage/BootStartImage, block_io.rs). The + * shared efi.h is left untouched so the stub's sources do not change. */ +typedef EFI_STATUS (*load_image_fn)(uint8_t boot_policy, EFI_HANDLE parent, void *device_path, + void *source, uint64_t source_size, EFI_HANDLE *out); +typedef EFI_STATUS (*start_image_fn)(EFI_HANDLE image, uint64_t *exit_data_size, CHAR16 **exit_data); +typedef EFI_STATUS (*write_blocks_fn)(EFI_BLOCK_IO_PROTOCOL *bio, uint32_t media_id, uint64_t lba, + uint64_t size, void *buf); +typedef EFI_STATUS (*flush_blocks_fn)(EFI_BLOCK_IO_PROTOCOL *bio); + +/* EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID (UEFI 2.10 section 9.2; + * vendor/uefi/src/proto/device_path/mod.rs LoadedImageDevicePath). */ +#define LOADED_IMAGE_DEVICE_PATH_GUID_INIT \ + { 0xbc62157e, 0x3e33, 0x4fec, { 0x99, 0x20, 0x2d, 0x3b, 0x36, 0xd7, 0x50, 0xdf } } + +static EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *conout; +static EFI_BOOT_SERVICES *bs; + +static uint8_t blk[4096] __attribute__((aligned(4096))); +static uint8_t hdr[4096]; +static uint8_t ents[GPT_ENT_MAX + 4096] __attribute__((aligned(4096))); +static uint8_t bounce[CK_SLOT_UNIT] __attribute__((aligned(4096))); +static struct ck_slot_manifest man[CK_SLOT_COUNT] __attribute__((aligned(4096))); +static struct ck_slot_control ctl_rec, ctl_back; + +/* ---- console -------------------------------------------------------------- */ +struct line { + char b[256]; + size_t n; +}; + +static void line_emit(void *ctx, char c) +{ + struct line *l = ctx; + if (l->n < sizeof l->b - 1) + l->b[l->n++] = c; +} + +static void say(const char *fmt, ...) __attribute__((format(printf, 1, 2))); +static void say(const char *fmt, ...) +{ + struct line l; + CHAR16 w[2 * sizeof l.b + 1]; + size_t k = 0; + va_list ap; + l.n = 0; + va_start(ap, fmt); + ck_vformat(line_emit, &l, fmt, ap); + va_end(ap); + for (size_t i = 0; i < l.n; i++) { + if (l.b[i] == '\n') + w[k++] = '\r'; + w[k++] = (uint8_t)l.b[i]; + } + w[k] = 0; + if (conout) + conout->OutputString(conout, w); +} + +/* ---- primary GPT ------------------------------------------------------------ */ +static uint32_t crc32(const uint8_t *p, size_t n) +{ + uint32_t c = 0xFFFFFFFFu; + for (size_t i = 0; i < n; i++) { + c ^= p[i]; + for (int k = 0; k < 8; k++) + c = (c >> 1) ^ (0xEDB88320u & (0u - (c & 1u))); + } + return ~c; +} + +static uint32_t le32(const uint8_t *p) +{ + return (uint32_t)p[0] | (uint32_t)p[1] << 8 | (uint32_t)p[2] << 16 | (uint32_t)p[3] << 24; +} + +static uint64_t le64(const uint8_t *p) +{ + return (uint64_t)le32(p) | (uint64_t)le32(p + 4) << 32; +} + +struct slots_part { + EFI_BLOCK_IO_PROTOCOL *bio; + uint32_t bs; + uint64_t first, last; +}; + +/* Number of slots-type entries in this disk's primary GPT (0: no GPT or none), + * the first one in *out; -1 with *why when the GPT is present but refused. */ +static int gpt_scan(EFI_BLOCK_IO_PROTOCOL *bio, struct slots_part *out, const char **why) +{ + static const uint8_t type[16] = CK_SLOT_PART_TYPE_BYTES; + const EFI_BLOCK_IO_MEDIA *m = bio->Media; + uint32_t bsz = m->BlockSize; + int count = 0; + if (bio->ReadBlocks(bio, m->MediaId, 1, bsz, blk) != EFI_SUCCESS) { + *why = "LBA 1 read failed"; + return -1; + } + if (memcmp(blk, "EFI PART", 8) != 0) + return 0; + uint32_t hsz = le32(blk + 12); + if (le32(blk + 8) != 0x00010000u || hsz < 92 || hsz > bsz) { + *why = "GPT header revision or size"; + return -1; + } + memcpy(hdr, blk, hsz); + memset(hdr + 16, 0, 4); + if (crc32(hdr, hsz) != le32(blk + 16)) { + *why = "GPT header CRC32 mismatch"; + return -1; + } + uint64_t fu = le64(blk + 40), lu = le64(blk + 48), elba = le64(blk + 72); + uint32_t nent = le32(blk + 80), esz = le32(blk + 84), ecrc = le32(blk + 88); + if (le64(blk + 24) != 1 || fu > lu || lu > m->LastBlock) { + *why = "GPT header LBAs"; + return -1; + } + if (esz < 128 || esz % 8 || nent == 0 || nent > 1024 || (uint64_t)nent * esz > GPT_ENT_MAX) { + *why = "GPT entry geometry"; + return -1; + } + uint64_t ebytes = (uint64_t)nent * esz, eblocks = (ebytes + bsz - 1) / bsz; + if (elba < 2 || elba + eblocks - 1 > m->LastBlock) { + *why = "GPT entry array LBA"; + return -1; + } + if (bio->ReadBlocks(bio, m->MediaId, elba, eblocks * bsz, ents) != EFI_SUCCESS) { + *why = "GPT entry array read failed"; + return -1; + } + if (crc32(ents, (size_t)ebytes) != ecrc) { + *why = "GPT entry array CRC32 mismatch"; + return -1; + } + for (uint32_t i = 0; i < nent; i++) { + const uint8_t *e = ents + (uint64_t)i * esz; + if (memcmp(e, type, 16) != 0) + continue; + uint64_t f = le64(e + 32), l = le64(e + 40); + if (f > l || f < fu || l > lu) { + *why = "slots partition outside the GPT usable range"; + return -1; + } + if (count++ == 0) { + out->bio = bio; + out->bs = bsz; + out->first = f; + out->last = l; + } + } + return count; +} + +/* Exactly one slots partition across every whole disk, or -1 with *why. */ +static int find_slots(struct slots_part *sp, const char **why) +{ + static const EFI_GUID bio_guid = EFI_BLOCK_IO_PROTOCOL_GUID_INIT; + EFI_HANDLE *handles = 0; + uint64_t n = 0; + int total = 0; + if (bs->LocateHandleBuffer(ByProtocol, &bio_guid, 0, &n, &handles) != EFI_SUCCESS || !handles) { + *why = "no block devices"; + return -1; + } + for (uint64_t i = 0; i < n; i++) { + EFI_BLOCK_IO_PROTOCOL *bio = 0; + struct slots_part c; + const char *w = 0; + if (bs->HandleProtocol(handles[i], &bio_guid, (void **)&bio) != EFI_SUCCESS || !bio || !bio->Media) + continue; + const EFI_BLOCK_IO_MEDIA *m = bio->Media; + if (!m->MediaPresent || m->LogicalPartition || (m->BlockSize != 512 && m->BlockSize != 4096) || + m->LastBlock < 34 || m->IoAlign > PAGE) + continue; + int rc = gpt_scan(bio, &c, &w); + if (rc < 0) { + say("slot_loader: disk %llu: GPT refused (%s)\n", (unsigned long long)i, w); + continue; + } + if (rc > 0 && total == 0) + *sp = c; + total += rc; + } + bs->FreePool(handles); + if (total == 0) { + *why = "no slots partition (type " CK_SLOT_PART_TYPE_TEXT ")"; + return -1; + } + if (total > 1) { + *why = "more than one slots partition"; + return -1; + } + return 0; +} + +/* ---- torn-slot device over the whole disk (absolute LBAs) ----------------- */ +static int dev_read(void *ctx, uint64_t lba, uint32_t count, uint8_t *buf) +{ + struct slots_part *sp = ctx; + uint64_t n = (uint64_t)count * sp->bs; + if (n == 0 || n > sizeof bounce) + return -1; + if (sp->bio->ReadBlocks(sp->bio, sp->bio->Media->MediaId, lba, n, bounce) != EFI_SUCCESS) + return -1; + memcpy(buf, bounce, (size_t)n); + return 0; +} + +static int dev_write(void *ctx, uint64_t lba, uint32_t count, const uint8_t *buf) +{ + struct slots_part *sp = ctx; + uint64_t n = (uint64_t)count * sp->bs; + write_blocks_fn wr = (write_blocks_fn)sp->bio->WriteBlocks; + if (n == 0 || n > sizeof bounce || !wr || sp->bio->Media->ReadOnly) + return -1; + /* Only the control region (units 0..3) is ever written. */ + if (lba < sp->first || lba + count > sp->first + CK_SLOT_CONTROL_UNITS * (CK_SLOT_UNIT / sp->bs)) + return -1; + memcpy(bounce, buf, (size_t)n); + return wr(sp->bio, sp->bio->Media->MediaId, lba, n, bounce) == EFI_SUCCESS ? 0 : -1; +} + +static int dev_flush(void *ctx) +{ + struct slots_part *sp = ctx; + flush_blocks_fn fl = (flush_blocks_fn)sp->bio->FlushBlocks; + return fl && fl(sp->bio) == EFI_SUCCESS ? 0 : -1; +} + +/* ---- slots -------------------------------------------------------------------- */ +/* Read image_len bytes of slot s into fresh pages; 0 when the manifest is not + * structurally readable or the image does not fit (ck_slot_verify says why). */ +static uint8_t *read_image(const struct slots_part *sp, uint64_t lba, const struct ck_slot_manifest *m, + uint64_t cap, uint64_t *pages_out, const char **why) +{ + const EFI_BLOCK_IO_MEDIA *md = sp->bio->Media; + uint64_t bytes = (m->image_len + sp->bs - 1) / sp->bs * sp->bs; + uint64_t pages = (bytes + PAGE - 1) / PAGE, base = 0, off = 0; + *pages_out = 0; + if (ck_slot_manifest_check(m, why) != 0 || m->image_len > cap) + return 0; + if (bs->AllocatePages(AllocateAnyPages, EfiLoaderData, pages, &base) != EFI_SUCCESS || !base) { + *why = "AllocatePages failed"; + return 0; + } + while (off < bytes) { + uint64_t n = bytes - off > READ_CHUNK ? READ_CHUNK : bytes - off; + if (sp->bio->ReadBlocks(sp->bio, md->MediaId, lba + off / sp->bs, n, (void *)(uintptr_t)(base + off)) != + EFI_SUCCESS) { + bs->FreePages(base, pages); + *why = "image read failed"; + return 0; + } + off += n; + } + *pages_out = pages; + return (uint8_t *)(uintptr_t)base; +} + +static const char *unusable_why(const struct ck_slot_eval *e, const struct ck_slot_control *ctl, unsigned s) +{ + if (!e->valid) + return e->why ? e->why : "invalid"; + if (ctl && e->generation < ctl->generation_floor) + return "below the generation floor"; + if (ctl && ctl->candidate_slot == s && ctl->tries_remaining == 0) + return "candidate out of tries"; + if (ctl && ctl->candidate_slot == s) + return "candidate, active unusable: never boots on its own authority"; + return "not selectable"; +} + +EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *st) +{ + static const EFI_GUID lidp_guid = LOADED_IMAGE_DEVICE_PATH_GUID_INIT; + struct slots_part sp; + struct ck_slot_eval ev[CK_SLOT_COUNT]; + struct ck_slot_decision d; + const struct ck_slot_control *ctl = 0; + uint8_t *img[CK_SLOT_COUNT] = {0, 0}; + uint64_t pages[CK_SLOT_COUNT] = {0, 0}; + const char *why = 0; + ts_device dev; + ts_region r; + ts_slot_state tss[2]; + uint64_t seq = 0; + int trc; + + conout = st->ConOut; + bs = st->BootServices; + say("slot_loader: AIENOS SLOTLDR v1 commit=%s keys=%u\n", AIENOS_COMMIT, ck_slot_loader_nkeys); + say("slot_loader: %s\n", ck_slot_loader_key_note); + if (ck_slot_loader_nkeys == 0) { + say("slot_loader: recovery_required (no trusted keys built in)\n"); + return EFI_LOAD_ERROR; + } + if (find_slots(&sp, &why) != 0) { + say("slot_loader: recovery_required (%s)\n", why); + return EFI_LOAD_ERROR; + } + uint64_t units = (sp.last - sp.first + 1) * sp.bs / CK_SLOT_UNIT; + uint64_t cap_units = ck_slot_cap_units(units), bpu = CK_SLOT_UNIT / sp.bs; + uint64_t image_cap = cap_units >= CK_SLOT_MIN_CAP_UNITS ? (cap_units - 1) * CK_SLOT_UNIT : 0; + say("slot_loader: slots partition first_lba=%llu last_lba=%llu block=%u units=%llu cap_units=%llu\n", + (unsigned long long)sp.first, (unsigned long long)sp.last, sp.bs, (unsigned long long)units, + (unsigned long long)cap_units); + if (cap_units < CK_SLOT_MIN_CAP_UNITS) { + say("slot_loader: recovery_required (slots partition too small)\n"); + return EFI_LOAD_ERROR; + } + + /* Control record (torn-slot region, units 0..3). */ + dev.ctx = &sp; + dev.block_size = sp.bs; + dev.block_count = sp.bio->Media->LastBlock + 1; + dev.read = dev_read; + dev.write = dev_write; + dev.flush = dev_flush; + trc = ts_open(&r, &dev, sp.first); + if (trc == TS_OK) + trc = ts_recover(&r, (uint8_t *)&ctl_rec, &seq, tss); + if (trc == TS_OK) { + if (ck_slot_control_check(&ctl_rec, &why) == 0) { + ctl = &ctl_rec; + say("slot_loader: control seq=%llu active=%c candidate=%c tries=%u flags=0x%x floor=%llu last_good=%llu\n", + (unsigned long long)seq, 'A' + ctl->active_slot, + ctl->candidate_slot == CK_SLOT_NONE ? '-' : 'A' + ctl->candidate_slot, ctl->tries_remaining, + ctl->flags, (unsigned long long)ctl->generation_floor, + (unsigned long long)ctl->last_good_generation); + } else { + say("slot_loader: control record refused (%s): no control, nothing will be written\n", why); + } + } else if (trc == TS_EMPTY) { + say("slot_loader: control none committed: no control, nothing will be written\n"); + } else { + say("slot_loader: control region unreadable or corrupt (rc=%d): no control, nothing will be written\n", trc); + } + + /* Both slots: manifest, image, verification. */ + for (unsigned s = 0; s < CK_SLOT_COUNT; s++) { + uint64_t lba = sp.first + ck_slot_manifest_unit(s, cap_units) * bpu; + const char *rw = 0; + ev[s].valid = 0; + ev[s].generation = ev[s].policy_generation = 0; + ev[s].why = 0; + if (sp.bio->ReadBlocks(sp.bio, sp.bio->Media->MediaId, lba, CK_SLOT_UNIT, &man[s]) != EFI_SUCCESS) { + ev[s].why = "manifest read failed"; + } else { + img[s] = read_image(&sp, lba + bpu, &man[s], image_cap, &pages[s], &rw); + if (!img[s] && rw && ck_slot_manifest_check(&man[s], &why) == 0 && man[s].image_len <= image_cap) + ev[s].why = rw; /* allocation or read failure */ + else + ck_slot_verify(&man[s], img[s], image_cap, ck_slot_loader_keys, ck_slot_loader_nkeys, &ev[s]); + } + if (ev[s].valid) + say("slot_loader: slot %c valid gen=%llu policy=%llu len=%llu%s\n", 'A' + s, + (unsigned long long)ev[s].generation, (unsigned long long)ev[s].policy_generation, + (unsigned long long)man[s].image_len, + ctl && ev[s].generation < ctl->generation_floor ? " (below the generation floor)" : ""); + else + say("slot_loader: slot %c refused (%s)\n", 'A' + s, ev[s].why ? ev[s].why : "invalid"); + } + + ck_slot_select(ctl, ev, &d); + if (d.loader_write) { + int crc = ts_commit(&r, (const uint8_t *)&d.ctl_out); + uint64_t bseq = 0; + if (crc == TS_OK) + crc = ts_recover(&r, (uint8_t *)&ctl_back, &bseq, 0); + if (crc == TS_OK && memcmp(&ctl_back, &d.ctl_out, sizeof ctl_back) != 0) + crc = TS_CORRUPT; + if (crc != TS_OK) { + unsigned c = (unsigned)d.boot_slot; + say("slot_loader: control commit failed (rc=%d): the candidate is not booted\n", crc); + ev[c].valid = 0; + ev[c].why = "control commit failed"; + ck_slot_select(ctl, ev, &d); + } else { + say("slot_loader: control committed seq=%llu tries=%u\n", (unsigned long long)bseq, + d.ctl_out.tries_remaining); + } + } + if (d.boot_slot < 0) { + say("slot_loader: recovery_required (A: %s; B: %s)\n", unusable_why(&ev[0], ctl, 0), + unusable_why(&ev[1], ctl, 1)); + for (unsigned s = 0; s < CK_SLOT_COUNT; s++) + if (img[s]) + bs->FreePages((uint64_t)(uintptr_t)img[s], pages[s]); + return EFI_LOAD_ERROR; + } + + unsigned b = (unsigned)d.boot_slot; + unsigned tries = d.loader_write ? d.ctl_out.tries_remaining : (ctl ? ctl->tries_remaining : 0); + say("slot_loader: boot=%c reason=%s gen=%llu tries=%u floor=%llu\n", 'A' + b, ck_slot_reason_text(d.reason), + (unsigned long long)ev[b].generation, tries, (unsigned long long)(ctl ? ctl->generation_floor : 0)); + if (img[b ^ 1u]) + bs->FreePages((uint64_t)(uintptr_t)img[b ^ 1u], pages[b ^ 1u]); + + void *dp = 0; + if (bs->HandleProtocol(image, &lidp_guid, &dp) != EFI_SUCCESS) + dp = 0; + EFI_HANDLE child = 0; + EFI_STATUS s = ((load_image_fn)bs->LoadImage)(0, image, dp, img[b], man[b].image_len, &child); + bs->FreePages((uint64_t)(uintptr_t)img[b], pages[b]); + if (s != EFI_SUCCESS || !child) { + say("slot_loader: LoadImage of slot %c status=0x%llx: not booted\n", 'A' + b, (unsigned long long)s); + return EFI_LOAD_ERROR; + } + say("slot_loader: starting slot %c\n", 'A' + b); + s = ((start_image_fn)bs->StartImage)(child, 0, 0); + say("slot_loader: slot %c returned status=0x%llx\n", 'A' + b, (unsigned long long)s); + return s; +} diff --git a/native/kernel/.crumb b/native/kernel/.crumb index 2f93b322..823b31f5 100644 --- a/native/kernel/.crumb +++ b/native/kernel/.crumb @@ -93,21 +93,21 @@ "purpose": "Directory native/kernel/tests. Purpose not yet described by a human." }, { - "digest": "3136405835c1c24b08ed7d35be097c73761632e89dfe81510a2315c0030b5ab7", - "last_commit": "f56f72b", + "digest": "2443251e4e44b6fb0efc7889c87eb6fa5510eb06d7ed84f64ec487621a2b859e", + "last_commit": "4900d1f", "name": "tools", "purpose": "Hosted (Linux-built) checkers for the native kernel, run by `make -C native/kernel test`; nothin" } ], - "children_root": "sha256:bc40eb982c84e2838e3d91f03154b4b04b59c83449f4a9e708520dc0c4e7d612", - "compiled_at": "2026-10-12T16:07:30Z", + "children_root": "sha256:5c4f07aa34ddf2d4f6148bbfc57d942862d4d74c93bce798f61a479ce2c1de6f", + "compiled_at": "2026-10-12T17:02:49Z", "compiler": "crumb-compile/1", - "digest": "sha256:45f810f4c2482700ded9443113f28d6d36c4817b79c3b3e4b4620e8f7c85f687", + "digest": "sha256:e67a5cfded2e60d58d49917a9807e23b1d5d71be32548f900c36a577f3d0c151", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 311, - "generated_at_commit": "f56f72b2bdf52b7f2347c6548e42459e465558a0", - "source_tree": "sha256:80142220b56e31c91c868a9d0ffca5d5ae3c8513be0cfdd4fd44b9d028095b8e" + "generated_at_commit": "d7c6c9c90f6711626732bcb168f95cbf45671685", + "source_tree": "sha256:98db14a6e3bddb8499fc9dad63509be6709a180df4ed206d4a81b101105ea6b5" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/GATES.md b/native/kernel/GATES.md index 558ff991..fc0b9af4 100644 --- a/native/kernel/GATES.md +++ b/native/kernel/GATES.md @@ -286,7 +286,7 @@ Every M0 rollback check is about UEFI one-time boot: BootNext dispatch of the candidate, fallback to Default after a fault, hang, malformed or absent candidate, BootNext consumed and Default unchanged. No A/B slot logic exists in the script or in crates/aienos-boot. ADR 0024 Q3 (aien-architecture) freezes loader expansion: no A/B -slots will be added. Rollback is the one-time BootNext rule; under +slots will be added to this loader (the stub; it still has none). The owner decision of 2026-10-12 puts A/B slots in a separate loader in front of it, SLOTLDR.EFI, gated by `SLOT_LOADER` (section at the end of this file); these M0 rows are unchanged by it. Rollback of the image itself is the one-time BootNext rule; under `docs/BOOT_HANDOFF_CONTRACT.md` section 7.1 these rows run with the C kernel image as the candidate: `scripts/qemu_ck_rollback_test.sh` (child `rollback` of `scripts/ck_gates.sh`), TEST-only candidates from `make CK_TEST_ROLLBACK=bad-magic|cpu-fault|hang`. The Rust mock stays stager and Default. Its own run (`scripts/qemu_native_rollback_test.sh`, Rust-mock evidence, labels `NATIVE_ROLLBACK_*`) is unchanged and kept apart from the C-image labels `CK_ROLLBACK_*`. BootNext and BootOrder are read by the host from the vars file after every boot (`native/kernel/tools/ck_uefi_vars.c`), not from a guest print. Run log: `evidence/ck_rollback_qemu_5deb3971bd88b5664489d47bc273613104e1eb2c7a3e353bfe73f7729717fad8.log` (code commit ecd12c6, clean tree). No `ck_gates.sh` receipt includes this child yet. AAVMF itself appends its auto-created options (UiApp, UEFI Misc Device, EFI Internal Shell) to BootOrder on the boot after the stager wrote `BootOrder=0001`. The absent lane, where no candidate code runs, shows the identical change, so "Default unchanged" is judged as: 0001 first, Boot0000 never in BootOrder, no change after the attempt boot, and equal to that no-candidate control. @@ -866,3 +866,21 @@ The product boundary. A `CK_SERVICE=1` image (`full-service/`, allowed with `CK_ | 183 | production Store: genesis boot 3 prints `store: security manifest sequence=1 generation=2 keyslot=bound previous=genesis`; cold resume boot 4 prints `sequence=2 generation=7 keyslot=bound previous=linked` (the manifest read back from the disk verified under K_root_auth, bound exactly the keyslot the keyed open bound, carried key_epoch 1, the generation that committed it and the manifest count); no `SecurityManifest` refusal in any boot. Limits: only the boot transaction writes a manifest (approve, continuity and journal commits do not advance security_sequence); agent_root_id, continuity_manifest_id and migration_manifest_id stay zero; TPM Slot 0 BLOCKED_HARDWARE; key rotation is row 184; hardware NOT_RUN | LIFECYCLE | QEMU PASS (2026-10-12: 154 rows, AIENOS_CK_LIFECYCLE and AIENOS_CK_LIFECYCLE_INFER PASS; boot 3 `sequence=1 generation=2 keyslot=bound previous=genesis`, boot 4 `sequence=2 generation=7 keyslot=bound previous=linked`, no refusal line; hardware NOT_RUN) | | 184 | P04 cut 2b, recovery secret rotation (ADR 0017 section 2.7 item 1, `rotate ` while READY; `svc/store_boot.c` ck_store_rotate_recovery): the current secret must unwrap K_vol from the bound KeySlotManifest first (proof of possession; a wrong secret writes nothing, `RecoverySecretRejected`); then one Store transaction commits the next KeySlotManifest (sequence n+1 naming the bound one, same K_vol and key epoch, slot 1 re-wrapped under the new secret with a fresh salt and nonce from the entropy service) plus a SecurityManifest (security_sequence+1, linked, binding the new manifest). Store v1 is append-only, so manifests form a chain (`store_sealed.c`: sequences 1..n exactly once, genesis has no link, each later one names its predecessor; the newest is bound; at most one new manifest per transaction, only as n+1 naming the bound one). K_vol is never kept resident between unlock and rotation. Boot 7 (the boot-3 disk again, a second cold resume at generation 6; boot record 7, continuity resume 8): `store: rotated recovery keyslot manifest_sequence=2 security_sequence=3 generation=9 (previous secret retired)`, `lifecycle: rotate ok state=ready`, the typed line echoed as 129 `*`, neither secret in the serial log. Host: stage-test 839 checks (test_rotate: wrong current refused with the disk byte-identical, S1->S2->S3 chain of three, each retired secret refused, TEST-key Store refuses `NoKeySlot`), stage-sanitize 839, stage-free 45 objects, store_sealed chain tests (sequence skip, duplicate sequence, link to an envelope, link to a non-newest manifest, forged link, claimed genesis with a link all refused; bootstrap returns the newest of a verified chain; superseded manifests stay readable). Limits: active_key_epoch stays 1 (rotation re-wraps K_vol, it does not change it; a K_vol compromise is section 2.7 item 2 migration, not done); TPM Slot 0 BLOCKED_HARDWARE; Argon2id profile and owner-root path not in this cut; hardware NOT_RUN | LIFECYCLE | QEMU PASS (2026-10-12: 183 rows on d2f8400, AIENOS_CK_LIFECYCLE and AIENOS_CK_LIFECYCLE_INFER PASS; boot 7 `store: rotated recovery keyslot manifest_sequence=2 security_sequence=3 generation=9 (previous secret retired)`, `lifecycle: rotate ok state=ready`, echo of 129 `*`, no secret in the log; hardware NOT_RUN) | | 185 | after rotation (boot 8, the boot-7 disk): the old secret is refused by the keyslot tag of the newest manifest (`RecoverySecretRejected`, disk not opened, not reformatted); the new secret opens the Store at generation 9, the keyed open binds the chain of two manifests, `store: security manifest sequence=4 generation=10 keyslot=bound previous=linked`, continuity RESUMES incarnation 3, the memory-only fact still answers from the disk; no SecurityManifest refusal; neither secret in the serial log | LIFECYCLE | QEMU PASS (2026-10-12: boot 8 old secret `RecoverySecretRejected` still LOCKED, new secret `opened generation=9`, `security manifest sequence=4 generation=10 keyslot=bound previous=linked`, `continuity: RESUMED incarnation=3`, fact answered from the disk; hardware NOT_RUN) | + +## SLOT_LOADER: SLOTLDR.EFI, the signed A/B image slot loader (native v1 plan P11 cut 2a, gate N7; C-only) -> CK `SLOT_LOADER` (scripts/qemu_ck_slot_loader_test.sh) + +Owner decision 2026-10-12 (Drake): slot loader approved, narrowly scoped to signed A/B image selection, boot-success tracking and rollback; emulator tests before hardware. `native/boot/slot_loader.c` builds `$(OUT)/SLOTLDR.EFI`, a separate UEFI application in front of the unchanged stub and kernel image (the qualified `BOOTAA64.EFI` stays byte-identical; its own stub has no slot logic). Format and rules: `docs/NATIVE_IMAGE_SLOTS.md` (sections 4, 5 and 7), `native/boot/slot_format.h`, `native/boot/slot_select.c`. Setup: the boot volume is a FAT directory whose `EFI/BOOT/BOOTAA64.EFI` is SLOTLDR.EFI built with `CK_TEST_SLOT_KEY=1` (RFC 8032 TEST 1, TEST-ONLY); a second virtio disk holds a GPT with one slots partition (`ck_gpt_image` layout `slots`, first_lba 2048, last_lba 96255, 11776 units, 5886 units per image); `ck_slot_tool slots-image` writes the control region and both slots. Payloads are the core image built twice (`AIENOS_COMMIT=slotA-` and `slotB-`), so the serial line `aienos_commit: slotX-` names the slot that ran. Every row also asks `ck_slot_tool select` (the same `slot_select.c`) for its decision over the same files and requires the same answer. Boot-success tracking in this cut is the tries counter the loader consumes before each candidate boot; promote on a kernel health milestone is cut 2b (the kernel never writes the control record yet). Limits: QEMU only; one slots partition on any disk (two refuse); primary GPT only (backup header not read; a bad primary fails closed); images up to the slot capacity; the dual-invalid case returns to the firmware, the recovery image is cut 4. Not part of the package (`docs/NATIVE_PACKAGE.md`) yet. + +| # | Check | CK gate | Status | +|---|---|---|---| +| 186 | fresh media, control `active=A`, A valid, B empty: `slot_loader: slot B refused (bad magic)`, `slot_loader: boot=A reason=active gen=1 tries=0 floor=0`, slot A's kernel runs (`kernel: alive`, `aienos_commit: slotA-`), QEMU exit 0; the chained image still reads its own boot volume (`model_map: absent (no \EFI\AIENOS\MODEL.MAP on the boot volume)`) | SLOT_LOADER | QEMU PASS (hardware NOT_RUN) | +| 187 | successful update to the candidate and rollback after unsuccessful boots: B staged (gen 2, tries 3). Boots 1-3 each commit the try before the jump (`control committed seq=2 tries=2`, `seq=3 tries=1`, `seq=4 tries=0`), read back from the disk by the host tool after each boot, and boot B (`boot=B reason=candidate_try`, `aienos_commit: slotB-`); boot 4 boots A (`boot=A reason=candidate_exhausted_active`) and writes nothing (control stays `seq=4 candidate=1 tries=0`; marking the candidate failed is the kernel's job in cut 2b, per `slot_select.c` rule 3) | SLOT_LOADER | QEMU PASS (hardware NOT_RUN) | +| 188 | invalid signature: one byte of B's signed manifest flipped: `signature does not verify`, `boot=A reason=candidate_invalid_active`, no try consumed | SLOT_LOADER | QEMU PASS (hardware NOT_RUN) | +| 189 | wrong key: B signed by RFC 8032 TEST 2, not a trusted key: `signer_id names no trusted key`, boots A, no try consumed | SLOT_LOADER | QEMU PASS (hardware NOT_RUN) | +| 190 | tampered image: one byte of B's image flipped, manifest intact: `image SHA-512 mismatch`, boots A, no try consumed | SLOT_LOADER | QEMU PASS (hardware NOT_RUN) | +| 191 | interrupted update: the staging control record torn (2048 bytes of its body written, no commit header): the host tool and the loader both recover the previous record (`control seq=1 active=A candidate=- tries=0`), `boot=A reason=active`, B never tried; control: the whole record would have tried B | SLOT_LOADER | QEMU PASS (hardware NOT_RUN) | +| 192 | both slots invalid: `slot_loader: recovery_required (A: image SHA-512 mismatch; B: signer_id names no trusted key)`, the loader returns `EFI_LOAD_ERROR` to the firmware, no slot started, no kernel ran, the control record untouched; QEMU is stopped by the row timeout (60 s) because the firmware falls through to its next boot option | SLOT_LOADER | QEMU PASS (hardware NOT_RUN) | +| 193 | generation floor: B validly signed at gen 1 while the floor is 2: `slot B valid gen=1`, `(below the generation floor)`, `boot=A reason=candidate_invalid_active gen=2 tries=3 floor=2`, no try consumed | SLOT_LOADER | QEMU PASS (hardware NOT_RUN) | +| 194 | build (`make -C native/kernel slot-loader-check`, part of `make test`): SLOTLDR.EFI links from its own object list (checked: none of the kernel symbols `ck_kernel_entry`, `kmain`, `ck_boot_model_load`, `ck_printf`), its source calls no runtime services, UEFI variables, `ExitBootServices` or `SetWatchdogTimer`; the TEST-key build prints the TEST-ONLY note and an owner-key build (`CK_SLOT_KEYS`, fixture keys) does not; refused (each with its message): no key source, both key options, an unreadable keys file, and `CK_HARDWARE_STAGING=1 CK_TEST_SLOT_KEY=1` | SLOT_LOADER (host) | PASS (`SLOT_LOADER_BUILD: PASS`) | + +Run (2026-10-12, code commit bff20a1 on main ff5da2d, QEMU 8.2 aarch64 virt + AAVMF, TCG): `AIENOS_CK_SLOT_LOADER: PASS (8 rows, 11 boots, 76 checks; QEMU, not hardware)`, 126 s; each slot boot about 6 s, row 7 stopped at 60 s. SLOTLDR.EFI is 36864 bytes. The core `BOOTAA64.EFI` built from this tree is byte-identical to the one built from main ff5da2d (same `AIENOS_COMMIT`, sha256 643fdb5991cfe261). Also PASS in CI (aienos#326, ARM64 job of run 38274680333, `required gate SLOT_LOADER: PASS`). After the rebase onto main 22157e1 (aienos#324 and #325) neither the loader nor the gate script changed, so the gate was not rerun locally (the lock was held by another gate); CI reran it on the final tree. Hardware NOT_RUN. diff --git a/native/kernel/Makefile b/native/kernel/Makefile index 651f496c..d9a9144e 100644 --- a/native/kernel/Makefile +++ b/native/kernel/Makefile @@ -90,6 +90,14 @@ # make print-kcflags flags stage code must be built with # make udp-echo host UDP echo helper for scripts/qemu_ck_net_test.sh: # $(OUT)/host/ck_udp_echo (hosted, test tooling only) +# make slot-loader CK_SLOT_KEYS= | CK_TEST_SLOT_KEY=1 +# SLOTLDR.EFI, the signed A/B slot loader in front of the +# unchanged image (native/boot/slot_loader.c, P11 cut 2a): +# $(OUT)/SLOTLDR.EFI; owner keys baked in from CK_SLOT_KEYS, +# or the TEST-ONLY RFC 8032 TEST 1 key; the TEST key is +# refused with CK_HARDWARE_STAGING. Gate: +# scripts/qemu_ck_slot_loader_test.sh +# make slot-loader-check build checks + refusals -> SLOT_LOADER_BUILD: PASS # # CK_EXTRA_CFLAGS=... extra kernel flags for one-off checks, e.g. # -DCK_SELFTEST_EL2_FAULT (brk at EL2: the EL2 fatal path) @@ -229,6 +237,30 @@ endif OUT ?= $(REPO)/target/native-kernel-test-rollback-$(strip $(CK_TEST_ROLLBACK)) SMP_TEST_FLAGS += -DCK_TEST_ROLLBACK_$(subst -,_,$(shell echo '$(strip $(CK_TEST_ROLLBACK))' | tr a-z A-Z))=1 endif +# SLOTLDR.EFI trusted keys (native v1 plan P11 cut 2a; native/boot/slot_loader.c, +# make slot-loader): +# CK_SLOT_KEYS= owner public keys, "owner_root_ed25519 <64 hex>" lines +# (tools/ck_owner_gen.c format; ck_slot_tool keys-c refuses +# every known TEST key) +# CK_TEST_SLOT_KEY=1 TEST-ONLY: RFC 8032 TEST 1; the loader prints +# "slot_loader: TEST-ONLY key ..."; refused with +# CK_HARDWARE_STAGING and together with CK_SLOT_KEYS. +# Checked here, before the hardware staging owner-file checks, so the refusal +# names the TEST key itself. +CK_SLOT_KEYS ?= +CK_TEST_SLOT_KEY ?= +ifneq ($(strip $(CK_TEST_SLOT_KEY)),) +ifneq ($(strip $(CK_TEST_SLOT_KEY)),1) +$(error CK_TEST_SLOT_KEY must be empty or 1) +endif +ifneq ($(strip $(CK_HARDWARE_STAGING)),) +$(error CK_TEST_SLOT_KEY (TEST-ONLY slot loader key) cannot be combined with CK_HARDWARE_STAGING) +endif +ifneq ($(strip $(CK_SLOT_KEYS)),) +$(error CK_TEST_SLOT_KEY and CK_SLOT_KEYS are exclusive: one trusted key source per slot loader) +endif +endif + OUT ?= $(REPO)/target/native-kernel AIENOS_COMMIT ?= $(shell git -C $(REPO) rev-parse HEAD 2>/dev/null || echo unknown) @@ -1066,8 +1098,8 @@ smmu-l2-mutants: $(OUT)/host/test_smmu else echo "mutant flag refused under CK_HARDWARE_STAGING"; fi; \ if [ $$fail = 0 ]; then echo "CK_SMMU_L2_MUTANTS: PASS"; else echo "CK_SMMU_L2_MUTANTS: FAIL"; exit 1; fi -test: $(addprefix $(OUT)/host/,$(TESTS)) handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test slot-test slot-free package-test - @fail=0; for t in $(filter-out handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test slot-test slot-free package-test,$^); do $$t || fail=1; done; \ +test: $(addprefix $(OUT)/host/,$(TESTS)) handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test slot-test slot-free package-test slot-loader-check + @fail=0; for t in $(filter-out handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants osh-op-mutant test-continuity-subject-restart gsp-fw-inspect-test gsp-cot-test gsp-bindata-test gsp-bootargs-test gsp-rpc-test slot-test slot-free package-test slot-loader-check,$^); do $$t || fail=1; done; \ if [ $$fail = 0 ]; then echo "CK_CORE_HOST: PASS"; else echo "CK_CORE_HOST: FAIL"; exit 1; fi sanitize: $(addprefix $(OUT)/host-san/,$(TESTS)) @@ -1435,7 +1467,7 @@ cont-tool: $(CONT_TOOL) GPT_IMG_TOOL := $(OUT)/host/ck_gpt_image GPT_IMG_SRCS := $(KDIR)/dev/disk_part.c $(NATIVE)/disk/disk.c $(NATIVE)/disk/disk_file.c \ $(KDIR)/tools/gpt_write.c $(KDIR)/tools/ck_gpt_image.c -$(GPT_IMG_TOOL): $(GPT_IMG_SRCS) $(KDIR)/dev/disk_part.h $(KDIR)/tools/gpt_write.h $(NATIVE)/disk/disk.h +$(GPT_IMG_TOOL): $(GPT_IMG_SRCS) $(KDIR)/dev/disk_part.h $(KDIR)/tools/gpt_write.h $(NATIVE)/disk/disk.h $(BOOT)/slot_format.h @mkdir -p $(dir $@) $(HOSTCC) -std=gnu11 -O2 -Wall -Wextra -Werror -I$(KDIR)/dev -I$(KDIR)/tools -I$(NATIVE)/disk -o $@ $(GPT_IMG_SRCS) gpt-image: $(GPT_IMG_TOOL) @@ -1575,6 +1607,77 @@ package-test: $(SLOT_TOOL) NATIVE_PACKAGE_TOOL_OUT=$(OUT) bash $(REPO)/scripts/native_package_test.sh | grep -E '^NATIVE_PACKAGE_TEST: (PASS|FAIL)' | grep -q PASS || { NATIVE_PACKAGE_TOOL_OUT=$(OUT) bash $(REPO)/scripts/native_package_test.sh | grep -E '^FAIL|NATIVE_PACKAGE_TEST'; exit 1; } @echo "NATIVE_PACKAGE_TEST: PASS" +# ---- SLOTLDR.EFI: the signed A/B slot loader (native v1 plan P11 cut 2a, gate N7) ---- +# native/boot/slot_loader.c: a separate UEFI application in FRONT of the unchanged +# stub + kernel image (BOOTAA64.EFI is not touched). It reads the slots partition, +# verifies both slots against the keys baked in here, applies slot_select.c, commits +# the control record before a candidate try, then LoadImage + StartImage of the +# verified bytes. Own object list: no kernel objects (checked), no runtime services, +# no UEFI variables, no ExitBootServices (checked in the source). Keys: CK_SLOT_KEYS +# or CK_TEST_SLOT_KEY=1 (see the top of this file). docs/NATIVE_IMAGE_SLOTS.md. +# make slot-loader CK_TEST_SLOT_KEY=1 -> $(OUT)/SLOTLDR.EFI (TEST-ONLY key) +# make slot-loader CK_SLOT_KEYS= -> $(OUT)/SLOTLDR.EFI (owner keys) +# make slot-loader-check build checks + refusals (in make test) +# QEMU gate: scripts/qemu_ck_slot_loader_test.sh (AIENOS_CK_SLOT_LOADER). +SLOTLDR_DIR := $(OUT)/slotldr +SLOTLDR_ELF := $(SLOTLDR_DIR)/slotldr.elf +SLOTLDR_EFI := $(OUT)/SLOTLDR.EFI +SLOTLDR_KEYS_C := $(SLOTLDR_DIR)/slot_keys.c +SLOTLDR_C := $(BOOT)/slot_loader.c $(BOOT)/slot_select.c $(NATIVE)/sig/sha512.c $(NATIVE)/sig/ed25519.c \ + $(NATIVE)/sig/ct.c $(NATIVE)/argus/sha256.c $(NATIVE)/store/torn_slot.c $(KDIR)/core/libc_min.c \ + $(KDIR)/core/fmt.c +SLOTLDR_OBJS := $(patsubst $(NATIVE)/%.c,$(SLOTLDR_DIR)/obj/%.o,$(SLOTLDR_C)) \ + $(SLOTLDR_DIR)/obj/boot/efi_entry.o $(SLOTLDR_DIR)/obj/slot_keys.o +SLOTLDR_CFLAGS := $(KCFLAGS) $(ART_INC) -I$(NATIVE)/store +SLOTLDR_HDRS := $(BOOT)/slot_format.h $(BOOT)/efi.h $(NATIVE)/store/torn_slot.h $(KDIR)/core/fmt.h $(ART_HDRS) +SLOTLDR_KEY_SRC := $(if $(strip $(CK_TEST_SLOT_KEY)),--test-key,$(if $(strip $(CK_SLOT_KEYS)),--keys $(abspath $(CK_SLOT_KEYS)),)) +$(SLOTLDR_DIR)/obj/%.o: $(NATIVE)/%.c $(SLOTLDR_HDRS) + @mkdir -p $(dir $@) + $(KCC) $(SLOTLDR_CFLAGS) -c -o $@ $< +$(SLOTLDR_DIR)/obj/boot/slot_loader.o: $(BOOT)/slot_loader.c $(SLOTLDR_HDRS) $(OUT)/commit.stamp + @mkdir -p $(dir $@) + $(KCC) $(SLOTLDR_CFLAGS) -DAIENOS_COMMIT='"$(AIENOS_COMMIT)"' -c -o $@ $< +$(SLOTLDR_DIR)/obj/boot/efi_entry.o: $(BOOT)/efi_entry.S + @mkdir -p $(dir $@) + $(KCC) $(KCFLAGS) -c -o $@ $< +# Rewritten only when the key table changes (ck_slot_tool keys-c compares). +$(SLOTLDR_KEYS_C): $(SLOT_TOOL) FORCE + @[ -n "$(SLOTLDR_KEY_SRC)" ] || { echo "slot-loader: give CK_SLOT_KEYS= or CK_TEST_SLOT_KEY=1 (TEST only)"; exit 1; } + @mkdir -p $(dir $@) + @$(SLOT_TOOL) keys-c $(SLOTLDR_KEY_SRC) --out $@ +$(SLOTLDR_DIR)/obj/slot_keys.o: $(SLOTLDR_KEYS_C) + @mkdir -p $(dir $@) + $(KCC) $(SLOTLDR_CFLAGS) -c -o $@ $< +$(SLOTLDR_ELF): $(SLOTLDR_OBJS) $(BOOT)/image.ld + @if grep -nE -- '->(RuntimeServices|ExitBootServices|SetVariable|GetVariable|SetWatchdogTimer)' $(BOOT)/slot_loader.c; then \ + echo "slot_loader.c calls a service the slot loader must never call"; exit 1; fi + $(call link_image,$@,$(SLOTLDR_OBJS)) + @k=$$($(KNM) $@ | grep -E ' [TtDdBbRr] (ck_kernel_entry|kmain|ck_boot_model_load|ck_printf)$$' || true); \ + if [ -n "$$k" ]; then echo "SLOTLDR links kernel objects: $$k"; rm -f $@; exit 1; fi + @if [ "$(strip $(CK_TEST_SLOT_KEY))" = 1 ]; then \ + grep -aqF "TEST-ONLY key" $@ || { echo "TEST-key SLOTLDR lacks its TEST-ONLY announcement"; rm -f $@; exit 1; }; \ + elif grep -aqF "TEST-ONLY" $@; then echo "owner-key SLOTLDR carries a TEST-ONLY note"; rm -f $@; exit 1; fi +$(SLOTLDR_EFI): $(SLOTLDR_ELF) + $(call pe_image,$<,$@) +slot-loader: $(SLOTLDR_EFI) +SLOTLDR_FIXTURE_KEYS := $(KDIR)/tests/fixtures/owner/TEST-FIXTURE-owner-pubkeys.txt +slot-loader-check: + @$(MAKE) -s --no-print-directory OUT=$(OUT)/slotldr-check-test CK_TEST_SLOT_KEY=1 slot-loader >/dev/null + @grep -aqF "TEST-ONLY key" $(OUT)/slotldr-check-test/SLOTLDR.EFI + @$(MAKE) -s --no-print-directory OUT=$(OUT)/slotldr-check-owner CK_SLOT_KEYS=$(SLOTLDR_FIXTURE_KEYS) slot-loader >/dev/null + @if grep -aqF "TEST-ONLY" $(OUT)/slotldr-check-owner/SLOTLDR.EFI; then echo "SLOT_LOADER_BUILD: FAIL owner-key loader carries TEST-ONLY"; exit 1; fi + @for c in "CK_HARDWARE_STAGING=1 CK_TEST_SLOT_KEY=1|cannot be combined with CK_HARDWARE_STAGING" \ + "CK_TEST_SLOT_KEY=1 CK_SLOT_KEYS=$(SLOTLDR_FIXTURE_KEYS)|are exclusive" \ + "CK_SLOT_KEYS=$(SLOTLDR_FIXTURE_KEYS:.txt=.missing)|cannot read the keys file" \ + "|give CK_SLOT_KEYS"; do \ + args=$${c%%|*}; want=$${c#*|}; \ + if $(MAKE) -s --no-print-directory OUT=$(OUT)/slotldr-check-refuse $$args slot-loader >$(OUT)/slotldr-refuse.log 2>&1; then \ + echo "SLOT_LOADER_BUILD: FAIL not refused: $$args"; exit 1; fi; \ + grep -qF -- "$$want" $(OUT)/slotldr-refuse.log || { echo "SLOT_LOADER_BUILD: FAIL refused without '$$want': $$args"; cat $(OUT)/slotldr-refuse.log; exit 1; }; \ + echo "slot-loader refused as required: $${args:-no key source} ($$want)"; \ + done + @echo "SLOT_LOADER_BUILD: PASS (TEST-key and owner-key loaders built; TEST key refused with hardware staging)" + # ---- host checker for the AIENOS_CK_SCREEN gate (scripts/qemu_ck_screen_test.sh) ---- FB_CHECK_TOOL := $(OUT)/host/ck_fb_check $(FB_CHECK_TOOL): $(KDIR)/tools/ck_fb_check.c $(KDIR)/core/fbcon.c $(KDIR)/core/fbcon.h $(KDIR)/core/font8x8.h @@ -1611,5 +1714,5 @@ clean: rm -rf $(OUT) FORCE: -.PHONY: uefi-vars +.PHONY: uefi-vars slot-loader slot-loader-check .PHONY: all full test sanitize handoff-mutant acpi-dev-mutant iort-mutants smmu-l2-mutants acpi-scan clean print-kcflags udp-echo tool store-image gpt-image cont-tool owner-gen fb-check continuity-mutants continuity-resolve-mutants FORCE diff --git a/native/kernel/tools/.crumb b/native/kernel/tools/.crumb index 4659e92a..53b94860 100644 --- a/native/kernel/tools/.crumb +++ b/native/kernel/tools/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-12T16:07:30Z", + "compiled_at": "2026-10-12T17:02:49Z", "compiler": "crumb-compile/1", - "digest": "sha256:3136405835c1c24b08ed7d35be097c73761632e89dfe81510a2315c0030b5ab7", + "digest": "sha256:2443251e4e44b6fb0efc7889c87eb6fa5510eb06d7ed84f64ec487621a2b859e", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "files": 18, - "generated_at_commit": "f56f72b2bdf52b7f2347c6548e42459e465558a0", - "source_tree": "sha256:ea97d599f85b682753158aae34deb974b23d342d27c6ece029910ed13ca5d64d" + "generated_at_commit": "d7c6c9c90f6711626732bcb168f95cbf45671685", + "source_tree": "sha256:b535e6d5085aa3b6122ad018540624319ae809928b63bbab47464f6f8e81c149" }, "owner_lane": "", "provenance": { diff --git a/native/kernel/tools/ck_gpt_image.c b/native/kernel/tools/ck_gpt_image.c index 50ae69f6..230fd5cf 100644 --- a/native/kernel/tools/ck_gpt_image.c +++ b/native/kernel/tools/ck_gpt_image.c @@ -14,6 +14,10 @@ * no-gpt sentinel fills only: no protective MBR, no GPT * esp-model ESP_MIB MODEL_FILE ESP + model in 3 out-of-order * extents (see esp_model below; model ingest gate) + * slots one AIENOS image slots partition [1, M-1) (type + * CK_SLOT_PART_TYPE_TEXT, native/boot/slot_format.h), left + * zero; prints "gpt_image bs=B blocks=N slots_first_lba=F + * slots_last_lba=L" (slot loader gate) * CORRUPTION: bad-primary-crc bad-backup-crc bad-primary-entries * bad-backup-entries no-pmbr * Prints one line: "gpt_image bs=B blocks=N aienos_first_lba=F @@ -32,6 +36,7 @@ #include "disk_file.h" #include "disk_part.h" #include "gpt_write.h" +#include "../../boot/slot_format.h" static int usage(void) { @@ -113,6 +118,15 @@ static int cmd_create(int argc, char **argv) const char *lay = argv[5]; unsigned flags = 0; if (!strcmp(lay, "esp-model")) return esp_model(argc, argv, bs, blocks, per, flags); + if (!strcmp(lay, "slots")) { + static const uint8_t slots_type[16] = CK_SLOT_PART_TYPE_BYTES; + gw_part sp = {slots_type, 1 * per, (mib - 1u) * per - 1u, "AIENOS-SLOTS", 0}; + if (argc != 6) return usage(); + if (gw_write(argv[2], bs, blocks, &sp, 1, flags)) return 1; + printf("gpt_image bs=%u blocks=%llu slots_first_lba=%llu slots_last_lba=%llu\n", bs, + (unsigned long long)blocks, (unsigned long long)sp.first, (unsigned long long)sp.last); + return 0; + } for (int i = 6; i < argc; i++) { if (!strcmp(argv[i], "bad-primary-crc")) flags |= GW_BAD_PRIMARY_CRC; else if (!strcmp(argv[i], "bad-backup-crc")) flags |= GW_BAD_BACKUP_CRC; diff --git a/native/kernel/tools/ck_slot_tool.c b/native/kernel/tools/ck_slot_tool.c index b6b88fde..99358a00 100644 --- a/native/kernel/tools/ck_slot_tool.c +++ b/native/kernel/tools/ck_slot_tool.c @@ -14,7 +14,7 @@ * (signer_id = SHA-256(pubkey) lies inside the signed bytes, so it is set * before the bytes are emitted; attach-sig checks the same bytes) * ck_slot_tool attach-sig M --sig SIG --out M2 --pubkey HEX64 - * ck_slot_tool sign-test M --out M2 RFC 8032 TEST 1 key. NEVER for hardware. + * ck_slot_tool sign-test M --out M2 [--test2] RFC 8032 TEST 1 (or TEST 2) key. NEVER for hardware. * ck_slot_tool verify M --image F (--keys FILE | --test-key) [--cap BYTES] * FILE: tools/ck_owner_gen.c format, "owner_root_ed25519 <64 hex>" * ck_slot_tool control-init --active 0|1 --out C @@ -28,8 +28,14 @@ * ck_slot_tool control-commit --region F --record C torn-slot commit into a * 4-unit region file (512-byte blocks), as the kernel/loader would * ck_slot_tool control-recover --region F --out C + * ck_slot_tool keys-c (--keys FILE | --test-key) --out F.c trusted-key table + * compiled into SLOTLDR.EFI (native/boot/slot_loader.c) + * ck_slot_tool slots-image --disk IMG --bs 512|4096 --first LBA --last LBA + * [--a M,IMG] [--b M,IMG] [--control C] write a slots partition (control + * region, manifests, images) into a disk image where SLOTLDR.EFI reads it * Every refusal prints "refused: " and exits 1. */ #include +#include #include #include #include @@ -46,6 +52,10 @@ static const uint8_t TEST1_SEED[32] = { static const uint8_t TEST1_PK[32] = { 0xd7, 0x5a, 0x98, 0x01, 0x82, 0xb1, 0x0a, 0xb7, 0xd5, 0x4b, 0xfe, 0xd3, 0xc9, 0x64, 0x07, 0x3a, 0x0e, 0xe1, 0x72, 0xf3, 0xda, 0xa6, 0x23, 0x25, 0xaf, 0x02, 0x1a, 0x68, 0xf7, 0x07, 0x51, 0x1a}; +/* RFC 8032 section 7.1 TEST 2 seed: the "unknown signer" of the slot loader gate. */ +static const uint8_t TEST2_SEED[32] = { + 0x4c, 0xcd, 0x08, 0x9b, 0x28, 0xff, 0x96, 0xda, 0x9d, 0xb6, 0xc3, 0x46, 0xec, 0x11, 0x4e, 0x0f, + 0x5b, 0x8a, 0x31, 0x9f, 0x35, 0xab, 0xa6, 0x24, 0xda, 0x8c, 0xf6, 0xed, 0x4f, 0xb8, 0xa6, 0xfb}; static const uint8_t TEST2_PK[32] = { 0x3d, 0x40, 0x17, 0xc3, 0xe8, 0x43, 0x89, 0x5a, 0x92, 0xb7, 0x0a, 0xa7, 0x4d, 0x1b, 0x7e, 0xbc, 0x9c, 0x98, 0x2c, 0xcf, 0x2e, 0xc4, 0x96, 0x8c, 0xc0, 0xcd, 0x55, 0xf1, 0x2a, 0xf4, 0x66, 0x0c}; @@ -375,6 +385,50 @@ static void bind_dev(ts_device *dev, struct filedev *d) dev->flush = fd_flush; } +/* ---- keys-c rendering ------------------------------------------------------- */ +/* Bounded append: on truncation or an encoding error *n becomes cap, which the + * caller refuses as "key table too large"; never writes past buf[cap - 1] and + * never computes a size from an offset past cap. */ +static void app(char *buf, size_t cap, size_t *n, const char *fmt, ...) +{ + va_list ap; + int r; + if (*n >= cap) + return; + va_start(ap, fmt); + r = vsnprintf(buf + *n, cap - *n, fmt, ap); + va_end(ap); + if (r < 0 || (size_t)r >= cap - *n) + *n = cap; + else + *n += (size_t)r; +} + +/* The C key table SLOTLDR.EFI is built with. Returns its length, or cap when + * it does not fit (the caller refuses). */ +static size_t keys_c_render(char *text, size_t cap, const uint8_t (*keys)[32], unsigned nkeys, int test) +{ + size_t n = 0; + app(text, cap, &n, + "/* Generated by ck_slot_tool keys-c (native/kernel/Makefile slot-loader). Do not edit. */\n" + "#include \n" + "const unsigned ck_slot_loader_nkeys = %u;\n" + "const char ck_slot_loader_key_note[] = \"%s\";\n" + "const uint8_t ck_slot_loader_keys[%u][32] = {\n", + nkeys, + test ? "TEST-ONLY key (RFC 8032 TEST 1): never for hardware" + : "trusted keys: owner_root_ed25519 from CK_SLOT_KEYS", + nkeys); + for (unsigned k = 0; k < nkeys; k++) { + app(text, cap, &n, " {"); + for (unsigned i = 0; i < 32; i++) + app(text, cap, &n, "0x%02x%s", keys[k][i], i == 31 ? "" : ", "); + app(text, cap, &n, "},\n"); + } + app(text, cap, &n, "};\n"); + return n; +} + /* ---- self-test ------------------------------------------------------------- */ static unsigned g_checks, g_fails; @@ -415,6 +469,9 @@ static int selftest(void) } aienos_ed25519_public_key(pk, TEST1_SEED); check(memcmp(pk, TEST1_PK, 32) == 0, "TEST 1 public key derives from the seed"); + aienos_ed25519_public_key(pk, TEST2_SEED); + check(memcmp(pk, TEST2_PK, 32) == 0, "TEST 2 public key derives from the seed"); + aienos_ed25519_public_key(pk, TEST1_SEED); memcpy(keys[0], TEST1_PK, 32); fill_manifest(&good, img, sizeof img, 7, 5, 3, "0123456789abcdef0123456789abcdef01234567", @@ -628,6 +685,20 @@ static int selftest(void) check(ck_slot_control_check(&back, &why) == 0, "recovered control is structurally valid"); } + /* keys-c rendering: bounded, refuses instead of overflowing. */ + { + static char kt[8192], small[sizeof kt]; + size_t full = keys_c_render(kt, sizeof kt, &TEST1_PK, 1, 1); + check(full > 0 && full < sizeof kt && strstr(kt, "TEST-ONLY key") != 0, "keys-c: TEST key table renders"); + check(keys_c_render(small, full + 1, &TEST1_PK, 1, 1) == full && memcmp(small, kt, full) == 0, + "keys-c: exact-fit buffer gives the same bytes"); + check(keys_c_render(small, full, &TEST1_PK, 1, 1) == full, "keys-c: one byte short is refused (length = cap)"); + check(keys_c_render(small, 64, &TEST1_PK, 1, 1) == 64, "keys-c: a 64-byte buffer is refused (length = cap)"); + memset(keys, 0x5a, sizeof keys); + check(keys_c_render(small, 512, (const uint8_t (*)[32])keys, MAX_KEYS, 0) == 512, + "keys-c: eight keys into 512 bytes refused, no write past the buffer"); + } + printf("CK_SLOT_TOOL_SELFTEST: %s (%u checks, %u failures)\n", g_fails ? "FAIL" : "PASS", g_checks, g_fails); return g_fails ? 1 : 0; } @@ -730,12 +801,13 @@ static int cmd_sign_test(int argc, char **argv) return refuse("sign-test M --out M2"); if (load_manifest(argv[2], &m) != 0) return 1; - sign_manifest(&m, TEST1_SEED); + sign_manifest(&m, flag(argc, argv, "--test2") ? TEST2_SEED : TEST1_SEED); if (ck_slot_manifest_check(&m, &why) != 0) return refuse(why); if (write_file(out, &m, sizeof m) != 0) return refuse("cannot write the manifest"); - printf("signed with RFC 8032 TEST 1: tests only, NEVER for hardware (ck_owner_gen refuses this key)\n"); + printf("signed with RFC 8032 TEST %d: tests only, NEVER for hardware (ck_owner_gen refuses this key)\n", + flag(argc, argv, "--test2") ? 2 : 1); return 0; } @@ -1051,6 +1123,148 @@ static int cmd_control_recover(int argc, char **argv) return 0; } +/* keys-c: the trusted-key table SLOTLDR.EFI is built with (native/kernel + * Makefile slot-loader). --keys FILE takes owner keys (TEST keys refused by + * load_keys); --test-key embeds RFC 8032 TEST 1 and a TEST-ONLY note that the + * Makefile's slot loader checks look for. Writes F only when it changes. */ +static int cmd_keys_c(int argc, char **argv) +{ + uint8_t keys[MAX_KEYS][32]; + unsigned nkeys = 0; + const char *out = opt(argc, argv, "--out"), *kf = opt(argc, argv, "--keys"), *why; + int test = flag(argc, argv, "--test-key"); + char text[8192]; + size_t n = 0; + uint8_t *old; + size_t oldn; + if (!out || (test == !!kf)) + return refuse("keys-c (--keys FILE | --test-key) --out F.c"); + if (test) { + memcpy(keys[0], TEST1_PK, 32); + nkeys = 1; + } else if (load_keys(kf, keys, &nkeys, &why) != 0) { + return refuse(why); + } + n = keys_c_render(text, sizeof text, (const uint8_t (*)[32])keys, nkeys, test); + if (n >= sizeof text) + return refuse("key table too large"); + if (read_file(out, &old, &oldn) == 0) { + int same = oldn == n && memcmp(old, text, n) == 0; + free(old); + if (same) { + printf("keys-c: %u key(s), %s unchanged\n", nkeys, out); + return 0; + } + } + if (write_file(out, text, n) != 0) + return refuse("cannot write the key table"); + printf("keys-c: %u key(s)%s written to %s\n", nkeys, test ? " (TEST-ONLY)" : "", out); + return 0; +} + +/* slots-image: write a slots partition's content into a disk image, at the + * partition's LBAs, exactly where SLOTLDR.EFI reads it (slot_format.h + * geometry): the control region (zeroed, then the record committed through + * the torn-slot protocol when --control is given), and for each slot its + * manifest unit and image (or a zero manifest unit when absent). Test and + * provisioning tooling for the QEMU gate scripts/qemu_ck_slot_loader_test.sh. + * slots-image --disk IMG --bs 512|4096 --first LBA --last LBA + * [--a M,IMG] [--b M,IMG] [--control C] + * Prints "slots: units=U cap_units=C image_cap=B control_off=O a_off=X b_off=Y" + * (byte offsets in the disk image). */ +static int put_slot(FILE *f, const char *spec, uint64_t off, uint64_t cap, const char *name) +{ + static uint8_t zero[CK_SLOT_UNIT]; + struct ck_slot_manifest m; + uint8_t *img = 0; + size_t len = 0; + char path[1024]; + const char *comma; + if (fseeko(f, (off_t)off, SEEK_SET) != 0) + return refuse("seek failed"); + if (!spec) { + if (fwrite(zero, 1, sizeof zero, f) != sizeof zero) + return refuse("write failed"); + printf("slot %s: empty (zero manifest unit)\n", name); + return 0; + } + comma = strchr(spec, ','); + if (!comma || (size_t)(comma - spec) >= sizeof path) + return refuse("slot spec must be MANIFEST,IMAGE"); + memcpy(path, spec, (size_t)(comma - spec)); + path[comma - spec] = 0; + if (load_manifest(path, &m) != 0) + return 1; + if (read_file(comma + 1, &img, &len) != 0) + return refuse("cannot read the slot image"); + if (len > cap) { + free(img); + return refuse("slot image larger than the slot capacity"); + } + if (fwrite(&m, 1, sizeof m, f) != sizeof m || fwrite(img, 1, len, f) != len) { + free(img); + return refuse("write failed"); + } + if (len % CK_SLOT_UNIT && fwrite(zero, 1, CK_SLOT_UNIT - len % CK_SLOT_UNIT, f) != CK_SLOT_UNIT - len % CK_SLOT_UNIT) { + free(img); + return refuse("write failed"); + } + free(img); + printf("slot %s: manifest + %zu image bytes\n", name, len); + return 0; +} + +static int cmd_slots_image(int argc, char **argv) +{ + const char *disk = opt(argc, argv, "--disk"), *cf = opt(argc, argv, "--control"); + uint64_t bsz, first, last; + static uint8_t region[CK_SLOT_CONTROL_UNITS * CK_SLOT_UNIT]; + if (!disk || parse_u64(opt(argc, argv, "--bs"), &bsz) != 0 || (bsz != 512 && bsz != 4096) || + parse_u64(opt(argc, argv, "--first"), &first) != 0 || parse_u64(opt(argc, argv, "--last"), &last) != 0 || + last < first) + return refuse("slots-image --disk IMG --bs 512|4096 --first LBA --last LBA [--a M,IMG] [--b M,IMG] [--control C]"); + uint64_t units = (last - first + 1) * bsz / CK_SLOT_UNIT, cap_units = ck_slot_cap_units(units); + if (cap_units < CK_SLOT_MIN_CAP_UNITS) + return refuse("partition too small for two slots"); + uint64_t base = first * bsz, cap = (cap_units - 1) * CK_SLOT_UNIT; + uint64_t a_off = base + ck_slot_manifest_unit(0, cap_units) * CK_SLOT_UNIT; + uint64_t b_off = base + ck_slot_manifest_unit(1, cap_units) * CK_SLOT_UNIT; + memset(region, 0, sizeof region); + if (cf) { + struct ck_slot_control c; + struct filedev fd = {region, sizeof region}; + ts_device dev; + ts_region r; + uint8_t rec[TS_RECORD_BYTES]; + uint64_t seq; + if (load_control(cf, &c) != 0) + return 1; + bind_dev(&dev, &fd); + if (ts_open(&r, &dev, 0) != TS_OK || ts_recover(&r, rec, &seq, 0) != TS_EMPTY || + ts_commit(&r, (const uint8_t *)&c) != TS_OK) + return refuse("torn-slot commit into the fresh region failed"); + print_control(&c); + } + FILE *f = fopen(disk, "r+b"); + if (!f) + return refuse("cannot open the disk image"); + if (fseeko(f, (off_t)base, SEEK_SET) != 0 || fwrite(region, 1, sizeof region, f) != sizeof region) { + fclose(f); + return refuse("control region write failed"); + } + if (put_slot(f, opt(argc, argv, "--a"), a_off, cap, "A") != 0 || + put_slot(f, opt(argc, argv, "--b"), b_off, cap, "B") != 0) { + fclose(f); + return 1; + } + if (fclose(f) != 0) + return refuse("disk image close failed"); + printf("slots: units=%llu cap_units=%llu image_cap=%llu control_off=%llu a_off=%llu b_off=%llu\n", + (unsigned long long)units, (unsigned long long)cap_units, (unsigned long long)cap, + (unsigned long long)base, (unsigned long long)a_off, (unsigned long long)b_off); + return 0; +} + int main(int argc, char **argv) { if (argc < 2) @@ -1079,6 +1293,10 @@ int main(int argc, char **argv) return cmd_select(argc, argv); if (strcmp(argv[1], "control-commit") == 0) return cmd_control_commit(argc, argv); + if (strcmp(argv[1], "keys-c") == 0) + return cmd_keys_c(argc, argv); + if (strcmp(argv[1], "slots-image") == 0) + return cmd_slots_image(argc, argv); if (strcmp(argv[1], "control-recover") == 0) return cmd_control_recover(argc, argv); return refuse("unknown mode"); diff --git a/scripts/.crumb b/scripts/.crumb index b7a7a11e..ecc91bd0 100644 --- a/scripts/.crumb +++ b/scripts/.crumb @@ -7,14 +7,14 @@ "generated": { "children": [], "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "compiled_at": "2026-10-12T16:07:30Z", + "compiled_at": "2026-10-12T17:02:49Z", "compiler": "crumb-compile/1", - "digest": "sha256:654df809529c9ef3d80af6141a30543a957e3ebde6010d9726519f7fa2a24138", + "digest": "sha256:472997503f5d637af1f91e8eab7ecfe10ddee01e79bd42fb46ba245f061c3607", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 86, - "generated_at_commit": "f56f72b2bdf52b7f2347c6548e42459e465558a0", - "source_tree": "sha256:4104c7c8197e5e1acabf1ccda571c9c116fba7b88bd340f017459bee27d23d7d" + "files": 87, + "generated_at_commit": "d7c6c9c90f6711626732bcb168f95cbf45671685", + "source_tree": "sha256:6135f7ced35ec6d2f1cd76121c425b428064f5c344d255c1c6e760f1eca6fb76" }, "owner_lane": "", "provenance": { diff --git a/scripts/ck_gates.sh b/scripts/ck_gates.sh index 9a57a968..87bae261 100755 --- a/scripts/ck_gates.sh +++ b/scripts/ck_gates.sh @@ -12,11 +12,12 @@ # scripts/qemu_ck_infer_test.sh, scripts/qemu_ck_screen_test.sh, # scripts/qemu_ck_console_test.sh, # scripts/qemu_ck_rollback_test.sh, scripts/qemu_ck_osc_unit_test.sh, -# scripts/qemu_ck_osc_launch_test.sh, scripts/qemu_ck_osh_core_test.sh, scripts/qemu_ck_osh_op_test.sh), and prints +# scripts/qemu_ck_osc_launch_test.sh, scripts/qemu_ck_osh_core_test.sh, scripts/qemu_ck_osh_op_test.sh, +# scripts/qemu_ck_slot_loader_test.sh), and prints # one line per gate: # AIENOS_CK_: PASS|FAIL|NOT_RUN [(reason)] # for M1 M3 SMMU NVME_SHUTDOWN P2_ARTIFACT M0_ROLLBACK OSC_UNIT OSC_LAUNCH OSH_CORE OSH_OP M4_NVME M4_STORE M4_STORE_CRASH -# M4_CONTINUITY M4_RECOVERY M4_ALLEN ARGUS1_REVOKE KEYBOARD NET SMP DISK_LAYOUT FPU INFER SCREEN CONSOLE. Gates with no C +# M4_CONTINUITY M4_RECOVERY M4_ALLEN ARGUS1_REVOKE KEYBOARD NET SMP DISK_LAYOUT FPU INFER SCREEN CONSOLE SLOT_LOADER. Gates with no C # implementation print NOT_RUN (MISSING_IMPLEMENTATION: ) and never # run anything. A missing child script, a child that reports NOT_RUN, a child # that prints no verdict line, or a PASS line contradicted by the child's exit @@ -67,6 +68,7 @@ set -uo pipefail # osc_launch -> verdict line from scripts/qemu_ck_osc_launch_test.sh (OSC unit task launch, OSC_UNIT_ARTIFACT v1 section 9; QEMU, TEST signer, not physical) # osh_core -> verdict line from scripts/qemu_ck_osh_core_test.sh (OSH shell core as EL0 tasks, step trace equals Linux; QEMU, TEST signer, not physical) # osh_op -> verdict line from scripts/qemu_ck_osh_op_test.sh (a real capability-authorized OSH operation, klog; QEMU, TEST signer, not physical) +# slots -> verdict line from scripts/qemu_ck_slot_loader_test.sh (SLOTLDR.EFI signed A/B slot loader: bounded tries, rollback, refusals; QEMU, TEST signer, not physical) # missing -> NOT_RUN (MISSING_IMPLEMENTATION), never run, never PASS # =========================================================================== CK_GATE_TABLE=' @@ -95,8 +97,9 @@ FPU|fpu|- INFER|infer|- SCREEN|screen|- CONSOLE|console|- +SLOT_LOADER|slots|- ' -CHILDREN=(boot store net artifact smp crash disk cont recov allen kbd fpu infer screen console rollback osc osc_launch osh_core osh_op) +CHILDREN=(boot store net artifact smp crash disk cont recov allen kbd fpu infer screen console rollback osc osc_launch osh_core osh_op slots) # =========================================================================== repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -154,6 +157,7 @@ set_default_children() { [osc_launch]="${repo_root}/scripts/qemu_ck_osc_launch_test.sh" [osh_core]="${repo_root}/scripts/qemu_ck_osh_core_test.sh" [osh_op]="${repo_root}/scripts/qemu_ck_osh_op_test.sh" + [slots]="${repo_root}/scripts/qemu_ck_slot_loader_test.sh" ) } @@ -387,7 +391,7 @@ self_test() { } scenario() { # NAME BOOT_SCRIPT STORE_SCRIPT [NET_SCRIPT] [ARTIFACT_SCRIPT] [SMP_SCRIPT] [CRASH_SCRIPT] [DISK_SCRIPT] (absent: missing) scen="$1" - declare -gA child_script=([boot]="$2" [store]="$3" [net]="${4:-${tmp}/kids/net_not_present.sh}" [artifact]="${5:-${tmp}/kids/no_artifact_child.sh}" [smp]="${6:-${tmp}/kids/no_smp_child.sh}" [crash]="${7:-${tmp}/kids/no_crash_child.sh}" [disk]="${8:-${tmp}/kids/no_disk_child.sh}" [cont]="${tmp}/kids/no_cont_child.sh" [recov]="${tmp}/kids/no_recov_child.sh" [allen]="${tmp}/kids/no_allen_child.sh" [kbd]="${kbd_kid:-${tmp}/kids/no_kbd_child.sh}" [fpu]="${tmp}/kids/no_fpu_child.sh" [infer]="${tmp}/kids/no_infer_child.sh" [screen]="${tmp}/kids/no_screen_child.sh" [console]="${console_kid:-${tmp}/kids/no_console_child.sh}" [rollback]="${rollback_kid:-${tmp}/kids/no_rollback_child.sh}" [osc]="${osc_kid:-${tmp}/kids/no_osc_child.sh}" [osc_launch]="${osc_launch_kid:-${tmp}/kids/no_osc_launch_child.sh}" [osh_core]="${osh_core_kid:-${tmp}/kids/no_osh_core_child.sh}" [osh_op]="${osh_op_kid:-${tmp}/kids/no_osh_op_child.sh}") + declare -gA child_script=([boot]="$2" [store]="$3" [net]="${4:-${tmp}/kids/net_not_present.sh}" [artifact]="${5:-${tmp}/kids/no_artifact_child.sh}" [smp]="${6:-${tmp}/kids/no_smp_child.sh}" [crash]="${7:-${tmp}/kids/no_crash_child.sh}" [disk]="${8:-${tmp}/kids/no_disk_child.sh}" [cont]="${tmp}/kids/no_cont_child.sh" [recov]="${tmp}/kids/no_recov_child.sh" [allen]="${tmp}/kids/no_allen_child.sh" [kbd]="${kbd_kid:-${tmp}/kids/no_kbd_child.sh}" [fpu]="${tmp}/kids/no_fpu_child.sh" [infer]="${tmp}/kids/no_infer_child.sh" [screen]="${tmp}/kids/no_screen_child.sh" [console]="${console_kid:-${tmp}/kids/no_console_child.sh}" [rollback]="${rollback_kid:-${tmp}/kids/no_rollback_child.sh}" [osc]="${osc_kid:-${tmp}/kids/no_osc_child.sh}" [osc_launch]="${osc_launch_kid:-${tmp}/kids/no_osc_launch_child.sh}" [osh_core]="${osh_core_kid:-${tmp}/kids/no_osh_core_child.sh}" [osh_op]="${osh_op_kid:-${tmp}/kids/no_osh_op_child.sh}" [slots]="${slots_kid:-${tmp}/kids/no_slots_child.sh}") run_children 2>/dev/null evaluate_table >"${tmp}/${scen}.out" } @@ -403,8 +407,8 @@ self_test() { "$(fake smpA 0 'PASS 3 secondary cores checked in' 'AIENOS_CK_SMP_MUTATION: FAIL' 'AIENOS_CK_SMP: PASS')" expect M1 PASS; expect M3 PASS; expect M4_NVME PASS; expect M4_STORE PASS; expect ARGUS1_REVOKE PASS; expect SMMU PASS; expect NVME_SHUTDOWN PASS; expect NET PASS; expect SMP PASS; expect_missing_all count_rows - [[ "${n_pass}/${n_fail}/${n_notrun}/${n_total}" == "9/0/16/25" && ${overall} == NOT_ALL_GATES_PASS ]] \ - && ok "A: counts 9/0/16 of 25, verdict NOT_ALL_GATES_PASS" || bad "A: counts ${n_pass}/${n_fail}/${n_notrun}/${n_total} ${overall}" + [[ "${n_pass}/${n_fail}/${n_notrun}/${n_total}" == "9/0/17/26" && ${overall} == NOT_ALL_GATES_PASS ]] \ + && ok "A: counts 9/0/17 of 26, verdict NOT_ALL_GATES_PASS" || bad "A: counts ${n_pass}/${n_fail}/${n_notrun}/${n_total} ${overall}" [[ "$(nvme_dma_mode)" == "Confined (QEMU SMMUv3 stage 1, out-of-window DMA faulted); no-SMMU boot denied (NoSmmu); TEST-ONLY bypass image checked separately" ]] && ok "A: confined DMA mode recorded from the store PASS lines" || bad "A: dma mode '$(nvme_dma_mode)'" grep -qxF "AIENOS_CK_M4_NVME: PASS (${M4_NVME_PASS_NOTE})" "${tmp}/A.out" \ && ok "A: M4_NVME PASS line carries the confined-mode note" || bad "A: M4_NVME PASS line lacks the note" @@ -416,7 +420,7 @@ self_test() { && ok "a missing-source row is NOT_RUN (MISSING_IMPLEMENTATION: reason)" || bad "missing-source row not NOT_RUN" grep -q '^AIENOS_CK_KEYBOARD: NOT_RUN' "${tmp}/A.out" \ && ok "A: KEYBOARD claimed PASS by the store child stays NOT_RUN without its own child" || bad "A: KEYBOARD line wrong" - [[ "$(grep -c '^AIENOS_CK_[A-Z0-9_]*: ' "${tmp}/A.out")" == 25 ]] && ok "A: exactly 25 verdict lines" || bad "A: verdict line count" + [[ "$(grep -c '^AIENOS_CK_[A-Z0-9_]*: ' "${tmp}/A.out")" == 26 ]] && ok "A: exactly 26 verdict lines" || bad "A: verdict line count" # B: boot FAIL; store script missing -> its three gates NOT_RUN, never PASS. scenario B "$(fake bootB 1 'FAIL kernel: alive' 'AIENOS_CK_M3: FAIL' 'AIENOS_CK_M1: FAIL')" "${tmp}/kids/does_not_exist.sh" @@ -587,10 +591,10 @@ self_test() { # Restore the clean-tree receipt as the one the checks below look at. write_receipt if command -v jq >/dev/null; then - jq -e '.physical == "NOT_RUN" and (.gates | length) == 25 and .verdict == "NOT_ALL_GATES_PASS" + jq -e '.physical == "NOT_RUN" and (.gates | length) == 26 and .verdict == "NOT_ALL_GATES_PASS" and ([.gates[] | select(.id == "M1")][0].verdict == "PASS") and ([.gates[] | select(.id == "ARGUS1_REVOKE")][0].verdict == "FAIL") - and (.children | length) == 20 and .commit_subject == "quote \" backslash \\ tab\tend"' "${receipt_path}" >/dev/null \ + and (.children | length) == 21 and .commit_subject == "quote \" backslash \\ tab\tend"' "${receipt_path}" >/dev/null \ && ok "receipt is valid JSON (jq) with expected fields" || bad "receipt JSON invalid or fields wrong" else echo "NOT_RUN jq not installed; JSON validity not machine-checked"; jq_skipped=1 @@ -603,18 +607,18 @@ self_test() { bad "an existing receipt was overwritten or the clash was not refused" fi - # The gate table parses: 25 rows, known sources, reasons only on missing rows. + # The gate table parses: 26 rows, known sources, reasons only on missing rows. local g s w rows=0 tbad=0 while IFS='|' read -r g s w; do [[ -n "${g}" ]] || continue rows=$((rows + 1)) case "${s}" in - boot|store|net|artifact|smp|crash|disk|cont|recov|allen|kbd|fpu|infer|screen|console|rollback|osc|osc_launch|osh_core|osh_op) [[ "${w}" == - ]] || tbad=1 ;; + boot|store|net|artifact|smp|crash|disk|cont|recov|allen|kbd|fpu|infer|screen|console|rollback|osc|osc_launch|osh_core|osh_op|slots) [[ "${w}" == - ]] || tbad=1 ;; missing) [[ -n "${w}" && "${w}" != - ]] || tbad=1 ;; *) tbad=1 ;; esac done <<<"${CK_GATE_TABLE}" - [[ ${tbad} == 0 && ${rows} == 25 ]] && ok "gate table: 25 rows well-formed" || bad "gate table malformed (${rows} rows)" + [[ ${tbad} == 0 && ${rows} == 26 ]] && ok "gate table: 26 rows well-formed" || bad "gate table malformed (${rows} rows)" # Dirty-tree refusal, end to end, on a private clone (never this tree). # Both runs stop before any child script (no QEMU). diff --git a/scripts/qemu_ck_slot_loader_test.sh b/scripts/qemu_ck_slot_loader_test.sh new file mode 100755 index 00000000..b375e8b4 --- /dev/null +++ b/scripts/qemu_ck_slot_loader_test.sh @@ -0,0 +1,299 @@ +#!/usr/bin/env bash +# qemu_ck_slot_loader_test.sh -- QEMU gate for SLOTLDR.EFI, the AIENOS signed +# A/B image slot loader (native/boot/slot_loader.c; native v1 plan P11 cut 2a, +# gate N7; docs/NATIVE_IMAGE_SLOTS.md section 7). QEMU is an emulator: a PASS +# here qualifies nothing physical (hardware NOT_RUN). +# +# Setup: the boot disk is a FAT directory (fat:rw:, as scripts/qemu_ck_boot_test.sh) +# whose EFI/BOOT/BOOTAA64.EFI is SLOTLDR.EFI built with CK_TEST_SLOT_KEY=1 +# (RFC 8032 TEST 1). A second virtio disk holds a GPT with one slots partition +# (ck_gpt_image layout "slots"); ck_slot_tool slots-image writes the control +# record and the two slots into it. The slot payloads are the unchanged core +# image built twice, with AIENOS_COMMIT slotA- and slotB-, so +# the serial line "aienos_commit: slotX-" names the slot that really ran. The +# core image prints its report and resets (PSCI); with -no-reboot QEMU exits 0. +# Every row also asks the host tool (ck_slot_tool select, same slot_select.c) +# for its decision over the same files and requires the loader to agree. +# +# Rows (each check prints PASS or FAIL with the serial line it needed): +# 1 fresh media, control active=A, A valid, B empty: boots A (active). +# 2 B staged (tries 3): boots 1-3 boot B (candidate_try) with tries 2, 1, 0 +# committed before the jump and read back from the disk by the tool; +# boot 4 boots A (candidate_exhausted_active) and writes nothing. +# 3 B manifest flipped in its signed bytes: "signature does not verify", boots A. +# 4 B signed by RFC 8032 TEST 2 (not trusted): "signer_id names no trusted key", boots A. +# 5 B image flipped, manifest intact: "image SHA-512 mismatch", boots A. +# 6 torn control write (the staging record's body half written, no commit +# header): the previous record is recovered, boots A (active), B not tried. +# 7 both slots invalid: "recovery_required (A: ...; B: ...)", the loader returns +# to the firmware, no kernel runs (QEMU is stopped by the row timeout). +# 8 B validly signed but below the generation floor: refused, boots A. +# +# Output: one PASS/FAIL line per check, then +# AIENOS_CK_SLOT_LOADER: PASS|FAIL|NOT_RUN [(...)] +# NOT_RUN (exit 3) while the machine quiet flag is held (read only) or another +# gate holds the QEMU gate lock (scripts/lib_gate_hold.sh, aienos#278); exit 2 +# when QEMU or AAVMF is missing. No Python. +set -euo pipefail +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" +tag="AIENOS_CK_SLOT_LOADER" +code_fd="${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" +vars_fd="${AAVMF_VARS:-/usr/share/AAVMF/AAVMF_VARS.fd}" +command -v qemu-system-aarch64 >/dev/null || { echo "qemu-system-aarch64 not installed"; echo "${tag}: NOT_RUN (no qemu-system-aarch64)"; exit 2; } +[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; echo "${tag}: NOT_RUN (no AAVMF)"; exit 2; } +cross="" +if [ "$(uname -m)" != "aarch64" ]; then cross="aarch64-linux-gnu-"; fi +commit="$(git rev-parse HEAD 2>/dev/null || echo 0000000000000000000000000000000000000000)" +out="${repo_root}/target/native-kernel-slot-loader" +mk() { make -s -C native/kernel CROSS="${cross}" "$@" >/dev/null; } +mk OUT="${out}" AIENOS_COMMIT="${commit}" CK_TEST_SLOT_KEY=1 slot-loader slot-tool gpt-image +mk OUT="${out}/payload-a" AIENOS_COMMIT="slotA-${commit}" +mk OUT="${out}/payload-b" AIENOS_COMMIT="slotB-${commit}" +tool="${out}/host/ck_slot_tool" +gpt="${out}/host/ck_gpt_image" +img_a="${out}/payload-a/BOOTAA64.EFI" +img_b="${out}/payload-b/BOOTAA64.EFI" + +. "${repo_root}/scripts/lib_gate_hold.sh" +if ! gh_quiet_check || ! gh_lock_take qemu_ck_slot_loader_test "${AIENOS_GATE_MINUTES:-60}"; then + echo "NOT_RUN ${gh_why}" + echo "${tag}: NOT_RUN (${gh_why})" + exit 3 +fi +work="$(mktemp -d)" +cleanup() { + rm -rf "${work}" + gh_lock_release +} +trap cleanup EXIT + +fails=0 +checks=0 +boots=0 +qemu_secs=0 +ok() { checks=$((checks + 1)); echo "PASS $*"; } +bad() { checks=$((checks + 1)); fails=$((fails + 1)); echo "FAIL $*"; } + +# ---- fixtures: ESP, slots disk, manifests, control records ----------------------- +mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS" +touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT" +cp "${out}/SLOTLDR.EFI" "${work}/esp/EFI/BOOT/BOOTAA64.EFI" +disk="${work}/slots.img" +gline="$("${gpt}" create "${disk}" 512 48 slots)" +first="$(sed -n 's/.*slots_first_lba=\([0-9]*\).*/\1/p' <<<"${gline}")" +last="$(sed -n 's/.*slots_last_lba=\([0-9]*\).*/\1/p' <<<"${gline}")" +[[ -n "${first}" && -n "${last}" ]] || { echo "FAIL ck_gpt_image gave no slots geometry: ${gline}"; echo "${tag}: FAIL"; exit 1; } +cp "${disk}" "${work}/blank.img" + +mm() { # name image generation [policy] [--test2] + "${tool}" make-manifest --image "$2" --generation "$3" --policy-generation "${4:-0}" --commit "${commit}" \ + --provenance "slot loader gate" --timestamp 1760000000 --out "${work}/$1.u" >/dev/null + "${tool}" sign-test "${work}/$1.u" --out "${work}/$1" ${5:-} >/dev/null +} +mm A1 "${img_a}" 1 +mm A2 "${img_a}" 2 2 +mm B1 "${img_b}" 1 +mm B2 "${img_b}" 2 +mm B2k2 "${img_b}" 2 0 --test2 +"${tool}" control-init --active 0 --out "${work}/c_init_a" >/dev/null +"${tool}" stage "${work}/c_init_a" --slot 1 --generation 2 --out "${work}/c_stage_b" >/dev/null +"${tool}" control-init --active 1 --out "${work}/c_f0" >/dev/null +"${tool}" stage "${work}/c_f0" --slot 0 --generation 2 --out "${work}/c_f1" >/dev/null +"${tool}" promote "${work}/c_f1" --slot 0 --generation 2 --policy-generation 2 --out "${work}/c_f2" >/dev/null +"${tool}" stage "${work}/c_f2" --slot 1 --generation 3 --out "${work}/c_floor" >/dev/null + +geo="" +slots() { # slots-image args...: fresh disk, then write + cp "${work}/blank.img" "${disk}" + geo="$("${tool}" slots-image --disk "${disk}" --bs 512 --first "${first}" --last "${last}" "$@" | grep "^slots:" || true)" + [[ -n "${geo}" ]] || bad "slots-image refused: $*" +} +geo_val() { sed -n "s/.* $1=\([0-9]*\).*/\1/p" <<<"${geo}"; } +flip() { # file byte-offset: xor 0x01 + local b + b="$(od -An -tu1 -j "$2" -N1 "$1" | tr -d ' ')" + # shellcheck disable=SC2059 + printf "$(printf '\\%03o' $((b ^ 1)))" | dd of="$1" bs=1 seek="$2" conv=notrunc status=none +} +region() { # extract the 4-unit control region to $1 + dd if="${disk}" of="$1" bs=512 skip="${first}" count=32 status=none +} +ctl_now() { # the control record as the tool recovers it from the disk + region "${work}/region.now" + "${tool}" control-recover --region "${work}/region.now" | grep -E '^(control|seq)' | tr '\n' ' ' || true +} + +# ---- one boot ------------------------------------------------------------------ +boot() { # name timeout-seconds + local name="$1" to="$2" t0 rc + cp "${vars_fd}" "${work}/vars.fd" + t0="$(date +%s)" + set +e + timeout "${to}" qemu-system-aarch64 \ + -M virt,virtualization=on,gic-version=3 -accel tcg,thread=single -cpu max -smp 4 -m 2048 \ + -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \ + -drive if=pflash,format=raw,file="${work}/vars.fd" \ + -drive if=none,id=esp,format=raw,file=fat:rw:"${work}/esp" \ + -device virtio-blk-pci,drive=esp \ + -drive if=none,id=slots,format=raw,file="${disk}" \ + -device virtio-blk-pci,drive=slots \ + -device ramfb -display none -nic none \ + -serial file:"${work}/${name}.raw" -no-reboot + rc=$? + set -e + boots=$((boots + 1)) + qemu_secs=$((qemu_secs + $(date +%s) - t0)) + tr -d '\r' <"${work}/${name}.raw" >"${work}/${name}.log" + [[ -z "${AIENOS_LOG_DIR:-}" ]] || cp "${work}/${name}.log" "${AIENOS_LOG_DIR}/qemu_ck_slot_loader_${name}.log" + echo "boot ${name}: qemu exit ${rc} after $(( $(date +%s) - t0 )) s" + last_rc="${rc}" + last_log="${work}/${name}.log" +} +has() { # row label fixed-text + if grep -qF -- "$3" "${last_log}"; then ok "row $1: $2 [$3]"; else bad "row $1: $2 (no serial line containing: $3)"; show=1; fi +} +lacks() { # row label fixed-text + if grep -qF -- "$3" "${last_log}"; then bad "row $1: $2 (serial has: $3)"; show=1; else ok "row $1: $2 [no \"$3\"]"; fi +} +ran() { # row slot(A|B): the payload of that slot ran to its kernel and reset cleanly + has "$1" "slot $2 payload ran" "aienos_commit: slot$2-${commit}" + has "$1" "kernel entered" "kernel: alive" + if [[ "${last_rc}" == 0 ]]; then ok "row $1: QEMU exit 0 (PSCI reset)"; else bad "row $1: QEMU exit ${last_rc}"; show=1; fi +} +ctl_is() { # row label expected-substring + local c + c="$(ctl_now)" + if grep -qF -- "$3" <<<"${c}"; then ok "row $1: $2 [disk: ${c}]"; else bad "row $1: $2 (disk control: ${c}; want ${3})"; fi +} +tool_agrees() { # row control-file a-spec b-spec expected-decision + local cap d + cap="$(geo_val image_cap)" + d="$("${tool}" select --control "$2" --a "$3" --b "$4" --test-key --cap "${cap}" | grep '^decision:' || true)" + if grep -qF -- "$5" <<<"${d}"; then ok "row $1: host tool decides the same [${d}]"; else bad "row $1: host tool decision ${d}; want ${5}"; fi +} +row_end() { # row + if [[ "${show:-0}" == 1 ]]; then echo "---- serial (last 60 lines) of row $1 ----"; tail -n 60 "${last_log}"; fi + show=0 +} + +A1="${work}/A1,${img_a}" +A2="${work}/A2,${img_a}" +B1="${work}/B1,${img_b}" +B2="${work}/B2,${img_b}" +B2k2="${work}/B2k2,${img_b}" + +# ---- row 1: fresh media, A valid, B empty -------------------------------------- +slots --a "${A1}" --control "${work}/c_init_a" +boot r1 180 +has 1 "TEST key announced" "slot_loader: TEST-ONLY key" +has 1 "slots partition found" "slot_loader: slots partition first_lba=${first} last_lba=${last}" +has 1 "empty slot B refused" "slot_loader: slot B refused (bad magic)" +has 1 "decision" "slot_loader: boot=A reason=active gen=1 tries=0 floor=0" +has 1 "chained stub sees the boot volume (LoadImage device path)" "model_map: absent (no \\EFI\\AIENOS\\MODEL.MAP on the boot volume)" +ran 1 A +ctl_is 1 "control untouched" "seq=1 control: active=0 candidate=none tries=0" +tool_agrees 1 "${work}/c_init_a" "${A1}" none "boot_slot=A reason=active loader_write=0" +row_end 1 + +# ---- row 2: candidate B, three tries, then rollback to A ----------------------- +slots --a "${A1}" --b "${B2}" --control "${work}/c_stage_b" +tool_agrees 2 "${work}/c_stage_b" "${A1}" "${B2}" "boot_slot=B reason=candidate_try loader_write=1" +for t in 2 1 0; do + boot "r2-tries${t}" 180 + has 2 "candidate try committed before the jump" "slot_loader: control committed seq=$((4 - t)) tries=${t}" + has 2 "decision" "slot_loader: boot=B reason=candidate_try gen=2 tries=${t} floor=0" + ran 2 B + ctl_is 2 "tries on disk after the boot" "seq=$((4 - t)) control: active=0 candidate=1 tries=${t} " + row_end 2 +done +region "${work}/c_exhausted.region" +"${tool}" control-recover --region "${work}/c_exhausted.region" --out "${work}/c_exhausted" >/dev/null +boot r2-exhausted 180 +has 2 "decision after the third try" "slot_loader: boot=A reason=candidate_exhausted_active gen=1 tries=0 floor=0" +lacks 2 "nothing written when exhausted" "slot_loader: control committed" +ran 2 A +ctl_is 2 "control unchanged (candidate left for the kernel to abandon, cut 2b)" "seq=4 control: active=0 candidate=1 tries=0 " +tool_agrees 2 "${work}/c_exhausted" "${A1}" "${B2}" "boot_slot=A reason=candidate_exhausted_active loader_write=0" +row_end 2 + +# ---- row 3: B manifest flipped inside the signed bytes -------------------------- +slots --a "${A1}" --b "${B2}" --control "${work}/c_stage_b" +flip "${disk}" $(( $(geo_val b_off) + 321 )) # timestamp byte 1: still well formed, signature broken +boot r3 180 +has 3 "B refused" "slot_loader: slot B refused (signature does not verify)" +has 3 "decision" "slot_loader: boot=A reason=candidate_invalid_active gen=1 tries=3 floor=0" +lacks 3 "no try consumed" "slot_loader: control committed" +ran 3 A +ctl_is 3 "control untouched" "seq=1 control: active=0 candidate=1 tries=3 " +row_end 3 + +# ---- row 4: B signed by an untrusted key (RFC 8032 TEST 2) ---------------------- +slots --a "${A1}" --b "${B2k2}" --control "${work}/c_stage_b" +boot r4 180 +has 4 "B refused" "slot_loader: slot B refused (signer_id names no trusted key)" +has 4 "decision" "slot_loader: boot=A reason=candidate_invalid_active gen=1 tries=3 floor=0" +ran 4 A +tool_agrees 4 "${work}/c_stage_b" "${A1}" "${B2k2}" "boot_slot=A reason=candidate_invalid_active loader_write=0" +row_end 4 + +# ---- row 5: B image tampered, manifest intact ------------------------------------ +slots --a "${A1}" --b "${B2}" --control "${work}/c_stage_b" +flip "${disk}" $(( $(geo_val b_off) + 4096 + 1000 )) +boot r5 180 +has 5 "B refused" "slot_loader: slot B refused (image SHA-512 mismatch)" +has 5 "decision" "slot_loader: boot=A reason=candidate_invalid_active gen=1 tries=3 floor=0" +ran 5 A +row_end 5 + +# ---- row 6: torn control write --------------------------------------------------- +slots --a "${A1}" --b "${B2}" --control "${work}/c_init_a" +region "${work}/r6.old" +cp "${work}/r6.old" "${work}/r6.full" +"${tool}" control-commit --region "${work}/r6.full" --record "${work}/c_stage_b" >/dev/null +if cmp -s -n 4096 "${work}/r6.old" "${work}/r6.full"; then torn_off=8192; else torn_off=0; fi +# Power cut after half of the new body: 2048 bytes of it land, its commit header never does. +dd if="${work}/r6.full" of="${disk}" bs=1 skip="${torn_off}" seek=$(( first * 512 + torn_off )) count=2048 \ + conv=notrunc status=none +ctl_is 6 "host tool recovers the previous record" "seq=1 control: active=0 candidate=none tries=0" +tool_agrees 6 "${work}/c_init_a" "${A1}" "${B2}" "boot_slot=A reason=active loader_write=0" +# Control: had the staging record landed whole, the decision would have been a try of B. +d6="$("${tool}" select --control "${work}/c_stage_b" --a "${A1}" --b "${B2}" --test-key --cap "$(geo_val image_cap)" | grep "^decision:" || true)" +if grep -qF "boot_slot=B reason=candidate_try" <<<"${d6}"; then ok "row 6: control: the unfinished record would have tried B [${d6}]"; else bad "row 6: control decision ${d6}; want a try of B"; fi +boot r6 180 +has 6 "previous record recovered" "slot_loader: control seq=1 active=A candidate=- tries=0" +has 6 "decision per the old record" "slot_loader: boot=A reason=active gen=1 tries=0 floor=0" +lacks 6 "B not tried" "reason=candidate_try" +ran 6 A +row_end 6 + +# ---- row 7: both slots invalid -> recovery required -------------------------------- +slots --a "${A1}" --b "${B2k2}" --control "${work}/c_init_a" +flip "${disk}" $(( $(geo_val a_off) + 4096 + 1000 )) +boot r7 "${AIENOS_SLOT_RECOVERY_TIMEOUT:-60}" +has 7 "recovery required, both reasons" "slot_loader: recovery_required (A: image SHA-512 mismatch; B: signer_id names no trusted key)" +lacks 7 "no slot started" "slot_loader: starting slot" +lacks 7 "no kernel ran" "kernel: alive" +lacks 7 "no payload ran" "aienos_commit: slot" +ctl_is 7 "control untouched" "seq=1 control: active=0 candidate=none tries=0" +row_end 7 + +# ---- row 8: B below the generation floor --------------------------------------------- +slots --a "${A2}" --b "${B1}" --control "${work}/c_floor" +boot r8 180 +has 8 "B valid but below the floor" "slot_loader: slot B valid gen=1 policy=0" +has 8 "floor named" "(below the generation floor)" +has 8 "decision" "slot_loader: boot=A reason=candidate_invalid_active gen=2 tries=3 floor=2" +lacks 8 "no try consumed" "slot_loader: control committed" +ran 8 A +tool_agrees 8 "${work}/c_floor" "${A2}" "${B1}" "boot_slot=A reason=candidate_invalid_active loader_write=0" +row_end 8 + +gh_lock_release +echo "slot loader gate: ${boots} boots, ${checks} checks, ${fails} failures, QEMU ${qemu_secs} s (commit ${commit:0:12}; QEMU only, hardware NOT_RUN)" +if [[ "${fails}" == 0 ]]; then + echo "${tag}: PASS (8 rows, ${boots} boots, ${checks} checks; QEMU, not hardware)" +else + echo "${tag}: FAIL (${fails} of ${checks} checks)" + exit 1 +fi ```