interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / scripts / trust1_m5_qualify.sh

878 lines · 52700 bytes Raw Blame History
1#!/usr/bin/env bash
2# SPDX-License-Identifier: Apache-2.0
3# Copyright 2026 Drake Stapleton (AIEN / aien-dev)
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17# trust1_m5_qualify.sh: one native qualification entrypoint for TRUST-1 + M5.
18#
19# It refuses a dirty tree, records the exact commit and the machine it ran on
20# (read-only: no sudo, no TPM writes, no efivar or boot-entry writes, no disk
21# writes outside its own output folder), runs every software gate that exists
22# today, lists every operator/hardware/unimplemented gate as NOT_RUN (never
23# PASS) with its blocker class (BLOCKED_OPERATOR, BLOCKED_HARDWARE or
24# MISSING_IMPLEMENTATION) as the reason, and writes one JSON receipt named by
25# the sha256 of its own content. Verdicts are only PASS, FAIL or NOT_RUN: a
26# blocker is the table's reason for not running, never a measured result.
27#
28# Usage: bash scripts/trust1_m5_qualify.sh [--with-qemu] [--out DIR]
29# bash scripts/trust1_m5_qualify.sh --self-test
30# --with-qemu also run the QEMU suites (default off). Vetoed (NOT_RUN) while
31# ~/workspace/.spark-quiet exists.
32# --out DIR where logs and the receipt go (default: a new temp folder
33# outside the tree). DIR may be evidence/: the receipt is the
34# only file the run adds there, written after the dirty-tree
35# re-check, ready to commit.
36# --self-test fast negative controls of the verdict logic and the
37# dirty-tree refusal; runs no gate and touches no hardware.
38#
39# Overall verdict: QUALIFIED only if every canonical gate is PASS, otherwise
40# NOT_QUALIFIED with the list of gates that are not PASS.
41# Exit: 0 no software gate FAILed (NOT_RUN allowed, whatever its blocker),
42# 1 at least one software gate FAILed or the run dirtied the tree,
43# 2 usage error or dirty tree at start.
44set -uo pipefail
45
46# ===========================================================================
47# CANONICAL GATE TABLE (the lead edits verdict mapping here)
48#
49# Fields, separated by '|':
50# id | kind | runner | notrun_rc | marker | description
51# kind:
52# software run now; PASS needs exit 0 AND the marker line in the log
53# cargo like software, and the log must show N>0 passed, 0 failed
54# auto like software if the runner's file exists, else NOT_RUN
55# with blocker MISSING_IMPLEMENTATION (being built in parallel)
56# qemu software, only with --with-qemu and no .spark-quiet; else NOT_RUN
57# operator NOT_RUN, blocker BLOCKED_OPERATOR; never run, never PASS
58# hardware NOT_RUN, blocker BLOCKED_HARDWARE; never run, never PASS
59# missing NOT_RUN, blocker MISSING_IMPLEMENTATION; never run, never PASS
60# runner: name of a run_* function below ('-' for none).
61# notrun_rc: exit code that means "a tool is missing" -> NOT_RUN ('-' none).
62# marker: extended regex that must match a line of the log ('-' for none).
63# ===========================================================================
64GATE_TABLE='
65t1_measurement_tools|software|run_measurement_tools|2|^TRUST-1 measurement tools self-test: ALL PASS$|TRUST-1 Gate 0/2 read-only tools self-test on a software TPM
66t1_key_ceremony|software|run_key_ceremony|3|^TRUST-1 key ceremony self-test \(throwaway keys\): ALL PASS$|TRUST-1 Gate 3 key ceremony self-test with throwaway keys
67t1_gate7_preflight|software|run_gate7_preflight|-|^GATE7_PREFLIGHT: PASS|TRUST-1 Gate 7 read-only pre-flight (depends on operator state)
68t1_recovery_tools|software|run_recovery_tools|3|^RECOVERY_TOOLS: PASS|recovery initrd ships mount, EFI repair and boot-entry restore tools
69store_torn_slot_c|software|run_store_c|-|^TORN_SLOT_HOST_EMULATION: PASS|Store C reference torn-write test (host block-device emulation)
70store_native_c|software|run_store_c|-|^AIENOS_STORE_NATIVE: PASS$|C twin of the System Store v1 engine + sealed Store (host file-backed; golden vectors byte-identical to Rust)
71store_rust_crosscheck|software|run_store_rust_xcheck|2|^STORE_RUST_CROSSCHECK: PASS$|Rust aienos-store-tool opens C-written stores and reads back the same generation and objects (C to Rust direction; NOT_RUN when the Rust tool is not built)
72m5_crypto_crate|cargo|run_cargo_crypto|-|^test result: ok\.|cargo test -p aienos-crypto
73m5_kernel_crypto_security|cargo|run_cargo_kernel|-|^test result: ok\.|cargo test -p aienos-kernel --lib (crypto:: security::)
74t1_gate5_policy_sim|auto|run_gate5_sim|-|^TRUST1_GATE5_POLICY_SIM: PASS$|TRUST-1 Gate 5 policy simulator self-test
75m5_native_test|auto|run_native_m5|-|^M5_NATIVE: PASS$|make -C native/m5 test
76crypto_native_test|auto|run_native_crypto|-|^AIENOS_CRYPTO_NATIVE: PASS$|make -C native/crypto test
77disk_native_test|auto|run_native_disk|-|^AIENOS_DISK_NATIVE: PASS$|make -C native/disk test (block layer + C NVMe driver vs a software controller model, host only)
78qemu_secureboot_signing|qemu|run_qemu_sb|-|^TRUST-1 Gate 4 Secure Boot signing test: ALL PASS$|QEMU Secure Boot signing test (TRUST-1 Gate 4)
79qemu_store_512b_crash|qemu|run_qemu_store512|-|^STORE_512B_CRASH_RECOVERY_QEMU: PASS$|QEMU Store crash recovery on 512-byte blocks
80qemu_native_nvme|qemu|run_qemu_native_nvme|-|^AIENOS_STORE_NVME_QEMU: PASS$|C NVMe driver write/flush/reset/read-back on QEMU virtual NVMe (emulator only)
81ck_m1_boot_qemu|qemu|run_qemu_ck_boot|3|^AIENOS_CK_M1: PASS( .*)?$|C kernel (native/boot + native/kernel, Lane 18) UEFI boot observables on QEMU, scripts/qemu_ck_boot_test.sh (emulator only)
82ck_store_kernel_qemu|qemu|run_qemu_ck_store|3|^AIENOS_CK_M4_STORE: PASS( .*)?$|sealed C Store (native/store + native/m5, TEST keys) in the C kernel boot path on QEMU virtual NVMe, DMA confined by the emulated SMMU, scripts/qemu_ck_store_test.sh (emulator only; not a real device, not real keys)
83ck_argus1_revoke_qemu|qemu|run_qemu_ck_argus|3|^AIENOS_CK_ARGUS1_REVOKE: PASS( .*)?$|ARGUS-1 narrow revoke inside the C kernel on QEMU, scripts/qemu_ck_store_test.sh (emulator only)
84t1_gate0_second_offline_location|operator|-|-|-|Gate 0: second offline backup location
85t1_gate0_cold_boot_pcr_stability|hardware|-|-|-|Gate 0: cold-boot PCR stability on Machine 1
86t1_gate0_firmware_refresh_pause|operator|-|-|-|Gate 0: firmware refresh paused
87t1_gate1_attended_recovery_boot|operator|-|-|-|Gate 1: attended recovery-stick boot
88t1_gate2_reboot_campaign|hardware|-|-|-|Gate 2: reboot measurement campaign
89t1_gate3_offline_key_ceremony|operator|-|-|-|Gate 3: offline owner key ceremony
90t1_gate6|operator|-|-|-|Gate 6 (attended)
91t1_gate7|hardware|-|-|-|Gate 7: attended owner-key enrollment boot, checkpoints A-E
92t1_gate8|operator|-|-|-|Gate 8 (attended)
93t1_gate9|operator|-|-|-|Gate 9 (attended)
94m5_sealed_volume_keys_real_tpm|missing|-|-|-|M5: sealed volume keys bound to a real TPM
95m5_store_encrypted_objects|software|run_store_c|-|^STORE_SEALED: PASS$|M5: encrypted objects in the C sealed Store (host file-backed only; not QEMU, not Machine 1)
96m5_store_kernel_binding|missing|-|-|-|M5: sealed C Store bound into the kernel boot path on a real device with real keys (the QEMU binding with TEST keys is row ck_store_kernel_qemu; it does not count here)
97m5_owner_signed_chain_machine1|missing|-|-|-|M5: owner-signed trust chain on Machine 1
98m5_production_store_512b|missing|-|-|-|M5: production Store on 512-byte geometry on Machine 1 (C engine native/store + C NVMe driver native/disk are host/QEMU tested and the C kernel loads the Store in QEMU with TEST keys; no real-device run, not qualified on Machine 1)
99t1_gate4_manifest_ab|missing|-|-|-|Gate 4: signed boot manifest + A/B slot selection in the loader (awaits the C/asm loader)
100m5_migration_sig_test_key|auto|run_native_m5_migsig|-|^AIENOS_M5_MIGRATION_SIG: PASS$|M5: owner-signed migration record (native/m5 + native/sig Ed25519), host test with TEST keys only
101m5_migration_owner_signature|operator|-|-|-|M5: migration signed by the real owner key (needs the Gate 3 offline key ceremony)
102t1_attended_evidence_checker|software|run_attended_evidence_checker|2|^TRUST1_ATTENDED_EVIDENCE_CHECK self-test \(HOST VALIDATION ONLY\): ALL PASS$|HOST VALIDATION ONLY: attended-evidence checker rejects missing, wrong-digest, partial and failing records (fixtures; proves no physical event, gate rows stay NOT_RUN)
103'
104# ===========================================================================
105
106repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
107QUIET_FLAG="${AIENOS_QUIET_FLAG:-${HOME}/workspace/.spark-quiet}"
108# Set when a QEMU gate is evaluated while the quiet flag is up. The receipt
109# header reads this (plus the gate rows and a write-time sample), so a flag
110# that was up during the gates and down at write time still shows as present.
111quiet_flag_seen_at_gates=false
112
113die() { echo "trust1_m5_qualify: $*" >&2; exit 2; }
114json_str() {
115 local s="$1"
116 s="${s//\\/\\\\}"; s="${s//\"/\\\"}"; s="${s//$'\t'/\\t}"; s="${s//$'\r'/}"; s="${s//$'\n'/\\n}"
117 printf '"%s"' "$(printf '%s' "${s}" | tr -d '\000-\010\013\014\016-\037')"
118}
119sha_of() { sha256sum | cut -d' ' -f1; }
120
121# ---------------------------------------------------------------- dirty tree
122tree_state() { git -C "$1" status --porcelain --untracked-files=normal; }
123refuse_if_dirty() {
124 local st; st="$(tree_state "$1")" || die "git status failed in $1"
125 if [[ -n "${st}" ]]; then
126 echo "trust1_m5_qualify: refusing to run on a dirty tree. Commit, stash or remove these first:" >&2
127 printf '%s\n' "${st}" >&2
128 exit 2
129 fi
130}
131
132# ------------------------------------------------- prerequisite host builds
133# Some checks need a binary this script used to expect to exist already. A
134# fresh checkout has none, so the check reported NOT_RUN ("a required tool is
135# missing") even though cargo could build it. These helpers build the binary
136# for THIS commit into the run's work folder. Return codes follow the row's
137# notrun_rc: 0 ready; the NOTRUN code (cargo or the UEFI target is absent, the
138# check cannot run, NOT_RUN and the verdict stays NOT_QUALIFIED); 1 the build
139# itself failed (a real FAIL: the code at this commit does not build).
140QUAL_CARGO="${QUAL_CARGO:-cargo}"
141QUAL_RUSTC="${QUAL_RUSTC:-rustc}"
142STORE_TOOL_BIN=""; LOADER_EFI=""
143prereq_store_tool() { # prereq_store_tool NOTRUN_RC
144 if [[ -n "${RUST_STORE_TOOL:-}" ]]; then STORE_TOOL_BIN="${RUST_STORE_TOOL}"; return 0; fi
145 command -v "${QUAL_CARGO}" >/dev/null 2>&1 || { echo "prerequisite: cargo not found, cannot build aienos-store-tool"; return "$1"; }
146 local td="${work_dir}/build/cargo-store-tool"
147 echo "prerequisite: building aienos-store-tool at $(git -C "${repo_root}" rev-parse --short HEAD) into ${td}"
148 (cd "${repo_root}" && "${QUAL_CARGO}" build --quiet --release -p aienos-store-tool --target-dir "${td}") \
149 || { echo "prerequisite build FAILED: aienos-store-tool"; return 1; }
150 STORE_TOOL_BIN="${td}/release/aienos-store-tool"
151 [[ -x "${STORE_TOOL_BIN}" ]] || { echo "prerequisite build FAILED: ${STORE_TOOL_BIN} not produced"; return 1; }
152}
153prereq_loader() { # prereq_loader NOTRUN_RC
154 if [[ -n "${AIENOS_KEY_CEREMONY_EFI:-}" ]]; then LOADER_EFI="${AIENOS_KEY_CEREMONY_EFI}"; return 0; fi
155 command -v "${QUAL_CARGO}" >/dev/null 2>&1 || { echo "prerequisite: cargo not found, cannot build the EFI loader"; return "$1"; }
156 local libdir; libdir="$("${QUAL_RUSTC}" --print target-libdir --target aarch64-unknown-uefi 2>/dev/null)"
157 [[ -n "${libdir}" && -d "${libdir}" ]] || { echo "prerequisite: rust target aarch64-unknown-uefi not installed, cannot build the EFI loader"; return "$1"; }
158 local td="${work_dir}/build/cargo-loader"
159 echo "prerequisite: building aienos-handoff.efi at $(git -C "${repo_root}" rev-parse --short HEAD) into ${td}"
160 (cd "${repo_root}" && AIENOS_COMMIT="$(git rev-parse HEAD)" AIENOS_RESTART_SECS=1 "${QUAL_CARGO}" build --quiet --release \
161 -p aienos-boot --target aarch64-unknown-uefi --features handoff --bin aienos-handoff --target-dir "${td}") \
162 || { echo "prerequisite build FAILED: aienos-handoff.efi"; return 1; }
163 LOADER_EFI="${td}/aarch64-unknown-uefi/release/aienos-handoff.efi"
164 [[ -f "${LOADER_EFI}" ]] || { echo "prerequisite build FAILED: ${LOADER_EFI} not produced"; return 1; }
165}
166
167# --------------------------------------------------------------- gate runners
168# Each runner writes everything to stdout/stderr; the caller logs it.
169run_measurement_tools() { bash "${repo_root}/scripts/test_trust1_measurement_tools.sh"; }
170run_key_ceremony() {
171 # The Boot Signer check needs a built EFI loader. Build one into this run's
172 # own work folder (never the repo's target/, so a stale prebuilt loader
173 # from another commit cannot stand in) unless AIENOS_KEY_CEREMONY_EFI
174 # names one. Exit 3 (NOT_RUN) only if the tools to build it are missing.
175 prereq_loader 3 || return $?
176 AIENOS_KEY_CEREMONY_EFI="${AIENOS_KEY_CEREMONY_EFI:-${LOADER_EFI}}" \
177 bash "${repo_root}/scripts/test_trust1_key_ceremony.sh"
178}
179run_gate7_preflight() { bash "${repo_root}/scripts/trust1_gate7_preflight.sh"; }
180run_recovery_tools() { bash "${repo_root}/scripts/verify_recovery_tools.sh"; }
181run_attended_evidence_checker() { bash "${repo_root}/scripts/test_trust1_attended_evidence_check.sh"; }
182# The native Makefiles run ./$(TEST), so OUT must be relative to the
183# Makefile folder; it still points outside the tree.
184native_make_test() {
185 local dir="${repo_root}/native/$1" out="${work_dir}/build/$1"
186 mkdir -p "${out}"
187 make -C "${dir}" OUT="$(realpath --relative-to="${dir}" "${out}")" test
188}
189run_store_c() { native_make_test store; }
190# Rust cross-check of C-written stores: builds aienos-store-tool for this
191# commit into the work folder (RUST_STORE_TOOL overrides); exit 2 = NOT_RUN only
192# if cargo is absent, 1 if the build fails.
193run_store_rust_xcheck() {
194 prereq_store_tool 2 || return $?
195 local dir="${repo_root}/native/store" out="${work_dir}/build/store-xcheck"
196 mkdir -p "${out}"
197 local rel; rel="$(realpath --relative-to="${dir}" "${out}")"
198 make -C "${dir}" OUT="${rel}" "${rel}/store_xcheck" || return 1
199 (cd "${dir}" && RUST_STORE_TOOL="${STORE_TOOL_BIN}" sh tests/rust_crosscheck.sh "./${rel}/store_xcheck" "${rel}")
200}
201run_cargo_crypto() { (cd "${repo_root}" && cargo test -p aienos-crypto); }
202run_cargo_kernel() { (cd "${repo_root}" && cargo test -p aienos-kernel --lib -- crypto:: security::); }
203run_gate5_sim() { bash "${repo_root}/scripts/trust1_gate5_policy_sim.sh" selftest; }
204run_native_m5() { native_make_test m5; }
205run_native_crypto() { native_make_test crypto; }
206run_native_m5_migsig() { native_make_test m5; }
207run_native_disk() { native_make_test disk; }
208run_qemu_native_nvme() { bash "${repo_root}/scripts/qemu_native_nvme_test.sh"; }
209run_qemu_sb() { bash "${repo_root}/scripts/qemu_secureboot_signing_test.sh"; }
210run_qemu_store512() { bash "${repo_root}/scripts/qemu_store_512b_crash_test.sh"; }
211# C kernel (Lane 18) QEMU scripts take the quiet flag themselves and print
212# "AIENOS_CK_<gate>: PASS|FAIL|NOT_RUN". ck_child_gate SCRIPT GATE runs SCRIPT
213# once per qualification run (the store script serves two rows) and maps:
214# missing script or a NOT_RUN line -> exit 3 (the rows' notrun_rc); two
215# different verdict lines -> 1; exit 3 without a NOT_RUN line -> 1; exit 1
216# with this gate's PASS line and another gate's FAIL line -> 0 (the marker
217# check still needs the PASS line); anything else -> the script's exit.
218ck_scripts_dir="${repo_root}/scripts"
219ck_child_gate() {
220 local script="${ck_scripts_dir}/$1" gate="$2" out rc verdicts
221 if [[ ! -f "${script}" ]]; then
222 echo "$1 not present at this commit"; echo "AIENOS_CK_${gate}: NOT_RUN"; return 3
223 fi
224 mkdir -p "${work_dir}/build"
225 out="${work_dir}/build/ck_${1%.sh}.out"
226 if [[ -f "${out}.rc" ]]; then
227 echo "(reusing this run's earlier $1 output)"
228 else
229 bash "${script}" >"${out}" 2>&1 </dev/null
230 echo "$?" >"${out}.rc"
231 fi
232 cat "${out}"
233 rc="$(cat "${out}.rc")"
234 verdicts="$(sed -nE "s/^AIENOS_CK_${gate}: (PASS|FAIL|NOT_RUN)( .*)?\$/\\1/p" "${out}" | sort -u)"
235 [[ "$(grep -c . <<<"${verdicts}")" -le 1 ]] || { echo "contradictory AIENOS_CK_${gate} lines"; return 1; }
236 [[ "${verdicts}" == NOT_RUN ]] && return 3
237 [[ "${rc}" == 3 ]] && return 1
238 if [[ "${rc}" == 1 && "${verdicts}" == PASS ]] && grep -qE '^AIENOS_CK_[A-Z0-9_]+: FAIL( .*)?$' "${out}"; then
239 return 0
240 fi
241 return "${rc}"
242}
243run_qemu_ck_boot() { ck_child_gate qemu_ck_boot_test.sh M1; }
244run_qemu_ck_store() { ck_child_gate qemu_ck_store_test.sh M4_STORE; }
245run_qemu_ck_argus() { ck_child_gate qemu_ck_store_test.sh ARGUS1_REVOKE; }
246
247# Is the implementation of an 'auto' gate present?
248auto_present() {
249 case "$1" in
250 run_gate5_sim) [[ -f "${repo_root}/scripts/trust1_gate5_policy_sim.sh" ]] ;;
251 run_native_m5) [[ -f "${repo_root}/native/m5/Makefile" ]] ;;
252 run_native_crypto) [[ -f "${repo_root}/native/crypto/Makefile" ]] ;;
253 run_native_m5_migsig) [[ -f "${repo_root}/native/m5/m5_owner_sig.c" ]] ;;
254 run_native_disk) [[ -f "${repo_root}/native/disk/Makefile" ]] ;;
255 *) declare -F "$1" >/dev/null ;;
256 esac
257}
258
259# ----------------------------------------------------------- verdict logic
260# classify_log KIND RC NOTRUN_RC MARKER LOG -> prints verdict and a reason.
261classify_log() {
262 local kind="$1" rc="$2" notrun_rc="$3" marker="$4" log="$5"
263 if [[ "${notrun_rc}" != "-" && "${rc}" == "${notrun_rc}" ]]; then
264 echo "NOT_RUN|exit ${rc}: a required tool is missing"; return
265 fi
266 if [[ "${rc}" != 0 ]]; then echo "FAIL|exit ${rc}"; return; fi
267 if [[ "${marker}" != "-" ]] && ! grep -Eq -- "${marker}" "${log}"; then
268 echo "FAIL|exit 0 but expected marker not found"; return
269 fi
270 if [[ "${kind}" == cargo ]]; then
271 # Every 'test result' line must be ok with 0 failed; at least one
272 # test must have run in total (a typo'd filter runs 0 tests).
273 local passed failed bad
274 passed="$(sed -n 's/^test result: ok\. \([0-9][0-9]*\) passed.*/\1/p' "${log}" | awk '{s+=$1} END {print s+0}')"
275 failed="$(sed -n 's/^test result: .*; \([0-9][0-9]*\) failed;.*/\1/p' "${log}" | awk '{s+=$1} END {print s+0}')"
276 bad="$(grep -c '^test result: FAILED' "${log}")"
277 if [[ "${bad}" != 0 || "${failed}" != 0 ]]; then echo "FAIL|${failed} tests failed"; return; fi
278 if [[ "${passed}" -le 0 ]]; then echo "FAIL|0 tests ran (filter matched nothing)"; return; fi
279 echo "PASS|${passed} tests passed, 0 failed"; return
280 fi
281 echo "PASS|exit 0, marker found"
282}
283
284# evaluate_gate ID KIND RUNNER NOTRUN_RC MARKER -> appends one row to results.
285# Row: id|kind|verdict|reason|log_sha256|log_lines|seconds
286evaluate_gate() {
287 local id="$1" kind="$2" runner="$3" notrun_rc="$4" marker="$5"
288 local verdict reason log="${work_dir}/logs/${id}.log" rc t0 t1 out
289 case "${kind}" in
290 # Not checked by this script, so the verdict is NOT_RUN. The reason
291 # starts with the blocker class from the table; that is the table's
292 # claim about why, not a measured result.
293 operator) results+=("${id}|${kind}|NOT_RUN|BLOCKED_OPERATOR: needs an attended operator step; this script cannot check it|-|0|0"); return ;;
294 hardware) results+=("${id}|${kind}|NOT_RUN|BLOCKED_HARDWARE: needs attended hardware boots on Machine 1; this script cannot check it|-|0|0"); return ;;
295 missing) results+=("${id}|${kind}|NOT_RUN|MISSING_IMPLEMENTATION: the gate table lists no implementation to run|-|0|0"); return ;;
296 auto)
297 if ! auto_present "${runner}"; then
298 results+=("${id}|${kind}|NOT_RUN|MISSING_IMPLEMENTATION: runner file not present at this commit|-|0|0"); return
299 fi ;;
300 qemu)
301 if [[ "${with_qemu}" != 1 ]]; then
302 results+=("${id}|${kind}|NOT_RUN|QEMU suites are off (pass --with-qemu)|-|0|0"); return
303 fi
304 if [[ -e "${QUIET_FLAG}" ]]; then
305 quiet_flag_seen_at_gates=true
306 results+=("${id}|${kind}|NOT_RUN|quiet flag ${QUIET_FLAG} is up; heavy runs refused|-|0|0"); return
307 fi ;;
308 software|cargo) ;;
309 *) results+=("${id}|${kind}|FAIL|unknown kind in gate table|-|0|0"); return ;;
310 esac
311 if ! declare -F "${runner}" >/dev/null; then
312 results+=("${id}|${kind}|FAIL|runner ${runner} is not defined|-|0|0"); return
313 fi
314 echo "--- [${id}] running ..." >&2
315 t0="$(date +%s)"
316 "${runner}" >"${log}" 2>&1 </dev/null
317 rc=$?
318 t1="$(date +%s)"
319 out="$(classify_log "${kind}" "${rc}" "${notrun_rc}" "${marker}" "${log}")"
320 verdict="${out%%|*}"; reason="${out#*|}"
321 results+=("${id}|${kind}|${verdict}|${reason}|$(sha_of <"${log}")|$(wc -l <"${log}")|$((t1 - t0))")
322 echo "--- [${id}] ${verdict} (${reason})" >&2
323}
324
325run_table() {
326 local line id kind runner notrun_rc marker desc
327 while IFS='|' read -r id kind runner notrun_rc marker desc; do
328 [[ -n "${id}" ]] || continue
329 evaluate_gate "${id}" "${kind}" "${runner}" "${notrun_rc}" "${marker}"
330 descs["${id}"]="${desc}"
331 done <<<"${GATE_TABLE}"
332}
333
334# count_results -> sets n_pass n_fail n_notrun n_blocked n_missing sw_fail
335count_results() {
336 n_pass=0; n_fail=0; n_notrun=0; n_blocked=0; n_missing=0; sw_fail=0; n_total=0
337 local r v why
338 for r in "${results[@]}"; do
339 IFS='|' read -r _ _ v why _ <<<"${r}"
340 if [[ "${v}" == NOT_RUN ]]; then
341 case "${why}" in BLOCKED_OPERATOR:*|BLOCKED_HARDWARE:*) v=BLOCKED ;; MISSING_IMPLEMENTATION:*) v=MISSING ;; esac
342 fi
343 n_total=$((n_total + 1))
344 case "${v}" in
345 PASS) n_pass=$((n_pass + 1)) ;;
346 FAIL) n_fail=$((n_fail + 1)); sw_fail=1 ;;
347 NOT_RUN) n_notrun=$((n_notrun + 1)) ;;
348 BLOCKED) n_blocked=$((n_blocked + 1)) ;;
349 MISSING) n_missing=$((n_missing + 1)) ;;
350 *) n_fail=$((n_fail + 1)); sw_fail=1 ;;
351 esac
352 done
353}
354
355# ---------------------------------------------------------- machine identity
356# Read-only, never sudo. Anything unreadable is recorded as "not readable".
357readf() { [[ -r "$1" ]] && tr -d '\000' <"$1" 2>/dev/null | head -c 256 | tr -d '\n' || echo "not readable"; }
358read_hash() { [[ -r "$1" ]] && [[ -s "$1" ]] && sha_of <"$1" || echo "not readable"; }
359efivar_byte() {
360 local f="${EFIVARS}/$1-8be4df61-93ca-11d2-aa0d-00e098032b8c"
361 [[ -r "${f}" ]] || { echo "not readable"; return; }
362 od -An -tu1 -j4 -N1 "${f}" | tr -d ' '
363}
364collect_machine() {
365 EFIVARS="${AIENOS_EFIVARS_DIR:-/sys/firmware/efi/efivars}"
366 m_host="$(uname -n)"
367 m_machine_id_sha="$(read_hash /etc/machine-id)"
368 m_product="$(readf /sys/class/dmi/id/product_name)"
369 m_board="$(readf /sys/class/dmi/id/board_name)"
370 m_serial_sha="$(read_hash /sys/class/dmi/id/product_serial)"
371 m_cpu="$(lscpu 2>/dev/null | sed -n 's/^Model name: *//p' | sort -u | paste -sd';' -)"
372 [[ -n "${m_cpu}" ]] || m_cpu="not readable"
373 m_kernel="$(uname -r)"
374 m_bios_version="$(readf /sys/class/dmi/id/bios_version)"
375 m_bios_date="$(readf /sys/class/dmi/id/bios_date)"
376 m_sb_efivar="$(efivar_byte SecureBoot)"
377 m_setup_mode="$(efivar_byte SetupMode)"
378 m_sb_mokutil="$(command -v mokutil >/dev/null && mokutil --sb-state 2>&1 | head -1 || echo "mokutil not installed")"
379 # TPM: read-only getcap properties.
380 m_tpm_present="no"; m_tpm_mfr="not readable"; m_tpm_vendor="not readable"; m_tpm_fw="not readable"
381 if [[ -e /dev/tpmrm0 || -e /dev/tpm0 ]]; then
382 m_tpm_present="yes"
383 local caps
384 if command -v tpm2_getcap >/dev/null && caps="$(tpm2_getcap properties-fixed 2>/dev/null)"; then
385 m_tpm_mfr="$(awk '/^TPM2_PT_MANUFACTURER:/{f=1;next} f&&/value:/{gsub(/"/,"",$2);print $2;exit}' <<<"${caps}")"
386 m_tpm_vendor="$(awk '/^TPM2_PT_VENDOR_STRING_[1-4]:/{f=1;next} f&&/value:/{gsub(/"/,"",$2);printf "%s",$2;f=0}' <<<"${caps}")"
387 m_tpm_fw="$(awk '/^TPM2_PT_FIRMWARE_VERSION_[12]:/{f=1;next} f&&/raw:/{printf "%s%s",(n++?".":""),$2;f=0}' <<<"${caps}")"
388 fi
389 fi
390 # PCR 0-15 sha256, the same read tpm_measurement_campaign.sh uses.
391 pcr_lines=()
392 local pcrs
393 if command -v tpm2_pcrread >/dev/null && pcrs="$(tpm2_pcrread sha256:0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 2>/dev/null)"; then
394 mapfile -t pcr_lines < <(awk 'match($0, /^ *[0-9]+ *: *0x[0-9A-Fa-f]+/) {
395 line=$0; gsub(/[ :]+/," ",line); sub(/^ /,"",line); split(line,f," ");
396 printf "%d %s\n", f[1], tolower(substr(f[2],3)) }' <<<"${pcrs}" | sort -n)
397 fi
398 # Boot disk logical block size: /boot/efi (else /) -> parent disk.
399 local src parent
400 m_boot_disk="not readable"; m_lbs="not readable"
401 src="$(findmnt -no SOURCE /boot/efi 2>/dev/null || findmnt -no SOURCE / 2>/dev/null)"
402 if [[ -n "${src}" ]]; then
403 parent="$(lsblk -no PKNAME "${src}" 2>/dev/null | head -1)"
404 [[ -n "${parent}" ]] || parent="$(basename "${src}")"
405 m_boot_disk="${parent}"
406 [[ -r "/sys/block/${parent}/queue/logical_block_size" ]] && m_lbs="$(cat "/sys/block/${parent}/queue/logical_block_size")"
407 fi
408 # Full host capture through the existing tool (read-only). It may fail
409 # without root (event log); that is recorded, not hidden.
410 m_capture="not run"
411 local cap="${work_dir}/host_capture"
412 if bash "${repo_root}/scripts/tpm_measurement_campaign.sh" capture "${cap}" trust1_m5_qualify \
413 >"${work_dir}/logs/host_capture.log" 2>&1 </dev/null; then
414 m_capture="ok $(sed -n 's/^capture_digest=//p' "${work_dir}/logs/host_capture.log")"
415 else
416 m_capture="failed: $(grep -m1 -iE 'error|die|fail|not' "${work_dir}/logs/host_capture.log" | head -c 200)"
417 fi
418}
419
420# --------------------------------------------------------------- receipt
421write_receipt() {
422 local tmp="${work_dir}/receipt.tmp" i r id kind v reason lsha lines secs first blocker
423 # quiet_flag_present is true if the flag was up at ANY sampled point of
424 # the run: when a QEMU gate was evaluated, in any row refused for it, or
425 # now. It must never read false while a row says NOT_RUN for the flag.
426 local qf_write=false qf_refused=0 qf_any
427 [[ -e "${QUIET_FLAG}" ]] && qf_write=true
428 for r in "${results[@]}"; do
429 IFS='|' read -r _ _ v reason _ <<<"${r}"
430 [[ "${v}" == NOT_RUN && "${reason}" == "quiet flag "* ]] && qf_refused=$((qf_refused + 1))
431 done
432 qf_any=false
433 [[ ${quiet_flag_seen_at_gates} == true || ${qf_refused} -gt 0 || ${qf_write} == true ]] && qf_any=true
434 {
435 echo "{"
436 echo " \"schema\": \"aienos.trust1_m5_qualification.v2\","
437 echo " \"started_utc\": $(json_str "${started_utc}"),"
438 echo " \"finished_utc\": $(json_str "$(date -u +%FT%TZ)"),"
439 echo " \"commit\": $(json_str "${head_sha}"),"
440 echo " \"commit_subject\": $(json_str "${head_subject}"),"
441 echo " \"tree_clean_before\": ${tree_clean_before},"
442 echo " \"tree_clean_after\": ${tree_clean_after},"
443 echo " \"with_qemu_requested\": $([[ ${with_qemu} == 1 ]] && echo true || echo false),"
444 echo " \"quiet_flag_present\": ${qf_any},"
445 echo " \"quiet_flag_present_at_write\": ${qf_write},"
446 echo " \"quiet_flag_refused_gates\": ${qf_refused},"
447 echo " \"machine\": {"
448 echo " \"hostname\": $(json_str "${m_host}"),"
449 echo " \"machine_id_sha256\": $(json_str "${m_machine_id_sha}"),"
450 echo " \"dmi_product\": $(json_str "${m_product}"),"
451 echo " \"dmi_board\": $(json_str "${m_board}"),"
452 echo " \"dmi_serial_sha256\": $(json_str "${m_serial_sha}"),"
453 echo " \"cpu_model\": $(json_str "${m_cpu}"),"
454 echo " \"kernel\": $(json_str "${m_kernel}"),"
455 echo " \"firmware_version\": $(json_str "${m_bios_version}"),"
456 echo " \"firmware_date\": $(json_str "${m_bios_date}"),"
457 echo " \"secure_boot_efivar\": $(json_str "${m_sb_efivar}"),"
458 echo " \"setup_mode_efivar\": $(json_str "${m_setup_mode}"),"
459 echo " \"secure_boot_mokutil\": $(json_str "${m_sb_mokutil}"),"
460 echo " \"tpm_present\": $(json_str "${m_tpm_present}"),"
461 echo " \"tpm_manufacturer\": $(json_str "${m_tpm_mfr}"),"
462 echo " \"tpm_vendor_string\": $(json_str "${m_tpm_vendor}"),"
463 echo " \"tpm_firmware_version_raw\": $(json_str "${m_tpm_fw}"),"
464 printf ' "pcr_sha256": {'
465 if [[ ${#pcr_lines[@]} -eq 0 ]]; then
466 printf '"status": "not readable"'
467 else
468 first=1
469 for r in "${pcr_lines[@]}"; do
470 [[ ${first} == 1 ]] || printf ', '
471 first=0
472 printf '"%s": "%s"' "${r%% *}" "${r#* }"
473 done
474 fi
475 echo "},"
476 echo " \"boot_disk\": $(json_str "${m_boot_disk}"),"
477 echo " \"boot_disk_logical_block_size\": $(json_str "${m_lbs}"),"
478 echo " \"host_capture\": $(json_str "${m_capture}")"
479 echo " },"
480 echo " \"gates\": ["
481 for i in "${!results[@]}"; do
482 IFS='|' read -r id kind v reason lsha lines secs <<<"${results[$i]}"
483 blocker="-"; [[ "${v}" == NOT_RUN && "${reason}" =~ ^(BLOCKED_OPERATOR|BLOCKED_HARDWARE|MISSING_IMPLEMENTATION): ]] && blocker="${BASH_REMATCH[1]}"
484 printf ' {"id": %s, "kind": %s, "verdict": %s, "blocker": %s, "reason": %s, "description": %s, "log_sha256": %s, "log_lines": %s, "seconds": %s}' \
485 "$(json_str "${id}")" "$(json_str "${kind}")" "$(json_str "${v}")" "$(json_str "${blocker}")" "$(json_str "${reason}")" \
486 "$(json_str "${descs[${id}]:-}")" "$(json_str "${lsha}")" "${lines:-0}" "${secs:-0}"
487 [[ $i -lt $((${#results[@]} - 1)) ]] && echo "," || echo ""
488 done
489 echo " ],"
490 echo " \"counts\": {\"total\": ${n_total}, \"pass\": ${n_pass}, \"fail\": ${n_fail}, \"not_run\": ${n_notrun}, \"blocked\": ${n_blocked}, \"missing\": ${n_missing}},"
491 echo " \"verdict\": $(json_str "${overall}"),"
492 printf ' "not_pass": ['
493 first=1
494 for r in "${not_pass[@]}"; do
495 [[ ${first} == 1 ]] || printf ', '
496 first=0; printf '%s' "$(json_str "${r}")"
497 done
498 echo "]"
499 echo "}"
500 } >"${tmp}"
501 receipt_sha="$(sha_of <"${tmp}")"
502 receipt_path="${out_dir}/trust1_m5_qualification_${receipt_sha}.json"
503 mv "${tmp}" "${receipt_path}"
504}
505
506summarize() {
507 local r id kind v reason
508 not_pass=()
509 printf '\n%-36s %-9s %-24s %s\n' GATE KIND VERDICT REASON
510 for r in "${results[@]}"; do
511 IFS='|' read -r id kind v reason _ <<<"${r}"
512 printf '%-36s %-9s %-24s %s\n' "${id}" "${kind}" "${v}" "${reason}"
513 [[ "${v}" == PASS ]] || not_pass+=("${id}:${v}")
514 done
515 count_results
516 if [[ ${#not_pass[@]} -eq 0 && ${n_total} -gt 0 ]]; then overall=QUALIFIED; else overall=NOT_QUALIFIED; fi
517 echo ""
518 echo "Counts: total=${n_total} pass=${n_pass} fail=${n_fail} not_run=${n_notrun} blocked=${n_blocked} missing=${n_missing}"
519 echo "Verdict: ${overall}"
520}
521
522# ----------------------------------------------------------------- self-test
523self_test() {
524 local st_fail=0 tmp
525 tmp="$(mktemp -d "${TMPDIR:-/tmp}/trust1-m5-selftest.XXXXXX")" || exit 2
526 work_dir="${tmp}"; mkdir -p "${work_dir}/logs"
527 ok() { echo "PASS $*"; }
528 bad() { echo "FAIL $*"; st_fail=1; }
529 expect() { # expect ID WANTED_VERDICT
530 local r v
531 for r in "${results[@]}"; do
532 IFS='|' read -r id _ v _ <<<"${r}"
533 if [[ "${id}" == "$1" ]]; then
534 [[ "${v}" == "$2" ]] && ok "$1 -> $2" || bad "$1 -> ${v}, expected $2"
535 return
536 fi
537 done
538 bad "$1 has no result row"
539 }
540 expect_why() { # expect_why ID BLOCKER: the NOT_RUN reason names the blocker class
541 local r v why
542 for r in "${results[@]}"; do
543 IFS='|' read -r id _ v why _ <<<"${r}"
544 if [[ "${id}" == "$1" ]]; then
545 [[ "${why}" == "$2:"* ]] && ok "$1 reason names $2" || bad "$1 reason '${why}' does not start with $2:"
546 return
547 fi
548 done
549 bad "$1 has no result row"
550 }
551 fake_fail() { echo "boom"; return 1; }
552 fake_nomarker() { echo "all good, honest"; return 0; }
553 fake_pass() { echo "FAKE: ALL PASS"; return 0; }
554 fake_missing() { echo "Error: tool not installed"; return 2; }
555 fake_zero() { printf 'running 0 tests\n\ntest result: ok. 0 passed; 0 failed; 0 ignored\n'; return 0; }
556 fake_cargo_ok() { printf 'test result: ok. 7 passed; 0 failed; 0 ignored\ntest result: ok. 0 passed; 0 failed; 0 ignored\n'; return 0; }
557 fake_cargo_badrc() { printf 'test result: ok. 3 passed; 0 failed; 0 ignored\n'; return 101; }
558 sentinel="${tmp}/ran"
559 fake_sentinel() { : >"${sentinel}"; echo "FAKE: ALL PASS"; }
560 with_qemu=1; results=()
561 local saved_quiet="${QUIET_FLAG}"
562 evaluate_gate neg_fail software fake_fail - -
563 evaluate_gate neg_nomarker software fake_nomarker - '^FAKE: ALL PASS$'
564 evaluate_gate pos_pass software fake_pass - '^FAKE: ALL PASS$'
565 evaluate_gate notrun_rc2 software fake_missing 2 -
566 evaluate_gate rc2_not_notrun software fake_missing - -
567 evaluate_gate cargo_zero cargo fake_zero - '^test result: ok\.'
568 evaluate_gate cargo_ok cargo fake_cargo_ok - '^test result: ok\.'
569 evaluate_gate cargo_badrc cargo fake_cargo_badrc - '^test result: ok\.'
570 evaluate_gate auto_absent auto run_does_not_exist_anywhere - -
571 evaluate_gate op_never_pass operator fake_sentinel - -
572 evaluate_gate hw_never_pass hardware fake_sentinel - -
573 evaluate_gate miss_never_pass missing fake_sentinel - -
574 QUIET_FLAG="${tmp}/quiet"; : >"${QUIET_FLAG}"
575 evaluate_gate qemu_quiet qemu fake_sentinel - -
576 with_qemu=0; rm -f "${QUIET_FLAG}"
577 evaluate_gate qemu_off qemu fake_sentinel - -
578 QUIET_FLAG="${saved_quiet}"
579 expect neg_fail FAIL; expect neg_nomarker FAIL; expect pos_pass PASS
580 expect notrun_rc2 NOT_RUN; expect rc2_not_notrun FAIL
581 expect cargo_zero FAIL; expect cargo_ok PASS; expect cargo_badrc FAIL
582 expect auto_absent NOT_RUN
583 expect op_never_pass NOT_RUN; expect hw_never_pass NOT_RUN
584 expect miss_never_pass NOT_RUN
585 expect_why auto_absent MISSING_IMPLEMENTATION; expect_why miss_never_pass MISSING_IMPLEMENTATION
586 expect_why op_never_pass BLOCKED_OPERATOR; expect_why hw_never_pass BLOCKED_HARDWARE
587 expect qemu_quiet NOT_RUN; expect qemu_off NOT_RUN
588 [[ ! -e "${sentinel}" ]] && ok "blocked/missing/vetoed gates never ran their runner" || bad "a blocked/missing/vetoed runner ran"
589
590 # Prerequisite builds (no real cargo): a missing tool is the row's NOT_RUN
591 # code, a failed build is FAIL (1), a built artifact is ready (0), and an
592 # override skips the build. Never a silent pass.
593 fake_cargo_build_ok() { # fake cargo: create what the real build would, under --target-dir
594 local td="" a; while [[ $# -gt 0 ]]; do [[ "$1" == --target-dir ]] && td="$2"; shift; done
595 mkdir -p "${td}/release" "${td}/aarch64-unknown-uefi/release"
596 : >"${td}/release/aienos-store-tool"; chmod +x "${td}/release/aienos-store-tool"
597 : >"${td}/aarch64-unknown-uefi/release/aienos-handoff.efi"
598 }
599 fake_cargo_build_bad() { return 101; }
600 fake_cargo_build_none() { return 0; }
601 fake_rustc_has_uefi() { echo "${tmp}"; }
602 fake_rustc_no_uefi() { echo "${tmp}/no-such-libdir"; }
603 prc() { # prc WANTED_RC DESCRIPTION CMD...
604 local want="$1" desc="$2" got; shift 2
605 "$@" >/dev/null 2>&1; got=$?
606 [[ "${got}" == "${want}" ]] && ok "prereq: ${desc} -> exit ${want}" || bad "prereq: ${desc} -> exit ${got}, expected ${want}"
607 }
608 local saved_cargo="${QUAL_CARGO}" saved_rustc="${QUAL_RUSTC}" saved_tool="${RUST_STORE_TOOL:-}" saved_efi="${AIENOS_KEY_CEREMONY_EFI:-}"
609 unset RUST_STORE_TOOL AIENOS_KEY_CEREMONY_EFI
610 QUAL_CARGO=cargo_that_does_not_exist_anywhere; QUAL_RUSTC=fake_rustc_has_uefi
611 prc 2 "no cargo, store tool is NOT_RUN" prereq_store_tool 2
612 prc 3 "no cargo, loader is NOT_RUN" prereq_loader 3
613 QUAL_CARGO=fake_cargo_build_bad
614 prc 1 "failed store tool build is FAIL, not NOT_RUN" prereq_store_tool 2
615 prc 1 "failed loader build is FAIL, not NOT_RUN" prereq_loader 3
616 QUAL_CARGO=fake_cargo_build_none
617 prc 1 "build that produced no store tool is FAIL" prereq_store_tool 2
618 prc 1 "build that produced no loader is FAIL" prereq_loader 3
619 QUAL_CARGO=fake_cargo_build_ok; QUAL_RUSTC=fake_rustc_no_uefi
620 prc 3 "UEFI rust target absent, loader is NOT_RUN" prereq_loader 3
621 QUAL_RUSTC=fake_rustc_has_uefi
622 prc 0 "store tool built" prereq_store_tool 2
623 [[ -x "${STORE_TOOL_BIN}" && "${STORE_TOOL_BIN}" == "${work_dir}"/* ]] && ok "prereq: store tool lives in the work folder, not the repo target/" || bad "prereq: store tool path ${STORE_TOOL_BIN}"
624 prc 0 "loader built" prereq_loader 3
625 [[ -f "${LOADER_EFI}" && "${LOADER_EFI}" == "${work_dir}"/* ]] && ok "prereq: loader lives in the work folder, not the repo target/" || bad "prereq: loader path ${LOADER_EFI}"
626 QUAL_CARGO=cargo_that_does_not_exist_anywhere
627 RUST_STORE_TOOL=/some/tool AIENOS_KEY_CEREMONY_EFI=/some/loader.efi
628 prc 0 "RUST_STORE_TOOL override skips the build" prereq_store_tool 2
629 prc 0 "AIENOS_KEY_CEREMONY_EFI override skips the build" prereq_loader 3
630 QUAL_CARGO="${saved_cargo}"; QUAL_RUSTC="${saved_rustc}"
631 unset RUST_STORE_TOOL AIENOS_KEY_CEREMONY_EFI
632 [[ -n "${saved_tool}" ]] && export RUST_STORE_TOOL="${saved_tool}"
633 [[ -n "${saved_efi}" ]] && export AIENOS_KEY_CEREMONY_EFI="${saved_efi}"
634
635 # Counts come only from the table: 2 PASS, 5 FAIL, 3 NOT_RUN, 2 blocked, 2 missing.
636 count_results
637 [[ "${n_pass}/${n_fail}/${n_notrun}/${n_blocked}/${n_missing}/${n_total}" == "2/5/3/2/2/14" ]] \
638 && ok "counts derived from the table (2/5/3/2/2 of 14)" \
639 || bad "counts ${n_pass}/${n_fail}/${n_notrun}/${n_blocked}/${n_missing}/${n_total}, expected 2/5/3/2/2/14"
640 [[ ${sw_fail} == 1 ]] && ok "a FAIL row sets the failing exit status" || bad "FAIL row did not set sw_fail"
641
642 # Verdict: one non-PASS row is enough for NOT_QUALIFIED; all PASS -> QUALIFIED.
643 summarize >/dev/null
644 [[ "${overall}" == NOT_QUALIFIED ]] && ok "mixed table -> NOT_QUALIFIED" || bad "mixed table -> ${overall}"
645 results=("a|software|PASS|x|-|0|0" "b|cargo|PASS|x|-|0|0")
646 summarize >/dev/null
647 [[ "${overall}" == QUALIFIED ]] && ok "all-PASS table -> QUALIFIED" || bad "all-PASS table -> ${overall}"
648 results=("a|software|PASS|x|-|0|0" "b|operator|NOT_RUN|BLOCKED_OPERATOR: x|-|0|0")
649 summarize >/dev/null
650 count_results
651 [[ "${overall}" == NOT_QUALIFIED && ${sw_fail} == 0 ]] && ok "PASS + BLOCKED -> NOT_QUALIFIED, exit 0" || bad "PASS + BLOCKED -> ${overall} sw_fail=${sw_fail}"
652
653 # C kernel QEMU rows (ck_*): canned child scripts, no QEMU. Uses the
654 # table's own runner, notrun_rc and marker for each row.
655 ck_case() { # CASE ROW_ID WANTED SCRIPT_NAME RC LINES...
656 local cs="$1" row="$2" want="$3" name="$4" crc="$5" rid rkind rrun rnrc rmark rdesc
657 shift 5
658 ck_scripts_dir="${tmp}/ck_${cs}"; mkdir -p "${ck_scripts_dir}"
659 if [[ "${name}" != - ]]; then
660 { echo '#!/usr/bin/env bash'; echo "echo x >>\"${ck_scripts_dir}/runs\""
661 printf 'printf "%%s\\n"'; printf ' %q' "$@"; echo; echo "exit ${crc}"; } >"${ck_scripts_dir}/${name}"
662 fi
663 while IFS='|' read -r rid rkind rrun rnrc rmark rdesc; do
664 [[ "${rid}" == "${row}" ]] || continue
665 evaluate_gate "${cs}_${row}" "${rkind}" "${rrun}" "${rnrc}" "${rmark}" 2>/dev/null
666 done <<<"${GATE_TABLE}"
667 expect "${cs}_${row}" "${want}"
668 }
669 local saved_results=("${results[@]}")
670 QUIET_FLAG="${tmp}/no_quiet_flag_here"; with_qemu=1; results=()
671 rm -rf "${work_dir}/build"
672 ck_case boot_pass ck_m1_boot_qemu PASS qemu_ck_boot_test.sh 0 'PASS kernel: alive' 'AIENOS_CK_M1: PASS'
673 rm -rf "${work_dir}/build"
674 ck_case boot_notrun ck_m1_boot_qemu NOT_RUN qemu_ck_boot_test.sh 3 'NOT_RUN quiet flag held' 'AIENOS_CK_M1: NOT_RUN'
675 rm -rf "${work_dir}/build"
676 ck_case boot_rc3_nomark ck_m1_boot_qemu FAIL qemu_ck_boot_test.sh 3 'killed'
677 rm -rf "${work_dir}/build"
678 ck_case boot_fail ck_m1_boot_qemu FAIL qemu_ck_boot_test.sh 1 'AIENOS_CK_M1: FAIL'
679 rm -rf "${work_dir}/build"
680 ck_case boot_both ck_m1_boot_qemu FAIL qemu_ck_boot_test.sh 0 'AIENOS_CK_M1: PASS' 'AIENOS_CK_M1: FAIL'
681 rm -rf "${work_dir}/build"
682 ck_case store_absent ck_store_kernel_qemu NOT_RUN - 0
683 rm -rf "${work_dir}/build"
684 ck_case mixed ck_store_kernel_qemu FAIL qemu_ck_store_test.sh 1 \
685 'AIENOS_CK_M4_NVME: PASS' 'AIENOS_CK_M4_STORE: FAIL' 'AIENOS_CK_ARGUS1_REVOKE: PASS'
686 ck_case mixed ck_argus1_revoke_qemu PASS qemu_ck_store_test.sh 1 \
687 'AIENOS_CK_M4_NVME: PASS' 'AIENOS_CK_M4_STORE: FAIL' 'AIENOS_CK_ARGUS1_REVOKE: PASS'
688 [[ "$(wc -l <"${tmp}/ck_mixed/runs")" == 1 ]] && ok "store script ran once for its two rows" || bad "store script ran $(wc -l <"${tmp}/ck_mixed/runs") times"
689 rm -rf "${work_dir}/build"
690 ck_case pass_rc2 ck_argus1_revoke_qemu FAIL qemu_ck_store_test.sh 2 'AIENOS_CK_ARGUS1_REVOKE: PASS'
691 QUIET_FLAG="${saved_quiet}"; ck_scripts_dir="${repo_root}/scripts"; rm -rf "${work_dir}/build"
692 results=("${saved_results[@]}")
693
694 # The canonical table parses: every row has 6 fields and a known kind,
695 # and no blocked/missing row carries a runner.
696 local id kind runner nrc marker desc rows=0 tbad=0
697 while IFS='|' read -r id kind runner nrc marker desc; do
698 [[ -n "${id}" ]] || continue
699 rows=$((rows + 1))
700 case "${kind}" in
701 software|cargo|qemu) declare -F "${runner}" >/dev/null || tbad=1 ;;
702 auto) [[ "${runner}" != - ]] || tbad=1 ;;
703 operator|hardware|missing) [[ "${runner}" == - ]] || tbad=1 ;;
704 *) tbad=1 ;;
705 esac
706 [[ -n "${desc}" ]] || tbad=1
707 done <<<"${GATE_TABLE}"
708 [[ ${tbad} == 0 && ${rows} -gt 0 ]] && ok "canonical table: ${rows} rows well-formed" || bad "canonical table malformed"
709
710 # JSON escaping and receipt naming by content hash.
711 out_dir="${tmp}/out"; mkdir -p "${out_dir}"
712 started_utc=x; head_sha=x; head_subject='quote " backslash \ tab end'; tree_clean_before=true; tree_clean_after=true
713 m_host=h; m_machine_id_sha=x; m_product=x; m_board=x; m_serial_sha=x; m_cpu=x; m_kernel=x
714 m_bios_version=x; m_bios_date=x; m_sb_efivar=1; m_setup_mode=0; m_sb_mokutil=x; m_tpm_present=no
715 m_tpm_mfr=x; m_tpm_vendor=x; m_tpm_fw=x; m_boot_disk=x; m_lbs=512; m_capture=x; pcr_lines=("0 ab" "1 cd")
716 declare -gA descs=([a]=da [b]=db)
717 write_receipt
718 if [[ "$(sha_of <"${receipt_path}")" == "${receipt_sha}" && "${receipt_path}" == *"_${receipt_sha}.json" ]]; then
719 ok "receipt name is the sha256 of its content"
720 else
721 bad "receipt name does not match its content hash"
722 fi
723 if command -v jq >/dev/null; then
724 jq -e '.verdict == "NOT_QUALIFIED" and .counts.blocked == 1 and .gates[1].verdict == "NOT_RUN" and .gates[1].blocker == "BLOCKED_OPERATOR" and .gates[0].blocker == "-" and .tree_clean_before == true and .machine.pcr_sha256["1"] == "cd"' "${receipt_path}" >/dev/null \
725 && ok "receipt is valid JSON (jq) with expected fields" || bad "receipt is not valid JSON or fields wrong"
726 else
727 echo "SKIP jq not installed; JSON validity not machine-checked"; jq_skipped=1
728 fi
729
730 # The two scripts that return 3 for "a check was skipped" must map to NOT_RUN
731 # through their table rows, never PASS and never an accidental FAIL.
732 for g in t1_key_ceremony t1_recovery_tools; do
733 row="$(grep "^${g}|" "${BASH_SOURCE[0]}" | head -1)"
734 IFS='|' read -r _ _ _ nrc marker _ <<<"${row}"
735 v="$(classify_log software 3 "${nrc}" "${marker}" /dev/null)"
736 [[ "${v%%|*}" == NOT_RUN ]] && ok "${g}: exit 3 (a skipped check) -> NOT_RUN" || bad "${g}: exit 3 classified ${v%%|*}"
737 v="$(classify_log software 0 "${nrc}" "${marker}" /dev/null)"
738 [[ "${v%%|*}" == FAIL ]] && ok "${g}: exit 0 without its marker line -> FAIL" || bad "${g}: exit 0 without marker classified ${v%%|*}"
739 done
740
741 # Quiet-flag header must match the rows (TR-02 inspector fix item 3).
742 # Mutation: the flag is up while a QEMU gate is evaluated and down when
743 # the receipt is written. The old header sampled only at write time and
744 # said false next to a NOT_RUN "quiet flag" row; it must now say true.
745 local saved_quiet2="${QUIET_FLAG}" saved_results2=("${results[@]}") qf_hdr qf_w qf_n
746 QUIET_FLAG="${tmp}/quiet_mut"; : >"${QUIET_FLAG}"
747 with_qemu=1; results=(); quiet_flag_seen_at_gates=false
748 evaluate_gate qf_mut_qemu qemu fake_sentinel - - 2>/dev/null
749 rm -f "${QUIET_FLAG}"
750 summarize >/dev/null
751 write_receipt
752 qf_hdr="$(sed -nE 's/^ "quiet_flag_present": (true|false),$/\1/p' "${receipt_path}")"
753 qf_w="$(sed -nE 's/^ "quiet_flag_present_at_write": (true|false),$/\1/p' "${receipt_path}")"
754 qf_n="$(sed -nE 's/^ "quiet_flag_refused_gates": ([0-9]+),$/\1/p' "${receipt_path}")"
755 [[ "${qf_hdr}" == true && "${qf_w}" == false && "${qf_n}" == 1 ]] \
756 && ok "quiet flag up at gates, down at write -> header present=true (at_write=false, refused=1)" \
757 || bad "quiet flag up at gates, down at write -> header present=${qf_hdr} at_write=${qf_w} refused=${qf_n}, expected true/false/1"
758 # Refused row alone (no gate-time sample) still forces the header true.
759 quiet_flag_seen_at_gates=false
760 write_receipt
761 qf_hdr="$(sed -nE 's/^ "quiet_flag_present": (true|false),$/\1/p' "${receipt_path}")"
762 [[ "${qf_hdr}" == true ]] && ok "a NOT_RUN quiet-flag row alone forces header present=true" \
763 || bad "a NOT_RUN quiet-flag row left header present=${qf_hdr}"
764 # Control: flag never up -> header false.
765 results=(); quiet_flag_seen_at_gates=false
766 evaluate_gate qf_ctl_qemu qemu fake_sentinel - - 2>/dev/null
767 summarize >/dev/null
768 write_receipt
769 qf_hdr="$(sed -nE 's/^ "quiet_flag_present": (true|false),$/\1/p' "${receipt_path}")"
770 [[ "${qf_hdr}" == false ]] && ok "quiet flag never up -> header present=false" \
771 || bad "quiet flag never up -> header present=${qf_hdr}, expected false"
772 QUIET_FLAG="${saved_quiet2}"; results=("${saved_results2[@]}"); quiet_flag_seen_at_gates=false
773
774 # Dirty-tree refusal, end to end, on a private clone (never this tree).
775 local clone="${tmp}/clone" rc
776 if git clone -q --shared "${repo_root}" "${clone}" 2>/dev/null; then
777 cp "${BASH_SOURCE[0]}" "${clone}/scripts/trust1_m5_qualify.sh"
778 git -C "${clone}" add scripts/trust1_m5_qualify.sh
779 git -C "${clone}" -c user.name=t -c user.email=t@t commit -qm selftest --allow-empty
780 : >"${clone}/untracked_junk"
781 bash "${clone}/scripts/trust1_m5_qualify.sh" --machine-only --out "${tmp}/o1" >/dev/null 2>&1; rc=$?
782 [[ ${rc} == 2 ]] && ok "dirty tree (untracked file) refused, exit 2" || bad "dirty tree gave exit ${rc}, expected 2"
783 rm -f "${clone}/untracked_junk"
784 echo x >>"${clone}/README.md" 2>/dev/null || echo x >"${clone}/README.md"
785 bash "${clone}/scripts/trust1_m5_qualify.sh" --machine-only --out "${tmp}/o2" >/dev/null 2>&1; rc=$?
786 [[ ${rc} == 2 ]] && ok "dirty tree (modified tracked file) refused, exit 2" || bad "modified tree gave exit ${rc}, expected 2"
787 git -C "${clone}" checkout -q -- . 2>/dev/null; git -C "${clone}" clean -qfd
788 # A run that dirties the tree must exit 1.
789 AIENOS_QUALIFY_TEST_DIRTY=1 bash "${clone}/scripts/trust1_m5_qualify.sh" --machine-only --out "${tmp}/o3" >/dev/null 2>&1; rc=$?
790 [[ ${rc} == 1 ]] && ok "a run that dirties the tree exits 1" || bad "dirtying run gave exit ${rc}, expected 1"
791 # --out inside the tree: exit 0 and the receipt is the only new file.
792 git -C "${clone}" clean -qfd
793 bash "${clone}/scripts/trust1_m5_qualify.sh" --machine-only --out "${clone}/evidence/qualify_st" >/dev/null 2>&1; rc=$?
794 local added; added="$(git -C "${clone}" status --porcelain --untracked-files=all)"
795 if [[ ${rc} == 0 && "${added}" =~ ^\?\?\ evidence/qualify_st/trust1_m5_qualification_[0-9a-f]{64}\.json$ ]]; then
796 ok "--out inside the tree: exit 0, receipt is the only new file"
797 else
798 bad "--out inside the tree: exit ${rc}, tree change: ${added}"
799 fi
800 else
801 bad "could not make a private clone for the dirty-tree test"
802 fi
803
804 rm -rf --one-file-system "${tmp}"
805 if [[ ${st_fail} == 0 && ${jq_skipped:-0} == 0 ]]; then echo "TRUST1_M5_QUALIFY_SELF_TEST: PASS"; exit 0; fi
806 if [[ ${st_fail} == 0 ]]; then echo "TRUST1_M5_QUALIFY_SELF_TEST: PASS (jq missing: receipt JSON validity NOT_RUN)"; exit 0; fi
807 echo "TRUST1_M5_QUALIFY_SELF_TEST: FAIL"; exit 1
808}
809
810# ---------------------------------------------------------------------- main
811main() {
812 with_qemu=0; out_arg=""; mode=full
813 while [[ $# -gt 0 ]]; do
814 case "$1" in
815 --with-qemu) with_qemu=1 ;;
816 --out) [[ $# -ge 2 ]] || die "--out needs a directory"; out_arg="$2"; shift ;;
817 --self-test) mode=self ;;
818 --machine-only) mode=machine ;; # internal: identity + receipt, no gates
819 -h|--help) sed -n '2,28p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'; exit 0 ;;
820 *) die "unknown argument: $1" ;;
821 esac
822 shift
823 done
824 declare -gA descs=()
825 results=()
826 if [[ ${mode} == self ]]; then self_test; fi
827
828 refuse_if_dirty "${repo_root}"
829 local before; before="$(tree_state "${repo_root}")"
830 # Measured, not assumed: refuse_if_dirty above exits on a dirty tree, and
831 # this re-reads the state the receipt reports.
832 if [[ -z "${before}" ]]; then tree_clean_before=true; else tree_clean_before=false; fi
833 head_sha="$(git -C "${repo_root}" rev-parse HEAD)"
834 head_subject="$(git -C "${repo_root}" log -1 --format=%s HEAD)"
835 started_utc="$(date -u +%FT%TZ)"
836
837 if [[ -n "${out_arg}" ]]; then
838 # Resolved now, created only after the dirty-tree re-check, so an
839 # in-tree DIR (evidence/) gets the receipt and nothing else.
840 out_dir="$(realpath -m -- "${out_arg}")"
841 else
842 out_dir="$(mktemp -d "${TMPDIR:-/tmp}/trust1-m5-qualify.XXXXXX")" || die "mktemp failed"
843 fi
844 # Logs and builds always live outside the tree.
845 work_dir="$(mktemp -d "${TMPDIR:-/tmp}/trust1-m5-work.XXXXXX")" || die "mktemp failed"
846 mkdir -p "${work_dir}/logs" "${work_dir}/build"
847
848 echo "TRUST-1 + M5 qualification at ${head_sha} (${head_subject})"
849 collect_machine
850 echo "Machine: ${m_host} | ${m_product} | firmware ${m_bios_version} (${m_bios_date}) | SecureBoot=${m_sb_efivar} SetupMode=${m_setup_mode} | TPM ${m_tpm_present} ${m_tpm_mfr} | boot disk ${m_boot_disk} LBS ${m_lbs}"
851 if [[ ${mode} == full ]]; then
852 run_table
853 fi
854 [[ "${AIENOS_QUALIFY_TEST_DIRTY:-0}" == 1 ]] && : >"${repo_root}/qualify_dirty_marker"
855
856 # The run must not have changed the tree (the receipt is not written yet).
857 local after; after="$(tree_state "${repo_root}")"
858 tree_clean_after=true
859 if [[ "${after}" != "${before}" ]]; then
860 tree_clean_after=false
861 echo "trust1_m5_qualify: the run changed the tree:" >&2
862 printf '%s\n' "${after}" >&2
863 results+=("tree_unchanged_after_run|software|FAIL|the run changed tracked or untracked files|-|0|0")
864 descs[tree_unchanged_after_run]="the qualification run left the tree as it found it"
865 fi
866
867 summarize
868 mkdir -p "${out_dir}" || die "cannot create ${out_dir}"
869 write_receipt
870 echo "Logs: ${work_dir}/logs"
871 echo "Receipt: ${receipt_path}"
872 echo "TRUST1_M5_QUALIFICATION: ${overall} (pass=${n_pass} fail=${n_fail} not_run=${n_notrun} blocked=${n_blocked} missing=${n_missing})"
873 [[ ${sw_fail} == 0 ]] && exit 0 || exit 1
874}
875
876if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
877 main "$@"
878fi