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/802e263ac6871477 # 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#204 (code only) closed derived `802e263ac6871477` #204 Imported from GitHub aien-dev/aienux#204 (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 `9807281de453ae565337e535e99f6acea2136230` · Head `49afbde8d44b8dbe3d92c03cb3e4f4cb1159f456` ### Apply it ``` git checkout -b patch-802e263ac6871477 9807281de453ae565337e535e99f6acea2136230 curl -fsSL https://interplane.io/drakestapleton/aienux/patches/802e263ac6871477.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 204 49afbde8d44b8dbe3d92c03cb3e4f4cb1159f456 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aienux","number":204,"url":"https://github.com/aien-dev/aienux/pull/204","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:35:57Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/evidence/ck_gates_160c4e5b25c8c60f7d0d97bf2dd7a8916cad11fe3772a09045b1e84af57f25a0.json b/evidence/ck_gates_160c4e5b25c8c60f7d0d97bf2dd7a8916cad11fe3772a09045b1e84af57f25a0.json new file mode 100644 index 00000000..e2c3ee73 --- /dev/null +++ b/evidence/ck_gates_160c4e5b25c8c60f7d0d97bf2dd7a8916cad11fe3772a09045b1e84af57f25a0.json @@ -0,0 +1,40 @@ +{ + "schema": "aienos.ck_gates.v1", + "started_utc": "2026-10-01T11:21:11Z", + "finished_utc": "2026-10-01T11:23:03Z", + "commit": "197b8360bfd2ee00c7b31e82b712f17f52cc599b", + "commit_subject": "ck: P2_ARTIFACT sealed artifact loader in the C kernel (QEMU gate)", + "tree_clean_before": true, + "tree_clean_after": true, + "quiet_flag": "/home/drakestapleton/workspace/.spark-quiet", + "quiet_flag_present_at_start": false, + "host": {"hostname": "spark-b87b", "arch": "aarch64", "kernel": "7.0.0-1019-nvidia", "cpu_model": "Cortex-A725;Cortex-X925"}, + "qemu": {"binary": "/usr/bin/qemu-system-aarch64", "version": "QEMU emulator version 8.2.2 (Debian 1:8.2.2+ds-0ubuntu1.18)"}, + "firmware": {"aavmf_code": "/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd", "aavmf_code_sha256": "4a4cb7f6d8106bb2a7dd8c763fab14b1810152136fc4304e5b728f0043e84f12", "aavmf_vars": "/usr/share/AAVMF/AAVMF_VARS.fd", "aavmf_vars_sha256": "b3b855c5a80310168051164986855692d1bdb06e67619856177965cd87c6774f"}, + "nvme_dma_mode": "Confined (QEMU SMMUv3 stage 1, out-of-window DMA faulted); no-SMMU boot denied (NoSmmu); TEST-ONLY bypass image checked separately", + "children": [ + {"name": "boot", "script": "scripts/qemu_ck_boot_test.sh", "present": true, "script_sha256": "64bcb2d1285485b989dc8309ce0b024ea799d3bce13cff22f62924d3ae4b7cce", "exit": "0", "seconds": 6, "log_sha256": "bb655365a8aeae638a6f7214f8d7e5770e597b6fd0e64c58e6bd0ffe79d2ca2f", "log_lines": 22}, + {"name": "store", "script": "scripts/qemu_ck_store_test.sh", "present": true, "script_sha256": "b005ed29619d1113536a0686cedafe84fcea95fa30321307ec1d1335ea231925", "exit": "0", "seconds": 89, "log_sha256": "ec6d169e4c22262c48769778c4939c21f2c00e14bc7328a02a464c644c7a475e", "log_lines": 533}, + {"name": "artifact", "script": "scripts/qemu_ck_artifact_test.sh", "present": true, "script_sha256": "8aa38b624d29b3b62189c6bd9dec12a7551d16c45b1ba21686a3fc30fb14618f", "exit": "0", "seconds": 16, "log_sha256": "d5b54877710c4b59f66376cd9f181afe77168093c606abe079eeea253a45413d", "log_lines": 167} + ], + "gates": [ + {"id": "M1", "marker": "AIENOS_CK_M1", "source": "boot", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "M3", "marker": "AIENOS_CK_M3", "source": "boot", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "SMMU", "marker": "AIENOS_CK_SMMU", "source": "store", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "NVME_SHUTDOWN", "marker": "AIENOS_CK_NVME_SHUTDOWN", "source": "store", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "P2_ARTIFACT", "marker": "AIENOS_CK_P2_ARTIFACT", "source": "artifact", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "M0_ROLLBACK", "marker": "AIENOS_CK_M0_ROLLBACK", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: C loader signatures, A/B, BootNext and rollback are parked (native/boot/README.md)"}, + {"id": "M4_NVME", "marker": "AIENOS_CK_M4_NVME", "source": "store", "verdict": "PASS", "reason": "SMMU-confined NVMe DMA in QEMU (iommu=smmuv3, default build); TEST-ONLY bypass build boot-checked separately"}, + {"id": "M4_STORE", "marker": "AIENOS_CK_M4_STORE", "source": "store", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "M4_STORE_CRASH", "marker": "AIENOS_CK_M4_STORE_CRASH", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: no C Store crash/kill campaign (4 KiB or 512 B) and no slot reuse (C Store is append-only)"}, + {"id": "M4_CONTINUITY", "marker": "AIENOS_CK_M4_CONTINUITY", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: no continuity core (ADR 0016 agent identity and memory) in the C kernel"}, + {"id": "M4_RECOVERY", "marker": "AIENOS_CK_M4_RECOVERY", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: no Recovery Core (ADR 0006) in the C kernel"}, + {"id": "ARGUS1_REVOKE", "marker": "AIENOS_CK_ARGUS1_REVOKE", "source": "store", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "KEYBOARD", "marker": "AIENOS_CK_KEYBOARD", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: no xHCI/USB HID keyboard driver in the C kernel"} + ], + "counts": {"total": 13, "pass": 8, "fail": 0, "not_run": 5}, + "verdict": "NOT_ALL_GATES_PASS", + "parity": "native/kernel/GATES.md", + "physical": "NOT_RUN", + "physical_statement": "QEMU emulator runs only. Nothing here was run on Machine 1 or any GB10; no physical qualification is claimed." +} diff --git a/evidence/ck_gates_bb4040322b026f5f561733fdcaf900770070f2281800b0e3603c2aa2c670b7ff.json b/evidence/ck_gates_bb4040322b026f5f561733fdcaf900770070f2281800b0e3603c2aa2c670b7ff.json new file mode 100644 index 00000000..51ec853d --- /dev/null +++ b/evidence/ck_gates_bb4040322b026f5f561733fdcaf900770070f2281800b0e3603c2aa2c670b7ff.json @@ -0,0 +1,42 @@ +{ + "schema": "aienos.ck_gates.v1", + "started_utc": "2026-10-01T12:13:47Z", + "finished_utc": "2026-10-01T12:15:51Z", + "commit": "4f56a967f6a798724ac9cbe40df670332545f35d", + "commit_subject": "ck: review fixes for the C artifact loader", + "tree_clean_before": true, + "tree_clean_after": true, + "quiet_flag": "/home/drakestapleton/workspace/.spark-quiet", + "quiet_flag_present_at_start": false, + "host": {"hostname": "spark-b87b", "arch": "aarch64", "kernel": "7.0.0-1019-nvidia", "cpu_model": "Cortex-A725;Cortex-X925"}, + "qemu": {"binary": "/usr/bin/qemu-system-aarch64", "version": "QEMU emulator version 8.2.2 (Debian 1:8.2.2+ds-0ubuntu1.18)"}, + "firmware": {"aavmf_code": "/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd", "aavmf_code_sha256": "4a4cb7f6d8106bb2a7dd8c763fab14b1810152136fc4304e5b728f0043e84f12", "aavmf_vars": "/usr/share/AAVMF/AAVMF_VARS.fd", "aavmf_vars_sha256": "b3b855c5a80310168051164986855692d1bdb06e67619856177965cd87c6774f"}, + "nvme_dma_mode": "Confined (QEMU SMMUv3 stage 1, out-of-window DMA faulted); no-SMMU boot denied (NoSmmu); TEST-ONLY bypass image checked separately", + "children": [ + {"name": "boot", "script": "scripts/qemu_ck_boot_test.sh", "present": true, "script_sha256": "64bcb2d1285485b989dc8309ce0b024ea799d3bce13cff22f62924d3ae4b7cce", "exit": "0", "seconds": 7, "log_sha256": "dd71e117053605a1e3c726e8e3cb8dfc368006c28e1fae987e111c696bf3302f", "log_lines": 22}, + {"name": "store", "script": "scripts/qemu_ck_store_test.sh", "present": true, "script_sha256": "b005ed29619d1113536a0686cedafe84fcea95fa30321307ec1d1335ea231925", "exit": "0", "seconds": 86, "log_sha256": "045a506aac0a65eab0a5fe1f39fedf6566269bcda16c8977204dc8c25bf33772", "log_lines": 533}, + {"name": "net", "script": "scripts/qemu_ck_net_test.sh", "present": true, "script_sha256": "ff5bdf5246950bc9e825c76ecc541f39460b88c181a948225a7a393f25a71b25", "exit": "0", "seconds": 13, "log_sha256": "9d6357785ba61fa99dcadcc4b06e0b922c5e2899702dcf02af3c2a4c8a2bf0ec", "log_lines": 59}, + {"name": "artifact", "script": "scripts/qemu_ck_artifact_test.sh", "present": true, "script_sha256": "1b9b9d0fe9a01fe3ba4a2a65d418ce95bc011c3cb0c055b297c8e8b1abde42d9", "exit": "0", "seconds": 18, "log_sha256": "ef9643041e417e134a643f82ea3fef30c66d0f809b1e98e6a362e7ae34952ce8", "log_lines": 167} + ], + "gates": [ + {"id": "M1", "marker": "AIENOS_CK_M1", "source": "boot", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "M3", "marker": "AIENOS_CK_M3", "source": "boot", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "SMMU", "marker": "AIENOS_CK_SMMU", "source": "store", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "NVME_SHUTDOWN", "marker": "AIENOS_CK_NVME_SHUTDOWN", "source": "store", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "P2_ARTIFACT", "marker": "AIENOS_CK_P2_ARTIFACT", "source": "artifact", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "M0_ROLLBACK", "marker": "AIENOS_CK_M0_ROLLBACK", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: C loader signatures, A/B, BootNext and rollback are parked (native/boot/README.md)"}, + {"id": "M4_NVME", "marker": "AIENOS_CK_M4_NVME", "source": "store", "verdict": "PASS", "reason": "SMMU-confined NVMe DMA in QEMU (iommu=smmuv3, default build); TEST-ONLY bypass build boot-checked separately"}, + {"id": "M4_STORE", "marker": "AIENOS_CK_M4_STORE", "source": "store", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "M4_STORE_CRASH", "marker": "AIENOS_CK_M4_STORE_CRASH", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: no C Store crash/kill campaign (4 KiB or 512 B) and no slot reuse (C Store is append-only)"}, + {"id": "M4_CONTINUITY", "marker": "AIENOS_CK_M4_CONTINUITY", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: no continuity core (ADR 0016 agent identity and memory) in the C kernel"}, + {"id": "M4_RECOVERY", "marker": "AIENOS_CK_M4_RECOVERY", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: no Recovery Core (ADR 0006) in the C kernel"}, + {"id": "ARGUS1_REVOKE", "marker": "AIENOS_CK_ARGUS1_REVOKE", "source": "store", "verdict": "PASS", "reason": "child reported PASS, exit 0"}, + {"id": "KEYBOARD", "marker": "AIENOS_CK_KEYBOARD", "source": "missing", "verdict": "NOT_RUN", "reason": "MISSING_IMPLEMENTATION: no xHCI/USB HID keyboard driver in the C kernel"}, + {"id": "NET", "marker": "AIENOS_CK_NET", "source": "net", "verdict": "PASS", "reason": "QEMU user networking (slirp): attach, UDP TX seen by the host helper, UDP reply RX parsed by M6-A; QEMU does not route virtio-net DMA through the SMMU (no ACCESS_PLATFORM), so confinement is not proven for it"} + ], + "counts": {"total": 14, "pass": 9, "fail": 0, "not_run": 5}, + "verdict": "NOT_ALL_GATES_PASS", + "parity": "native/kernel/GATES.md", + "physical": "NOT_RUN", + "physical_statement": "QEMU emulator runs only. Nothing here was run on Machine 1 or any GB10; no physical qualification is claimed." +} diff --git a/native/kernel/GATES.md b/native/kernel/GATES.md index 2e30ac57..6e605eec 100644 --- a/native/kernel/GATES.md +++ b/native/kernel/GATES.md @@ -20,9 +20,10 @@ Status vocabulary: C gates (one line each from `ck_gates.sh`): `M1` and `M3` (from `scripts/qemu_ck_boot_test.sh`), `M4_NVME`, `M4_STORE`, `ARGUS1_REVOKE` `SMMU`, `NVME_SHUTDOWN` (from `scripts/qemu_ck_store_test.sh`; rows 21-24b, 47-72, 76 and -96-101 were checked against its exact grep patterns), `NET` (C-only, from +96-101 were checked against its exact grep patterns), `P2_ARTIFACT` (from +`scripts/qemu_ck_artifact_test.sh`, rows 33-41), `NET` (C-only, from `scripts/qemu_ck_net_test.sh`; rows 102-106), and the NOT_RUN gates -`P2_ARTIFACT`, `M0_ROLLBACK`, `M4_STORE_CRASH`, +`M0_ROLLBACK`, `M4_STORE_CRASH`, `M4_CONTINUITY`, `M4_RECOVERY`, `KEYBOARD`. `M4_NVME` and `SMMU` PASS in the SMMU-confined mode (default `make full` @@ -121,22 +122,64 @@ per-stream page tables, `ck_dma_confine` / `ck_dma_unconfine` / | 31 | xHCI bus master revoked after the phase (`dma_gate: xhci bus master revoked`) | KEYBOARD | NOT_RUN (MISSING_IMPLEMENTATION) | | 32 | no panic or fault | KEYBOARD | NOT_RUN (MISSING_IMPLEMENTATION) | -## SEED-0B / P2-5 artifact loader: scripts/qemu_artifact_test.sh -> CK `P2_ARTIFACT` +## SEED-0B / P2-5 artifact loader: scripts/qemu_artifact_test.sh -> CK `P2_ARTIFACT` (scripts/qemu_ck_artifact_test.sh) + +The C loader is `native/kernel/core/artifact_loader.c` with the format, +signature, admission and receipt code in `native/kernel/artifact/` and the +host tool `native/kernel/tools/ck_artifact_tool.c` (C ports of +aienos-artifact, admission.rs, receipt.rs and aienos-artifact-tool; the tool's +pack, sign, negative corpus and expected.txt are byte-identical to the Rust +tool's). Two boots as in the Rust gate: `make CK_SEED0B_TEST_ANCHOR=1` +(trusts the RFC 8032 TEST 1 public key only, labelled TEST ONLY) and the +ordinary build (no anchors). Same QEMU command line plus one `-fw_cfg` file. + +How the C gate differs from the Rust gate (all apply to rows 33-41): + +- **Candidate source**: one QEMU fw_cfg file `opt/aienos/artifacts` (a + bundle: `AIENBND\0`, count, then name/length/bytes per candidate) instead of + `\EFI\AIENOS\ARTIFACTS\*.AIEN` read by the UEFI loader. The C boot stub + (native/boot) reads no files. The kernel finds the fw_cfg window from the + ACPI DSDT (`QEMU0002` device, Memory32Fixed), nothing hard-coded. The + 640 KiB per-file limit and the input-frame shortage path (FirmwareRead) + are applied by the kernel at the same stage (`received`). +- **Build and tools**: make + gcc and the in-tree C tool, not cargo and the + Rust tool; the probe programs are the same committed fixtures packed by + the same `pack.sh`. No Machine 1 captured-log mode (stays with the Rust gate). +- **Address space**: the task runs on ASID 0 with a full TLB flush on every + TTBR0 switch (Rust: ASID 2). EL0 FP/SIMD use traps (fault) instead of + running with zeroed FP state. One loaded task at a time. +- **Frames**: content + page-table frames come as one contiguous batch, and + the private code-alias (shadow) tables as a second one; absolute free-frame + counts differ from the Rust kernel's, the before == after check is the same. +- **Capabilities**: a 16-slot loader capability table (generation-checked + handles `gen << 32 | index`), not the Rust CapabilityTable type. +- **Signatures**: the C Ed25519 (native/sig) also rejects small-order and + non-canonical public keys and R points; no corpus case depends on this. +- **QEMU exit**: any status other than 0 fails (Rust: only timeout 124). +- Verdict line `AIENOS_CK_P2_ARTIFACT`; the Rust per-category markers + (ARTIFACT_PARSE ... HOSTILE_MATRIX) are not printed, every check counts + toward the one verdict. | # | Rust check (pattern) | CK gate | Status | | --- | --- | --- | --- | -| 33 | common: kernel alive + M3 threads/el0/ipc proofs unchanged | P2_ARTIFACT | NOT_RUN (MISSING_IMPLEMENTATION: no artifact loader) | -| 34 | firmware read all candidates (`^artifact_candidates: N$`), report not truncated, final report | P2_ARTIFACT | NOT_RUN (MISSING_IMPLEMENTATION) | -| 35 | frames reclaimed (`artifact_frames_free_before` == `_after`) | P2_ARTIFACT | NOT_RUN (MISSING_IMPLEMENTATION) | -| 36 | qualification build labelled TEST ONLY, receipt tier line | P2_ARTIFACT | NOT_RUN (MISSING_IMPLEMENTATION) | -| 37 | P26SEED read via grant, write/forged denied, granted subset of requested, exactly one capability, receipt | P2_ARTIFACT | NOT_RUN (MISSING_IMPLEMENTATION) | -| 38 | P25EXEC / P25WX (W^X fault) / P25SPIN (time budget) / P25TAMP (BadSignature) outcomes + receipts | P2_ARTIFACT | NOT_RUN (MISSING_IMPLEMENTATION: no EL0 loader, no signature verify of artifacts) | -| 39 | hostile set: each refused at its stage or admitted-and-contained, receipts checked by the host tool | P2_ARTIFACT | NOT_RUN (MISSING_IMPLEMENTATION) | -| 40 | H29 READ\|WRITE requested -> READ granted | P2_ARTIFACT | NOT_RUN (MISSING_IMPLEMENTATION) | -| 41 | production build refuses every candidate, zero admitted | P2_ARTIFACT | NOT_RUN (MISSING_IMPLEMENTATION) | +| 33 | common: kernel alive + M3 threads/el0/ipc proofs unchanged | P2_ARTIFACT | IDENTICAL | +| 34 | firmware read all candidates (`^artifact_candidates: N$`), report not truncated, final report | P2_ARTIFACT | DIFFERS (the kernel reads the fw_cfg bundle, not firmware files; same line and count; also fails on `artifact_bundle: malformed`) | +| 35 | frames reclaimed (`artifact_frames_free_before` == `_after`) | P2_ARTIFACT | IDENTICAL (absolute counts differ) | +| 36 | qualification build labelled TEST ONLY, receipt tier line | P2_ARTIFACT | IDENTICAL | +| 37 | P26SEED read via grant, write/forged denied, granted subset of requested, exactly one capability, receipt | P2_ARTIFACT | IDENTICAL | +| 38 | P25EXEC / P25WX (W^X fault) / P25SPIN (time budget) / P25TAMP (BadSignature) outcomes + receipts | P2_ARTIFACT | IDENTICAL | +| 39 | hostile set: each refused at its stage or admitted-and-contained, receipts checked by the host tool | P2_ARTIFACT | DIFFERS (same expected.txt and checks, receipts checked by the C tool; also requires at least 29 cases) | +| 40 | H29 READ\|WRITE requested -> READ granted | P2_ARTIFACT | IDENTICAL | +| 41 | production build refuses every candidate, zero admitted | P2_ARTIFACT | IDENTICAL | ## M0 rollback: scripts/qemu_native_rollback_test.sh -> CK `M0_ROLLBACK` +Every M0 rollback check is about the UEFI boot loader (BootNext consumed +before ExitBootServices, A/B slot choice, fallback to Default), which lives in +native/boot. Nothing in it is kernel scope, so the C kernel has no part of it +to port; `M0_ROLLBACK` stays MISSING_IMPLEMENTATION until the C loader work +(parked) is done. + | # | Rust check (marker) | CK gate | Status | | --- | --- | --- | --- | | 42 | `AAVMF_BOOTNEXT_NVRAM` / `NATIVE_ROLLBACK_NORMAL` | M0_ROLLBACK | NOT_RUN (MISSING_IMPLEMENTATION: C loader BootNext/A-B/rollback parked, native/boot/README.md) | @@ -269,7 +312,7 @@ complete. ## Summary counts -Rows 1-106: IDENTICAL 20, DIFFERS 30, NOT_RUN 56 (rows 92-95 have no CK gate at all; rows 96-106 are C-only). Rows 102-106 were checked against scripts/qemu_ck_net_test.sh. Rows 13, 24, 47-72, 76 and 96-101 were re-verified against scripts/qemu_ck_store_test.sh and scripts/lib_ck_m1_checks.sh at the commit that adds this line. +Rows 1-106: IDENTICAL 28, DIFFERS 37, NOT_RUN 41, counted from the table (the previous summary, 20/30/56, was miscounted: the table on main had 21/35/50; rows 33-41 then moved from NOT_RUN to 7 IDENTICAL + 2 DIFFERS with the C artifact loader; rows 92-95 have no CK gate at all; rows 96-106 are C-only). Rows 33-41 were checked against scripts/qemu_ck_artifact_test.sh. Rows 102-106 were checked against scripts/qemu_ck_net_test.sh. Rows 13, 24, 47-72, 76 and 96-101 were re-verified against scripts/qemu_ck_store_test.sh and scripts/lib_ck_m1_checks.sh at the commit that adds this line. `scripts/trust1_m5_qualify.sh --with-qemu` also runs three of these gates as qemu rows: `ck_m1_boot_qemu` (M1), `ck_store_kernel_qemu` (M4_STORE) and diff --git a/native/kernel/Makefile b/native/kernel/Makefile index 51bca0fc..a0800086 100644 --- a/native/kernel/Makefile +++ b/native/kernel/Makefile @@ -63,6 +63,21 @@ $(error CK_QEMU_UNSAFE_DMA must be empty or 1) endif endif +# SEED-0B qualification build: trusts the RFC 8032 TEST 1 public key only. +# TEST ONLY; never combined with hardware staging. Use its own OUT. +CK_SEED0B_TEST_ANCHOR ?= +ifneq ($(strip $(CK_SEED0B_TEST_ANCHOR)),) +ifneq ($(strip $(CK_SEED0B_TEST_ANCHOR)),1) +$(error CK_SEED0B_TEST_ANCHOR must be empty or 1) +endif +ifneq ($(strip $(CK_HARDWARE_STAGING)),) +$(error CK_SEED0B_TEST_ANCHOR (TEST key trust) cannot be combined with CK_HARDWARE_STAGING) +endif +ART_TRUST_FLAGS := -DCK_SEED0B_TEST_ANCHOR=1 +else +ART_TRUST_FLAGS := +endif + KINC := -I$(KDIR)/include -I$(KDIR)/core -I$(KDIR)/mm -I$(KDIR)/arch -I$(BOOT) MODULE_INC := -I$(NATIVE)/disk -I$(NATIVE)/store -I$(NATIVE)/m5 -I$(NATIVE)/crypto \ -I$(NATIVE)/capability -I$(NATIVE)/argus -I$(NATIVE)/net @@ -80,6 +95,14 @@ CORE_C := $(BOOT)/efi_main.c \ $(KDIR)/core/smmu.c $(KDIR)/core/smmu_svc.c $(KDIR)/core/sched.c $(KDIR)/core/ipc.c \ $(KDIR)/core/m3.c \ $(KDIR)/mm/frames.c $(KDIR)/mm/heap.c $(KDIR)/mm/mmu.c $(KDIR)/mm/pt.c +# P2 sealed-artifact loader: format/admission/receipt (artifact/), SHA-256 +# (argus), Ed25519/SHA-512 (sig). Built into the core so every image carries +# the loader; the TEST-anchor qualification build is CK_SEED0B_TEST_ANCHOR=1. +ART_C := $(KDIR)/core/artifact_loader.c $(KDIR)/artifact/format.c $(KDIR)/artifact/admission.c \ + $(KDIR)/artifact/receipt.c $(NATIVE)/argus/sha256.c $(NATIVE)/sig/sha512.c \ + $(NATIVE)/sig/ed25519.c $(NATIVE)/sig/ct.c +ART_INC := -I$(KDIR)/svc/compat -I$(KDIR)/artifact -I$(NATIVE)/sig -I$(NATIVE)/argus +CORE_C += $(ART_C) CORE_S := $(BOOT)/efi_entry.S $(KDIR)/arch/vectors.S $(KDIR)/arch/m3.S HDRS := $(wildcard $(KDIR)/include/*.h $(KDIR)/*/*.h $(BOOT)/*.h) @@ -107,6 +130,8 @@ STAGE_HDRS := $(HDRS) $(wildcard $(NATIVE)/*/*.h $(NATIVE)/argus/bridge/*.h $(KD STAGE_BUILT := $(foreach s,$(STAGE_SRCS),$(STAGE_KOBJ)/$(subst /,_,$(patsubst $(REPO)/%,%,$(abspath $(s)))).o) # STAGE_CFLAGS first: svc/compat must shadow the hosted headers. No fortify. STAGE_KCFLAGS := $(STAGE_CFLAGS) $(KCFLAGS) $(MODULE_INC) -U_FORTIFY_SOURCE $(STAGE_DMA_FLAGS) +# The core already links argus/sha256.c (artifact loader); link it once. +STAGE_LINK := $(filter-out %/native_argus_sha256.c.o,$(STAGE_BUILT)) ELF := $(OUT)/aienos-ck.elf EFI := $(OUT)/BOOTAA64.EFI @@ -131,6 +156,21 @@ $(KOBJ)/kernel/core/report.o: $(KDIR)/core/report.c $(HDRS) $(OUT)/commit.stamp @mkdir -p $(dir $@) $(KCC) $(KCFLAGS) -DAIENOS_COMMIT='"$(AIENOS_COMMIT)"' -c -o $@ $< +# Artifact loader objects: compat headers for , TEST-anchor flag. +ART_OBJS := $(patsubst $(NATIVE)/%.c,$(KOBJ)/%.o,$(ART_C)) +ART_HDRS := $(wildcard $(NATIVE)/sig/*.h $(NATIVE)/argus/sha256.h $(KDIR)/svc/compat/*.h) +$(ART_OBJS): KCFLAGS += $(ART_INC) +$(ART_OBJS): $(ART_HDRS) + +$(OUT)/trust.stamp: FORCE + @mkdir -p $(OUT) + @echo '$(ART_TRUST_FLAGS)' | cmp -s - $@ || echo '$(ART_TRUST_FLAGS)' > $@ + +$(KOBJ)/kernel/core/artifact_loader.o: $(KDIR)/core/artifact_loader.c $(HDRS) $(ART_HDRS) \ + $(OUT)/commit.stamp $(OUT)/trust.stamp + @mkdir -p $(dir $@) + $(KCC) $(KCFLAGS) $(ART_TRUST_FLAGS) -DAIENOS_COMMIT='"$(AIENOS_COMMIT)"' -c -o $@ $< + $(KOBJ)/%.o: $(NATIVE)/%.S @mkdir -p $(dir $@) $(KCC) $(KCFLAGS) -c -o $@ $< @@ -166,7 +206,7 @@ $(ELF): $(CORE_OBJS) $(BOOT)/image.ld if [ -n "$$s" ]; then echo "core image defines stage symbols: $$s"; rm -f $@; exit 1; fi $(FULL_ELF): $(CORE_OBJS) $(STAGE_BUILT) $(BOOT)/image.ld - $(call link_image,$@,$(CORE_OBJS) $(STAGE_BUILT)) + $(call link_image,$@,$(CORE_OBJS) $(STAGE_LINK)) @for s in ck_stage_devices ck_stage_security ck_stage_store ck_stage_quiesce; do \ $(KNM) $@ | grep -qE " [TW] $$s$$" || { echo "full image lacks $$s"; rm -f $@; exit 1; }; done @@ -179,7 +219,7 @@ $(FULL_EFI): $(FULL_ELF) # ---- host unit tests ---- HOST_SRCS := $(KDIR)/core/fmt.c $(KDIR)/core/acpi.c $(KDIR)/core/smmu.c $(KDIR)/mm/frames.c \ $(KDIR)/mm/pt.c $(KDIR)/mm/heap.c $(KDIR)/core/sched.c $(KDIR)/core/ipc.c -TESTS := test_fmt test_frames test_pt test_acpi test_heap test_smmu test_sched test_ipc +TESTS := test_fmt test_frames test_pt test_acpi test_heap test_smmu test_sched test_ipc test_artifact HCFLAGS := -std=gnu11 -O1 -g -Wall -Wextra -Werror -I$(KDIR)/core -I$(KDIR)/mm -I$(KDIR)/tests SANFLAGS := -fsanitize=address,undefined -fno-sanitize-recover=all -fno-omit-frame-pointer @@ -205,8 +245,29 @@ $(OUT)/host/ck_udp_echo: $(KDIR)/tools/ck_udp_echo.c @mkdir -p $(dir $@) $(HOSTCC) -std=gnu11 -O2 -Wall -Wextra -Werror -o $@ $< +# Artifact library host test and the in-tree C artifact tool (pack, sign with +# TEST keys, negative corpus, bundle, receipt check) used by the QEMU gate. +ART_HOST_SRCS := $(KDIR)/artifact/format.c $(KDIR)/artifact/admission.c $(KDIR)/artifact/receipt.c \ + $(NATIVE)/argus/sha256.c $(NATIVE)/sig/sha512.c $(NATIVE)/sig/ed25519.c $(NATIVE)/sig/ct.c +ART_HOST_INC := -I$(KDIR)/artifact -I$(NATIVE)/sig -I$(NATIVE)/argus +ART_HOST_DEPS := $(ART_HOST_SRCS) $(wildcard $(KDIR)/artifact/*.h) $(ART_HDRS) + +$(OUT)/host/test_artifact: $(KDIR)/tests/test_artifact.c $(ART_HOST_DEPS) $(KDIR)/tests/ck_test.h + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) $(ART_HOST_INC) -o $@ $< $(ART_HOST_SRCS) + +$(OUT)/host-san/test_artifact: $(KDIR)/tests/test_artifact.c $(ART_HOST_DEPS) $(KDIR)/tests/ck_test.h + @mkdir -p $(dir $@) + $(HOSTCC) $(HCFLAGS) $(SANFLAGS) $(ART_HOST_INC) -o $@ $< $(ART_HOST_SRCS) + +ART_TOOL := $(OUT)/host/ck_artifact_tool +$(ART_TOOL): $(KDIR)/tools/ck_artifact_tool.c $(ART_HOST_DEPS) + @mkdir -p $(dir $@) + $(HOSTCC) -std=gnu11 -O2 -Wall -Wextra -Werror $(ART_HOST_INC) -o $@ $< $(ART_HOST_SRCS) +tool: $(ART_TOOL) + clean: rm -rf $(OUT) FORCE: -.PHONY: all full test sanitize clean print-kcflags udp-echo FORCE +.PHONY: all full test sanitize clean print-kcflags udp-echo tool FORCE diff --git a/native/kernel/artifact/admission.c b/native/kernel/artifact/admission.c new file mode 100644 index 00000000..cc556a00 --- /dev/null +++ b/native/kernel/artifact/admission.c @@ -0,0 +1,168 @@ +/* admission.c -- the boot admission policy and its evaluation (port of + * aienos-kernel admission.rs and the boot policy of artifact_loader.rs). */ +#include "ck_artifact.h" +#include "sha256.h" + +#define POLICY_HEADER 64u + +void cka_boot_policy(struct cka_policy *pol, const uint8_t (*anchors)[32], unsigned nanchors) +{ + struct cka_limits l = {64, 64, 16, 16, 0, 0, 1000000000ull, 1000000000ull, 65536}; + struct cka_cap rule = {CKA_KIND_OBJECT, 1, 1, 1, 16, 32, 0, 32}; + pol->limits = l; + pol->nrules = 1; + pol->rules[0] = rule; + if (nanchors > CKA_POLICY_MAX_SIGNERS) + nanchors = CKA_POLICY_MAX_SIGNERS; + pol->nsigners = nanchors; + for (unsigned i = 0; i < nanchors; i++) + sha256_hash(anchors[i], 32, pol->signers[i]); +} + +size_t cka_policy_canonical(const struct cka_policy *pol, uint8_t *o, size_t cap) +{ + size_t need = POLICY_HEADER + (size_t)CKA_CAP_SIZE * pol->nrules + 32u * pol->nsigners; + if (cap < need) + return 0; + for (size_t i = 0; i < POLICY_HEADER; i++) + o[i] = 0; + static const char magic[8] = "AIENPOL"; + for (int i = 0; i < 8; i++) + o[i] = (uint8_t)magic[i]; + cka_wr16(o + 10, POLICY_HEADER); + cka_wr16(o + 12, CKA_CAP_SIZE); + cka_wr16(o + 14, (uint16_t)pol->nrules); + const struct cka_limits *l = &pol->limits; + cka_wr32(o + 16, l->code_pages); + cka_wr32(o + 20, l->data_pages); + cka_wr32(o + 24, l->stack_pages); + cka_wr32(o + 28, l->max_caps); + cka_wr32(o + 32, l->ipc_msgs); + cka_wr32(o + 36, l->ipc_bytes); + cka_wr64(o + 40, l->cpu); + cka_wr64(o + 48, l->elapsed); + cka_wr32(o + 56, l->syscalls); + cka_wr16(o + 60, (uint16_t)pol->nsigners); + size_t off = POLICY_HEADER; + for (unsigned i = 0; i < pol->nrules; i++, off += CKA_CAP_SIZE) + cka_cap_encode(&pol->rules[i], o + off); + for (unsigned i = 0; i < pol->nsigners; i++, off += 32) + for (int k = 0; k < 32; k++) + o[off + k] = pol->signers[i][k]; + return off; +} + +void cka_policy_digest(const struct cka_policy *pol, uint8_t out[32]) +{ + uint8_t buf[POLICY_HEADER + CKA_CAP_SIZE * CKA_POLICY_MAX_RULES + 32 * CKA_POLICY_MAX_SIGNERS]; + size_t n = cka_policy_canonical(pol, buf, sizeof buf); + static const char dom[] = "AIENOS-ADMISSION-POLICY-V1"; + cka_digest_domain(dom, sizeof dom, buf, n, out); +} + +static int over(const struct cka_env *e, const struct cka_limits *l) +{ + return e->code_pages > l->code_pages || e->data_pages > l->data_pages || + e->stack_pages > l->stack_pages || (uint32_t)e->max_caps > l->max_caps || + e->ipc_msgs > l->ipc_msgs || e->ipc_bytes > l->ipc_bytes || e->cpu > l->cpu || + e->elapsed > l->elapsed || e->syscalls > l->syscalls; +} + +/* intersect_request: 1 = grant written, 0 = skip, <0 = -error */ +static int intersect(const struct cka_cap *req, const struct cka_cap *rule, struct cka_cap *g) +{ + uint32_t rights = req->rights & rule->rights; + if (!rights) + return 0; + uint32_t ops = req->max_ops < rule->max_ops ? req->max_ops : rule->max_ops; + uint64_t bytes = req->max_bytes < rule->max_bytes ? req->max_bytes : rule->max_bytes; + uint64_t off, len; + if (req->bounds == 1) { + uint64_t rend = req->off + req->len, pend = rule->off + rule->len; + if (rend < req->off || pend < rule->off) + return -CKA_LENGTH_OVERFLOW; + uint64_t start = req->off > rule->off ? req->off : rule->off; + uint64_t end = rend < pend ? rend : pend; + if (start >= end) + return 0; + off = start; + len = end - start; + if (len < bytes) + bytes = len; + } else if (req->bounds == 2) { + off = len = 0; + } else { + return -CKA_MALFORMED_CAP; + } + if (!ops || !bytes) + return 0; + g->kind = req->kind; + g->id = req->id; + g->rights = rights; + g->bounds = req->bounds; + g->max_ops = ops; + g->max_bytes = bytes; + g->off = off; + g->len = len; + int rc = cka_cap_validate(g); + return rc ? -rc : 1; +} + +int cka_evaluate(const struct cka_policy *pol, const struct cka_parsed *p, + const uint8_t signer_fp[32], const struct cka_limits *avail, + struct cka_decision *d) +{ + d->ngrants = 0; + if (p->target != CKA_TARGET_AARCH64_LE) + return CKA_WRONG_TARGET; + if (p->abi != CKA_ABI_V1) + return CKA_WRONG_ABI; + int known = 0; + for (unsigned i = 0; i < pol->nsigners && !known; i++) { + uint8_t acc = 0; + for (int k = 0; k < 32; k++) + acc |= (uint8_t)(pol->signers[i][k] ^ signer_fp[k]); + known = acc == 0; + } + if (!known) + return CKA_UNTRUSTED_SIGNER; + if (p->entry & 3) + return CKA_BAD_ENTRY; + if (p->entry > 0xffffffffu - 4) + return CKA_LENGTH_OVERFLOW; + if (p->entry + 4 > p->code.flen) + return CKA_BAD_ENTRY; + if (p->payload_len > CKA_MAX_PAYLOAD) + return CKA_RESOURCE_LIMIT; + int rc = cka_env_validate(&p->env, p->ncaps); + if (rc) + return rc; + if (over(&p->env, &pol->limits)) + return CKA_RESOURCE_LIMIT; + if (p->env.code_pages > 0xffffffffu / 4096 || p->env.data_pages > 0xffffffffu / 4096 || + p->env.stack_pages > 0xffffffffu / 4096) + return CKA_LENGTH_OVERFLOW; + if (over(&p->env, avail)) + return CKA_RESOURCE_LIMIT; + for (unsigned i = 0; i < p->ncaps; i++) { + const struct cka_cap *req = &p->caps[i], *rule = 0; + for (unsigned r = 0; r < pol->nrules && !rule; r++) + if (pol->rules[r].kind == req->kind && pol->rules[r].id == req->id) + rule = &pol->rules[r]; + if (!rule) + continue; + struct cka_cap g; + int got = intersect(req, rule, &g); + if (got < 0) + return -got; + if (!got) + continue; + if (!cka_cap_is_attenuation_of(&g, req) || !cka_cap_is_attenuation_of(&g, rule)) + return CKA_RIGHTS_ESCALATION; + if (g.rights > 0xff) + return CKA_RIGHTS_ESCALATION; + d->grants[d->ngrants++] = g; + } + cka_grants_digest(d->grants, d->ngrants, d->granted_digest); + return CKA_OK; +} diff --git a/native/kernel/artifact/ck_artifact.h b/native/kernel/artifact/ck_artifact.h new file mode 100644 index 00000000..fe1867e8 --- /dev/null +++ b/native/kernel/artifact/ck_artifact.h @@ -0,0 +1,223 @@ +/* ck_artifact.h -- SEED-0B sealed artifact format, admission policy and + * admission receipts in C (port of crates/aienos-artifact: format.rs, + * capability.rs, resource.rs, verify.rs, admission.rs, receipt.rs and the + * boot policy of aienos-kernel artifact_loader.rs). Pure code: no kernel + * state, builds freestanding (kernel) and hosted (host tests, tool). + * Error codes, stage codes and byte layouts are the Rust ones (ADR 0014). */ +#ifndef AIENOS_CK_ARTIFACT_H +#define AIENOS_CK_ARTIFACT_H + +#include +#include + +/* ---- error codes (ArtifactError, receipt reason codes 1..20) ---- */ +enum { + CKA_OK = 0, + CKA_BAD_MAGIC = 1, + CKA_UNSUPPORTED_VERSION = 2, + CKA_WRONG_TARGET = 3, + CKA_WRONG_ABI = 4, + CKA_LENGTH_OVERFLOW = 5, + CKA_TRUNCATED = 6, + CKA_WRONG_LENGTH = 7, + CKA_RESERVED_NONZERO = 8, + CKA_UNSUPPORTED_FLAGS = 9, + CKA_SECTION_OVERLAP = 10, + CKA_BAD_SECTION = 11, + CKA_BAD_ENTRY = 12, + CKA_MALFORMED_CAP = 13, + CKA_RESOURCE_LIMIT = 14, + CKA_BAD_SIG_FORMAT = 15, + CKA_DIGEST_MISMATCH = 16, + CKA_UNTRUSTED_SIGNER = 17, + CKA_BAD_SIGNATURE = 18, + CKA_RIGHTS_ESCALATION = 19, + CKA_MALFORMED_RECEIPT = 20, +}; +/* LoadError reason codes (receipt reason 0x101..0x10a). */ +enum { + CKL_NO_FRAMES = 0x101, + CKL_STAGING_TOO_LARGE = 0x102, + CKL_MAPPING = 0x103, + CKL_MAPPED_DIGEST = 0x104, + CKL_WX_AUDIT = 0x105, + CKL_CAP_INSTALL = 0x106, + CKL_SCHEDULER_FULL = 0x107, + CKL_EXECUTED_DIGEST = 0x108, + CKL_RECLAIM = 0x109, + CKL_FIRMWARE_READ = 0x10a, +}; +/* Rejection stages (receipt stage 1..9). */ +enum { + CKS_RECEIVED = 1, CKS_STAGED, CKS_VERIFIED, CKS_AUTHORIZED, CKS_RESERVED, + CKS_MAPPED, CKS_HASHED, CKS_SEALED, CKS_CAPS, +}; +const char *cka_error_name(unsigned code); /* Rust Debug name, "?" if unknown */ +const char *cka_stage_name(unsigned stage); + +#define CKA_HEADER_SIZE 128u +#define CKA_SECTION_SIZE 32u +#define CKA_CAP_SIZE 48u +#define CKA_ENV_SIZE 48u +#define CKA_SIG_SIZE 100u +#define CKA_MAX_CAPS 16u +#define CKA_MAX_ARTIFACT (16u << 20) +#define CKA_MAX_PAYLOAD (8u << 20) +#define CKA_CAPS_OFFSET 192u +#define CKA_TARGET_AARCH64_LE 1u +#define CKA_ABI_V1 1u +#define CKA_KIND_CHANNEL 2u +#define CKA_KIND_OBJECT 3u +#define CKA_VALID_RIGHTS 0x3fu + +struct cka_cap { + uint16_t kind; + uint32_t id, rights, bounds, max_ops; + uint64_t max_bytes, off, len; +}; +struct cka_env { + uint32_t code_pages, data_pages, stack_pages; + uint16_t max_caps; + uint32_t ipc_msgs, ipc_bytes; + uint64_t cpu, elapsed; + uint32_t syscalls; +}; +struct cka_section { + uint16_t kind, perms; + uint32_t rel, flen, mlen, align; +}; +struct cka_parsed { + uint16_t target, abi, ncaps, sig_alg; + uint32_t total, entry, res_off, payload_off, payload_len, sig_off; + struct cka_section code, data; + struct cka_cap caps[CKA_MAX_CAPS]; + struct cka_env env; + uint8_t fp[32]; + uint8_t sig[64]; +}; +struct cka_ident { + uint8_t id[32], payload[32], requested[32], resources[32]; +}; + +void cka_cap_encode(const struct cka_cap *c, uint8_t out[CKA_CAP_SIZE]); +int cka_cap_decode(const uint8_t b[CKA_CAP_SIZE], struct cka_cap *c); +int cka_cap_validate(const struct cka_cap *c); +int cka_cap_is_attenuation_of(const struct cka_cap *g, const struct cka_cap *r); +void cka_env_encode(const struct cka_env *e, uint8_t out[CKA_ENV_SIZE]); +int cka_env_validate(const struct cka_env *e, unsigned ncaps); + +/* format.rs parse; parse_and_identify adds the 16 MiB bound and the digests. */ +int cka_parse(const uint8_t *b, size_t len, struct cka_parsed *p); +int cka_identify(const uint8_t *b, size_t len, struct cka_parsed *p, struct cka_ident *id); +/* verify.rs: anchors are TEST/public keys (32 bytes each). Fills signer_fp. */ +int cka_verify(const uint8_t *b, size_t len, const uint8_t (*anchors)[32], unsigned nanchors, + struct cka_parsed *p, struct cka_ident *id, uint8_t signer_fp[32]); +void cka_signature_message(const uint8_t id[32], uint8_t *msg, size_t *len); /* msg >= 64 */ + +/* ---- digests ---- */ +void cka_digest_domain(const char *domain, size_t dlen, const uint8_t *b, size_t len, + uint8_t out[32]); +void cka_grants_digest(const struct cka_cap *g, unsigned n, uint8_t out[32]); + +/* ---- admission policy (admission.rs) ---- */ +#define CKA_POLICY_MAX_RULES 4u +#define CKA_POLICY_MAX_SIGNERS 4u +struct cka_limits { + uint32_t code_pages, data_pages, stack_pages, max_caps, ipc_msgs, ipc_bytes; + uint64_t cpu, elapsed; + uint32_t syscalls; +}; +struct cka_policy { + struct cka_limits limits; + unsigned nrules, nsigners; + struct cka_cap rules[CKA_POLICY_MAX_RULES]; + uint8_t signers[CKA_POLICY_MAX_SIGNERS][32]; +}; +/* The boot policy; with a TEST anchor the signer list is SHA256(anchor). */ +void cka_boot_policy(struct cka_policy *pol, const uint8_t (*anchors)[32], unsigned nanchors); +size_t cka_policy_canonical(const struct cka_policy *pol, uint8_t *out, size_t cap); +void cka_policy_digest(const struct cka_policy *pol, uint8_t out[32]); +struct cka_decision { + unsigned ngrants; + struct cka_cap grants[CKA_MAX_CAPS]; + uint8_t granted_digest[32]; +}; +/* evaluate(): avail = available resources of the machine. */ +int cka_evaluate(const struct cka_policy *pol, const struct cka_parsed *p, + const uint8_t signer_fp[32], const struct cka_limits *avail, + struct cka_decision *d); + +/* ---- admission receipt (receipt.rs) ---- */ +#define CKA_RECEIPT_SIZE 512u +#define CKA_RECEIPT_SIGNED_LEN 400u +enum { CKR_ADMITTED = 1, CKR_REJECTED = 2 }; +enum { CKR_TIER_SEED0B_QEMU = 1 }; +enum { + CKR_NOT_RUN = 0, CKR_EXITED, CKR_TIMEOUT, CKR_FAULT, CKR_BAD_SYSCALL, CKR_RESOURCE_OVERRUN, +}; +#define CKR_F_READ_OK 0x01u +#define CKR_F_WRITE_DENIED 0x02u +#define CKR_F_RECLAIMED 0x04u +#define CKR_F_CANARY 0x08u +#define CKR_F_FORGED_DENIED 0x10u +#define CKR_F_MAPPED 0x20u +#define CKR_F_EXECUTED 0x40u +#define CKR_F_WX 0x80u +struct cka_receipt { + uint32_t flags; + uint16_t decision, tier; + uint64_t seq; + uint8_t nonce[16]; + uint64_t time; + uint32_t status; + int32_t exit; + uint32_t result_flags; + uint16_t stage, reason; + uint32_t syscalls, reads, denials, frames; + uint8_t id[32], payload[32], signer[32], policy[32], requested[32], granted[32], + resources[32], verifier[32], machine[32]; + uint64_t generation, context; + uint16_t sig_alg; + uint8_t fp[32], sig[64]; +}; +const char *cka_status_name(uint32_t status); +void cka_receipt_nonce(const uint8_t verifier[32], uint64_t seq, uint8_t out[16]); +void cka_receipt_encode(const struct cka_receipt *r, uint8_t out[CKA_RECEIPT_SIZE]); +int cka_receipt_decode(const uint8_t b[CKA_RECEIPT_SIZE], struct cka_receipt *r); +int cka_receipt_validate(const struct cka_receipt *r); +void cka_receipt_digest(const uint8_t b[CKA_RECEIPT_SIZE], uint8_t out[32]); +int cka_receipt_is_signed(const uint8_t b[CKA_RECEIPT_SIZE]); +/* Signs an unsigned record in place with an Ed25519 seed (TEST key only). */ +int cka_receipt_sign(uint8_t b[CKA_RECEIPT_SIZE], const uint8_t seed[32]); +int cka_receipt_verify(const uint8_t b[CKA_RECEIPT_SIZE], const uint8_t (*anchors)[32], + unsigned nanchors); +/* Verifier identity of a build (commit = 40 lowercase hex, else "unpinned-build"). */ +void cka_verifier_identity(const char *commit, uint8_t feature, uint8_t out[32]); + +/* ---- TEST-ONLY qualification keys (RFC 8032 test vectors 1 and 2) ---- */ +extern const uint8_t cka_test1_pk[32]; +extern const uint8_t cka_test2_pk[32]; + +/* little-endian field helpers */ +static inline uint16_t cka_rd16(const uint8_t *b) { return (uint16_t)(b[0] | b[1] << 8); } +static inline uint32_t cka_rd32(const uint8_t *b) +{ + return (uint32_t)b[0] | (uint32_t)b[1] << 8 | (uint32_t)b[2] << 16 | (uint32_t)b[3] << 24; +} +static inline uint64_t cka_rd64(const uint8_t *b) +{ + return (uint64_t)cka_rd32(b) | (uint64_t)cka_rd32(b + 4) << 32; +} +static inline void cka_wr16(uint8_t *b, uint16_t v) { b[0] = (uint8_t)v; b[1] = (uint8_t)(v >> 8); } +static inline void cka_wr32(uint8_t *b, uint32_t v) +{ + for (int i = 0; i < 4; i++) + b[i] = (uint8_t)(v >> (8 * i)); +} +static inline void cka_wr64(uint8_t *b, uint64_t v) +{ + for (int i = 0; i < 8; i++) + b[i] = (uint8_t)(v >> (8 * i)); +} + +#endif diff --git a/native/kernel/artifact/format.c b/native/kernel/artifact/format.c new file mode 100644 index 00000000..ed0c7690 --- /dev/null +++ b/native/kernel/artifact/format.c @@ -0,0 +1,354 @@ +/* format.c -- SEED-0B artifact parse, capability and envelope records, + * identity digests and signature verification (format.rs, capability.rs, + * resource.rs, id.rs, canonical.rs, verify.rs). */ +#include "ck_artifact.h" +#include "aienos_sig.h" +#include "sha256.h" + +#define DOM(s) (s), (sizeof(s)) + +/* RFC 8032 section 7.1 test vectors: TEST ONLY, never an owner key. */ +const uint8_t cka_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}; +const uint8_t cka_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}; + +static const char *const err_names[21] = { + "Ok", "BadMagic", "UnsupportedVersion", "WrongTarget", "WrongAbi", "LengthOverflow", + "Truncated", "WrongLength", "ReservedNonZero", "UnsupportedFlags", "SectionOverlap", + "BadSection", "BadEntryPoint", "MalformedCapability", "ResourceLimit", "BadSignatureFormat", + "DigestMismatch", "UntrustedSigner", "BadSignature", "RightsEscalation", "MalformedReceipt"}; +static const char *const load_names[10] = { + "NoFrames", "StagingTooLarge", "Mapping", "MappedDigestMismatch", "WxAudit", + "CapabilityInstall", "SchedulerFull", "ExecutedDigestMismatch", "Reclaim", "FirmwareRead"}; +static const char *const stage_names[10] = {"none", "received", "staged", "verified", "authorized", + "reserved", "mapped", "hashed", "sealed", "caps"}; + +const char *cka_error_name(unsigned code) +{ + if (code < 21) + return err_names[code]; + if (code >= 0x101 && code <= 0x10a) + return load_names[code - 0x101]; + return "?"; +} + +const char *cka_stage_name(unsigned stage) +{ + return stage < 10 ? stage_names[stage] : "?"; +} + +static int all_zero(const uint8_t *b, size_t n) +{ + uint8_t acc = 0; + for (size_t i = 0; i < n; i++) + acc |= b[i]; + return acc == 0; +} + +static int eq32(const uint8_t *a, const uint8_t *b) +{ + uint8_t acc = 0; + for (int i = 0; i < 32; i++) + acc |= (uint8_t)(a[i] ^ b[i]); + return acc == 0; +} + +void cka_digest_domain(const char *domain, size_t dlen, const uint8_t *b, size_t len, + uint8_t out[32]) +{ + sha256_ctx c; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)domain, dlen); + if (len) + sha256_update(&c, b, len); + sha256_final(&c, out); +} + +/* ---- capability records (capability.rs) ---- */ +void cka_cap_encode(const struct cka_cap *c, uint8_t o[CKA_CAP_SIZE]) +{ + for (unsigned i = 0; i < CKA_CAP_SIZE; i++) + o[i] = 0; + cka_wr16(o, c->kind); + cka_wr32(o + 4, c->id); + cka_wr32(o + 8, c->rights); + cka_wr32(o + 12, c->bounds); + cka_wr32(o + 16, c->max_ops); + cka_wr64(o + 24, c->max_bytes); + cka_wr64(o + 32, c->off); + cka_wr64(o + 40, c->len); +} + +int cka_cap_validate(const struct cka_cap *c) +{ + if ((c->kind != CKA_KIND_OBJECT && c->kind != CKA_KIND_CHANNEL) || c->id == 0 || + c->rights == 0 || (c->rights & ~CKA_VALID_RIGHTS) || c->max_ops == 0 || c->max_bytes == 0) + return CKA_MALFORMED_CAP; + if (c->kind == CKA_KIND_OBJECT && c->bounds == 1) { + if (c->off + c->len < c->off) + return CKA_LENGTH_OVERFLOW; + if (c->len == 0 || c->max_bytes > c->len) + return CKA_MALFORMED_CAP; + return CKA_OK; + } + if (c->kind == CKA_KIND_CHANNEL && c->bounds == 2) + return (c->off || c->len) ? CKA_MALFORMED_CAP : CKA_OK; + return CKA_MALFORMED_CAP; +} + +int cka_cap_decode(const uint8_t b[CKA_CAP_SIZE], struct cka_cap *c) +{ + if (cka_rd16(b + 2) || cka_rd32(b + 20)) + return CKA_RESERVED_NONZERO; + c->kind = cka_rd16(b); + c->id = cka_rd32(b + 4); + c->rights = cka_rd32(b + 8); + c->bounds = cka_rd32(b + 12); + c->max_ops = cka_rd32(b + 16); + c->max_bytes = cka_rd64(b + 24); + c->off = cka_rd64(b + 32); + c->len = cka_rd64(b + 40); + return cka_cap_validate(c); +} + +int cka_cap_is_attenuation_of(const struct cka_cap *g, const struct cka_cap *r) +{ + if (cka_cap_validate(g) || cka_cap_validate(r) || g->kind != r->kind || g->id != r->id || + g->bounds != r->bounds || (g->rights & ~r->rights) || g->max_ops > r->max_ops || + g->max_bytes > r->max_bytes) + return 0; + if (g->bounds == 1) + return g->off >= r->off && g->off + g->len <= r->off + r->len; + return 1; +} + +/* ---- envelope (resource.rs) ---- */ +void cka_env_encode(const struct cka_env *e, uint8_t o[CKA_ENV_SIZE]) +{ + for (unsigned i = 0; i < CKA_ENV_SIZE; i++) + o[i] = 0; + cka_wr32(o, e->code_pages); + cka_wr32(o + 4, e->data_pages); + cka_wr32(o + 8, e->stack_pages); + cka_wr16(o + 12, e->max_caps); + cka_wr32(o + 16, e->ipc_msgs); + cka_wr32(o + 20, e->ipc_bytes); + cka_wr64(o + 24, e->cpu); + cka_wr64(o + 32, e->elapsed); + cka_wr32(o + 40, e->syscalls); +} + +int cka_env_validate(const struct cka_env *e, unsigned ncaps) +{ + if (e->code_pages < 1 || e->code_pages > 64 || e->data_pages < 1 || e->data_pages > 64 || + e->stack_pages < 1 || e->stack_pages > 16 || ncaps > e->max_caps || + e->max_caps > CKA_MAX_CAPS || e->ipc_msgs > 1024 || e->ipc_bytes > 1048576u || + e->cpu < 1 || e->cpu > 1000000000ull || e->elapsed < 1 || e->elapsed > 1000000000ull || + e->syscalls < 1 || e->syscalls > 65536) + return CKA_RESOURCE_LIMIT; + return CKA_OK; +} + +static int env_decode(const uint8_t *b, unsigned ncaps, struct cka_env *e) +{ + if (cka_rd16(b + 14) || cka_rd32(b + 44)) + return CKA_RESERVED_NONZERO; + e->code_pages = cka_rd32(b); + e->data_pages = cka_rd32(b + 4); + e->stack_pages = cka_rd32(b + 8); + e->max_caps = cka_rd16(b + 12); + e->ipc_msgs = cka_rd32(b + 16); + e->ipc_bytes = cka_rd32(b + 20); + e->cpu = cka_rd64(b + 24); + e->elapsed = cka_rd64(b + 32); + e->syscalls = cka_rd32(b + 40); + return cka_env_validate(e, ncaps); +} + +/* ---- parse (format.rs) ---- */ +static void section_read(const uint8_t *b, struct cka_section *s) +{ + s->kind = cka_rd16(b); + s->perms = cka_rd16(b + 2); + s->rel = cka_rd32(b + 8); + s->flen = cka_rd32(b + 12); + s->mlen = cka_rd32(b + 16); + s->align = cka_rd32(b + 20); +} + +int cka_parse(const uint8_t *b, size_t len, struct cka_parsed *p) +{ + static const uint8_t magic[8] = {'A', 'I', 'E', 'N', 'A', 'R', 'T', 0}; + if (len < CKA_HEADER_SIZE) + return CKA_TRUNCATED; + if (len > CKA_MAX_ARTIFACT) + return CKA_RESOURCE_LIMIT; + for (int i = 0; i < 8; i++) + if (b[i] != magic[i]) + return CKA_BAD_MAGIC; + if (cka_rd16(b + 8) != 0 || cka_rd16(b + 10) != CKA_HEADER_SIZE) + return CKA_UNSUPPORTED_VERSION; + p->target = cka_rd16(b + 12); + p->abi = cka_rd16(b + 14); + if (p->target != CKA_TARGET_AARCH64_LE) + return CKA_WRONG_TARGET; + if (p->abi != CKA_ABI_V1) + return CKA_WRONG_ABI; + if (cka_rd32(b + 16) != 0) + return CKA_UNSUPPORTED_FLAGS; + p->total = cka_rd32(b + 20); + if (p->total != len) + return CKA_WRONG_LENGTH; + if (cka_rd32(b + 24) != CKA_HEADER_SIZE || cka_rd16(b + 28) != 2 || + cka_rd16(b + 30) != CKA_SECTION_SIZE || cka_rd16(b + 32) || cka_rd16(b + 34)) + return CKA_UNSUPPORTED_VERSION; + p->entry = cka_rd32(b + 36); + if (cka_rd32(b + 40) != CKA_CAPS_OFFSET || cka_rd16(b + 46) != CKA_CAP_SIZE || + cka_rd16(b + 52) != CKA_ENV_SIZE || cka_rd16(b + 54) != 0) + return CKA_UNSUPPORTED_VERSION; + if (!all_zero(b + 72, CKA_HEADER_SIZE - 72)) + return CKA_RESERVED_NONZERO; + p->ncaps = cka_rd16(b + 44); + if (p->ncaps > CKA_MAX_CAPS) + return CKA_RESOURCE_LIMIT; + p->res_off = cka_rd32(b + 48); + if (p->res_off != CKA_CAPS_OFFSET + CKA_CAP_SIZE * p->ncaps) + return CKA_SECTION_OVERLAP; + uint32_t env_end = p->res_off + CKA_ENV_SIZE; + p->payload_off = cka_rd32(b + 56); + if (p->payload_off != ((env_end + 15u) & ~15u)) + return CKA_SECTION_OVERLAP; + /* total == len >= 128 here; the gap lies inside the file only if it fits */ + if ((uint64_t)p->payload_off > len) + return CKA_WRONG_LENGTH; + if (!all_zero(b + env_end, p->payload_off - env_end)) + return CKA_RESERVED_NONZERO; + p->payload_len = cka_rd32(b + 60); + if (p->payload_len > CKA_MAX_PAYLOAD) + return CKA_RESOURCE_LIMIT; + if (cka_rd16(b + 68) != CKA_SIG_SIZE || cka_rd16(b + 70) != 1) + return CKA_BAD_SIG_FORMAT; + p->sig_off = cka_rd32(b + 64); + if ((uint64_t)p->sig_off != (uint64_t)p->payload_off + p->payload_len) + return CKA_SECTION_OVERLAP; + if ((uint64_t)p->sig_off + CKA_SIG_SIZE != p->total) + return CKA_WRONG_LENGTH; + const uint8_t *s0 = b + 128, *s1 = b + 160; + if (cka_rd32(s0 + 4) || !all_zero(s0 + 24, 8) || cka_rd32(s1 + 4) || !all_zero(s1 + 24, 8)) + return CKA_RESERVED_NONZERO; + section_read(s0, &p->code); + section_read(s1, &p->data); + const struct cka_section *c = &p->code, *d = &p->data; + if (c->kind != 1 || c->perms != 5 || c->rel != 0 || c->flen == 0 || c->mlen != c->flen || + c->align != 4096) + return CKA_BAD_SECTION; + if (d->kind != 2 || d->perms != 3 || d->rel != c->flen || d->flen == 0 || d->mlen < d->flen || + d->align != 4096) + return CKA_BAD_SECTION; + if ((uint64_t)c->flen + d->flen != p->payload_len) + return CKA_SECTION_OVERLAP; + for (unsigned i = 0; i < p->ncaps; i++) { + int rc = cka_cap_decode(b + CKA_CAPS_OFFSET + CKA_CAP_SIZE * i, &p->caps[i]); + if (rc) + return rc; + } + for (unsigned i = 1; i < p->ncaps; i++) { + const struct cka_cap *a = &p->caps[i - 1], *z = &p->caps[i]; + if (!(a->kind < z->kind || (a->kind == z->kind && a->id < z->id))) + return CKA_MALFORMED_CAP; + } + int rc = env_decode(b + p->res_off, p->ncaps, &p->env); + if (rc) + return rc; + if ((uint64_t)c->mlen > (uint64_t)p->env.code_pages * 4096u || + (uint64_t)d->mlen > (uint64_t)p->env.data_pages * 4096u) + return CKA_RESOURCE_LIMIT; + if ((p->entry & 3) || (uint64_t)p->entry + 4 > c->flen) + return CKA_BAD_ENTRY; + const uint8_t *sg = b + p->sig_off; + p->sig_alg = cka_rd16(sg); + if (p->sig_alg != 1) + return CKA_BAD_SIG_FORMAT; + if (sg[2] || sg[3]) + return CKA_RESERVED_NONZERO; + if (p->sig_alg != cka_rd16(b + 70)) + return CKA_BAD_SIG_FORMAT; + for (int i = 0; i < 32; i++) + p->fp[i] = sg[4 + i]; + for (int i = 0; i < 64; i++) + p->sig[i] = sg[36 + i]; + return CKA_OK; +} + +int cka_identify(const uint8_t *b, size_t len, struct cka_parsed *p, struct cka_ident *id) +{ + if (len > CKA_MAX_ARTIFACT) + return CKA_RESOURCE_LIMIT; + int rc = cka_parse(b, len, p); + if (rc) + return rc; + cka_digest_domain(DOM("AIENOS-ARTIFACT-V1"), b, p->sig_off, id->id); + sha256_hash(b + p->payload_off, p->payload_len, id->payload); + cka_digest_domain(DOM("AIENOS-ARTIFACT-CAP-REQUESTS-V1"), b + CKA_CAPS_OFFSET, + (size_t)CKA_CAP_SIZE * p->ncaps, id->requested); + uint8_t env[CKA_ENV_SIZE]; + cka_env_encode(&p->env, env); + cka_digest_domain(DOM("AIENOS-ARTIFACT-RESOURCES-V1"), env, sizeof env, id->resources); + return CKA_OK; +} + +void cka_signature_message(const uint8_t id[32], uint8_t *msg, size_t *len) +{ + static const char dom[] = "AIENOS-ARTIFACT-SIGNATURE-V1"; + size_t n = sizeof dom; + for (size_t i = 0; i < n; i++) + msg[i] = (uint8_t)dom[i]; + for (int i = 0; i < 32; i++) + msg[n + i] = id[i]; + *len = n + 32; +} + +int cka_verify(const uint8_t *b, size_t len, const uint8_t (*anchors)[32], unsigned nanchors, + struct cka_parsed *p, struct cka_ident *id, uint8_t signer_fp[32]) +{ + int rc = cka_identify(b, len, p, id); + if (rc) + return rc; + const uint8_t *key = 0; + uint8_t fp[32]; + for (unsigned i = 0; i < nanchors && !key; i++) { + sha256_hash(anchors[i], 32, fp); + if (eq32(fp, p->fp)) + key = anchors[i]; + } + if (!key) + return CKA_UNTRUSTED_SIGNER; + sha256_hash(key, 32, fp); + if (!eq32(fp, p->fp)) + return CKA_UNTRUSTED_SIGNER; + uint8_t msg[96]; + size_t mlen; + cka_signature_message(id->id, msg, &mlen); + if (aienos_ed25519_verify(p->sig, msg, mlen, key) != 0) + return CKA_BAD_SIGNATURE; + for (int i = 0; i < 32; i++) + signer_fp[i] = p->fp[i]; + return CKA_OK; +} + +void cka_grants_digest(const struct cka_cap *g, unsigned n, uint8_t out[32]) +{ + sha256_ctx c; + static const char dom[] = "AIENOS-ADMISSION-CAP-GRANTS-V1"; + uint8_t rec[CKA_CAP_SIZE]; + sha256_init(&c); + sha256_update(&c, (const uint8_t *)dom, sizeof dom); + for (unsigned i = 0; i < n; i++) { + cka_cap_encode(&g[i], rec); + sha256_update(&c, rec, sizeof rec); + } + sha256_final(&c, out); +} diff --git a/native/kernel/artifact/receipt.c b/native/kernel/artifact/receipt.c new file mode 100644 index 00000000..ad1ff857 --- /dev/null +++ b/native/kernel/artifact/receipt.c @@ -0,0 +1,259 @@ +/* receipt.c -- SEED-0B admission receipts (port of aienos-artifact + * receipt.rs): 512-byte canonical record, digest, nonce, validation and the + * TEST-ONLY qualification signature. */ +#include "ck_artifact.h" +#include "aienos_sig.h" +#include "sha256.h" + +static const char rmagic[8] = "AIENRCP"; +static const char sig_dom[] = "AIENOS-ADMISSION-RECEIPT-SIGNATURE-V1"; + +const char *cka_status_name(uint32_t s) +{ + static const char *const n[6] = {"NotRun", "Exited", "Timeout", + "Fault", "BadSyscall", "ResourceOverrun"}; + return s < 6 ? n[s] : "?"; +} + +void cka_receipt_nonce(const uint8_t verifier[32], uint64_t seq, uint8_t out[16]) +{ + static const char dom[] = "AIENOS-ADMISSION-RECEIPT-NONCE-V1"; + uint8_t s[8], d[32]; + sha256_ctx c; + cka_wr64(s, seq); + sha256_init(&c); + sha256_update(&c, (const uint8_t *)dom, sizeof dom); + sha256_update(&c, verifier, 32); + sha256_update(&c, s, 8); + sha256_final(&c, d); + for (int i = 0; i < 16; i++) + out[i] = d[i]; +} + +static void put(uint8_t *o, const uint8_t *s, unsigned n) +{ + for (unsigned i = 0; i < n; i++) + o[i] = s[i]; +} + +void cka_receipt_encode(const struct cka_receipt *r, uint8_t o[CKA_RECEIPT_SIZE]) +{ + for (unsigned i = 0; i < CKA_RECEIPT_SIZE; i++) + o[i] = 0; + put(o, (const uint8_t *)rmagic, 8); + cka_wr16(o + 10, 96); + cka_wr32(o + 12, CKA_RECEIPT_SIZE); + cka_wr32(o + 16, r->flags); + cka_wr16(o + 20, r->decision); + cka_wr16(o + 22, r->tier); + cka_wr64(o + 24, r->seq); + put(o + 32, r->nonce, 16); + cka_wr64(o + 48, r->time); + cka_wr32(o + 64, r->status); + cka_wr32(o + 68, (uint32_t)r->exit); + cka_wr32(o + 72, r->result_flags); + cka_wr16(o + 76, r->stage); + cka_wr16(o + 78, r->reason); + cka_wr32(o + 80, r->syscalls); + cka_wr32(o + 84, r->reads); + cka_wr32(o + 88, r->denials); + cka_wr32(o + 92, r->frames); + put(o + 96, r->id, 32); + put(o + 128, r->payload, 32); + put(o + 160, r->signer, 32); + put(o + 192, r->policy, 32); + put(o + 224, r->requested, 32); + put(o + 256, r->granted, 32); + put(o + 288, r->resources, 32); + put(o + 320, r->verifier, 32); + put(o + 352, r->machine, 32); + cka_wr64(o + 384, r->generation); + cka_wr64(o + 392, r->context); + if (r->sig_alg) { + cka_wr16(o + 400, r->sig_alg); + put(o + 404, r->fp, 32); + put(o + 436, r->sig, 64); + } +} + +static int nz(const uint8_t *b, unsigned from, unsigned to) +{ + uint8_t acc = 0; + for (unsigned i = from; i < to; i++) + acc |= b[i]; + return acc != 0; +} + +int cka_receipt_decode(const uint8_t b[CKA_RECEIPT_SIZE], struct cka_receipt *r) +{ + for (int i = 0; i < 8; i++) + if (b[i] != (uint8_t)rmagic[i]) + return CKA_BAD_MAGIC; + if (cka_rd16(b + 8) != 0 || cka_rd16(b + 10) != 96 || cka_rd32(b + 12) != CKA_RECEIPT_SIZE) + return CKA_UNSUPPORTED_VERSION; + r->flags = cka_rd32(b + 16); + r->result_flags = cka_rd32(b + 72); + if ((r->flags & ~7u) || (r->result_flags & ~0xffu)) + return CKA_UNSUPPORTED_FLAGS; + if (nz(b, 56, 64) || nz(b, 500, 512)) + return CKA_RESERVED_NONZERO; + r->sig_alg = 0; + if (nz(b, 400, 500)) { + if (cka_rd16(b + 400) != 1) + return CKA_BAD_SIG_FORMAT; + if (b[402] || b[403]) + return CKA_RESERVED_NONZERO; + r->sig_alg = 1; + } + r->decision = cka_rd16(b + 20); + r->tier = cka_rd16(b + 22); + r->status = cka_rd32(b + 64); + if ((r->decision != CKR_ADMITTED && r->decision != CKR_REJECTED) || + r->tier != CKR_TIER_SEED0B_QEMU || r->status > CKR_RESOURCE_OVERRUN) + return CKA_MALFORMED_RECEIPT; + r->seq = cka_rd64(b + 24); + put(r->nonce, b + 32, 16); + r->time = cka_rd64(b + 48); + r->exit = (int32_t)cka_rd32(b + 68); + r->stage = cka_rd16(b + 76); + r->reason = cka_rd16(b + 78); + r->syscalls = cka_rd32(b + 80); + r->reads = cka_rd32(b + 84); + r->denials = cka_rd32(b + 88); + r->frames = cka_rd32(b + 92); + put(r->id, b + 96, 32); + put(r->payload, b + 128, 32); + put(r->signer, b + 160, 32); + put(r->policy, b + 192, 32); + put(r->requested, b + 224, 32); + put(r->granted, b + 256, 32); + put(r->resources, b + 288, 32); + put(r->verifier, b + 320, 32); + put(r->machine, b + 352, 32); + r->generation = cka_rd64(b + 384); + r->context = cka_rd64(b + 392); + put(r->fp, b + 404, 32); + put(r->sig, b + 436, 64); + return cka_receipt_validate(r); /* as receipt::decode in Rust */ +} + +int cka_receipt_validate(const struct cka_receipt *r) +{ + static const uint8_t zero[32]; + int bad = CKA_MALFORMED_RECEIPT; + uint8_t acc = 0; + for (int i = 0; i < 32; i++) + acc |= (uint8_t)(r->machine[i] ^ zero[i]); + if (!(r->flags & 1) && acc) + return bad; + if (!(r->flags & 2) && (r->generation || r->context)) + return bad; + if (!(r->flags & 4) && r->time) + return bad; + int reason_ok = (r->reason >= 1 && r->reason <= 19) || (r->reason >= 0x101 && r->reason <= 0x10a); + if (r->stage > 9 || (r->reason && !reason_ok)) + return bad; + if (r->decision == CKR_REJECTED) { + if (!r->stage || !r->reason || r->status != CKR_NOT_RUN || r->exit || r->syscalls || + r->reads || r->denials || (r->result_flags & ~CKR_F_RECLAIMED)) + return bad; + } else if (r->stage || r->reason) { + return bad; + } + if ((r->result_flags & CKR_F_CANARY) && (r->status != CKR_EXITED || r->exit)) + return bad; + uint8_t n[16]; + cka_receipt_nonce(r->verifier, r->seq, n); + acc = 0; + for (int i = 0; i < 16; i++) + acc |= (uint8_t)(n[i] ^ r->nonce[i]); + return acc ? bad : CKA_OK; +} + +void cka_receipt_digest(const uint8_t b[CKA_RECEIPT_SIZE], uint8_t out[32]) +{ + static const char dom[] = "AIENOS-ADMISSION-RECEIPT-V1"; + cka_digest_domain(dom, sizeof dom, b, CKA_RECEIPT_SIGNED_LEN, out); +} + +int cka_receipt_is_signed(const uint8_t b[CKA_RECEIPT_SIZE]) +{ + return nz(b, CKA_RECEIPT_SIGNED_LEN, CKA_RECEIPT_SIZE); +} + +static void sig_message(const uint8_t digest[32], uint8_t *m, size_t *len) +{ + for (size_t i = 0; i < sizeof sig_dom; i++) + m[i] = (uint8_t)sig_dom[i]; + put(m + sizeof sig_dom, digest, 32); + *len = sizeof sig_dom + 32; +} + +int cka_receipt_sign(uint8_t b[CKA_RECEIPT_SIZE], const uint8_t seed[32]) +{ + struct cka_receipt r; + if (cka_receipt_is_signed(b)) + return CKA_BAD_SIG_FORMAT; + int rc = cka_receipt_decode(b, &r); + if (rc) + return rc; + uint8_t d[32], pk[32], m[96]; + size_t mlen; + cka_receipt_digest(b, d); + sig_message(d, m, &mlen); + if (aienos_ed25519_public_key(pk, seed) != AIENOS_SIG_OK || + aienos_ed25519_sign(b + 436, m, mlen, seed) != AIENOS_SIG_OK) + return CKA_BAD_SIGNATURE; + cka_wr16(b + 400, 1); + sha256_hash(pk, 32, b + 404); + return CKA_OK; +} + +int cka_receipt_verify(const uint8_t b[CKA_RECEIPT_SIZE], const uint8_t (*anchors)[32], + unsigned nanchors) +{ + struct cka_receipt r; + int rc = cka_receipt_decode(b, &r); + if (rc) + return rc; + if (!r.sig_alg) + return CKA_BAD_SIG_FORMAT; + const uint8_t *key = 0; + uint8_t fp[32]; + for (unsigned i = 0; i < nanchors && !key; i++) { + sha256_hash(anchors[i], 32, fp); + uint8_t acc = 0; + for (int k = 0; k < 32; k++) + acc |= (uint8_t)(fp[k] ^ r.fp[k]); + if (!acc) + key = anchors[i]; + } + if (!key) + return CKA_UNTRUSTED_SIGNER; + uint8_t d[32], m[96]; + size_t mlen; + cka_receipt_digest(b, d); + sig_message(d, m, &mlen); + return aienos_ed25519_verify(r.sig, m, mlen, key) == AIENOS_SIG_OK ? CKA_OK : CKA_BAD_SIGNATURE; +} + +void cka_verifier_identity(const char *commit, uint8_t feature, uint8_t out[32]) +{ + static const char dom[] = "AIENOS-VERIFIER-IDENTITY-V1"; + uint8_t id[45]; + int ok = 1; + for (int i = 0; i < 40 && ok; i++) { + char c = commit[i]; + ok = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + id[i] = (uint8_t)c; + } + if (ok && commit[40] == 0) { + cka_wr16(id + 40, CKA_TARGET_AARCH64_LE); + cka_wr16(id + 42, CKA_ABI_V1); + id[44] = feature; + cka_digest_domain(dom, sizeof dom, id, sizeof id, out); + } else { + static const char unpinned[] = "unpinned-build"; + cka_digest_domain(dom, sizeof dom, (const uint8_t *)unpinned, sizeof unpinned - 1, out); + } +} diff --git a/native/kernel/core/artifact_loader.c b/native/kernel/core/artifact_loader.c new file mode 100644 index 00000000..f9a3ac88 --- /dev/null +++ b/native/kernel/core/artifact_loader.c @@ -0,0 +1,1274 @@ +/* artifact_loader.c -- P2 sealed-artifact loader of the C kernel core. + * + * Port of crates/aienos-kernel/src/artifact_loader.rs (load_bound, + * process_candidate, shadow code alias, W^X audit, receipts) and + * task_runtime.rs (EL0 run, syscall table, budgets) onto the C core. The + * format, signature and admission logic is native/kernel/artifact/ (ported + * from aienos-artifact and admission.rs, cross-checked byte for byte against + * the Rust tool). + * + * Candidates come from QEMU's fw_cfg file "opt/aienos/artifacts" (a bundle, + * see tools/ck_artifact_tool.c), not from ESP files read by the Rust UEFI + * loader: the C boot stub (native/boot) does not read files. The fw_cfg base + * is taken from the ACPI DSDT (device QEMU0002); nothing is assumed. + * + * Trust: the qualification build (CK_SEED0B_TEST_ANCHOR=1) trusts the + * RFC 8032 TEST 1 public key ONLY (SEED-0B, TEST ONLY). The ordinary build + * has no anchors and refuses every candidate. No real key material here. + * + * Differences from the Rust kernel, all recorded in GATES.md: + * - one address space at a time on ASID 0 with a full TLB flush on every + * TTBR0 switch (Rust: TASK_ASID 2); + * - EL0 FP/SIMD traps (CPACR FPEN = 01) instead of zeroed FP state; + * - content+table frames and shadow frames are each one contiguous batch; + * - the loader scheduler is a single occupancy flag (one task at a time, + * LOADED_TASK_SLOTS = 4 for the availability snapshot, as in Rust). */ + +#include "arch.h" +#include "ck_internal.h" +#include "pt.h" +#include "ck_artifact.h" +#include "sha256.h" + +#ifndef AIENOS_COMMIT +#define AIENOS_COMMIT "unknown" +#endif + +#define PAGE 4096ull +#define ENTRIES 512u +#define TABLE_FRAMES 4u +#define MAX_BATCH 160u +#define MAX_CODE_PAGES 64u +#define MAX_DATA_PAGES 64u +#define MAX_STACK_PAGES 16u +#define TASK_CAPS 16u +#define LOADED_TASK_SLOTS 4u +#define MAX_CANDIDATES 48u +#define MAX_NAME 32u + +#define ADDR_MASK 0x0000fffffffff000ull +#define ATTR_MASK 0xffff000000000ffcull +#define BLOCK_1G 0x0000ffffc0000000ull +#define BLOCK_2M 0x0000ffffffe00000ull +#define DESC_TYPE 3ull +#define DESC_TABLE 3ull +#define DESC_BLOCK 1ull +#define AP_RO (1ull << 7) +#define PXN (1ull << 53) +#define UXN (1ull << 54) +#define LEAF_COMMON \ + (CK_PTE_ATTRIDX(CK_MAIR_IDX_NORMAL) | CK_PTE_SH_INNER | CK_PTE_AF | (1ull << 11) | PXN | \ + DESC_TABLE) +#define USER_CODE(pa) (((pa) & ADDR_MASK) | LEAF_COMMON | (3ull << 6)) +#define USER_DATA(pa) (((pa) & ADDR_MASK) | LEAF_COMMON | (1ull << 6) | UXN) + +#define SYS_EXIT 2u +#define SYS_OBJECT_READ 6u +#define SYS_OBJECT_WRITE 7u +#define DENIED (~0ull) +#define SEED_OBJECT_ID 1u +#define SEED_OBJECT_BYTES 32u +#define SPSR_EL1H_MASKED 0x3c5ull +#define RIGHT_READ 0x1u +#define RIGHT_WRITE 0x2u + +struct ck_artifact_summary { + unsigned candidates, admitted, rejected; +}; +static struct ck_artifact_summary ck_artifact_summary; + +extern struct ck_frame *(*ck_tick_switch)(struct ck_frame *f); +extern int (*ck_lower_sync)(struct ck_frame *f, uint64_t esr); +void ck_el0_enter(uint64_t entry, uint64_t user_sp, const uint64_t regs[31]); +void ck_el0_resume(void); + +#ifdef CK_SEED0B_TEST_ANCHOR +static const uint8_t (*const anchors)[32] = &cka_test1_pk; +#define NANCHORS 1u +#define FEATURE_TEST_ANCHOR 1u +#else +static const uint8_t (*const anchors)[32] = 0; +#define NANCHORS 0u +#define FEATURE_TEST_ANCHOR 0u +#endif + +/* ============================ platform ============================== */ + +static inline uint64_t *tbl(uint64_t pa) { return (uint64_t *)(uintptr_t)pa; } +static inline uint8_t *mem(uint64_t pa) { return (uint8_t *)(uintptr_t)pa; } +static inline unsigned tidx(uint64_t va, unsigned level) +{ + return (unsigned)((va >> (39 - 9 * level)) & 511); +} +static inline uint64_t free_frames(void) { return ck_mm_free_frames(); } + +static void clean_range(uint64_t pa, uint64_t len, int icache) +{ + uint64_t ctr = ck_rd(ctr_el0); + uint64_t dline = 4ull << ((ctr >> 16) & 0xf), iline = 4ull << (ctr & 0xf); + uint64_t end = pa + len; + for (uint64_t x = pa & ~(dline - 1); x < end; x += dline) + __asm__ volatile("dc civac, %0" ::"r"(x) : "memory"); + ck_dsb_ish(); + if (icache) { + for (uint64_t x = pa & ~(iline - 1); x < end; x += iline) + __asm__ volatile("ic ivau, %0" ::"r"(x) : "memory"); + ck_dsb_ish(); + } + ck_isb(); +} + +static void swap_ttbr0(uint64_t ttbr0) +{ + ck_dsb_ish(); + ck_wr(ttbr0_el1, ttbr0); + ck_isb(); + __asm__ volatile("tlbi vmalle1" ::: "memory"); + ck_dsb_ish(); + ck_isb(); +} + +/* ============================ task layout =========================== */ + +struct layout { + unsigned window; + uint64_t base; + unsigned cp, dp, sp; /* code, data, stack pages */ + uint64_t code_len, data_len, data_mlen, entry; +}; + +static unsigned code_first(void) { return 1; } +static unsigned data_first(const struct layout *l) { return code_first() + l->cp + 1; } +static unsigned stack_first(const struct layout *l) { return data_first(l) + l->dp + 1; } +static unsigned window_pages(const struct layout *l) { return stack_first(l) + l->sp + 1; } +static unsigned content_frames(const struct layout *l) { return l->cp + l->dp + l->sp; } +static uint64_t code_base(const struct layout *l) { return l->base + code_first() * PAGE; } +static uint64_t code_end(const struct layout *l) { return code_base(l) + l->cp * PAGE; } +static uint64_t data_base(const struct layout *l) { return l->base + data_first(l) * PAGE; } +static uint64_t data_end(const struct layout *l) { return data_base(l) + l->dp * PAGE; } +static uint64_t stack_base(const struct layout *l) { return l->base + stack_first(l) * PAGE; } +static uint64_t stack_top(const struct layout *l) { return stack_base(l) + l->sp * PAGE; } + +/* TaskLayout::new: 0 or CKA_RESOURCE_LIMIT. */ +static int layout_new(struct layout *l, unsigned window, const struct cka_env *env, + uint64_t code_len, uint64_t data_len, uint64_t data_mlen, uint64_t entry) +{ + l->window = window; + l->base = (uint64_t)window << 39; + l->cp = env->code_pages; + l->dp = env->data_pages; + l->sp = env->stack_pages; + l->code_len = code_len; + l->data_len = data_len; + l->data_mlen = data_mlen; + l->entry = entry; + if (window < 1 || window >= 256 || env->code_pages == 0 || env->code_pages > MAX_CODE_PAGES || + env->data_pages == 0 || env->data_pages > MAX_DATA_PAGES || env->stack_pages == 0 || + env->stack_pages > MAX_STACK_PAGES || code_len == 0 || code_len > l->cp * PAGE || + data_len > data_mlen || data_mlen > l->dp * PAGE || (entry & 3) || entry + 4 > code_len || + window_pages(l) > ENTRIES) + return CKA_RESOURCE_LIMIT; + return 0; +} + +static uint64_t expected_leaf(const struct layout *l, unsigned index, const uint64_t *frames) +{ + unsigned d = data_first(l), s = stack_first(l); + if (index >= 1 && index < 1 + l->cp) + return USER_CODE(frames[index - 1]); + if (index >= d && index < d + l->dp) + return USER_DATA(frames[l->cp + index - d]); + if (index >= s && index < s + l->sp) + return USER_DATA(frames[l->cp + l->dp + index - s]); + return 0; +} + +/* ============================ reports =============================== */ + +struct bindings { + uint8_t id[32], payload[32], signer[32], policy[32], requested[32], granted[32], + resources[32]; + int mapped_bytes_matched, wx_sealed; +}; + +enum { ST_NOT_RUN, ST_EXITED, ST_TIMEOUT, ST_FAULT, ST_BAD_SYSCALL, ST_OVERRUN }; +struct outcome { + unsigned status; + uint64_t value; /* exit code / syscall number */ + uint64_t esr, far, elr; + uint32_t syscalls, reads_ok, denials, write_denials, invalid_handle; +}; + +struct report { + int admitted; + unsigned stage, error; /* failed stage and reason code (0 = none) */ + int have_id; + uint8_t id[32]; + int tier_test; + uint64_t frames_reserved, free_before, free_after; + unsigned caps_installed, caps_live_after; + struct cka_cap granted[TASK_CAPS]; + uint64_t code_base, code_end, data_base, data_end, stack_base, stack_end; + int wx_enforced, byte_chain; + struct outcome out; + struct bindings b; +}; + +static int reclaimed(const struct report *r) +{ + return r->free_after == r->free_before && r->caps_live_after == 0; +} + +/* ============================ loader caps =========================== */ + +struct cap_slot { + int live; + uint32_t gen, resource, rights; +}; +static struct cap_slot caps[TASK_CAPS]; +static uint32_t cap_gens[TASK_CAPS]; + +static void caps_reset(void) +{ + memset(caps, 0, sizeof caps); + memset(cap_gens, 0, sizeof cap_gens); +} + +static int caps_insert(uint32_t resource, uint32_t rights, uint64_t *raw) +{ + for (unsigned i = 0; i < TASK_CAPS; i++) { + if (caps[i].live || cap_gens[i] == 0xffffffffu) + continue; + uint32_t g = ++cap_gens[i]; + caps[i] = (struct cap_slot){1, g, resource, rights}; + *raw = (uint64_t)g << 32 | i; + return 0; + } + return -1; +} + +enum { LK_OK = 0, LK_INVALID = 1, LK_MISSING_RIGHTS = 2 }; +static int caps_lookup(uint64_t raw, uint32_t right, uint32_t *resource) +{ + uint32_t index = (uint32_t)raw, gen = (uint32_t)(raw >> 32); + if (gen == 0 || index >= TASK_CAPS || !caps[index].live || caps[index].gen != gen) + return LK_INVALID; + if ((caps[index].rights & right) != right) + return LK_MISSING_RIGHTS; + *resource = caps[index].resource; + return LK_OK; +} + +static void caps_remove(uint64_t raw) +{ + uint32_t index = (uint32_t)raw, gen = (uint32_t)(raw >> 32); + if (gen && index < TASK_CAPS && caps[index].live && caps[index].gen == gen) + caps[index].live = 0; +} + +static unsigned caps_live(void) +{ + unsigned n = 0; + for (unsigned i = 0; i < TASK_CAPS; i++) + n += caps[i].live ? 1u : 0u; + return n; +} + +/* ============================ loaded task =========================== */ + +struct task { + struct layout l; + uint64_t batch, nframes; /* content + table frames, contiguous */ + uint64_t shadow, nshadow, used; /* shadow batch, frames used by the alias */ + uint64_t frames[MAX_BATCH]; + uint64_t root; + uint64_t entry_pc, sp, args[4]; + unsigned ngrants; + struct cka_cap grants[TASK_CAPS]; + uint64_t handles[TASK_CAPS]; + uint64_t budget_cpu, budget_elapsed; + uint32_t budget_syscalls; + uint8_t code_digest[32]; +}; +static struct task task; +static int slot_busy; /* loader scheduler: one admitted task at a time */ + +static int release(struct task *t) +{ + int ok = 1; + if (t->nframes) { + memset(mem(t->batch), 0, t->nframes * PAGE); + if (ck_mm_frames_free(t->batch, t->nframes)) + ok = 0; + t->nframes = 0; + } + if (t->nshadow) { + memset(mem(t->shadow), 0, t->nshadow * PAGE); + if (ck_mm_frames_free(t->shadow, t->nshadow)) + ok = 0; + t->nshadow = 0; + } + slot_busy = 0; + return ok; +} + +/* kernel_translation: the descriptor mapping va (level-3 page or L1/L2 + * block) and its level, or -1. */ +static int translate(uint64_t root, uint64_t va, uint64_t *desc) +{ + uint64_t table = root; + for (unsigned level = 0; level < 4; level++) { + uint64_t e = tbl(table)[tidx(va, level)]; + if (level == 3 && (e & DESC_TYPE) == DESC_TABLE) { + *desc = e; + return 3; + } + if ((level == 1 || level == 2) && (e & DESC_TYPE) == DESC_BLOCK) { + *desc = e; + return (int)level; + } + if (level <= 2 && (e & DESC_TYPE) == DESC_TABLE) { + table = e & ADDR_MASK; + continue; + } + return -1; + } + return -1; +} + +static int shadow_needed(uint64_t kroot, const uint64_t *frames, unsigned n, uint64_t *count) +{ + uint64_t keys[MAX_CODE_PAGES][3]; + uint64_t c = 0, d; + for (unsigned i = 0; i < n; i++) { + uint64_t pa = frames[i]; + if (translate(kroot, pa, &d) < 0) + return CKL_MAPPING; + uint64_t k[3] = {pa >> 39, pa >> 30, pa >> 21}; + for (unsigned level = 0; level < 3; level++) { + int seen = 0; + for (unsigned j = 0; j < i && !seen; j++) + seen = keys[j][level] == k[level]; + if (!seen) + c++; + } + keys[i][0] = k[0]; + keys[i][1] = k[1]; + keys[i][2] = k[2]; + } + *count = c; + return 0; +} + +static int shadow_alias(struct task *t) +{ + uint64_t used = 0; + for (unsigned f = 0; f < t->l.cp; f++) { + uint64_t pa = t->frames[f], table = t->root; + for (unsigned level = 0; level < 3; level++) { + unsigned index = tidx(pa, level); + uint64_t entry = tbl(table)[index], child = entry & ADDR_MASK; + int priv = 0; + for (uint64_t j = 0; j < used && !priv; j++) + priv = t->shadow + j * PAGE == child; + if ((entry & DESC_TYPE) == DESC_TABLE && priv) { + table = child; + continue; + } + if (used >= t->nshadow) + return CKL_MAPPING; + uint64_t fresh = t->shadow + used * PAGE; + used++; + if ((entry & DESC_TYPE) == DESC_TABLE) { + memcpy(mem(fresh), mem(child), PAGE); + } else if (level == 1 && (entry & DESC_TYPE) == DESC_BLOCK) { + uint64_t attrs = entry & ATTR_MASK, base = entry & BLOCK_1G; + for (uint64_t k = 0; k < ENTRIES; k++) + tbl(fresh)[k] = (base + (k << 21)) | attrs | DESC_BLOCK; + } else if (level == 2 && (entry & DESC_TYPE) == DESC_BLOCK) { + uint64_t attrs = entry & ATTR_MASK, base = entry & BLOCK_2M; + for (uint64_t k = 0; k < ENTRIES; k++) + tbl(fresh)[k] = (base + (k << 12)) | attrs | DESC_TABLE; + } else { + return CKL_MAPPING; + } + tbl(table)[index] = (entry & ~ADDR_MASK & ~DESC_TYPE) | fresh | DESC_TABLE; + table = fresh; + } + unsigned index = tidx(pa, 3); + uint64_t leaf = tbl(table)[index]; + if ((leaf & DESC_TYPE) != DESC_TABLE || (leaf & ADDR_MASK) != pa) + return CKL_MAPPING; + tbl(table)[index] = leaf | AP_RO | PXN | UXN; + } + t->used = used; + return 0; +} + +static int audit_wx(const struct task *t) +{ + const struct layout *l = &t->l; + unsigned content = content_frames(l); + uint64_t l0e = tbl(t->root)[l->window], l1 = l0e & ADDR_MASK; + if (l0e != ((t->frames[content + 1] & ADDR_MASK) | DESC_TABLE)) + return 0; + for (unsigned i = 1; i < ENTRIES; i++) + if (tbl(l1)[i]) + return 0; + uint64_t l2 = tbl(l1)[0] & ADDR_MASK; + if (l2 != t->frames[content + 2]) + return 0; + for (unsigned i = 1; i < ENTRIES; i++) + if (tbl(l2)[i]) + return 0; + uint64_t l3 = tbl(l2)[0] & ADDR_MASK; + if (l3 != t->frames[content + 3]) + return 0; + for (unsigned i = 0; i < ENTRIES; i++) { + uint64_t leaf = tbl(l3)[i]; + if (leaf != expected_leaf(l, i, t->frames)) + return 0; + int writable = !(leaf & AP_RO), executable = !(leaf & UXN) || !(leaf & PXN); + if (leaf && writable && executable) + return 0; + } + for (unsigned f = 0; f < l->cp; f++) { + uint64_t pa = t->frames[f], leaf; + if (translate(t->root, pa, &leaf) != 3) + return 0; + if ((leaf & ADDR_MASK) != pa || !(leaf & AP_RO) || !(leaf & PXN) || !(leaf & UXN)) + return 0; + } + return 1; +} + +static void copy_section(const struct task *t, unsigned first, const uint8_t *src, uint64_t len) +{ + for (uint64_t off = 0; off < len; off += PAGE) { + uint64_t n = len - off < PAGE ? len - off : PAGE; + memcpy(mem(t->frames[first + off / PAGE]), src + off, n); + } +} + +static void hash_loaded(const struct task *t, uint8_t payload[32], uint8_t code[32]) +{ + sha256_ctx p, c; + sha256_init(&p); + sha256_init(&c); + for (unsigned i = 0; i < t->l.cp && i * PAGE < t->l.code_len; i++) { + uint64_t n = t->l.code_len - i * PAGE; + n = n < PAGE ? n : PAGE; + sha256_update(&p, mem(t->frames[i]), n); + sha256_update(&c, mem(t->frames[i]), n); + } + for (unsigned i = 0; i < t->l.dp && i * PAGE < t->l.data_len; i++) { + uint64_t n = t->l.data_len - i * PAGE; + n = n < PAGE ? n : PAGE; + sha256_update(&p, mem(t->frames[t->l.cp + i]), n); + } + sha256_final(&p, payload); + sha256_final(&c, code); +} + +static void code_digest(const struct task *t, uint8_t out[32]) +{ + sha256_ctx c; + sha256_init(&c); + for (unsigned i = 0; i < t->l.cp && i * PAGE < t->l.code_len; i++) { + uint64_t n = t->l.code_len - i * PAGE; + sha256_update(&c, mem(t->frames[i]), n < PAGE ? n : PAGE); + } + sha256_final(&c, out); +} + +/* ============================ load_bound ============================ */ + +static struct cka_policy policy; +static struct cka_parsed parsed; +static struct cka_ident ident; +static struct cka_decision decision; + +/* Returns 0 (task loaded) or the failure stage in *stage and reason. */ +static unsigned load_bound(uint64_t staged, uint64_t len, struct bindings *b, unsigned *stage, + int *tier_test) +{ + struct task *t = &task; + const uint8_t *bytes = mem(staged); + cka_policy_digest(&policy, b->policy); + unsigned free_slots = LOADED_TASK_SLOTS - (slot_busy ? 1u : 0u); + if (cka_identify(bytes, len, &parsed, &ident) == 0) { + memcpy(b->id, ident.id, 32); + memcpy(b->payload, ident.payload, 32); + memcpy(b->requested, ident.requested, 32); + memcpy(b->resources, ident.resources, 32); + } + uint8_t fp[32]; + int rc = cka_verify(bytes, len, anchors, NANCHORS, &parsed, &ident, fp); + if (rc) { + *stage = CKS_VERIFIED; + return (unsigned)rc; + } + memcpy(b->signer, fp, 32); + *tier_test = FEATURE_TEST_ANCHOR; + uint64_t ff = free_frames(); + uint32_t frames = 0; + if (free_slots) + frames = ff > TABLE_FRAMES ? (ff - TABLE_FRAMES > 0xffffffffull ? 0xffffffffu + : (uint32_t)(ff - TABLE_FRAMES)) + : 0; + struct cka_limits avail = { + .code_pages = frames, .data_pages = frames, .stack_pages = frames, .max_caps = TASK_CAPS, + .ipc_msgs = 0, .ipc_bytes = 0, .cpu = policy.limits.cpu, .elapsed = policy.limits.elapsed, + .syscalls = policy.limits.syscalls, + }; + rc = cka_evaluate(&policy, &parsed, fp, &avail, &decision); + if (rc) { + *stage = CKS_AUTHORIZED; + return (unsigned)rc; + } + memcpy(b->granted, decision.granted_digest, 32); + /* The admission binds the identity it was computed over (cka_evaluate + * works on the same parsed artifact, so this holds by construction). */ + if (decision.ngrants > TASK_CAPS) { + *stage = CKS_AUTHORIZED; + return CKA_RESOURCE_LIMIT; + } + uint64_t kroot = ck_mm_report()->root; + unsigned window = 0; + for (unsigned i = 1; i < 256 && !window; i++) + if (!tbl(kroot)[i]) + window = i; + if (!window) { + *stage = CKS_RESERVED; + return CKL_MAPPING; + } + memset(t, 0, sizeof *t); + const struct cka_section *cs = &parsed.code, *ds = &parsed.data; + rc = layout_new(&t->l, window, &parsed.env, cs->flen, ds->flen, ds->mlen, parsed.entry); + if (rc) { + *stage = CKS_AUTHORIZED; + return (unsigned)rc; + } + const uint8_t *code_src = bytes + parsed.payload_off; /* code_bytes(): payload[..flen] */ + const uint8_t *data_src = bytes + parsed.payload_off + ds->rel; + + /* ---- Reserved: scheduler slot, content+table frames, shadow frames. */ + *stage = CKS_RESERVED; + slot_busy = 1; + unsigned content = content_frames(&t->l), total = content + TABLE_FRAMES; + unsigned why; + if (total > MAX_BATCH || ck_mm_frames_alloc(total, &t->batch)) { + why = CKL_NO_FRAMES; + goto fail; + } + t->nframes = total; + for (unsigned i = 0; i < total; i++) + t->frames[i] = t->batch + i * PAGE; + uint64_t need; + if ((why = (unsigned)shadow_needed(kroot, t->frames, t->l.cp, &need))) + goto fail; + if (need > MAX_BATCH || ck_mm_frames_alloc(need, &t->shadow)) { + why = CKL_NO_FRAMES; + goto fail; + } + t->nshadow = need; + + /* ---- Mapped */ + *stage = CKS_MAPPED; + uint64_t l0 = t->frames[content], l1 = l0 + PAGE, l2 = l1 + PAGE, l3 = l2 + PAGE; + memset(mem(t->batch), 0, total * PAGE); + memset(mem(t->shadow), 0, need * PAGE); + memcpy(mem(l0), mem(kroot), PAGE); + t->root = l0; + tbl(l0)[window] = l1 | DESC_TABLE; + tbl(l1)[0] = l2 | DESC_TABLE; + tbl(l2)[0] = l3 | DESC_TABLE; + for (unsigned i = data_first(&t->l); i < window_pages(&t->l); i++) { + uint64_t leaf = expected_leaf(&t->l, i, t->frames); + if (leaf) + tbl(l3)[i] = leaf; + } + copy_section(t, 0, code_src, t->l.code_len); + copy_section(t, t->l.cp, data_src, t->l.data_len); + + /* ---- Hashed */ + *stage = CKS_HASHED; + uint8_t payload[32]; + hash_loaded(t, payload, t->code_digest); + if (memcmp(payload, ident.payload, 32)) { + why = CKL_MAPPED_DIGEST; + goto fail; + } + b->mapped_bytes_matched = 1; + + /* ---- Sealed */ + *stage = CKS_SEALED; + clean_range(t->batch, t->l.cp * PAGE, 1); + if ((why = (unsigned)shadow_alias(t))) + goto fail; + for (unsigned i = 0; i < t->l.cp; i++) + tbl(l3)[1 + i] = USER_CODE(t->frames[i]); + clean_range(t->batch, total * PAGE, 0); + if (t->used) + clean_range(t->shadow, t->used * PAGE, 0); + if (!audit_wx(t)) { + why = CKL_WX_AUDIT; + goto fail; + } + b->wx_sealed = 1; + + /* ---- Caps */ + *stage = CKS_CAPS; + caps_reset(); + t->ngrants = decision.ngrants; + memcpy(t->grants, decision.grants, sizeof t->grants); + for (unsigned i = 0; i < t->ngrants; i++) { + if (caps_insert(i, decision.grants[i].rights, &t->handles[i])) { + why = CKL_CAP_INSTALL; + goto fail; + } + } + uint64_t top = stack_top(&t->l), handles_va = top - 8ull * t->ngrants; + uint64_t top_frame = t->frames[content - 1]; + for (unsigned i = 0; i < t->ngrants; i++) + cka_wr64(mem(top_frame) + (handles_va + 8ull * i - (top - PAGE)), t->handles[i]); + clean_range(top_frame, PAGE, 0); + t->entry_pc = code_base(&t->l) + t->l.entry; + t->sp = handles_va & ~15ull; + t->args[0] = handles_va; + t->args[1] = t->ngrants; + t->args[2] = data_base(&t->l); + t->args[3] = t->l.data_mlen; + t->budget_cpu = parsed.env.cpu; + t->budget_elapsed = parsed.env.elapsed; + t->budget_syscalls = parsed.env.syscalls; + return 0; +fail: + caps_reset(); + release(t); + return why; +} + +/* ============================ EL0 runtime =========================== */ + +static struct { + int active, done; + uint64_t start, limit; + uint32_t budget_syscalls; + struct outcome out; + struct { uint64_t ops, bytes; } usage[TASK_CAPS]; + uint64_t object[4]; +} rt; + +static void terminate(struct ck_frame *f, unsigned status, uint64_t value) +{ + if (!rt.done) { + rt.done = 1; + rt.out.status = status; + rt.out.value = value; + } + f->elr = (uint64_t)(uintptr_t)ck_el0_resume; + f->spsr = SPSR_EL1H_MASKED; +} + +static int expired(uint64_t now) { return now - rt.start >= rt.limit; } + +enum { D_AUTHORITY = 1, D_INVALID, D_BOUNDS, D_BUDGET }; +static int object_access(uint64_t raw, uint32_t right, uint64_t off, unsigned *word) +{ + uint32_t index; + int lk = caps_lookup(raw, right, &index); + if (lk == LK_MISSING_RIGHTS) + return D_AUTHORITY; + if (lk != LK_OK) + return D_INVALID; + if (index >= task.ngrants) + return D_AUTHORITY; + const struct cka_cap *g = &task.grants[index]; + if (g->kind != CKA_KIND_OBJECT || g->id != SEED_OBJECT_ID || (g->rights & right) != right) + return D_AUTHORITY; + uint64_t end = off + 8, gend = g->off + g->len; + if (end < off || gend < g->off) + return D_BOUNDS; + if ((off & 7) || off < g->off || end > gend || end > SEED_OBJECT_BYTES) + return D_BOUNDS; + uint64_t bytes = rt.usage[index].bytes + 8; + if (bytes < rt.usage[index].bytes || rt.usage[index].ops >= g->max_ops || bytes > g->max_bytes) + return D_BUDGET; + rt.usage[index].ops++; + rt.usage[index].bytes = bytes; + *word = (unsigned)(off / 8); + return 0; +} + +static uint64_t deny(int why, int write) +{ + if (rt.out.denials != 0xffffffffu) + rt.out.denials++; + if (write && rt.out.write_denials != 0xffffffffu) + rt.out.write_denials++; + if (why == D_INVALID && rt.out.invalid_handle != 0xffffffffu) + rt.out.invalid_handle++; + return DENIED; +} + +static int loader_sync(struct ck_frame *f, uint64_t esr) +{ + if (!rt.active || (f->spsr & 0xf) != 0) + return -1; + uint64_t ec = (esr >> 26) & 0x3f; + if (ec != 0x15) { + uint64_t far; + __asm__ volatile("mrs %0, far_el1" : "=r"(far)); + if (!rt.done) { + rt.out.esr = esr; + rt.out.far = far; + rt.out.elr = f->elr; + } + terminate(f, ST_FAULT, 0); + return 0; + } + if (rt.out.syscalls != 0xffffffffu) + rt.out.syscalls++; + if (rt.out.syscalls > rt.budget_syscalls) { + terminate(f, ST_OVERRUN, 0); + return 0; + } + if (expired(ck_rd(cntpct_el0))) { + terminate(f, ST_TIMEOUT, 0); + return 0; + } + uint64_t number = f->x[8]; + if ((esr & 0xffff) != 0) { + terminate(f, ST_BAD_SYSCALL, number); + return 0; + } + unsigned word; + int why; + switch (number) { + case SYS_EXIT: + terminate(f, ST_EXITED, f->x[0]); + return 0; + case SYS_OBJECT_READ: + if ((why = object_access(f->x[0], RIGHT_READ, f->x[1], &word)) == 0) { + if (rt.out.reads_ok != 0xffffffffu) + rt.out.reads_ok++; + f->x[0] = rt.object[word]; + } else { + f->x[0] = deny(why, 0); + } + return 0; + case SYS_OBJECT_WRITE: + if ((why = object_access(f->x[0], RIGHT_WRITE, f->x[1], &word)) == 0) { + rt.object[word] = f->x[2]; + f->x[0] = 0; + } else { + f->x[0] = deny(why, 1); + } + return 0; + default: + terminate(f, ST_BAD_SYSCALL, number); + return 0; + } +} + +static struct ck_frame *loader_tick(struct ck_frame *f) +{ + if ((f->spsr & 0xf) == 0 && rt.active && expired(ck_rd(cntpct_el0))) + terminate(f, ST_TIMEOUT, 0); + return f; +} + +static void run_task(struct task *t, struct outcome *o) +{ + memset(&rt, 0, sizeof rt); + rt.object[0] = 0xa1e05eed00000001ull; + rt.object[1] = 0xa1e05eed00000002ull; + rt.object[2] = 0xa1e05eed00000003ull; + rt.object[3] = 0xa1e05eed00000004ull; + rt.limit = t->budget_cpu < t->budget_elapsed ? t->budget_cpu : t->budget_elapsed; + rt.budget_syscalls = t->budget_syscalls; + uint64_t regs[31] = {0}; + for (unsigned i = 0; i < 4; i++) + regs[i] = t->args[i]; + uint64_t hz = ck_rd(cntfrq_el0); + uint64_t interval = hz >= 100 ? hz / 100 : 625000; + uint64_t kttbr = ck_rd(ttbr0_el1), cpacr = ck_rd(cpacr_el1), cntkctl = ck_rd(cntkctl_el1); + ck_lower_sync = loader_sync; + ck_tick_switch = loader_tick; + rt.start = ck_rd(cntpct_el0); + rt.active = 1; + ck_wr(cpacr_el1, (cpacr & ~(3ull << 20)) | (1ull << 20)); /* FP/SIMD traps at EL0 */ + /* EL0 must not touch the physical/virtual timers (EL0PTEN, EL0VTEN): the + * budget timer is the kernel's, whatever firmware left in CNTKCTL_EL1. */ + ck_wr(cntkctl_el1, cntkctl & ~((1ull << 9) | (1ull << 8))); + swap_ttbr0(t->root); + ck_wr(cntp_cval_el0, rt.start + interval); + ck_wr(cntp_ctl_el0, 1); + ck_isb(); + ck_el0_enter(t->entry_pc, t->sp, regs); + __asm__ volatile("msr daifset, #2" ::: "memory"); + ck_wr(cntp_ctl_el0, 0); + ck_isb(); + swap_ttbr0(kttbr); + ck_wr(cpacr_el1, cpacr); + ck_wr(cntkctl_el1, cntkctl); + ck_isb(); + rt.active = 0; + ck_lower_sync = 0; + ck_tick_switch = 0; + *o = rt.out; +} + +/* ============================ candidates ============================ */ + +static uint64_t receipt_seq = 1; +static uint8_t verifier_id[32]; + +static void report_empty(struct report *r, uint64_t free_before) +{ + memset(r, 0, sizeof *r); + r->free_before = r->free_after = free_before; +} + +static void firmware_rejection(struct report *r, unsigned error) +{ + report_empty(r, free_frames()); + r->stage = CKS_RECEIVED; + r->error = error; + cka_policy_digest(&policy, r->b.policy); +} + +/* process_candidate: bytes at in_pa (len bytes, len >= 0). */ +static void process_candidate(const uint8_t *bytes, uint64_t len, struct report *r) +{ + report_empty(r, free_frames()); + uint64_t pages = (len + PAGE - 1) / PAGE; + if (len == 0 || pages > MAX_BATCH) { + r->stage = CKS_RECEIVED; + r->error = CKL_STAGING_TOO_LARGE; + r->free_after = free_frames(); + return; + } + uint64_t staged; + if (ck_mm_frames_alloc(pages, &staged)) { + r->stage = CKS_STAGED; + r->error = CKL_NO_FRAMES; + r->free_after = free_frames(); + return; + } + memset(mem(staged), 0, pages * PAGE); + memcpy(mem(staged), bytes, len); + unsigned stage = 0; + int tier_test = 0; + unsigned why = load_bound(staged, len, &r->b, &stage, &tier_test); + memset(mem(staged), 0, pages * PAGE); + int staging_released = ck_mm_frames_free(staged, pages) == 0; + if (why) { + r->stage = stage; + r->error = staging_released ? why : CKL_RECLAIM; + r->free_after = free_frames(); + return; + } + struct task *t = &task; + r->have_id = 1; + memcpy(r->id, ident.id, 32); + r->tier_test = tier_test; + r->frames_reserved = t->nframes + t->nshadow; + r->caps_installed = t->ngrants; + memcpy(r->granted, t->grants, sizeof r->granted); + r->code_base = code_base(&t->l); + r->code_end = code_end(&t->l); + r->data_base = data_base(&t->l); + r->data_end = data_end(&t->l); + r->stack_base = stack_base(&t->l); + r->stack_end = stack_top(&t->l); + r->wx_enforced = r->b.wx_sealed; + run_task(t, &r->out); + /* destroy */ + uint8_t now[32]; + code_digest(t, now); + int executed = memcmp(now, t->code_digest, 32) == 0; + for (unsigned i = 0; i < t->ngrants; i++) + caps_remove(t->handles[i]); + r->caps_live_after = caps_live(); + int released = release(t); + r->admitted = 1; + r->byte_chain = r->b.mapped_bytes_matched && executed; + r->free_after = free_frames(); + if (!executed) + r->error = CKL_EXECUTED_DIGEST; + else if (!released || !staging_released) + r->error = CKL_RECLAIM; +} + +static void hex(char *out, const uint8_t *b, size_t n) +{ + static const char d[] = "0123456789abcdef"; + for (size_t i = 0; i < n; i++) { + out[2 * i] = d[b[i] >> 4]; + out[2 * i + 1] = d[b[i] & 15]; + } + out[2 * n] = 0; +} + +static const char *classify_fault(const struct report *r) +{ + uint64_t esr = r->out.esr, far = r->out.far, ec = (esr >> 26) & 0x3f; + uint64_t status = (esr >> 2) & 0xf; +#define WITHIN(b, e) (far >= (b) && far < (e)) + int in_ds = WITHIN(r->data_base, r->data_end) || WITHIN(r->stack_base, r->stack_end); + if (ec == 0x24 && (esr & (1u << 6)) && status == 3 && WITHIN(r->code_base, r->code_end)) + return "code-write"; + if (ec == 0x20 && status == 3 && in_ds) + return "exec-nx"; + if (ec == 0x20 && status == 1) + return "exec-unmapped"; +#undef WITHIN + return "other"; +} + +static void print_candidate(const char *name, const struct report *r) +{ + const char *yn[2] = {"no", "yes"}; + if (!r->admitted) { + ck_printf("artifact: %s rejected stage=%s reason=%s reclaimed=%s\n", name, + r->stage ? cka_stage_name(r->stage) : "unknown", + r->error ? cka_error_name(r->error) : "unknown", yn[reclaimed(r)]); + return; + } + char id[17]; + hex(id, r->id, 8); + ck_printf("artifact: %s admitted id=%s tier=%s exec=", name, r->have_id ? id : "", + r->tier_test ? "seed0b-test" : "production"); + switch (r->out.status) { + case ST_EXITED: + ck_printf("exited:0x%llx", (unsigned long long)r->out.value); + break; + case ST_TIMEOUT: + ck_puts("timeout"); + break; + case ST_FAULT: + ck_printf("fault:%s", classify_fault(r)); + break; + case ST_BAD_SYSCALL: + ck_printf("bad-syscall:%llu", (unsigned long long)r->out.value); + break; + case ST_OVERRUN: + ck_puts("resource-overrun"); + break; + default: + ck_puts("not-run"); + break; + } + ck_printf(" bytes=%s wx=%s caps=%u revoked=%s reclaimed=%s frames=%llu syscalls=%u reads=%u " + "denials=%u\n", + r->byte_chain ? "identified=verified=admitted=mapped=executed" : "mismatch", + r->wx_enforced ? "enforced" : "violated", r->caps_installed, + yn[r->caps_live_after == 0], yn[reclaimed(r)], + (unsigned long long)r->frames_reserved, r->out.syscalls, r->out.reads_ok, + r->out.denials); +} + +static void print_grants(const char *name, const struct report *r) +{ + if (!r->admitted) + return; + for (unsigned i = 0; i < r->caps_installed; i++) { + const struct cka_cap *g = &r->granted[i]; + const char *kind = g->kind == CKA_KIND_OBJECT ? "object" + : g->kind == CKA_KIND_CHANNEL ? "channel" + : "other"; + ck_printf("grant: %s[%u] kind=%s id=%u rights=0x%x bounds=%llu+%llu max_ops=%u " + "max_bytes=%llu\n", + name, i, kind, g->id, g->rights, (unsigned long long)g->off, + (unsigned long long)g->len, g->max_ops, (unsigned long long)g->max_bytes); + } +} + +static void print_receipt(const char *name, const struct report *r) +{ + uint64_t seq = receipt_seq++; + struct cka_receipt rc; + memset(&rc, 0, sizeof rc); + int adm = r->admitted; + rc.decision = adm ? CKR_ADMITTED : CKR_REJECTED; + rc.tier = CKR_TIER_SEED0B_QEMU; + rc.seq = seq; + memcpy(rc.verifier, verifier_id, 32); + cka_receipt_nonce(verifier_id, seq, rc.nonce); + rc.status = CKR_NOT_RUN; + if (adm) { + static const uint32_t map[] = {CKR_NOT_RUN, CKR_EXITED, CKR_TIMEOUT, CKR_FAULT, + CKR_BAD_SYSCALL, CKR_RESOURCE_OVERRUN}; + rc.status = map[r->out.status]; + if (r->out.status == ST_EXITED) + rc.exit = (int32_t)(uint32_t)r->out.value; + } + uint32_t fl = 0; + if (reclaimed(r)) + fl |= CKR_F_RECLAIMED; + if (adm) { + if (r->out.reads_ok) + fl |= CKR_F_READ_OK; + if (r->out.write_denials) + fl |= CKR_F_WRITE_DENIED; + if (r->out.invalid_handle) + fl |= CKR_F_FORGED_DENIED; + if (rc.status == CKR_EXITED && rc.exit == 0) + fl |= CKR_F_CANARY; + if (r->b.mapped_bytes_matched) + fl |= CKR_F_MAPPED; + if (r->byte_chain) + fl |= CKR_F_EXECUTED; + if (r->b.wx_sealed) + fl |= CKR_F_WX; + } + rc.result_flags = fl; + rc.stage = adm ? 0 : (uint16_t)r->stage; + rc.reason = adm ? 0 : (uint16_t)r->error; + rc.syscalls = adm ? r->out.syscalls : 0; + rc.reads = adm ? r->out.reads_ok : 0; + rc.denials = adm ? r->out.denials : 0; + rc.frames = r->frames_reserved > 0xffffffffull ? 0xffffffffu : (uint32_t)r->frames_reserved; + memcpy(rc.id, r->b.id, 32); + memcpy(rc.payload, r->b.payload, 32); + memcpy(rc.signer, r->b.signer, 32); + memcpy(rc.policy, r->b.policy, 32); + memcpy(rc.requested, r->b.requested, 32); + memcpy(rc.granted, r->b.granted, 32); + memcpy(rc.resources, r->b.resources, 32); + if (cka_receipt_validate(&rc)) { + ck_printf("receipt: %s seq=%llu invalid\n", name, (unsigned long long)seq); + return; + } + static uint8_t rec[CKA_RECEIPT_SIZE]; + static char line[2 * CKA_RECEIPT_SIZE + 1]; + uint8_t dg[32]; + char dh[65]; + cka_receipt_encode(&rc, rec); + cka_receipt_digest(rec, dg); + hex(dh, dg, 32); + hex(line, rec, CKA_RECEIPT_SIZE); + ck_printf("receipt: %s seq=%llu digest=%s record=", name, (unsigned long long)seq, dh); + ck_puts(line); + ck_puts("\n"); +} + +/* ============================ fw_cfg source ========================= */ + +static volatile uint8_t *fwcfg; + +static void fw_select(uint16_t sel) +{ + *(volatile uint16_t *)(fwcfg + 8) = (uint16_t)((sel >> 8) | (sel << 8)); /* big endian */ + __asm__ volatile("dsb sy" ::: "memory"); +} +static void fw_read(uint8_t *out, uint64_t n) +{ + for (uint64_t i = 0; i < n; i++) + out[i] = fwcfg[0]; +} +static void fw_skip(uint64_t n) +{ + for (uint64_t i = 0; i < n; i++) + (void)fwcfg[0]; +} +static uint32_t be32(const uint8_t *b) +{ + return (uint32_t)b[0] << 24 | (uint32_t)b[1] << 16 | (uint32_t)b[2] << 8 | b[3]; +} + +/* The fw_cfg MMIO window from the DSDT: device _HID "QEMU0002", then its + * _CRS Memory32Fixed descriptor (0x86, length 9). 0 if absent. */ +static uint64_t fwcfg_from_dsdt(const char **why) +{ + const uint8_t *fadt = ck_acpi_find("FACP"); + if (!fadt) { + *why = "no FADT"; + return 0; + } + uint32_t flen = cka_rd32(fadt + 4); + uint64_t dsdt = 0; + if (flen >= 148) + dsdt = cka_rd64(fadt + 140); + if (!dsdt && flen >= 44) + dsdt = cka_rd32(fadt + 40); + if (!dsdt || !ck_mm_mapped(dsdt, 36)) { + *why = "DSDT not mapped"; + return 0; + } + const uint8_t *d = (const uint8_t *)(uintptr_t)dsdt; + uint32_t len = cka_rd32(d + 4); + if (len < 36 || memcmp(d, "DSDT", 4) || !ck_mm_mapped(dsdt, len)) { + *why = "DSDT not mapped"; + return 0; + } + static const char hid[] = "QEMU0002"; + for (uint32_t i = 36; i + 9 <= len; i++) { + if (memcmp(d + i, hid, 8)) + continue; + for (uint32_t j = i + 8; j + 12 <= len && j < i + 8 + 96; j++) + if (d[j] == 0x86 && d[j + 1] == 0x09 && d[j + 2] == 0x00) { + uint64_t base = cka_rd32(d + j + 4), size = cka_rd32(d + j + 8); + if (base && size >= 0x10) + return base; + } + } + *why = "no QEMU0002 device"; + return 0; +} + +/* Finds "opt/aienos/artifacts": selector and size, -1 if absent. */ +static int fw_find(uint16_t *sel, uint32_t *size) +{ + uint8_t b[64]; + fw_select(0x19); + fw_read(b, 4); + uint32_t n = be32(b); + for (uint32_t i = 0; i < n && i < 4096; i++) { + fw_read(b, 64); + b[63] = 0; + if (!memcmp(b + 8, "opt/aienos/artifacts", 21)) { + *sel = (uint16_t)(b[4] << 8 | b[5]); + *size = be32(b); + return 0; + } + } + return -1; +} + +static struct report rep; + +void ck_artifact_run(void) +{ + static int ran; + if (ran) + return; + ran = 1; + ck_set_stage("artifacts"); +#ifdef CK_SEED0B_TEST_ANCHOR + ck_puts("artifact_trust: seed0b-test qualification build \xe2\x80\x94 TEST ONLY\n"); +#endif + if (NANCHORS) + cka_boot_policy(&policy, anchors, NANCHORS); + else + cka_boot_policy(&policy, 0, 0); + cka_verifier_identity(AIENOS_COMMIT, FEATURE_TEST_ANCHOR, verifier_id); + + const char *why = 0; + uint64_t base = fwcfg_from_dsdt(&why); + uint16_t sel = 0; + uint32_t size = 0; + if (base && !ck_mm_mmio_try_map(base, 0x18)) + why = "fw_cfg window not mappable", base = 0; + if (base) { + fwcfg = (volatile uint8_t *)(uintptr_t)base; + uint8_t sig[4]; + fw_select(0); + fw_read(sig, 4); + if (memcmp(sig, "QEMU", 4)) + why = "fw_cfg signature", base = 0; + else if (fw_find(&sel, &size)) + why = "no opt/aienos/artifacts", base = 0; + } + uint8_t hdr[12]; + uint32_t count = 0; + if (base) { + fw_select(sel); + if (size < 12) + why = "bundle too short", base = 0; + else { + fw_read(hdr, 12); + if (memcmp(hdr, "AIENBND", 8)) + why = "bundle magic", base = 0; + else + count = cka_rd32(hdr + 8); + } + } + if (!base) + ck_printf("artifact_source: none (%s)\n", why); + else + ck_printf("artifact_source: fw_cfg base=0x%llx file=opt/aienos/artifacts bytes=%u\n", + (unsigned long long)base, size); + if (count > MAX_CANDIDATES) + count = MAX_CANDIDATES; + char vh[65], ph[65]; + uint8_t pd[32]; + cka_policy_digest(&policy, pd); + hex(vh, verifier_id, 32); + hex(ph, pd, 32); + ck_printf("artifact_candidates: %u\n", count); + ck_printf("artifact_receipt_tier: SEED-0B-QEMU\nartifact_verifier_identity: %s\n" + "artifact_policy_digest: %s\n", + vh, ph); + ck_printf("artifact_frames_free_before: %llu\n", (unsigned long long)free_frames()); + + unsigned admitted = 0, rejected = 0, seen = 0; + uint64_t left = size >= 12 ? size - 12 : 0; + for (uint32_t c = 0; c < count; c++) { + uint8_t nb[2], lb[4]; + char name[MAX_NAME + 1]; + if (left < 2) + break; + fw_read(nb, 2); + left -= 2; + unsigned nlen = cka_rd16(nb); + if (nlen == 0 || nlen > MAX_NAME || left < nlen + 4ull) + break; + fw_read((uint8_t *)name, nlen); + name[nlen] = 0; + fw_read(lb, 4); + left -= nlen + 4ull; + uint64_t len = cka_rd32(lb); + if (len > left) + break; + left -= len; + int ok_name = 1; + for (unsigned i = 0; i < nlen; i++) + if (name[i] <= ' ' || name[i] > '~') + ok_name = 0; + if (!ok_name) + break; + seen++; + uint64_t pages = (len + PAGE - 1) / PAGE, in = 0; + if (len > MAX_BATCH * PAGE) { + fw_skip(len); + firmware_rejection(&rep, CKL_STAGING_TOO_LARGE); + } else if (len && ck_mm_frames_alloc(pages, &in)) { + fw_skip(len); + firmware_rejection(&rep, CKL_FIRMWARE_READ); + } else { + if (len) + fw_read(mem(in), len); + process_candidate(len ? mem(in) : (const uint8_t *)"", len, &rep); + if (len) { + memset(mem(in), 0, pages * PAGE); + ck_mm_frames_free(in, pages); + } + } + if (rep.admitted) + admitted++; + else + rejected++; + print_candidate(name, &rep); + print_grants(name, &rep); + print_receipt(name, &rep); + } + if (seen != count) + ck_printf("artifact_bundle: malformed after %u of %u candidates\n", seen, count); + ck_printf("artifact_frames_free_after: %llu\n", (unsigned long long)free_frames()); + ck_artifact_summary.candidates = count; + ck_artifact_summary.admitted = admitted; + ck_artifact_summary.rejected = rejected; +} + + +void ck_artifact_final(void) +{ +#ifdef CK_SEED0B_TEST_ANCHOR + ck_puts("artifact_trust: seed0b-test qualification build \xe2\x80\x94 TEST ONLY\n"); +#endif + ck_printf("artifacts: candidates=%u admitted=%u rejected=%u\n", ck_artifact_summary.candidates, + ck_artifact_summary.admitted, ck_artifact_summary.rejected); +} diff --git a/native/kernel/core/ck_internal.h b/native/kernel/core/ck_internal.h index b1f26abc..fdd70461 100644 --- a/native/kernel/core/ck_internal.h +++ b/native/kernel/core/ck_internal.h @@ -59,6 +59,21 @@ uint64_t ck_mm_sctlr(void); /* Guard-page self test (EL1). 0 if every guard faulted and was contained. */ int ck_mm_guard_selftest(char *detail, size_t n); +/* ---- artifact loader support (mm/mmu.c) ---- */ +/* Contiguous 4 KiB frames from the free list; 0 on success. */ +int ck_mm_frames_alloc(uint64_t npages, uint64_t *pa); +/* Returns the frames; nonzero if the free list refused them. */ +int ck_mm_frames_free(uint64_t pa, uint64_t npages); +uint64_t ck_mm_free_frames(void); +/* 1 if [pa, pa+len) is identity mapped in the kernel tables. */ +int ck_mm_mapped(uint64_t pa, uint64_t len); +/* ck_mmio_map without the panic: 0 on RAM overlap or map failure. */ +volatile void *ck_mm_mmio_try_map(uint64_t phys, size_t len); + +/* ---- P2 artifact loader (core/artifact_loader.c) ---- */ +void ck_artifact_run(void); +void ck_artifact_final(void); + /* ---- GIC and timer (arch/gic.c, arch/timer.c) ---- */ struct ck_gic_report { uint64_t gicd, gicr; diff --git a/native/kernel/core/kmain.c b/native/kernel/core/kmain.c index 1c253656..c5413587 100644 --- a/native/kernel/core/kmain.c +++ b/native/kernel/core/kmain.c @@ -118,6 +118,9 @@ static __attribute__((noreturn)) void ck_el1_main(void *arg) /* M3 isolation checks (core/m3.c), before any stage registers an IRQ. */ ck_m3_run(); + /* P2 sealed-artifact loader (core/artifact_loader.c). */ + ck_artifact_run(); + run_stage("devices", ck_stage_devices); run_stage("security", ck_stage_security); run_stage("store", ck_stage_store); @@ -131,6 +134,7 @@ static __attribute__((noreturn)) void ck_el1_main(void *arg) ck_set_stage("final"); ck_puts("\n"); ck_report_header("final"); + ck_artifact_final(); ck_puts("note: QEMU qualifies nothing physical\n"); ck_reset(); } diff --git a/native/kernel/mm/mmu.c b/native/kernel/mm/mmu.c index f90a9960..f968bff9 100644 --- a/native/kernel/mm/mmu.c +++ b/native/kernel/mm/mmu.c @@ -339,3 +339,51 @@ int ck_mm_guard_selftest(char *detail, size_t n) (unsigned long long)rep.heap_guard_hi); return 0; } + +/* ---- artifact loader support (core/artifact_loader.c) ---- */ + +int ck_mm_frames_alloc(uint64_t npages, uint64_t *pa) +{ + return npages ? ck_frames_alloc(&frames, npages, CK_PAGE, pa) : -1; +} + +int ck_mm_frames_free(uint64_t pa, uint64_t npages) +{ + return ck_frames_add(&frames, pa, pa + npages * CK_PAGE); +} + +uint64_t ck_mm_free_frames(void) { return ck_frames_free_bytes(&frames) / CK_PAGE; } + +int ck_mm_mapped(uint64_t pa, uint64_t len) +{ + uint64_t lo = pa & ~(CK_PAGE - 1), hi = pa + len; + if (hi < pa) + return 0; + for (uint64_t p = lo; p < hi; p += CK_PAGE) { + uint64_t a; + if (ck_pt_lookup(&pt, p, &a, 0, 0) != 0 || a != p) + return 0; + } + return 1; +} + +volatile void *ck_mm_mmio_try_map(uint64_t phys, size_t len) +{ + uint64_t lo = phys & ~(CK_PAGE - 1); + uint64_t hi = (phys + len + CK_PAGE - 1) & ~(CK_PAGE - 1); + if (!len || hi <= lo || overlaps_ram(lo, hi)) + return 0; + for (uint64_t p = lo; p < hi; p += CK_PAGE) { + uint64_t a; + if (ck_pt_lookup(&pt, p, &a, 0, 0) == 0) { + if (a != p) + return 0; + continue; + } + if (ck_pt_map(&pt, p, p, CK_PAGE, CK_PT_DEVICE)) + return 0; + } + if (pt.live) + tlb_sync(); + return (volatile void *)(uintptr_t)phys; +} diff --git a/native/kernel/tests/test_artifact.c b/native/kernel/tests/test_artifact.c new file mode 100644 index 00000000..fd9b3ab8 --- /dev/null +++ b/native/kernel/tests/test_artifact.c @@ -0,0 +1,127 @@ +/* test_artifact.c -- host test of the C artifact library (format, TEST-key + * verification, admission policy, receipts) that the kernel loader uses. + * The pack/sign helpers come from the in-tree tool (its main is renamed). */ +#define main ck_artifact_tool_main +#include "../tools/ck_artifact_tool.c" +#undef main + +#include "ck_test.h" + +static struct cka_limits plenty(void) +{ + struct cka_limits l = {1000, 1000, 1000, 16, 0, 0, 1000000000ull, 1000000000ull, 65536}; + return l; +} + +static void test_verify_and_admit(void) +{ + struct buf b = signed_art(1, seed_read(1), res(1, 1, 1, 1, 8), exit0_w, 4, "BASELINE"); + struct cka_parsed p; + struct cka_ident id; + uint8_t fp[32], pkfp[32]; + CHECK(cka_identify(b.p, b.n, &p, &id) == 0); + CHECK(verify_test(&b, &p, &id, fp) == 0); + sha256_hash(cka_test1_pk, 32, pkfp); + CHECK(memcmp(fp, pkfp, 32) == 0); + + /* Production trust (no anchors): the same artifact is refused. */ + CHECK(cka_verify(b.p, b.n, 0, 0, &p, &id, fp) == CKA_UNTRUSTED_SIGNER); + + /* Qualification policy admits it with the requested read grant. */ + struct cka_policy pol; + struct cka_decision d; + struct cka_limits avail = plenty(); + CHECK(verify_test(&b, &p, &id, fp) == 0); + cka_boot_policy(&pol, &cka_test1_pk, 1); + CHECK(cka_evaluate(&pol, &p, fp, &avail, &d) == 0); + CHECK(d.ngrants == 1 && d.grants[0].rights == 1 && d.grants[0].id == 1); + + /* No frames available: ResourceLimit, never a partial admission. */ + avail.code_pages = avail.data_pages = avail.stack_pages = 0; + CHECK(cka_evaluate(&pol, &p, fp, &avail, &d) == CKA_RESOURCE_LIMIT); + + /* A policy without signers refuses the TEST signer. */ + struct cka_policy prod; + cka_boot_policy(&prod, 0, 0); + avail = plenty(); + CHECK(cka_evaluate(&prod, &p, fp, &avail, &d) != 0); + uint8_t d1[32], d2[32]; + cka_policy_digest(&pol, d1); + cka_policy_digest(&prod, d2); + CHECK(memcmp(d1, d2, 32) != 0); + + /* Any payload byte flipped: refused at verification. */ + struct buf t = clone(&b, 0); + t.p[p.payload_off] ^= 1; + CHECK(cka_verify(t.p, t.n, &cka_test1_pk, 1, &p, &id, fp) != 0); + /* Truncated: refused before any signature work. */ + CHECK(cka_identify(b.p, 100, &p, &id) != 0); + free(t.p); + free(b.p); +} + +static void test_receipt(void) +{ + struct cka_receipt r, back; + uint8_t rec[CKA_RECEIPT_SIZE], dg[32], dg2[32], ver[32]; + memset(&r, 0, sizeof r); + cka_verifier_identity("0123456789abcdef0123456789abcdef01234567", 1, ver); + r.decision = CKR_ADMITTED; + r.tier = CKR_TIER_SEED0B_QEMU; + r.seq = 1; + memcpy(r.verifier, ver, 32); + cka_receipt_nonce(ver, 1, r.nonce); + r.status = CKR_EXITED; + r.result_flags = 0xff; + r.syscalls = 9; + r.reads = 3; + r.denials = 5; + r.frames = 9; + memset(r.id, 0x11, 32); + memset(r.payload, 0x22, 32); + memset(r.signer, 0x33, 32); + memset(r.policy, 0x44, 32); + memset(r.requested, 0x55, 32); + memset(r.granted, 0x66, 32); + memset(r.resources, 0x77, 32); + CHECK(cka_receipt_validate(&r) == 0); + cka_receipt_encode(&r, rec); + CHECK(cka_receipt_decode(rec, &back) == 0); + CHECK(back.seq == 1 && back.syscalls == 9 && back.result_flags == 0xff); + cka_receipt_digest(rec, dg); + cka_receipt_digest(rec, dg2); + CHECK(memcmp(dg, dg2, 32) == 0); + CHECK(!cka_receipt_is_signed(rec)); + CHECK(cka_receipt_sign(rec, test2_seed) == 0); + CHECK(cka_receipt_verify(rec, &cka_test2_pk, 1) == 0); + CHECK(cka_receipt_verify(rec, &cka_test1_pk, 1) != 0); + rec[20] ^= 1; + CHECK(cka_receipt_verify(rec, &cka_test2_pk, 1) != 0); + + /* An admitted receipt cannot carry a rejection stage. */ + r.stage = CKS_VERIFIED; + r.reason = CKA_BAD_SIGNATURE; + CHECK(cka_receipt_validate(&r) != 0); + { + uint8_t bad[CKA_RECEIPT_SIZE]; + struct cka_receipt out; + cka_receipt_encode(&r, bad); + CHECK(cka_receipt_decode(bad, &out) != 0); /* decode validates */ + } +} + +static void test_names(void) +{ + CHECK(strcmp(cka_error_name(CKA_UNTRUSTED_SIGNER), "UntrustedSigner") == 0); + CHECK(strcmp(cka_error_name(CKL_WX_AUDIT), "WxAudit") == 0); + CHECK(strcmp(cka_stage_name(CKS_VERIFIED), "verified") == 0 || + strcmp(cka_stage_name(CKS_VERIFIED), "Verified") == 0); +} + +int main(void) +{ + test_verify_and_admit(); + test_receipt(); + test_names(); + return ck_t_verdict("test_artifact"); +} diff --git a/native/kernel/tools/ck_artifact_tool.c b/native/kernel/tools/ck_artifact_tool.c new file mode 100644 index 00000000..e2424669 --- /dev/null +++ b/native/kernel/tools/ck_artifact_tool.c @@ -0,0 +1,762 @@ +/* ck_artifact_tool.c -- host tool for the C kernel P2_ARTIFACT gate. + * C port of the commands of crates/aienos-artifact-tool that the gate uses + * (pack, sign, id, verify, negative-corpus, receipt from-hex|check|sign-test| + * verify), plus "bundle", which packs candidates into the fw_cfg file the C + * kernel reads (opt/aienos/artifacts). + * + * TEST ONLY: sign / negative-corpus / receipt sign-test use the RFC 8032 + * TEST 1 (artifact) and TEST 2 (receipt) seeds. These are public test + * vectors, never owner key material, and the tool has no other keys. */ +#include +#include +#include +#include + +#include "aienos_sig.h" +#include "ck_artifact.h" +#include "sha256.h" + +static const uint8_t test1_seed[32] = { + 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4, + 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60, +}; +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, +}; +/* RFC 8032 TEST 3 seed: a well-formed key no anchor set trusts (H15). */ +static const uint8_t untrusted_seed[32] = { + 0xc5, 0xaa, 0x8d, 0xf4, 0x3f, 0x9f, 0x83, 0x7b, 0xed, 0xb7, 0x44, 0x2f, 0x31, 0xdc, 0xb7, 0xb1, + 0x66, 0xd3, 0x85, 0x35, 0x07, 0x6f, 0x09, 0x4b, 0x85, 0xce, 0x3a, 0x2e, 0x0b, 0x44, 0x58, 0xf7, +}; + +static void die(const char *m) +{ + fprintf(stderr, "error: %s\n", m); + exit(1); +} + +struct buf { + uint8_t *p; + size_t n; +}; + +static struct buf readf(const char *path) +{ + FILE *f = fopen(path, "rb"); + if (!f) { + fprintf(stderr, "error: cannot open %s: %s\n", path, strerror(errno)); + exit(1); + } + struct buf b = {0, 0}; + size_t cap = 0; + for (;;) { + if (b.n == cap) { + cap = cap ? cap * 2 : 4096; + if (cap > ((size_t)64 << 20)) + die("input too large"); + b.p = realloc(b.p, cap); + if (!b.p) + die("out of memory"); + } + size_t r = fread(b.p + b.n, 1, cap - b.n, f); + b.n += r; + if (r == 0) + break; + } + if (ferror(f)) + die("read error"); + fclose(f); + return b; +} + +static void writef(const char *path, const uint8_t *p, size_t n) +{ + FILE *f = fopen(path, "wb"); + if (!f || (n && fwrite(p, 1, n, f) != n) || fclose(f) != 0) { + fprintf(stderr, "error: cannot write %s\n", path); + exit(1); + } +} + +static void hex(const uint8_t *b, size_t n, char *out) +{ + static const char d[] = "0123456789abcdef"; + for (size_t i = 0; i < n; i++) { + out[2 * i] = d[b[i] >> 4]; + out[2 * i + 1] = d[b[i] & 15]; + } + out[2 * n] = 0; +} + +static void phex(const char *label, const uint8_t *b) +{ + char h[65]; + hex(b, 32, h); + printf("%s%s\n", label, h); +} + +/* ---- minimal manifest JSON (the Rust Manifest, deny_unknown_fields) ---- */ +struct manifest { + uint32_t entry; + unsigned ncaps; + struct cka_cap caps[CKA_MAX_CAPS]; + struct cka_env env; +}; + +struct js { + const char *s; + size_t i, n; +}; + +static void ws(struct js *j) +{ + while (j->i < j->n && (j->s[j->i] == ' ' || j->s[j->i] == '\n' || j->s[j->i] == '\r' || + j->s[j->i] == '\t')) + j->i++; +} + +static void expect(struct js *j, char c) +{ + ws(j); + if (j->i >= j->n || j->s[j->i] != c) + die("manifest: malformed JSON"); + j->i++; +} + +static int peek(struct js *j, char c) +{ + ws(j); + return j->i < j->n && j->s[j->i] == c; +} + +static void key(struct js *j, char *out, size_t cap) +{ + expect(j, '"'); + size_t k = 0; + while (j->i < j->n && j->s[j->i] != '"') { + if (j->s[j->i] == '\\' || k + 1 >= cap) + die("manifest: unsupported key"); + out[k++] = j->s[j->i++]; + } + out[k] = 0; + expect(j, '"'); + expect(j, ':'); +} + +static uint64_t num(struct js *j, uint64_t max) +{ + ws(j); + uint64_t v = 0; + size_t start = j->i; + while (j->i < j->n && j->s[j->i] >= '0' && j->s[j->i] <= '9') { + unsigned d = (unsigned)(j->s[j->i++] - '0'); + if (v > (UINT64_MAX - d) / 10) + die("manifest: number overflow"); + v = v * 10 + d; + } + if (j->i == start || (j->i - start > 1 && j->s[start] == '0')) + die("manifest: expected an unsigned integer"); + if (v > max) + die("manifest: number out of range for its field"); + return v; +} + +#define U16 0xffffu +#define U32 0xffffffffu + +static void parse_cap(struct js *j, struct cka_cap *c) +{ + unsigned seen = 0; + expect(j, '{'); + while (!peek(j, '}')) { + char k[40]; + key(j, k, sizeof k); + unsigned bit; + if (!strcmp(k, "resource_kind")) c->kind = (uint16_t)num(j, U16), bit = 1; + else if (!strcmp(k, "resource_id")) c->id = (uint32_t)num(j, U32), bit = 2; + else if (!strcmp(k, "rights")) c->rights = (uint32_t)num(j, U32), bit = 4; + else if (!strcmp(k, "bounds_kind")) c->bounds = (uint32_t)num(j, U32), bit = 8; + else if (!strcmp(k, "max_operations")) c->max_ops = (uint32_t)num(j, U32), bit = 16; + else if (!strcmp(k, "max_bytes")) c->max_bytes = num(j, UINT64_MAX), bit = 32; + else if (!strcmp(k, "byte_offset")) c->off = num(j, UINT64_MAX), bit = 64; + else if (!strcmp(k, "byte_length")) c->len = num(j, UINT64_MAX), bit = 128; + else die("manifest: unknown capability field"); + if (seen & bit) + die("manifest: duplicate field"); + seen |= bit; + if (!peek(j, '}')) + expect(j, ','); + } + expect(j, '}'); + if (seen != 255) + die("manifest: missing capability field"); +} + +static void parse_env(struct js *j, struct cka_env *e) +{ + unsigned seen = 0; + expect(j, '{'); + while (!peek(j, '}')) { + char k[40]; + key(j, k, sizeof k); + unsigned bit; + if (!strcmp(k, "code_pages")) e->code_pages = (uint32_t)num(j, U32), bit = 1; + else if (!strcmp(k, "data_pages")) e->data_pages = (uint32_t)num(j, U32), bit = 2; + else if (!strcmp(k, "stack_pages")) e->stack_pages = (uint32_t)num(j, U32), bit = 4; + else if (!strcmp(k, "max_capabilities")) e->max_caps = (uint16_t)num(j, U16), bit = 8; + else if (!strcmp(k, "ipc_messages")) e->ipc_msgs = (uint32_t)num(j, U32), bit = 16; + else if (!strcmp(k, "ipc_bytes")) e->ipc_bytes = (uint32_t)num(j, U32), bit = 32; + else if (!strcmp(k, "cpu_ticks")) e->cpu = num(j, UINT64_MAX), bit = 64; + else if (!strcmp(k, "elapsed_ticks")) e->elapsed = num(j, UINT64_MAX), bit = 128; + else if (!strcmp(k, "syscall_count")) e->syscalls = (uint32_t)num(j, U32), bit = 256; + else die("manifest: unknown resources field"); + if (seen & bit) + die("manifest: duplicate field"); + seen |= bit; + if (!peek(j, '}')) + expect(j, ','); + } + expect(j, '}'); + if (seen != 511) + die("manifest: missing resources field"); +} + +static void parse_manifest(const struct buf *b, struct manifest *m) +{ + struct js j = {(const char *)b->p, 0, b->n}; + unsigned seen = 0; + memset(m, 0, sizeof *m); + expect(&j, '{'); + while (!peek(&j, '}')) { + char k[40]; + key(&j, k, sizeof k); + unsigned bit; + if (!strcmp(k, "entry_offset")) { + m->entry = (uint32_t)num(&j, U32); + bit = 1; + } else if (!strcmp(k, "capabilities")) { + expect(&j, '['); + while (!peek(&j, ']')) { + if (m->ncaps >= CKA_MAX_CAPS) + die("code, data, and capability count are outside v0 bounds"); + parse_cap(&j, &m->caps[m->ncaps++]); + if (!peek(&j, ']')) + expect(&j, ','); + } + expect(&j, ']'); + bit = 2; + } else if (!strcmp(k, "resources")) { + parse_env(&j, &m->env); + bit = 4; + } else { + die("manifest: unknown field"); + } + if (seen & bit) + die("manifest: duplicate field"); + seen |= bit; + if (!peek(&j, '}')) + expect(&j, ','); + } + expect(&j, '}'); + ws(&j); + if (j.i != j.n || seen != 7) + die("manifest: missing field or trailing data"); +} + +/* ---- pack (main.rs pack_bytes, same byte layout) ---- */ +static struct buf pack(const struct manifest *m, const uint8_t *code, size_t clen, + const uint8_t *data, size_t dlen) +{ + if (clen == 0 || dlen == 0 || m->ncaps > 16) + die("code, data, and capability count are outside v0 bounds"); + size_t res = CKA_CAPS_OFFSET + (size_t)m->ncaps * CKA_CAP_SIZE; + size_t pay = (res + CKA_ENV_SIZE + 15) & ~(size_t)15; + size_t plen = clen + dlen; + size_t sig = pay + plen; + size_t total = sig + CKA_SIG_SIZE; + if (total > CKA_MAX_ARTIFACT || plen > CKA_MAX_PAYLOAD) + die("artifact exceeds v0 maximum size"); + if ((uint64_t)m->env.data_pages * 4096u > 0xffffffffu) + die("data page overflow"); + struct buf b = {calloc(1, total), total}; + if (!b.p) + die("out of memory"); + uint8_t *p = b.p; + memcpy(p, "AIENART\0", 8); + cka_wr16(p + 8, 0); + cka_wr16(p + 10, CKA_HEADER_SIZE); + cka_wr16(p + 12, CKA_TARGET_AARCH64_LE); + cka_wr16(p + 14, CKA_ABI_V1); + cka_wr32(p + 20, (uint32_t)total); + cka_wr32(p + 24, 128); + cka_wr16(p + 28, 2); + cka_wr16(p + 30, CKA_SECTION_SIZE); + cka_wr32(p + 36, m->entry); + cka_wr32(p + 40, CKA_CAPS_OFFSET); + cka_wr16(p + 44, (uint16_t)m->ncaps); + cka_wr16(p + 46, CKA_CAP_SIZE); + cka_wr32(p + 48, (uint32_t)res); + cka_wr16(p + 52, CKA_ENV_SIZE); + cka_wr32(p + 56, (uint32_t)pay); + cka_wr32(p + 60, (uint32_t)plen); + cka_wr32(p + 64, (uint32_t)sig); + cka_wr16(p + 68, CKA_SIG_SIZE); + cka_wr16(p + 70, 1); + /* sections: kind, perms, rel, flen, mlen, align 4096 */ + uint8_t *s = p + 128; + cka_wr16(s, 1), cka_wr16(s + 2, 5), cka_wr32(s + 8, 0), cka_wr32(s + 12, (uint32_t)clen); + cka_wr32(s + 16, (uint32_t)clen), cka_wr32(s + 20, 4096); + s += 32; + cka_wr16(s, 2), cka_wr16(s + 2, 3), cka_wr32(s + 8, (uint32_t)clen); + cka_wr32(s + 12, (uint32_t)dlen), cka_wr32(s + 16, m->env.data_pages * 4096u); + cka_wr32(s + 20, 4096); + for (unsigned i = 0; i < m->ncaps; i++) + cka_cap_encode(&m->caps[i], p + CKA_CAPS_OFFSET + i * CKA_CAP_SIZE); + cka_env_encode(&m->env, p + res); + memcpy(p + pay, code, clen); + memcpy(p + pay + clen, data, dlen); + cka_wr16(p + sig, 1); + struct cka_parsed pa; + int e = cka_parse(p, total, &pa); + for (unsigned i = 0; !e && i < pa.ncaps; i++) + e = cka_cap_validate(&pa.caps[i]); + if (!e) + e = cka_env_validate(&pa.env, pa.ncaps); + if (e) { + fprintf(stderr, "error: packed artifact refused: %s\n", cka_error_name((unsigned)e)); + exit(1); + } + return b; +} + +static void sign_with(struct buf *b, const uint8_t seed[32]) +{ + struct cka_parsed p; + struct cka_ident id; + int e = cka_identify(b->p, b->n, &p, &id); + if (e) { + fprintf(stderr, "error: does not parse: %s\n", cka_error_name((unsigned)e)); + exit(1); + } + uint8_t pk[32], msg[64]; + size_t mlen; + if (aienos_ed25519_public_key(pk, seed) != AIENOS_SIG_OK) + die("public key"); + uint8_t *blk = b->p + p.sig_off; + sha256_hash(pk, 32, blk + 4); + cka_signature_message(id.id, msg, &mlen); + if (aienos_ed25519_sign(blk + 36, msg, mlen, seed) != AIENOS_SIG_OK) + die("sign"); +} + +static int verify_test(const struct buf *b, struct cka_parsed *p, struct cka_ident *id, + uint8_t fp[32]) +{ + const uint8_t (*anchors)[32] = &cka_test1_pk; + return cka_verify(b->p, b->n, anchors, 1, p, id, fp); +} + +/* ---- negative corpus (corpus.rs, same cases, names and expectations) ---- */ +#define MOV_X0_0 0xd2800000u +#define MOV_X8_2 0xd2800048u +#define MOV_X8_6 0xd28000c8u +#define MOV_X8_99 0xd2800c68u +#define SVC_0 0xd4000001u +#define B_SELF 0x14000000u +#define BR_X2 0xd61f0040u +#define SUB_X9_SP_16 0xd10043e9u +#define BR_X9 0xd61f0120u + +static size_t words(uint8_t *out, const uint32_t *w, size_t n) +{ + for (size_t i = 0; i < n; i++) + cka_wr32(out + 4 * i, w[i]); + return 4 * n; +} + +static struct cka_cap seed_read(uint32_t rights) +{ + struct cka_cap c = {3, 1, rights, 1, 4, 32, 0, 32}; + return c; +} + +static struct cka_env res(uint32_t code, uint32_t data, uint32_t stack, uint16_t caps, + uint32_t sys) +{ + struct cka_env e = {code, data, stack, caps, 0, 0, 100000000, 100000000, sys}; + return e; +} + +static struct buf signed_art(unsigned ncaps, struct cka_cap cap, struct cka_env env, + const uint32_t *w, size_t nw, const char *data8) +{ + struct manifest m; + memset(&m, 0, sizeof m); + m.ncaps = ncaps; + m.caps[0] = cap; + m.env = env; + uint8_t code[64]; + size_t cl = words(code, w, nw); + struct buf b = pack(&m, code, cl, (const uint8_t *)data8, 8); + sign_with(&b, test1_seed); + return b; +} + +static const uint32_t exit0_w[] = {MOV_X0_0, MOV_X8_2, SVC_0, B_SELF}; + +static struct buf clone(const struct buf *b, size_t extra) +{ + struct buf c = {calloc(1, b->n + extra + 1), b->n}; + if (!c.p) + die("out of memory"); + memcpy(c.p, b->p, b->n); + return c; +} + +static void corpus(const char *dir) +{ + struct buf base = signed_art(1, seed_read(1), res(1, 1, 1, 1, 8), exit0_w, 4, "BASELINE"); + size_t payload = cka_rd32(base.p + 56); + size_t resource = CKA_CAPS_OFFSET + CKA_CAP_SIZE; + size_t sig = base.n - 100; + char path[4096], exp[8192]; + size_t el = 0; + exp[0] = 0; +#define EMIT(NAME, BUF, EXPECT, WHAT) \ + do { \ + snprintf(path, sizeof path, "%s/%s", dir, NAME); \ + writef(path, (BUF).p, (BUF).n); \ + el += (size_t)snprintf(exp + el, sizeof exp - el, "%s %s # %s\n", NAME, EXPECT, WHAT); \ + free((BUF).p); \ + } while (0) +#define MUT(NAME, STMT, EXPECT, WHAT) \ + do { \ + struct buf b = clone(&base, 1); \ + STMT; \ + EMIT(NAME, b, EXPECT, WHAT); \ + } while (0) +#define V(R, C) "rejected verified " R " " C + MUT("H01-BAD-MAGIC.AIEN", b.p[0] = 'X', V("BadMagic", "0x1"), "magic is not AIENART\\0"); + MUT("H02-VERSION.AIEN", cka_wr16(b.p + 8, 1), V("UnsupportedVersion", "0x2"), + "format_version 1 (unsupported)"); + MUT("H03-TARGET.AIEN", cka_wr16(b.p + 12, 2), V("WrongTarget", "0x3"), + "target_arch 2 (not AArch64 LE)"); + MUT("H04-ABI.AIEN", cka_wr16(b.p + 14, 2), V("WrongAbi", "0x4"), "abi_version 2 (not ABI v1)"); + MUT("H05-TRUNCATED.AIEN", b.n -= 10, V("WrongLength", "0x7"), "last 10 bytes cut off"); + MUT("H06-TRAILING.AIEN", b.p[b.n++] = 0, V("WrongLength", "0x7"), + "one byte appended after the signature block"); + MUT("H07-TOTAL-LENGTH.AIEN", cka_wr32(b.p + 20, cka_rd32(b.p + 20) + 1), + V("WrongLength", "0x7"), "total_length field one larger than the file"); + MUT("H08-OFFSET-OVERFLOW.AIEN", cka_wr32(b.p + 60, 0xffffffffu), V("ResourceLimit", "0xe"), + "payload_length 0xffffffff (offset + length overflows)"); + MUT("H09-SECTION-OVERLAP.AIEN", cka_wr32(b.p + 160 + 8, 4), V("BadSection", "0xb"), + "data section starts inside the code section"); + MUT("H10-ENTRY-OUTSIDE.AIEN", cka_wr32(b.p + 36, 0x1000), V("BadEntryPoint", "0xc"), + "entry_offset beyond the code bytes"); + MUT("H11-PAYLOAD-MUTATED.AIEN", b.p[payload] ^= 1, V("BadSignature", "0x12"), + "one code byte changed after signing"); + MUT("H12-CAPS-MUTATED.AIEN", cka_wr32(b.p + CKA_CAPS_OFFSET + 8, 3), V("BadSignature", "0x12"), + "requested rights READ -> READ|WRITE after signing"); + MUT("H13-ENVELOPE-MUTATED.AIEN", cka_wr32(b.p + resource + 8, 2), V("BadSignature", "0x12"), + "stack_pages 1 -> 2 after signing"); + MUT("H14-SIGNATURE-MUTATED.AIEN", b.p[sig + 40] ^= 1, V("BadSignature", "0x12"), + "one signature byte changed"); + MUT("H15-UNKNOWN-SIGNER.AIEN", sign_with(&b, untrusted_seed), V("UntrustedSigner", "0x11"), + "valid Ed25519 signature by a key no anchor trusts"); + MUT("H16-SIG-FORMAT.AIEN", cka_wr16(b.p + sig, 2), V("BadSignatureFormat", "0xf"), + "signature block algorithm 2"); + MUT("H17-RESERVED-HEADER.AIEN", b.p[100] = 1, V("ReservedNonZero", "0x8"), + "reserved header byte 100 nonzero"); + MUT("H18-RIGHTS-UNKNOWN.AIEN", cka_wr32(b.p + CKA_CAPS_OFFSET + 8, 1u | 1u << 6), + V("MalformedCapability", "0xd"), "requested rights bit 6 (undefined)"); + MUT("H19-CAP-COUNT.AIEN", cka_wr16(b.p + 44, 17), V("ResourceLimit", "0xe"), + "capability_count 17 (> 16)"); + MUT("H20-ENVELOPE-LIMIT.AIEN", cka_wr32(b.p + resource, 65), V("ResourceLimit", "0xe"), + "code_pages 65 (> 64); refused while parsing, before signature checks"); + { + struct buf b = signed_art(0, seed_read(0), res(64, 64, 16, 0, 4), exit0_w, 4, "LARGEST!"); + EMIT("H21-LARGEST-ENVELOPE.AIEN", b, "admitted exited:0x0 0", + "largest valid envelope: 64 code, 64 data, 16 stack pages"); + } + MUT("H22-WX-SECTION.AIEN", cka_wr16(b.p + 128 + 2, 7), V("BadSection", "0xb"), + "code section permissions R|W|X"); + { + static const uint32_t w[] = {BR_X2}; + struct buf b = signed_art(0, seed_read(0), res(1, 1, 1, 0, 4), w, 1, "DATAPAGE"); + EMIT("H23-EXEC-DATA.AIEN", b, "admitted fault:exec-nx 0", + "branches into its own data page (mapped RW+NX)"); + } + { + static const uint32_t w[] = {SUB_X9_SP_16, BR_X9}; + struct buf b = signed_art(0, seed_read(0), res(1, 1, 1, 0, 4), w, 2, "STACKPAG"); + EMIT("H24-EXEC-STACK.AIEN", b, "admitted fault:exec-nx 0", + "branches onto its own stack (mapped RW+NX)"); + } + { + static const uint32_t w[] = {MOV_X8_99, SVC_0, B_SELF}; + struct buf b = signed_art(0, seed_read(0), res(1, 1, 1, 0, 4), w, 3, "BADSYSCL"); + EMIT("H25-BAD-SYSCALL.AIEN", b, "admitted bad-syscall:99 0", "invokes undefined syscall 99"); + } + { + static const uint32_t w[] = {MOV_X0_0, MOV_X8_6, SVC_0, SVC_0, SVC_0, MOV_X8_2, SVC_0, B_SELF}; + struct buf b = signed_art(0, seed_read(0), res(1, 1, 1, 0, 2), w, 8, "OVERRUN!"); + EMIT("H26-SYSCALL-BUDGET.AIEN", b, "admitted resource-overrun 0", + "third syscall exceeds syscall_count 2"); + } + { + struct cka_env r = res(1, 1, 1, 1, 8); + r.ipc_msgs = 1; + r.ipc_bytes = 64; + struct buf b = signed_art(1, seed_read(1), r, exit0_w, 4, "IPCWANTS"); + EMIT("H27-POLICY-IPC.AIEN", b, "rejected authorized ResourceLimit 0xe", + "requests 1 IPC message; local policy allows none"); + } + { + struct buf b = signed_art(1, seed_read(2), res(1, 1, 1, 1, 8), exit0_w, 4, "WRITEREQ"); + EMIT("H28-WRITE-ONLY-REQUEST.AIEN", b, "admitted exited:0x0 0", + "requests only WRITE on the SEED object; policy grants READ at most"); + } + { + struct buf b = signed_art(1, seed_read(3), res(1, 1, 1, 1, 8), exit0_w, 4, "RWREQUST"); + EMIT("H29-READ-WRITE-REQUEST.AIEN", b, "admitted exited:0x0 1", + "requests READ|WRITE; granted READ only"); + } + snprintf(path, sizeof path, "%s/expected.txt", dir); + writef(path, (const uint8_t *)exp, el); + free(base.p); + printf("NEGATIVE_CORPUS: TEST ONLY SEED-0B qualification inputs written\n"); +} + +/* ---- fw_cfg bundle: "AIENBND\0", u32 count, {u16 nlen, name, u32 len, bytes} ---- */ +static void bundle(int argc, char **argv) +{ + const char *out = argv[0]; + size_t cap = 12, n = 12; + uint8_t *b = malloc(cap); + if (!b) + die("out of memory"); + memcpy(b, "AIENBND\0", 8); + unsigned count = 0; + for (int i = 1; i < argc; i++) { + const char *name = strrchr(argv[i], '/'); + name = name ? name + 1 : argv[i]; + size_t nl = strlen(name); + if (nl == 0 || nl > 32) + die("bundle: candidate names are 1..32 bytes"); + struct buf f = readf(argv[i]); + size_t need = n + 2 + nl + 4 + f.n; + if (need > cap) { + cap = need * 2; + b = realloc(b, cap); + if (!b) + die("out of memory"); + } + cka_wr16(b + n, (uint16_t)nl); + memcpy(b + n + 2, name, nl); + cka_wr32(b + n + 2 + nl, (uint32_t)f.n); + memcpy(b + n + 6 + nl, f.p, f.n); + n = need; + count++; + free(f.p); + } + cka_wr32(b + 8, count); + writef(out, b, n); + free(b); + printf("BUNDLE: %u candidates\n", count); +} + +/* ---- receipts (receipt_cmd.rs) ---- */ +static void read_receipt(const char *path, uint8_t r[CKA_RECEIPT_SIZE]) +{ + struct buf b = readf(path); + if (b.n != CKA_RECEIPT_SIZE) { + fprintf(stderr, "error: receipt must be exactly 512 bytes, got %zu\n", b.n); + exit(1); + } + memcpy(r, b.p, CKA_RECEIPT_SIZE); + free(b.p); +} + +static void decoded(const uint8_t *b, struct cka_receipt *r) +{ + int e = cka_receipt_decode(b, r); + if (e) { + fprintf(stderr, "error: receipt rejected: %s\n", cka_error_name((unsigned)e)); + exit(1); + } +} + +static const char *decision(const struct cka_receipt *r) +{ + return r->decision == CKR_ADMITTED ? "Admitted" : "Rejected"; +} + +static int receipt(int argc, char **argv) +{ + static const uint8_t zero[32]; + uint8_t rec[CKA_RECEIPT_SIZE]; + struct cka_receipt r; + char h[65]; + if (argc == 3 && !strcmp(argv[0], "from-hex")) { + const char *t = argv[1]; + if (strlen(t) != 2 * CKA_RECEIPT_SIZE) + die("expected 1024 lowercase hex characters"); + for (unsigned i = 0; i < CKA_RECEIPT_SIZE; i++) { + unsigned v = 0; + for (int k = 0; k < 2; k++) { + char c = t[2 * i + k]; + if (c >= '0' && c <= '9') v = v * 16 + (unsigned)(c - '0'); + else if (c >= 'a' && c <= 'f') v = v * 16 + (unsigned)(c - 'a' + 10); + else die("expected 1024 lowercase hex characters"); + } + rec[i] = (uint8_t)v; + } + writef(argv[2], rec, CKA_RECEIPT_SIZE); + printf("FROM_HEX: PASS\n"); + return 0; + } + if (argc == 3 && !strcmp(argv[0], "check")) { + read_receipt(argv[1], rec); + if (cka_receipt_is_signed(rec)) + die("kernel-emitted receipts must be unsigned"); + decoded(rec, &r); + int admitted = r.decision == CKR_ADMITTED; + struct buf a = readf(argv[2]); + struct cka_parsed p; + struct cka_ident id; + const uint8_t *fields[5] = {r.id, r.payload, r.signer, r.requested, r.resources}; + static const char *names[5] = {"artifact_id", "payload_digest", + "artifact_signer_fingerprint", + "requested_capability_digest", "resource_envelope_digest"}; + if (cka_identify(a.p, a.n, &p, &id) != 0) { + if (admitted) + die("admitted receipt for an artifact the host cannot parse"); + for (int i = 0; i < 5; i++) + if (memcmp(fields[i], zero, 32)) { + fprintf(stderr, "error: %s must be zero for an unparseable artifact\n", + names[i]); + return 1; + } + } else { + const uint8_t *want[5] = {id.id, id.payload, p.fp, id.requested, id.resources}; + for (int i = 0; i < 5; i++) + if (memcmp(fields[i], want[i], 32) && + !(!admitted && !memcmp(fields[i], zero, 32))) { + fprintf(stderr, "error: %s does not bind the supplied artifact\n", names[i]); + return 1; + } + if (admitted && !memcmp(r.granted, zero, 32)) + die("admitted receipt without a granted-capability digest"); + } + free(a.p); + uint8_t d[32]; + cka_receipt_digest(rec, d); + hex(d, 32, h); + printf("RECEIPT_CHECK: PASS digest=%s decision=%s tier=SEED-0B-QEMU stage=%u reason=0x%x " + "status=%s exit=%d syscalls=%u reads_ok=%u denials=%u flags=0x%02x\n", + h, decision(&r), r.stage, r.reason, cka_status_name(r.status), r.exit, r.syscalls, + r.reads, r.denials, r.result_flags); + return 0; + } + if (argc == 3 && !strcmp(argv[0], "sign-test")) { + read_receipt(argv[1], rec); + decoded(rec, &r); + if (cka_receipt_sign(rec, test2_seed) != 0) + die("cannot sign receipt"); + writef(argv[2], rec, CKA_RECEIPT_SIZE); + uint8_t fp[32]; + sha256_hash(cka_test2_pk, 32, fp); + printf("RECEIPT_SIGN: TEST ONLY SEED-0B QUALIFICATION RECEIPT KEY\n"); + phex("RECEIPT_SIGNER_FINGERPRINT: ", fp); + return 0; + } + if (argc == 2 && !strcmp(argv[0], "verify")) { + read_receipt(argv[1], rec); + const uint8_t (*anchors)[32] = &cka_test2_pk; + int e = cka_receipt_verify(rec, anchors, 1); + if (e) { + fprintf(stderr, "error: receipt verification failed: %s\n", cka_error_name((unsigned)e)); + return 1; + } + decoded(rec, &r); + uint8_t d[32]; + cka_receipt_digest(rec, d); + hex(d, 32, h); + printf("RECEIPT_VERIFY: PASS digest=%s decision=%s tier=SEED-0B-QEMU " + "trust=SEED-0B-TEST-ONLY\n", h, decision(&r)); + return 0; + } + die("usage: receipt from-hex HEX OUT | check REC ARTIFACT | sign-test IN OUT | verify REC"); + return 1; +} + +int main(int argc, char **argv) +{ + if (argc == 6 && !strcmp(argv[1], "pack")) { + struct buf mj = readf(argv[2]), c = readf(argv[3]), d = readf(argv[4]); + struct manifest m; + parse_manifest(&mj, &m); + struct buf o = pack(&m, c.p, c.n, d.p, d.n); + writef(argv[5], o.p, o.n); + printf("PACK: PASS\n"); + return 0; + } + if (argc == 4 && !strcmp(argv[1], "sign")) { + struct buf b = readf(argv[2]); + struct cka_parsed p; + if (cka_parse(b.p, b.n, &p) != 0) + die("does not parse"); + sign_with(&b, test1_seed); + if (cka_parse(b.p, b.n, &p) != 0) + die("signed artifact does not parse"); + writef(argv[3], b.p, b.n); + uint8_t fp[32]; + sha256_hash(cka_test1_pk, 32, fp); + printf("SIGN: TEST ONLY SEED-0B QUALIFICATION IDENTITY\n"); + phex("SIGNER_FINGERPRINT: ", fp); + return 0; + } + if (argc == 3 && !strcmp(argv[1], "id")) { + struct buf b = readf(argv[2]); + struct cka_parsed p; + struct cka_ident id; + int e = cka_identify(b.p, b.n, &p, &id); + if (e) { + fprintf(stderr, "error: %s\n", cka_error_name((unsigned)e)); + return 1; + } + phex("", id.id); + return 0; + } + if (argc == 3 && !strcmp(argv[1], "verify")) { + struct buf b = readf(argv[2]); + struct cka_parsed p; + struct cka_ident id; + uint8_t fp[32]; + int e = verify_test(&b, &p, &id, fp); + if (e) { + fprintf(stderr, "error: %s\n", cka_error_name((unsigned)e)); + return 1; + } + printf("VERIFY: PASS\n"); + phex("ARTIFACT_ID: ", id.id); + phex("PAYLOAD_SHA256: ", id.payload); + phex("SIGNER_FINGERPRINT: ", fp); + printf("TRUST_TIER: SEED-0B-QUALIFICATION-TEST-ONLY\n"); + return 0; + } + if (argc == 3 && !strcmp(argv[1], "negative-corpus")) { + corpus(argv[2]); + return 0; + } + if (argc >= 3 && !strcmp(argv[1], "bundle")) { + bundle(argc - 2, argv + 2); + return 0; + } + if (argc >= 2 && !strcmp(argv[1], "receipt")) + return receipt(argc - 2, argv + 2); + fprintf(stderr, "usage: ck_artifact_tool pack MANIFEST CODE DATA OUT | sign IN OUT | id F | " + "verify F | negative-corpus DIR | bundle OUT FILE... | receipt ...\n"); + return 2; +} diff --git a/scripts/ck_gates.sh b/scripts/ck_gates.sh index c76b5e24..21bbf84b 100755 --- a/scripts/ck_gates.sh +++ b/scripts/ck_gates.sh @@ -4,7 +4,7 @@ # # It refuses a dirty tree, runs the C kernel QEMU scripts that exist # (scripts/qemu_ck_boot_test.sh, scripts/qemu_ck_store_test.sh, -# scripts/qemu_ck_net_test.sh), and prints +# scripts/qemu_ck_net_test.sh, scripts/qemu_ck_artifact_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 M4_NVME M4_STORE M4_STORE_CRASH @@ -39,6 +39,7 @@ set -uo pipefail # source: boot -> verdict line from scripts/qemu_ck_boot_test.sh # store -> verdict line from scripts/qemu_ck_store_test.sh # net -> verdict line from scripts/qemu_ck_net_test.sh +# artifact -> verdict line from scripts/qemu_ck_artifact_test.sh # missing -> NOT_RUN (MISSING_IMPLEMENTATION), never run, never PASS # =========================================================================== CK_GATE_TABLE=' @@ -46,7 +47,7 @@ M1|boot|- M3|boot|- SMMU|store|- NVME_SHUTDOWN|store|- -P2_ARTIFACT|missing|no signed artifact loader (EL0, W^X, admission receipts) in the C kernel +P2_ARTIFACT|artifact|- M0_ROLLBACK|missing|C loader signatures, A/B, BootNext and rollback are parked (native/boot/README.md) M4_NVME|store|- M4_STORE|store|- @@ -57,7 +58,7 @@ ARGUS1_REVOKE|store|- KEYBOARD|missing|no xHCI/USB HID keyboard driver in the C kernel NET|net|- ' -CHILDREN=(boot store net) +CHILDREN=(boot store net artifact) # =========================================================================== repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" @@ -95,6 +96,7 @@ set_default_children() { [boot]="${repo_root}/scripts/qemu_ck_boot_test.sh" [store]="${repo_root}/scripts/qemu_ck_store_test.sh" [net]="${repo_root}/scripts/qemu_ck_net_test.sh" + [artifact]="${repo_root}/scripts/qemu_ck_artifact_test.sh" ) } @@ -324,11 +326,11 @@ self_test() { } expect_missing_all() { local g - for g in P2_ARTIFACT M0_ROLLBACK M4_STORE_CRASH M4_CONTINUITY M4_RECOVERY KEYBOARD; do expect "${g}" NOT_RUN; done + for g in P2_ARTIFACT M0_ROLLBACK M4_STORE_CRASH M4_CONTINUITY M4_RECOVERY KEYBOARD; do expect "${g}" NOT_RUN; done # P2_ARTIFACT: no artifact child in A..G } - scenario() { # NAME BOOT_SCRIPT STORE_SCRIPT [NET_SCRIPT] (no NET_SCRIPT: missing) + scenario() { # NAME BOOT_SCRIPT STORE_SCRIPT [NET_SCRIPT] [ARTIFACT_SCRIPT] (absent: missing) scen="$1" - declare -gA child_script=([boot]="$2" [store]="$3" [net]="${4:-${tmp}/kids/net_not_present.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}") run_children 2>/dev/null evaluate_table >"${tmp}/${scen}.out" } @@ -385,6 +387,19 @@ self_test() { "$(fake storeG 0 'AIENOS_CK_M3: PASS' 'AIENOS_CK_M4_NVME: PASS')" expect M1 PASS; expect M3 FAIL; expect M4_NVME PASS + # H: artifact child PASS -> P2_ARTIFACT PASS; its claim for M0_ROLLBACK + # (no C implementation) stays NOT_RUN. I: artifact child NOT_RUN (quiet + # flag held, exit 3) -> NOT_RUN; J: FAIL -> FAIL. + scenario H "$(fake bootH 0 'AIENOS_CK_M1: PASS')" "$(fake storeH 0 'AIENOS_CK_M4_NVME: PASS')" "" \ + "$(fake artH 0 'PASS x' 'AIENOS_CK_M0_ROLLBACK: PASS' 'AIENOS_CK_P2_ARTIFACT: PASS')" + expect P2_ARTIFACT PASS; expect M0_ROLLBACK NOT_RUN; expect M1 PASS + scenario I "$(fake bootI 0 'AIENOS_CK_M1: PASS')" "$(fake storeI 0 'AIENOS_CK_M4_NVME: PASS')" "" \ + "$(fake artI 3 'NOT_RUN quiet flag held' 'AIENOS_CK_P2_ARTIFACT: NOT_RUN')" + expect P2_ARTIFACT NOT_RUN + scenario J "$(fake bootJ 0 'AIENOS_CK_M1: PASS')" "$(fake storeJ 0 'AIENOS_CK_M4_NVME: PASS')" "" \ + "$(fake artJ 1 'FAIL P25WX' 'AIENOS_CK_P2_ARTIFACT: FAIL')" + expect P2_ARTIFACT FAIL + # Receipt: named by its content hash, valid JSON, physical NOT_RUN, never overwritten. scenario R "$(fake bootR 0 'AIENOS_CK_M1: PASS')" "$(fake storeR 0 'AIENOS_CK_M4_NVME: PASS')" count_rows @@ -401,7 +416,7 @@ self_test() { jq -e '.physical == "NOT_RUN" and (.gates | length) == 14 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) == 3 and .commit_subject == "quote \" backslash \\ tab\tend"' "${receipt_path}" >/dev/null \ + and (.children | length) == 4 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 "SKIP jq not installed; JSON validity not machine-checked" @@ -420,7 +435,7 @@ self_test() { [[ -n "${g}" ]] || continue rows=$((rows + 1)) case "${s}" in - boot|store|net) [[ "${w}" == - ]] || tbad=1 ;; + boot|store|net|artifact) [[ "${w}" == - ]] || tbad=1 ;; missing) [[ -n "${w}" && "${w}" != - ]] || tbad=1 ;; *) tbad=1 ;; esac diff --git a/scripts/qemu_ck_artifact_test.sh b/scripts/qemu_ck_artifact_test.sh new file mode 100755 index 00000000..3561695c --- /dev/null +++ b/scripts/qemu_ck_artifact_test.sh @@ -0,0 +1,259 @@ +#!/usr/bin/env bash +# Boot the AIENOS C kernel core with the P2 sealed-artifact loader +# (native/kernel/core/artifact_loader.c) in QEMU AArch64 + UEFI (AAVMF) and +# check the serial console against the same expectations as the Rust gate +# scripts/qemu_artifact_test.sh (SEED-0B / P2-5). QEMU is not hardware: a +# PASS here qualifies nothing physical. +# +# Two boots, as in the Rust gate: +# 1. qualification build (make CK_SEED0B_TEST_ANCHOR=1): trusts the RFC 8032 +# TEST 1 public key only (TEST ONLY); P26SEED, P25EXEC/WX/SPIN/TAMP and +# the hostile set H01..H29 with their expected stage and reason; +# 2. ordinary build: empty production trust, every candidate refused. +# Every candidate's receipt is decoded, bound to the supplied artifact, +# digest-recomputed, TEST-signed and verified by the in-tree C tool. +# +# Differences from qemu_artifact_test.sh, all deliberate (native/kernel/GATES.md): +# - builds with make (gcc), the artifacts with the in-tree C tool +# (native/kernel/tools/ck_artifact_tool.c), not cargo / the Rust tool; the +# probe programs are the committed fixtures, packed by the same pack.sh; +# - candidates reach the kernel as one QEMU fw_cfg file +# (opt/aienos/artifacts, a bundle) instead of ESP files read by a UEFI +# loader: the C boot stub reads no files; +# - no Machine 1 captured-log mode (SEED-0B Machine 1 stays with the Rust gate); +# - takes the machine quiet flag itself (noclobber) and prints NOT_RUN while +# another run holds it; AIENOS_QUIET_FLAG / AIENOS_QUIET_TAG as in +# qemu_ck_boot_test.sh; +# - stricter: any QEMU exit status other than 0 fails. +# Last line: AIENOS_CK_P2_ARTIFACT: PASS|FAIL|NOT_RUN. +# Needs qemu-system-aarch64 and AAVMF (Ubuntu: qemu-system-arm qemu-efi-aarch64). +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" +verdict=AIENOS_CK_P2_ARTIFACT + +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 "${verdict}: NOT_RUN"; exit 2; } +[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; echo "${verdict}: NOT_RUN"; exit 2; } + +cross="" +if [ "$(uname -m)" != "aarch64" ]; then cross="aarch64-linux-gnu-"; fi +commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" +out_prod="${repo_root}/target/native-kernel" +out_qual="${repo_root}/target/native-kernel-seed0b-test" +make -s -C native/kernel CROSS="${cross}" OUT="${out_prod}" AIENOS_COMMIT="${commit}" >/dev/null +make -s -C native/kernel CROSS="${cross}" OUT="${out_qual}" AIENOS_COMMIT="${commit}" \ + CK_SEED0B_TEST_ANCHOR=1 >/dev/null +make -s -C native/kernel OUT="${out_prod}" tool >/dev/null +tool="${out_prod}/host/ck_artifact_tool" + +# Machine quiet flag: one heavy run at a time on the Spark. +quiet_flag="${AIENOS_QUIET_FLAG:-${HOME}/workspace/.spark-quiet}" +quiet_tag="${AIENOS_QUIET_TAG:-qemu_ck_artifact_test $$}" +if ! ( set -C; echo "${quiet_tag}" > "${quiet_flag}" ) 2>/dev/null; then + echo "NOT_RUN quiet flag ${quiet_flag} is held: $(head -c 200 "${quiet_flag}" 2>/dev/null || true)" + echo "${verdict}: NOT_RUN" + exit 3 +fi +own_flag=1 +release_flag() { + if [[ "${own_flag}" == 1 ]]; then + own_flag=0 + if [[ -f "${quiet_flag}" ]] && grep -qxF -- "${quiet_tag}" "${quiet_flag}"; then rm -f "${quiet_flag}"; fi + fi +} +work="$(mktemp -d)" +cleanup() { + rm -rf "${work}" + release_flag +} +trap cleanup EXIT +failed=0 +pass() { echo "PASS $1"; } +fail() { echo "FAIL $1"; failed=1; } + +# ---- inputs ----------------------------------------------------------------- +fixtures="crates/aienos-artifact-tool/fixtures/p2_5" +seed_fixtures="crates/aienos-artifact-tool/fixtures/p2_6" +art="${work}/artifacts" +mkdir -p "${art}" +"${fixtures}/pack.sh" "${tool}" "${art}" >/dev/null +"${seed_fixtures}/pack.sh" "${tool}" "${art}" >/dev/null +mv "${art}/ids.txt" "${work}/ids.txt" +"${tool}" negative-corpus "${art}" >/dev/null +mv "${art}/expected.txt" "${work}/expected.txt" +for f in "${art}"/H*.AIEN; do + n=$(basename "${f}") + awk -v n="${n}" '$1 == n { found = 1 } END { exit !found }' "${work}/ids.txt" \ + || echo "${n} $("${tool}" id "${f}" 2>/dev/null || echo none)" >>"${work}/ids.txt" +done +mapfile -t files < <(find "${art}" -maxdepth 1 -name '*.AIEN' | LC_ALL=C sort) +candidate_count=${#files[@]} +"${tool}" bundle "${work}/bundle.bin" "${files[@]}" >/dev/null +id_prefix() { awk -v n="$1" '$1 == n { print substr($2, 1, 16) }' "${work}/ids.txt"; } + +boot() { # image, serial text output + local esp="${work}/esp" log="${work}/serial.log" started status + rm -rf "${esp}" + mkdir -p "${esp}/EFI/BOOT" "${esp}/EFI/AIENOS" + touch "${esp}/EFI/AIENOS/BOOTREPORT.TXT" + cp "$1" "${esp}/EFI/BOOT/BOOTAA64.EFI" + cp "${vars_fd}" "${work}/vars.fd" + started=$(date +%s) + set +e + # Issue #61: single-threaded TCG; MTTCG hung in 1/40 soak boots. + nice -n 10 timeout "${AIENOS_QEMU_TIMEOUT:-300}" 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:"${esp}" \ + -device virtio-blk-pci,drive=esp \ + -fw_cfg name=opt/aienos/artifacts,file="${work}/bundle.bin" \ + -device ramfb -display none -nic none \ + -serial file:"${log}" -no-reboot + status=$? + set -e + tr -d '\r' <"${log}" >"$2" + echo "qemu exit ${status} after $(( $(date +%s) - started )) s (commit ${commit:0:12})" + [[ "${status}" == 0 ]] || fail "QEMU exit status ${status} (124 = timeout)" +} + +has() { grep -qE -- "$2" "$1"; } +check() { if has "$1" "$3"; then pass "$2"; else fail "$2"; fi; } +common_checks() { # serial + check "$1" "left firmware and entered the kernel" "kernel: alive" + check "$1" "M3 cooperative threads unchanged" "threads: ok" + check "$1" "M3 EL0 isolation proof unchanged" "el0: ok write=granted forged=denied fault=contained exit=0" + check "$1" "M3 typed IPC proof unchanged" "ipc: ok message=delivered cap=delegated rights=attenuated forged=denied revoked=denied" + check "$1" "kernel read all ${candidate_count} artifact candidates" "^artifact_candidates: ${candidate_count}$" + if grep -q "^report-truncated:" "$1"; then fail "kernel report lines were truncated"; else pass "no kernel report line was truncated"; fi + check "$1" "final report reached the console" "report_kind: final" + if has "$1" "report_kind: (panic|fault)"; then fail "panic or fault reported"; fi + if has "$1" "^receipt: [^ ]+ seq=[0-9]+ invalid$"; then fail "a candidate produced no valid receipt"; fi + if has "$1" "^artifact_bundle: malformed"; then fail "kernel found the bundle malformed"; fi + local before after + before=$(grep -oE "artifact_frames_free_before: [0-9]+" "$1" | awk '{print $2}' | tail -1) + after=$(grep -oE "artifact_frames_free_after: [0-9]+" "$1" | awk '{print $2}' | tail -1) + if [[ -n "${before}" && "${before}" == "${after}" ]]; then + pass "every frame returned after all candidates (${before} free before and after)" + else + fail "frame accounting across candidates (before=${before:-?} after=${after:-?})" + fi +} + +rtag="" +receipt_check() { # serial name pattern + local serial="$1" name="$2" want="$3" line record kdigest out + line=$(grep -E "^receipt: ${name//./\\.} seq=[0-9]+ digest=[0-9a-f]{64} record=[0-9a-f]{1024}$" "${serial}" | tail -1 || true) + if [[ -z "${line}" ]]; then fail "${name} receipt emitted"; return; fi + record=${line##*record=} + kdigest=$(sed -E 's/.* digest=([0-9a-f]{64}) .*/\1/' <<<"${line}") + local file="${work}/${rtag}-${name}.receipt" + if ! "${tool}" receipt from-hex "${record}" "${file}" >/dev/null 2>&1; then fail "${name} receipt record decodes on the host"; return; fi + if ! out=$("${tool}" receipt check "${file}" "${art}/${name}" 2>&1); then + fail "${name} receipt binds the supplied artifact (${out})"; return + fi + if [[ "${out}" != *"digest=${kdigest} "* ]]; then fail "${name} receipt digest recomputed by the host"; return; fi + if ! grep -qE -- "${want}" <<<"${out}"; then fail "${name} receipt records the observed outcome (${out})"; return; fi + if ! "${tool}" receipt sign-test "${file}" "${file}.signed" >/dev/null 2>&1; then fail "${name} receipt TEST ONLY signing"; return; fi + if "${tool}" receipt verify "${file}.signed" | grep -q "RECEIPT_VERIFY: PASS digest=${kdigest} "; then + pass "${name} receipt: bound, host digest match, observed outcome, TEST ONLY signature verifies" + else + fail "${name} signed receipt verifies" + fi +} +stage_code() { case "$1" in received) echo 1;; staged) echo 2;; verified) echo 3;; authorized) echo 4;; + reserved) echo 5;; mapped) echo 6;; hashed) echo 7;; sealed) echo 8;; caps) echo 9;; *) echo x;; esac; } +status_of() { case "$1" in exited:*) echo Exited;; timeout) echo Timeout;; fault:*) echo Fault;; + bad-syscall:*) echo BadSyscall;; resource-overrun) echo ResourceOverrun;; *) echo NotRun;; esac; } +admitted_line() { # name, exec regex, caps + echo "^artifact: ${1//./\\.} admitted id=$(id_prefix "$1") tier=seed0b-test exec=$2 bytes=identified=verified=admitted=mapped=executed wx=enforced caps=$3 revoked=yes reclaimed=yes frames=[0-9]+ " +} + +# ---- boot 1: qualification build ------------------------------------------- +qual="${work}/qualification.txt" +rtag=qual +boot "${out_qual}/BOOTAA64.EFI" "${qual}" +common_checks "${qual}" +check "${qual}" "qualification build is labelled TEST ONLY" \ + "artifact_trust: seed0b-test qualification build — TEST ONLY" +check "${qual}" "receipts carry the SEED-0B-QEMU tier" "^artifact_receipt_tier: SEED-0B-QEMU$" +check "${qual}" "P26SEED read through its grant, WRITE and forged authority denied, exit 0, reclaimed" \ + "$(admitted_line P26SEED.AIEN exited:0x0 1)syscalls=9 reads=3 denials=5$" +check "${qual}" "P26SEED granted exactly its READ request" \ + "^grant: P26SEED\.AIEN\[0\] kind=object id=1 rights=0x1 bounds=0\+32 max_ops=4 max_bytes=32$" +if [[ $(grep -c "^grant: P26SEED\.AIEN\[" "${qual}") == 1 ]]; then pass "P26SEED holds exactly one capability"; else fail "P26SEED holds exactly one capability"; fi +receipt_check "${qual}" P26SEED.AIEN "decision=Admitted tier=SEED-0B-QEMU stage=0 reason=0x0 status=Exited exit=0 syscalls=9 reads_ok=3 denials=5 flags=0xff$" +check "${qual}" "P25EXEC executed its exact authenticated bytes, exit 0, caps revoked, reclaimed" \ + "$(admitted_line P25EXEC.AIEN exited:0x0 1)syscalls=3 reads=1 denials=1$" +check "${qual}" "P25WX killed by a W^X fault on its code page, reclaimed" \ + "$(admitted_line P25WX.AIEN fault:code-write 0)syscalls=0 reads=0 denials=0$" +check "${qual}" "P25SPIN killed at its time budget, reclaimed" \ + "$(admitted_line P25SPIN.AIEN timeout 0)syscalls=0 reads=0 denials=0$" +check "${qual}" "P25TAMP (payload byte flipped after signing) rejected BadSignature, reclaimed" \ + "^artifact: P25TAMP\.AIEN rejected stage=verified reason=BadSignature reclaimed=yes$" +receipt_check "${qual}" P25EXEC.AIEN "decision=Admitted .* status=Exited exit=0 syscalls=3 reads_ok=1 denials=1 flags=0xfd$" +receipt_check "${qual}" P25WX.AIEN "decision=Admitted .* status=Fault exit=0 syscalls=0 reads_ok=0 denials=0 flags=0xe4$" +receipt_check "${qual}" P25SPIN.AIEN "decision=Admitted .* status=Timeout exit=0 syscalls=0 reads_ok=0 denials=0 flags=0xe4$" +receipt_check "${qual}" P25TAMP.AIEN "decision=Rejected .* stage=3 reason=0x12 status=NotRun exit=0 syscalls=0 reads_ok=0 denials=0 flags=0x04$" + +matrix_total=0 matrix_admitted=0 +while read -r name decision a b c _; do + [[ -n "${name}" ]] || continue + matrix_total=$((matrix_total + 1)) + if [[ "${decision}" == rejected ]]; then + check "${qual}" "${name} refused at ${a} (${b}), never ran, reclaimed" \ + "^artifact: ${name//./\\.} rejected stage=${a} reason=${b} reclaimed=yes$" + receipt_check "${qual}" "${name}" "decision=Rejected .* stage=$(stage_code "${a}") reason=${c} status=NotRun exit=0 syscalls=0 reads_ok=0 denials=0 flags=0x04$" + else + matrix_admitted=$((matrix_admitted + 1)) + check "${qual}" "${name} admitted and contained (${a}), reclaimed" "$(admitted_line "${name}" "${a}" "${b}")" + receipt_check "${qual}" "${name}" "decision=Admitted .* status=$(status_of "${a}") " + fi +done < <(sed 's/ #.*//' "${work}/expected.txt") +[[ "${matrix_total}" -ge 29 ]] && pass "hostile matrix has ${matrix_total} cases" || fail "hostile matrix has only ${matrix_total} cases" +check "${qual}" "H29 requested READ|WRITE and was granted READ only" \ + "^grant: H29-READ-WRITE-REQUEST\.AIEN\[0\] kind=object id=1 rights=0x1 " +if has "${qual}" "^grant: H28-"; then fail "H28 (WRITE-only request) received a capability"; else pass "H28 requested only WRITE and received no capability"; fi +check "${qual}" "final report summarises every admission decision" \ + "^artifacts: candidates=${candidate_count} admitted=$((4 + matrix_admitted)) rejected=$((1 + matrix_total - matrix_admitted))$" + +# ---- boot 2: ordinary build, empty production trust ------------------------- +prod="${work}/production.txt" +rtag=prod +boot "${out_prod}/BOOTAA64.EFI" "${prod}" +release_flag +common_checks "${prod}" +if has "${prod}" "seed0b-test qualification build"; then fail "ordinary build must not carry the qualification label"; fi +if has "${prod}" "^artifact: [^ ]+ admitted"; then fail "ordinary build admitted an artifact"; else pass "ordinary build admitted nothing"; fi +prod_expect() { # name -> "stage reason code" in the ordinary build + local line + line=$(sed 's/ #.*//' "${work}/expected.txt" | awk -v n="$1" '$1 == n') + if [[ -n "${line}" ]] && read -r _ d s r c <<<"${line}" && [[ "${d}" == rejected && "${s}" == verified \ + && "${r}" != BadSignature && "${r}" != UntrustedSigner ]]; then + echo "${s} ${r} ${c}" + else + echo "verified UntrustedSigner 0x11" + fi +} +for f in "${files[@]}"; do + name=$(basename "${f}") + read -r s r c <<<"$(prod_expect "${name}")" + check "${prod}" "ordinary build refuses ${name} (${r}), reclaimed" \ + "^artifact: ${name//./\\.} rejected stage=${s} reason=${r} reclaimed=yes$" + receipt_check "${prod}" "${name}" "decision=Rejected .* stage=$(stage_code "${s}") reason=${c} status=NotRun .* flags=0x04$" +done +check "${prod}" "final report summarises zero admitted" \ + "^artifacts: candidates=${candidate_count} admitted=0 rejected=${candidate_count}$" + +if [[ -n "${AIENOS_LOG_DIR:-}" ]]; then + cp "${qual}" "${AIENOS_LOG_DIR}/qemu_ck_artifact_qualification_serial.log" + cp "${prod}" "${AIENOS_LOG_DIR}/qemu_ck_artifact_production_serial.log" +fi +if [[ "${failed}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then + echo "---- qualification serial (artifact lines) ----" + grep -E "^(artifact|grant|kernel|report_kind|panic|fault|exception|esr|far)" "${qual}" | head -120 || true +fi +if [[ "${failed}" == 0 ]]; then echo "${verdict}: PASS"; else echo "${verdict}: FAIL"; exit 1; fi ```