aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
GitHub aien-dev/aienux#127 (code only)
Apply it
git checkout -b patch-27a87da545287fcd 4dd5726e6dedf6c7ddfdb2095e241063bfae98dc curl -fsSL https://interplane.io/drakestapleton/aienux/patches/27a87da545287fcd.patch | git am
Provenance
github-import 1
aien-dev/aienux
127
c1f0a5aad52be8e3fbe9ca9e6886e5f047d4c4ec
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":127,"url":"https://github.com/aien-dev/aienux/pull/127","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:35:47Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/aienos-artifact-tool/fixtures/p2_6/assemble.sh b/crates/aienos-artifact-tool/fixtures/p2_6/assemble.sh new file mode 100755 index 00000000..d0b85f2a --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_6/assemble.sh @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +# Reassemble the P2-6 SEED-0B probe from probe.S into OUT_DIR/<probe>/code.bin. +# The committed code.bin is the qualification input; this proves it is +# exactly what probe.S assembles to, with no relocations. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +out="${1:?usage: assemble.sh OUT_DIR}" +as_bin="${AS:-as}" +objcopy_bin="${OBJCOPY:-objcopy}" +if [[ "$(uname -m)" != "aarch64" ]]; then + as_bin="${AS:-aarch64-linux-gnu-as}" + objcopy_bin="${OBJCOPY:-aarch64-linux-gnu-objcopy}" +fi + +for probe in p26seed; do + mkdir -p "${out}/${probe}" + "${as_bin}" -o "${out}/${probe}/probe.o" "${here}/${probe}/probe.S" + if command -v readelf >/dev/null; then + if readelf -r "${out}/${probe}/probe.o" | grep -q "Relocation section"; then + echo "FAIL ${probe} has relocations" >&2 + exit 1 + fi + fi + "${objcopy_bin}" -O binary -j .text "${out}/${probe}/probe.o" "${out}/${probe}/code.bin" +done diff --git a/crates/aienos-artifact-tool/fixtures/p2_6/p26seed/code.bin b/crates/aienos-artifact-tool/fixtures/p2_6/p26seed/code.bin new file mode 100644 index 00000000..f2dad340 Binary files /dev/null and b/crates/aienos-artifact-tool/fixtures/p2_6/p26seed/code.bin differ diff --git a/crates/aienos-artifact-tool/fixtures/p2_6/p26seed/data.bin b/crates/aienos-artifact-tool/fixtures/p2_6/p26seed/data.bin new file mode 100644 index 00000000..3e0874d1 --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_6/p26seed/data.bin @@ -0,0 +1 @@ +SEED0B-1 \ No newline at end of file diff --git a/crates/aienos-artifact-tool/fixtures/p2_6/p26seed/manifest.json b/crates/aienos-artifact-tool/fixtures/p2_6/p26seed/manifest.json new file mode 100644 index 00000000..f2a6992e --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_6/p26seed/manifest.json @@ -0,0 +1,26 @@ +{ + "entry_offset": 0, + "capabilities": [ + { + "resource_kind": 3, + "resource_id": 1, + "rights": 1, + "bounds_kind": 1, + "max_operations": 4, + "max_bytes": 32, + "byte_offset": 0, + "byte_length": 32 + } + ], + "resources": { + "code_pages": 1, + "data_pages": 1, + "stack_pages": 1, + "max_capabilities": 1, + "ipc_messages": 0, + "ipc_bytes": 0, + "cpu_ticks": 100000000, + "elapsed_ticks": 100000000, + "syscall_count": 16 + } +} diff --git a/crates/aienos-artifact-tool/fixtures/p2_6/p26seed/probe.S b/crates/aienos-artifact-tool/fixtures/p2_6/p26seed/probe.S new file mode 100644 index 00000000..e74d8230 --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_6/p26seed/probe.S @@ -0,0 +1,131 @@ +// P2-6B first SEED-0B capability artifact: AArch64 EL0, position +// independent, no relocations. It requests exactly one capability: READ on +// SEED object 1, bytes [0, 32). Entry (task_runtime ABI): x0 = handle array, +// x1 = handle count, x2 = data base, x3 = data memory length. +// +// Exit 0 only if every allow/deny result is exactly as expected; otherwise +// each set bit names one failed expectation: +// 0x001 handle count != 1 +// 0x002 authenticated data word missing +// 0x004 READ(handle, 0) != SEED word 0 (authorized read) +// 0x008 READ(handle, 24) != SEED word 3 (authorized read) +// 0x010 WRITE(handle, 0) not denied (WRITE never granted) +// 0x020 READ(handle, 0) changed after the denied write +// 0x040 forged-generation handle not denied +// 0x080 never-issued slot handle not denied +// 0x100 zero handle not denied (no ambient authority) +// 0x200 READ(handle, 32) past the grant not denied + .text + .global _start +_start: + mov x19, x0 // handle array + mov x20, x1 // handle count + mov x21, x2 // data base + mov x22, xzr // failure bitmask + + // SEED word 0 = 0xa1e05eed00000001 in x24, word 3 in x25. + movz x24, #0x0001 + movk x24, #0x5eed, lsl #32 + movk x24, #0xa1e0, lsl #48 + movz x25, #0x0004 + movk x25, #0x5eed, lsl #32 + movk x25, #0xa1e0, lsl #48 + + cmp x20, #1 + b.eq 1f + orr x22, x22, #0x001 + b 90f // no handle: nothing else is meaningful +1: + // 0x002: data section is "SEED0B-1" = 0x312d423044454553 + ldr x9, [x21] + movz x10, #0x4553 + movk x10, #0x4445, lsl #16 + movk x10, #0x4230, lsl #32 + movk x10, #0x312d, lsl #48 + cmp x9, x10 + b.eq 2f + orr x22, x22, #0x002 +2: + ldr x23, [x19] // the one granted handle + + // 0x004: authorized READ at offset 0 + mov x0, x23 + mov x1, #0 + mov x8, #6 + svc #0 + cmp x0, x24 + b.eq 3f + orr x22, x22, #0x004 +3: + // 0x008: authorized READ at offset 24 + mov x0, x23 + mov x1, #24 + mov x8, #6 + svc #0 + cmp x0, x25 + b.eq 4f + orr x22, x22, #0x008 +4: + // 0x010: WRITE through the READ-only handle must be denied + mov x0, x23 + mov x1, #0 + mov x2, #0x57 + mov x8, #7 + svc #0 + cmn x0, #1 + b.eq 5f + orr x22, x22, #0x010 +5: + // 0x020: the denied write had no effect + mov x0, x23 + mov x1, #0 + mov x8, #6 + svc #0 + cmp x0, x24 + b.eq 6f + orr x22, x22, #0x020 +6: + // 0x040: forged generation (flip generation bit 0) + mov x9, #1 + lsl x9, x9, #32 + eor x0, x23, x9 + mov x1, #0 + mov x8, #6 + svc #0 + cmn x0, #1 + b.eq 7f + orr x22, x22, #0x040 +7: + // 0x080: slot 1 was never issued (index 1, generation 1) + mov x9, #1 + lsl x9, x9, #32 + orr x0, x9, #1 + mov x1, #0 + mov x8, #6 + svc #0 + cmn x0, #1 + b.eq 8f + orr x22, x22, #0x080 +8: + // 0x100: no ambient authority — the zero handle names nothing + mov x0, xzr + mov x1, #0 + mov x8, #6 + svc #0 + cmn x0, #1 + b.eq 9f + orr x22, x22, #0x100 +9: + // 0x200: offset 32 is outside the granted byte range [0, 32) + mov x0, x23 + mov x1, #32 + mov x8, #6 + svc #0 + cmn x0, #1 + b.eq 90f + orr x22, x22, #0x200 +90: + mov x0, x22 + mov x8, #2 + svc #0 +91: b 91b diff --git a/crates/aienos-artifact-tool/fixtures/p2_6/pack.sh b/crates/aienos-artifact-tool/fixtures/p2_6/pack.sh new file mode 100755 index 00000000..1b7914d1 --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_6/pack.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Pack and sign the first SEED-0B capability artifact with the TEST ONLY +# SEED-0B identity into OUT_DIR/P26SEED.AIEN and append "NAME ARTIFACT_ID" +# to OUT_DIR/ids.txt. +# +# TOOL must be a debug aienos-artifact-tool built with +# --features seed0b-test-signing (release builds refuse that feature). +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +tool="${1:?usage: pack.sh TOOL OUT_DIR}" +out="${2:?usage: pack.sh TOOL OUT_DIR}" +mkdir -p "${out}" +touch "${out}/ids.txt" + +"${tool}" pack "${here}/p26seed/manifest.json" "${here}/p26seed/code.bin" \ + "${here}/p26seed/data.bin" "${out}/p26seed.unsigned.aien" >/dev/null +"${tool}" sign "${out}/p26seed.unsigned.aien" "${out}/P26SEED.AIEN" >/dev/null +rm -f "${out}/p26seed.unsigned.aien" +"${tool}" verify "${out}/P26SEED.AIEN" >/dev/null +echo "P26SEED.AIEN $("${tool}" id "${out}/P26SEED.AIEN")" >>"${out}/ids.txt" diff --git a/crates/aienos-boot/src/handoff.rs b/crates/aienos-boot/src/handoff.rs index d2554ff9..d3f27469 100644 --- a/crates/aienos-boot/src/handoff.rs +++ b/crates/aienos-boot/src/handoff.rs @@ -1102,7 +1102,7 @@ fn save_report_file(text: &str) -> uefi::Result { } /// Most signed-artifact candidates firmware reads from `\EFI\AIENOS\ARTIFACTS`. -const MAX_ARTIFACT_CANDIDATES: usize = 8; +const MAX_ARTIFACT_CANDIDATES: usize = 32; /// Largest candidate firmware will read. Bigger files are refused unread. const MAX_ARTIFACT_FILE_BYTES: u64 = 640 * 1024; const ARTIFACT_NAME_BYTES: usize = 32; @@ -1267,10 +1267,21 @@ fn read_artifact_candidates() -> ArtifactCandidates { out } -/// Hand each candidate to the kernel loader, then send one `artifacts` -/// record with a line per candidate to the console. Returns the number of -/// admitted and rejected candidates. +/// Hand each candidate to the kernel loader. One `artifacts` header record +/// goes to the console first; then each candidate's result line and its +/// unsigned Admission Receipt v0 stream to the console on their own (they do +/// not fit, and do not belong, in the bounded NVRAM report). Returns the +/// number of admitted and rejected candidates. fn run_artifact_candidates(candidates: &ArtifactCandidates, kernel_root: usize) -> (usize, usize) { + use aienos_kernel::artifact_loader as loader; + let context = loader::ReceiptContext { + verifier_identity: loader::boot_verifier_identity(COMMIT), + tier: if cfg!(feature = "hardware-staging") { + aienos_kernel::artifact_loader::QualificationTier::Seed0bMachine1 + } else { + aienos_kernel::artifact_loader::QualificationTier::Seed0bQemu + }, + }; let mut record = Report::new(); header(&mut record, "artifacts"); #[cfg(feature = "seed0b-qualification")] @@ -1279,37 +1290,53 @@ fn run_artifact_candidates(candidates: &ArtifactCandidates, kernel_root: usize) "artifact_trust: seed0b-test qualification build — TEST ONLY" ); let _ = writeln!(record, "artifact_candidates: {}", candidates.count); + let _ = write!( + record, + "artifact_receipt_tier: {}\nartifact_verifier_identity: ", + context.tier.label() + ); + for byte in context.verifier_identity { + let _ = write!(record, "{byte:02x}"); + } + let _ = writeln!(record); + let _ = writeln!( + record, + "artifact_frames_free_before: {}", + aienos_kernel::boot::early_free_frames() + ); + send_to_console(record.as_str()); + let (mut admitted, mut rejected) = (0, 0); for candidate in &candidates.entries[..candidates.count] { let name = candidate.name(); - if candidate.oversize() { - rejected += 1; - let _ = writeln!( - record, - "artifact: {name} rejected stage=received reason=StagingTooLarge reclaimed=yes" - ); - continue; - } - let Some(bytes) = candidate.bytes() else { - rejected += 1; - let _ = writeln!( - record, - "artifact: {name} rejected stage=received reason=FirmwareRead reclaimed=yes" - ); - continue; + let report = if candidate.oversize() { + loader::firmware_rejection(loader::LoadError::StagingTooLarge) + } else if let Some(bytes) = candidate.bytes() { + unsafe { loader::run_boot_candidate(bytes, kernel_root) } + } else { + loader::firmware_rejection(loader::LoadError::FirmwareRead) }; - let result = - unsafe { aienos_kernel::artifact_loader::run_boot_candidate(bytes, kernel_root) }; - match result.decision { - aienos_kernel::artifact_loader::Decision::Admitted => admitted += 1, - aienos_kernel::artifact_loader::Decision::Rejected => rejected += 1, + match report.decision { + loader::Decision::Admitted => admitted += 1, + loader::Decision::Rejected => rejected += 1, } - aienos_kernel::artifact_loader::write_candidate_line(&mut record, name, &result); - } - if record.truncated() { - let _ = writeln!(record, "truncated: yes"); + let mut out = ReportBuf::<2048>::new(); + loader::write_candidate_line(&mut out, name, &report); + match loader::boot_receipt(&report, &context) { + (sequence, Some(bytes)) => loader::write_receipt_line(&mut out, name, sequence, &bytes), + (sequence, None) => { + let _ = writeln!(out, "receipt: {name} seq={sequence} invalid"); + } + } + send_to_console(out.as_str()); } - send_to_console(record.as_str()); + let mut tail = ReportBuf::<128>::new(); + let _ = writeln!( + tail, + "artifact_frames_free_after: {}", + aienos_kernel::boot::early_free_frames() + ); + send_to_console(tail.as_str()); (admitted, rejected) } diff --git a/crates/aienos-kernel/src/artifact_loader.rs b/crates/aienos-kernel/src/artifact_loader.rs index dc27c5e1..5fa1d996 100644 --- a/crates/aienos-kernel/src/artifact_loader.rs +++ b/crates/aienos-kernel/src/artifact_loader.rs @@ -31,6 +31,13 @@ use aienos_artifact::capability::{CapabilityRequest, MAX_CAPABILITIES, RESOURCE_KIND_OBJECT}; use aienos_artifact::error::ArtifactError; +pub use aienos_artifact::receipt::QualificationTier; +use aienos_artifact::receipt::{ + receipt_digest, receipt_nonce, validate as validate_receipt, ExecutionStatusCode, Receipt, + ReceiptDecision, RECEIPT_SIZE, RESULT_CANARY_PASSED, RESULT_EXECUTED_BYTES_MATCH, + RESULT_FORGED_DENIED, RESULT_MAPPED_BYTES_MATCH, RESULT_READ_OK, RESULT_RECLAIMED, + RESULT_WRITE_DENIED, RESULT_WX_SEALED, +}; use aienos_artifact::resource::{ ResourceEnvelope, MAX_CODE_PAGES, MAX_CPU_TICKS, MAX_DATA_PAGES, MAX_ELAPSED_TICKS, MAX_STACK_PAGES, MAX_SYSCALLS, @@ -100,6 +107,64 @@ pub enum LoadError { SchedulerFull, ExecutedDigestMismatch, Reclaim, + /// Firmware could not provide the candidate's bytes (handoff-level). + FirmwareRead, +} + +impl LoadError { + /// Stable ADR 0014 §7.3 reason code. + pub const fn reason_code(self) -> u16 { + match self { + Self::Artifact(e) => e as u16, + Self::NoFrames => 0x101, + Self::StagingTooLarge => 0x102, + Self::Mapping => 0x103, + Self::MappedDigestMismatch => 0x104, + Self::WxAudit => 0x105, + Self::CapabilityInstall => 0x106, + Self::SchedulerFull => 0x107, + Self::ExecutedDigestMismatch => 0x108, + Self::Reclaim => 0x109, + Self::FirmwareRead => 0x10a, + } + } +} + +impl CandidateState { + /// Stable ADR 0014 §7.3 stage code; `0` for states that are not a + /// rejection point. + pub const fn stage_code(self) -> u16 { + match self { + Self::Received => 1, + Self::Staged => 2, + Self::Verified => 3, + Self::Authorized => 4, + Self::Reserved => 5, + Self::Mapped => 6, + Self::Hashed => 7, + Self::Sealed => 8, + Self::CapsInstalled => 9, + _ => 0, + } + } +} + +/// Identity and check results the loader actually computed, recorded as +/// each stage passes. A field stays zero/false unless its stage completed, +/// so a rejection receipt never carries a value the kernel did not derive. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct ReceiptBindings { + pub artifact_id: Digest, + pub payload_digest: Digest, + pub artifact_signer_fingerprint: Digest, + pub policy_digest: Digest, + pub requested_capability_digest: Digest, + pub granted_capability_digest: Digest, + pub resource_envelope_digest: Digest, + /// SHA-256 of the bytes read back from private pages == admitted digest. + pub mapped_bytes_matched: bool, + /// `audit_wx` passed on the sealed task root. + pub wx_sealed: bool, } impl From<ArtifactError> for LoadError { @@ -133,6 +198,7 @@ pub struct CandidateReport { pub outcome: TaskOutcome, pub code_base: u64, pub code_end: u64, + pub bindings: ReceiptBindings, } impl CandidateReport { @@ -521,17 +587,62 @@ where P: LoaderPlatform, V: ArtifactVerifier, { + let mut bindings = ReceiptBindings::default(); + load_bound( + platform, + staged_pa, + staged_len, + verifier, + policy, + scheduler, + task_id, + &mut bindings, + ) +} + +/// [`load`], also recording in `bindings` what each completed stage derived. +#[allow(clippy::too_many_arguments)] +pub fn load_bound<P, V>( + platform: &mut P, + staged_pa: u64, + staged_len: usize, + verifier: &V, + policy: &AdmissionPolicy, + scheduler: &mut LoaderScheduler, + task_id: u32, + bindings: &mut ReceiptBindings, +) -> Result<LoadedTask, Failure> +where + P: LoaderPlatform, + V: ArtifactVerifier, +{ + bindings.policy_digest = policy.digest(); // ---- Verified + Authorized: pure decisions over the staged bytes. let free_slots = LOADED_TASK_SLOTS.saturating_sub(occupied_slots(scheduler)); let (admission, code_src, data_src, code_len, data_len, data_memory_len) = { let bytes = platform.bytes(staged_pa, staged_len); + // Identity is derivable from structure alone, before authentication. + if let Ok(identified) = aienos_artifact::verify::parse_and_identify(bytes) { + bindings.artifact_id = *identified.artifact_id.as_bytes(); + bindings.payload_digest = identified.payload_digest; + bindings.requested_capability_digest = + aienos_artifact::canonical::requested_capability_digest( + identified.artifact.capability_request_bytes, + ); + bindings.resource_envelope_digest = + aienos_artifact::canonical::resource_envelope_digest( + identified.artifact.resource_envelope_bytes, + ); + } let verified = verifier .verify(bytes) .map_err(|e| (CandidateState::Verified, e.into()))?; + bindings.artifact_signer_fingerprint = *verified.signer_fingerprint(); let available = available_resources(platform.free_frames(), free_slots); let admission = policy .evaluate(&verified, available) .map_err(|e| (CandidateState::Authorized, e.into()))?; + bindings.granted_capability_digest = admission.granted_capability_digest; let identified = verified.identified(); if admission.artifact_id != identified.artifact_id || admission.payload_digest != identified.payload_digest @@ -640,6 +751,7 @@ where if payload != admission.payload_digest { fail!(CandidateState::Hashed, LoadError::MappedDigestMismatch); } + bindings.mapped_bytes_matched = true; // ---- Sealed: code becomes EL0 RX; its EL1 alias read-only in this root. for frame in code_frames { @@ -668,6 +780,7 @@ where if !audit_wx(platform, &address_space) { fail!(CandidateState::Sealed, LoadError::WxAudit); } + bindings.wx_sealed = true; // ---- CapsInstalled: exactly the policy grants, in grant order. let mut capabilities = CapTable::new(0x5441_0000 | (task_id & 0xffff)); @@ -963,13 +1076,7 @@ where P: LoaderPlatform, E: TaskExecutor<P>, { - let not_run = TaskOutcome { - status: ExecutionStatus::NotRun, - syscalls: 0, - object_reads_ok: 0, - denials: 0, - elapsed_ticks: 0, - }; + let not_run = TaskOutcome::not_run(); if scheduler.tick(0) != Ok(Some(task.scheduler_id)) { return not_run; } @@ -1060,7 +1167,7 @@ where platform .bytes_mut(staged, bytes.len()) .copy_from_slice(bytes); - let loaded = load( + let loaded = load_bound( platform, staged, bytes.len(), @@ -1068,6 +1175,7 @@ where policy, scheduler, task_id, + &mut report.bindings, ); // The task owns its own copy; staging is scrubbed and returned now. platform.bytes_mut(staged, pages * PAGE).fill(0); @@ -1089,11 +1197,11 @@ where report.caps_installed = task.grant_count; report.code_base = task.address_space.layout.code_base(); report.code_end = task.address_space.layout.code_end(); - report.wx_enforced = true; + report.wx_enforced = report.bindings.wx_sealed; report.outcome = run_task(&mut task, platform, scheduler, executor); let teardown = destroy(task, platform, scheduler); report.decision = Decision::Admitted; - report.byte_chain = teardown.executed_bytes_match; + report.byte_chain = report.bindings.mapped_bytes_matched && teardown.executed_bytes_match; report.caps_live_after = teardown.caps_live_after; report.frames_free_after = platform.free_frames(); if !teardown.executed_bytes_match { @@ -1118,15 +1226,10 @@ fn empty_report(free_before: usize) -> CandidateReport { caps_live_after: 0, byte_chain: false, wx_enforced: false, - outcome: TaskOutcome { - status: ExecutionStatus::NotRun, - syscalls: 0, - object_reads_ok: 0, - denials: 0, - elapsed_ticks: 0, - }, + outcome: TaskOutcome::not_run(), code_base: 0, code_end: 0, + bindings: ReceiptBindings::default(), } } @@ -1221,6 +1324,67 @@ static BOOT_SCHEDULER: crate::sync::spinlock::SpinLock<LoaderScheduler> = crate::sync::spinlock::SpinLock::new(Scheduler::new([0])); static NEXT_TASK_ID: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(1); +static NEXT_RECEIPT_SEQUENCE: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(1); + +/// A candidate refused by the boot handoff before the kernel saw its bytes. +pub fn firmware_rejection(error: LoadError) -> CandidateReport { + let free = crate::boot::early_free_frames(); + let mut report = empty_report(free); + report.failed_stage = Some(CandidateState::Received); + report.error = Some(error); + report.bindings.policy_digest = match boot_policy(&boot_signers()) { + Ok(policy) => policy.digest(), + Err(_) => [0; 32], + }; + report +} + +/// Next boot-scoped receipt sequence (from 1) and the candidate's unsigned +/// canonical receipt. `None` only if the report violates §7, which would be +/// a loader bug; callers report it rather than emit a malformed record. +pub fn boot_receipt( + report: &CandidateReport, + context: &ReceiptContext, +) -> (u64, Option<[u8; RECEIPT_SIZE]>) { + let sequence = NEXT_RECEIPT_SEQUENCE.fetch_add(1, core::sync::atomic::Ordering::Relaxed); + let record = build_receipt(report, context, sequence) + .ok() + .map(|receipt| aienos_artifact::receipt::encode(&receipt)); + (sequence, record) +} + +/// Verifier identity digest for this build (ADR 0014 §7.1). +pub fn boot_verifier_identity(commit: &str) -> Digest { + let feature = u8::from(cfg!(feature = "seed0b-test-anchor")); + match aienos_artifact::receipt::verifier_identity_bytes( + commit.as_bytes(), + aienos_artifact::format::TARGET_AARCH64_LE, + aienos_artifact::format::ABI_V1, + feature, + ) { + Some(bytes) => aienos_artifact::canonical::verifier_identity_digest(&bytes), + None => aienos_artifact::canonical::verifier_identity_digest(b"unpinned-build"), + } +} + +fn boot_signers() -> [Digest; BOOT_SIGNERS] { + #[cfg(feature = "seed0b-test-anchor")] + { + [aienos_artifact::signature::signer_fingerprint( + &aienos_artifact::signature::seed0b_test_anchor::PUBLIC_KEY, + )] + } + #[cfg(not(feature = "seed0b-test-anchor"))] + { + [] + } +} + +#[cfg(feature = "seed0b-test-anchor")] +const BOOT_SIGNERS: usize = 1; +#[cfg(not(feature = "seed0b-test-anchor"))] +const BOOT_SIGNERS: usize = 0; + /// Stage, verify, admit, load, run and destroy one candidate. /// /// # Safety @@ -1228,16 +1392,10 @@ static NEXT_TASK_ID: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU /// allocator and after exception vectors, GIC and timer are set up. pub unsafe fn run_boot_candidate(bytes: &[u8], kernel_root: usize) -> CandidateReport { #[cfg(feature = "seed0b-test-anchor")] - let (anchors, signers) = { - use aienos_artifact::signature::seed0b_test_anchor::{Seed0bTestAnchorSet, PUBLIC_KEY}; - ( - Seed0bTestAnchorSet, - [aienos_artifact::signature::signer_fingerprint(&PUBLIC_KEY)], - ) - }; + let anchors = aienos_artifact::signature::seed0b_test_anchor::Seed0bTestAnchorSet; #[cfg(not(feature = "seed0b-test-anchor"))] - let (anchors, signers): (aienos_artifact::ProductionTrustAnchorSet, [Digest; 0]) = - (aienos_artifact::ProductionTrustAnchorSet::default(), []); + let anchors = aienos_artifact::ProductionTrustAnchorSet::default(); + let signers = boot_signers(); let verifier = aienos_artifact::ConfiguredArtifactVerifier::new( &anchors, aienos_artifact::Ed25519Verifier, @@ -1265,6 +1423,123 @@ pub unsafe fn run_boot_candidate(bytes: &[u8], kernel_root: usize) -> CandidateR ) } +// --------------------------------------------------------------------------- +// Admission Receipt v0 emission (ADR 0014 §7) +// --------------------------------------------------------------------------- + +/// Verifier-context facts a receipt binds that the loader does not derive. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct ReceiptContext { + pub verifier_identity: Digest, + pub tier: QualificationTier, +} + +/// Build the unsigned canonical receipt for one candidate from what the +/// loader and runtime observed. Every record passes the strict §7 rules +/// before it is returned; nothing is filled from expectations. +pub fn build_receipt( + report: &CandidateReport, + context: &ReceiptContext, + sequence: u64, +) -> Result<Receipt, ArtifactError> { + let b = &report.bindings; + let admitted = report.decision == Decision::Admitted; + let o = &report.outcome; + let (execution_status, exit_status) = if admitted { + match o.status { + ExecutionStatus::NotRun => (ExecutionStatusCode::NotRun, 0), + ExecutionStatus::Exited(code) => (ExecutionStatusCode::Exited, code as u32 as i32), + ExecutionStatus::Timeout => (ExecutionStatusCode::Timeout, 0), + ExecutionStatus::Fault { .. } => (ExecutionStatusCode::Fault, 0), + ExecutionStatus::BadSyscall(_) => (ExecutionStatusCode::BadSyscall, 0), + ExecutionStatus::ResourceOverrun => (ExecutionStatusCode::ResourceOverrun, 0), + } + } else { + (ExecutionStatusCode::NotRun, 0) + }; + let mut result_flags = 0; + let mut set = |on: bool, flag: u32| { + if on { + result_flags |= flag; + } + }; + set(report.reclaimed(), RESULT_RECLAIMED); + if admitted { + set(o.object_reads_ok > 0, RESULT_READ_OK); + set(o.write_denials > 0, RESULT_WRITE_DENIED); + set(o.invalid_handle_denials > 0, RESULT_FORGED_DENIED); + set( + execution_status == ExecutionStatusCode::Exited && exit_status == 0, + RESULT_CANARY_PASSED, + ); + set(b.mapped_bytes_matched, RESULT_MAPPED_BYTES_MATCH); + set(report.byte_chain, RESULT_EXECUTED_BYTES_MATCH); + set(b.wx_sealed, RESULT_WX_SEALED); + } + let (rejection_stage, rejection_reason) = if admitted { + (0, 0) + } else { + ( + report.failed_stage.map_or(0, CandidateState::stage_code), + report.error.map_or(0, LoadError::reason_code), + ) + }; + let counter = |v: u32| if admitted { v } else { 0 }; + let receipt = Receipt { + flags: 0, + decision: if admitted { + ReceiptDecision::Admitted + } else { + ReceiptDecision::Rejected + }, + tier: context.tier, + sequence, + nonce: receipt_nonce(&context.verifier_identity, sequence), + observed_time_ns: 0, + execution_status, + exit_status, + result_flags, + rejection_stage, + rejection_reason, + syscalls: counter(o.syscalls), + object_reads_ok: counter(o.object_reads_ok), + denials: counter(o.denials), + frames_reserved: u32::try_from(report.frames_reserved).unwrap_or(u32::MAX), + artifact_id: b.artifact_id, + payload_digest: b.payload_digest, + artifact_signer_fingerprint: b.artifact_signer_fingerprint, + policy_digest: b.policy_digest, + requested_capability_digest: b.requested_capability_digest, + granted_capability_digest: b.granted_capability_digest, + resource_envelope_digest: b.resource_envelope_digest, + verifier_identity: context.verifier_identity, + machine_id_digest: [0; 32], + generation: 0, + context_id: 0, + }; + validate_receipt(&receipt)?; + Ok(receipt) +} + +/// `receipt: NAME seq=N digest=HEX64 record=HEX1024` — the unsigned record +/// the host qualification harness checks, signs and verifies. +pub fn write_receipt_line( + out: &mut impl core::fmt::Write, + name: &str, + sequence: u64, + record: &[u8; RECEIPT_SIZE], +) { + let _ = write!(out, "receipt: {name} seq={sequence} digest="); + for byte in receipt_digest(record) { + let _ = write!(out, "{byte:02x}"); + } + let _ = write!(out, " record="); + for byte in record { + let _ = write!(out, "{byte:02x}"); + } + let _ = writeln!(out); +} + /// One stable report line per candidate. Formats (QEMU checks grep these): /// /// `artifact: NAME admitted id=HEX16 tier=seed0b-test exec=EXEC bytes=identified=verified=admitted=mapped=executed wx=enforced caps=N revoked=yes reclaimed=yes frames=N syscalls=N reads=N denials=N` diff --git a/crates/aienos-kernel/src/artifact_loader_tests.rs b/crates/aienos-kernel/src/artifact_loader_tests.rs index 6e25c213..06602309 100644 --- a/crates/aienos-kernel/src/artifact_loader_tests.rs +++ b/crates/aienos-kernel/src/artifact_loader_tests.rs @@ -431,6 +431,8 @@ fn outcome(status: ExecutionStatus) -> TaskOutcome { syscalls: 1, object_reads_ok: 0, denials: 0, + write_denials: 0, + invalid_handle_denials: 0, elapsed_ticks: 10, } } @@ -1200,6 +1202,8 @@ fn admitted_report(status: ExecutionStatus) -> CandidateReport { syscalls: 3, object_reads_ok: 2, denials: 1, + write_denials: 0, + invalid_handle_denials: 1, elapsed_ticks: 10, }; r.code_base = 0x80_0000_1000; @@ -1309,3 +1313,234 @@ fn sequential_candidates_reuse_resources_cleanly() { table_ids.dedup(); assert_eq!(table_ids.len(), 3, "task principals must be distinct"); } + +// --------------------------------------------------------------------------- +// Admission Receipt v0 emission +// --------------------------------------------------------------------------- + +const CTX: ReceiptContext = ReceiptContext { + verifier_identity: [0x5a; 32], + tier: QualificationTier::Seed0bQemu, +}; + +fn emitted(report: &CandidateReport, seq: u64) -> Receipt { + let receipt = build_receipt(report, &CTX, seq).expect("receipt must satisfy §7"); + let bytes = aienos_artifact::receipt::encode(&receipt); + assert!(aienos_artifact::receipt::is_unsigned(&bytes)); + assert_eq!(aienos_artifact::receipt::decode(&bytes), Ok(receipt)); + receipt +} + +#[test] +fn admitted_receipt_binds_identity_and_observed_outcome() { + let bytes = pack_signed(&spec(), &TEST_SEED); + let identified = aienos_artifact::verify::parse_and_identify(&bytes).unwrap(); + let a = anchors(); + let pol = policy(); + let mut run = Run::new(KernelMap::Blocks2M); + let mut executor = exec(|_, _| TaskOutcome { + status: ExecutionStatus::Exited(0), + syscalls: 9, + object_reads_ok: 3, + denials: 5, + write_denials: 1, + invalid_handle_denials: 3, + elapsed_ticks: 10, + }); + let report = run.candidate(&bytes, &verifier(&a), &pol, &mut executor, 21); + run.assert_clean(&report); + let r = emitted(&report, 1); + assert_eq!(r.decision, ReceiptDecision::Admitted); + assert_eq!((r.rejection_stage, r.rejection_reason), (0, 0)); + assert_eq!(r.execution_status, ExecutionStatusCode::Exited); + assert_eq!((r.syscalls, r.object_reads_ok, r.denials), (9, 3, 5)); + assert_eq!(r.frames_reserved as usize, report.frames_reserved); + assert_eq!(r.result_flags, 0xff, "every observed check passed"); + assert_eq!(&r.artifact_id, identified.artifact_id.as_bytes()); + assert_eq!(r.payload_digest, identified.payload_digest); + assert_eq!( + &r.artifact_signer_fingerprint, + identified.artifact.signer_fingerprint + ); + assert_eq!(r.policy_digest, pol.digest()); + assert_eq!( + r.requested_capability_digest, + aienos_artifact::canonical::requested_capability_digest( + identified.artifact.capability_request_bytes + ) + ); + assert_ne!(r.granted_capability_digest, [0; 32]); + assert_eq!(r.verifier_identity, CTX.verifier_identity); +} + +#[test] +fn receipt_flags_follow_observations_not_expectations() { + let bytes = pack_signed(&spec(), &TEST_SEED); + let a = anchors(); + // A task that read nothing, was denied nothing and faulted. + let mut run = Run::new(KernelMap::Block1G); + let mut executor = exec(|_, _| { + outcome(ExecutionStatus::Fault { + esr: 0x9200_0047, + far: 0, + elr: 0, + }) + }); + let report = run.candidate(&bytes, &verifier(&a), &policy(), &mut executor, 22); + let r = emitted(&report, 2); + assert_eq!(r.execution_status, ExecutionStatusCode::Fault); + for flag in [ + RESULT_READ_OK, + RESULT_WRITE_DENIED, + RESULT_FORGED_DENIED, + RESULT_CANARY_PASSED, + ] { + assert_eq!( + r.result_flags & flag, + 0, + "flag {flag:#x} set without observation" + ); + } + assert_ne!(r.result_flags & RESULT_WX_SEALED, 0); + assert_ne!(r.result_flags & RESULT_MAPPED_BYTES_MATCH, 0); + // A non-zero self-check exit never counts as a passed canary. + let mut run = Run::new(KernelMap::Block1G); + let mut executor = exec(|_, _| outcome(ExecutionStatus::Exited(0x10))); + let report = run.candidate(&bytes, &verifier(&a), &policy(), &mut executor, 23); + let r = emitted(&report, 3); + assert_eq!( + (r.exit_status, r.result_flags & RESULT_CANARY_PASSED), + (0x10, 0) + ); + // Code changed during execution: executed-bytes flag must be clear. + let mut run = Run::new(KernelMap::Pages4K); + let mut executor = exec(|ctx: TaskContext<'_>, p: &mut MockPlatform| { + let (pa, _) = effective(p, ctx.root, ctx.entry_pc).unwrap(); + p.bytes_mut(pa + (ctx.entry_pc & 0xfff), 1)[0] ^= 0xff; + outcome(ExecutionStatus::Exited(0)) + }); + let report = run.candidate(&bytes, &verifier(&a), &policy(), &mut executor, 24); + let r = emitted(&report, 4); + assert_eq!(r.result_flags & RESULT_EXECUTED_BYTES_MATCH, 0); + assert_ne!(r.result_flags & RESULT_MAPPED_BYTES_MATCH, 0); +} + +#[test] +fn rejection_receipts_record_earliest_stage_and_only_computed_fields() { + let a = anchors(); + let pol = policy(); + // Unparseable: every identity field zero, reason BadMagic at Verified. + let mut junk = pack_signed(&spec(), &TEST_SEED); + junk[0] ^= 0xff; + let (report, run) = reject_case(KernelMap::Block1G, &junk, &a, &pol, |_| {}); + run.assert_clean(&report); + let r = emitted(&report, 5); + assert_eq!(r.decision, ReceiptDecision::Rejected); + assert_eq!( + (r.rejection_stage, r.rejection_reason), + (3, ArtifactError::BadMagic as u16) + ); + assert_eq!(r.artifact_id, [0; 32]); + assert_eq!(r.payload_digest, [0; 32]); + assert_eq!(r.artifact_signer_fingerprint, [0; 32]); + assert_eq!(r.granted_capability_digest, [0; 32]); + assert_eq!(r.policy_digest, pol.digest()); + assert_eq!(r.execution_status, ExecutionStatusCode::NotRun); + assert_eq!(r.result_flags, RESULT_RECLAIMED); + assert_eq!( + (r.syscalls, r.object_reads_ok, r.denials, r.frames_reserved), + (0, 0, 0, 0) + ); + + // Bad signature: identity derived from structure, signer never trusted. + let mut tampered = pack_signed(&spec(), &TEST_SEED); + let at = payload_offset(&tampered); + tampered[at] ^= 1; + let (report, _) = reject_case(KernelMap::Block1G, &tampered, &a, &pol, |_| {}); + let r = emitted(&report, 6); + let identified = aienos_artifact::verify::parse_and_identify(&tampered).unwrap(); + assert_eq!( + (r.rejection_stage, r.rejection_reason), + (3, ArtifactError::BadSignature as u16) + ); + assert_eq!(&r.artifact_id, identified.artifact_id.as_bytes()); + assert_eq!(r.artifact_signer_fingerprint, [0; 32]); + assert_eq!(r.granted_capability_digest, [0; 32]); + + // Mapped-byte corruption: authorised (signer and grants bound), refused + // at Hashed with the loader reason, never executed. + let good = pack_signed(&spec(), &TEST_SEED); + let (report, run) = reject_case(KernelMap::Blocks2M, &good, &a, &pol, |r| { + r.platform.corrupt_after_copy = Some(2); + }); + run.assert_clean(&report); + let r = emitted(&report, 7); + assert_eq!((r.rejection_stage, r.rejection_reason), (7, 0x104)); + assert_ne!(r.artifact_signer_fingerprint, [0; 32]); + assert_ne!(r.granted_capability_digest, [0; 32]); + assert_eq!(r.result_flags, RESULT_RECLAIMED); + assert_eq!(r.execution_status, ExecutionStatusCode::NotRun); +} + +#[test] +fn stage_and_reason_codes_match_adr_0014_section_7_3() { + let stages = [ + (CandidateState::Received, 1), + (CandidateState::Staged, 2), + (CandidateState::Verified, 3), + (CandidateState::Authorized, 4), + (CandidateState::Reserved, 5), + (CandidateState::Mapped, 6), + (CandidateState::Hashed, 7), + (CandidateState::Sealed, 8), + (CandidateState::CapsInstalled, 9), + (CandidateState::Admitted, 0), + (CandidateState::Running, 0), + ]; + for (state, code) in stages { + assert_eq!(state.stage_code(), code, "{state:?}"); + } + assert_eq!( + LoadError::Artifact(ArtifactError::BadMagic).reason_code(), + 1 + ); + assert_eq!( + LoadError::Artifact(ArtifactError::RightsEscalation).reason_code(), + 19 + ); + let loader = [ + LoadError::NoFrames, + LoadError::StagingTooLarge, + LoadError::Mapping, + LoadError::MappedDigestMismatch, + LoadError::WxAudit, + LoadError::CapabilityInstall, + LoadError::SchedulerFull, + LoadError::ExecutedDigestMismatch, + LoadError::Reclaim, + LoadError::FirmwareRead, + ]; + for (i, e) in loader.iter().enumerate() { + assert_eq!(e.reason_code(), 0x101 + i as u16, "{e:?}"); + } +} + +#[test] +fn receipt_line_carries_digest_and_full_record() { + let bytes = pack_signed(&spec(), &TEST_SEED); + let (report, _) = reject_case(KernelMap::Block1G, &bytes, &anchors(), &policy(), |r| { + r.platform.corrupt_after_copy = Some(2); + }); + let record = aienos_artifact::receipt::encode(&emitted(&report, 9)); + let mut out = String::new(); + write_receipt_line(&mut out, "X.AIEN", 9, &record); + let digest: String = aienos_artifact::receipt::receipt_digest(&record) + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + let hex: String = record.iter().map(|b| format!("{b:02x}")).collect(); + assert_eq!( + out, + format!("receipt: X.AIEN seq=9 digest={digest} record={hex}\n") + ); +} diff --git a/crates/aienos-kernel/src/task_runtime.rs b/crates/aienos-kernel/src/task_runtime.rs index 60191ec0..cb838a84 100644 --- a/crates/aienos-kernel/src/task_runtime.rs +++ b/crates/aienos-kernel/src/task_runtime.rs @@ -71,9 +71,41 @@ pub struct TaskOutcome { pub syscalls: u32, pub object_reads_ok: u32, pub denials: u32, + /// Denied `SYS_OBJECT_WRITE` calls (subset of `denials`). + pub write_denials: u32, + /// Denials because the handle did not resolve in the task's table: + /// forged, never-issued, stale, or zero (subset of `denials`). + pub invalid_handle_denials: u32, pub elapsed_ticks: u64, } +impl TaskOutcome { + pub const fn not_run() -> Self { + Self { + status: ExecutionStatus::NotRun, + syscalls: 0, + object_reads_ok: 0, + denials: 0, + write_denials: 0, + invalid_handle_denials: 0, + elapsed_ticks: 0, + } + } +} + +/// Why one object access was refused. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Denial { + /// The handle does not resolve in this task's capability table. + InvalidHandle, + /// The handle resolves but lacks the right, or names another resource. + Authority, + /// Offset, alignment, grant range, or object size. + Bounds, + /// The grant's operation or byte budget is spent. + Budget, +} + #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct TaskBudget { pub cpu_ticks: u64, @@ -139,6 +171,8 @@ pub struct RuntimeState { pub syscalls: u32, pub object_reads_ok: u32, pub denials: u32, + pub write_denials: u32, + pub invalid_handle_denials: u32, pub usage: [GrantUsage; TASK_CAPABILITIES], pub object: [u64; 4], } @@ -151,6 +185,8 @@ impl RuntimeState { syscalls: 0, object_reads_ok: 0, denials: 0, + write_denials: 0, + invalid_handle_denials: 0, usage: [GrantUsage { operations: 0, bytes: 0, @@ -188,28 +224,34 @@ impl RuntimeState { SYS_EXIT => SyscallAction::Terminate(ExecutionStatus::Exited(args[0])), SYS_OBJECT_READ => { match self.object_access(caps, grants, args[0], Rights::READ, args[1]) { - Some(word) => { + Ok(word) => { self.object_reads_ok = self.object_reads_ok.saturating_add(1); SyscallAction::Return(self.object[word]) } - None => self.deny(), + Err(why) => self.deny(why, false), } } SYS_OBJECT_WRITE => { match self.object_access(caps, grants, args[0], Rights::WRITE, args[1]) { - Some(word) => { + Ok(word) => { self.object[word] = args[2]; SyscallAction::Return(0) } - None => self.deny(), + Err(why) => self.deny(why, true), } } other => SyscallAction::Terminate(ExecutionStatus::BadSyscall(other)), } } - fn deny(&mut self) -> SyscallAction { + fn deny(&mut self, why: Denial, write: bool) -> SyscallAction { self.denials = self.denials.saturating_add(1); + if write { + self.write_denials = self.write_denials.saturating_add(1); + } + if why == Denial::InvalidHandle { + self.invalid_handle_denials = self.invalid_handle_denials.saturating_add(1); + } SyscallAction::Return(SYSCALL_DENIED) } @@ -223,36 +265,45 @@ impl RuntimeState { raw_handle: u64, right: Rights, offset: u64, - ) -> Option<usize> { - let handle = Handle::from_raw(raw_handle).ok()?; - let index = caps.lookup(handle, right).ok()? as usize; - let grant = grants.get(index).copied().flatten()?; + ) -> Result<usize, Denial> { + let handle = Handle::from_raw(raw_handle).map_err(|_| Denial::InvalidHandle)?; + let index = match caps.lookup(handle, right) { + Ok(index) => index as usize, + Err(crate::caps::CapError::MissingRights) => return Err(Denial::Authority), + Err(_) => return Err(Denial::InvalidHandle), + }; + let grant = grants + .get(index) + .copied() + .flatten() + .ok_or(Denial::Authority)?; if grant.resource.kind() != ResourceKind::Object || grant.resource.id() != SEED_OBJECT_ID || !grant.rights.contains(right) { - return None; + return Err(Denial::Authority); } - let end = offset.checked_add(8)?; + let end = offset.checked_add(8).ok_or(Denial::Bounds)?; let grant_end = grant .bounds .byte_offset - .checked_add(grant.bounds.byte_length)?; + .checked_add(grant.bounds.byte_length) + .ok_or(Denial::Bounds)?; if offset & 7 != 0 || offset < grant.bounds.byte_offset || end > grant_end || end > SEED_OBJECT_BYTES { - return None; + return Err(Denial::Bounds); } - let usage = self.usage.get_mut(index)?; - let bytes = usage.bytes.checked_add(8)?; + let usage = self.usage.get_mut(index).ok_or(Denial::Authority)?; + let bytes = usage.bytes.checked_add(8).ok_or(Denial::Budget)?; if usage.operations >= grant.bounds.max_operations || bytes > grant.bounds.max_bytes { - return None; + return Err(Denial::Budget); } usage.operations += 1; usage.bytes = bytes; - Some((offset / 8) as usize) + Ok((offset / 8) as usize) } fn outcome(&self, status: ExecutionStatus, now: u64) -> TaskOutcome { @@ -261,6 +312,8 @@ impl RuntimeState { syscalls: self.syscalls, object_reads_ok: self.object_reads_ok, denials: self.denials, + write_denials: self.write_denials, + invalid_handle_denials: self.invalid_handle_denials, elapsed_ticks: elapsed_since(self.start, now), } } @@ -385,13 +438,7 @@ pub unsafe fn run(task: TaskContext<'_>, kernel_root: usize) -> TaskOutcome { #[cfg(not(target_arch = "aarch64"))] { let _ = (task, kernel_root); - TaskOutcome { - status: ExecutionStatus::NotRun, - syscalls: 0, - object_reads_ok: 0, - denials: 0, - elapsed_ticks: 0, - } + TaskOutcome::not_run() } } @@ -430,13 +477,7 @@ unsafe fn run_inner(task: TaskContext<'_>, kernel_root: usize) -> TaskOutcome { let active = unsafe { (*core::ptr::addr_of_mut!(ACTIVE)).take() }; match active { Some(active) => active.state.outcome(active.status, now), - None => TaskOutcome { - status: ExecutionStatus::NotRun, - syscalls: 0, - object_reads_ok: 0, - denials: 0, - elapsed_ticks: 0, - }, + None => TaskOutcome::not_run(), } } @@ -597,6 +638,62 @@ mod tests { (caps, [Some(g)], handle.to_raw()) } + #[test] + fn denials_are_classified_from_observed_lookups() { + let (caps, grants, h) = setup(grant(Rights::READ, 0, 32, 8, 64)); + let budget = TaskBudget { + syscalls: 32, + ..BUDGET + }; + let mut st = RuntimeState::new(budget, 0); + let call = |st: &mut RuntimeState, number: u64, args: [u64; 3]| { + st.syscall(&caps, &grants, 0, number, args, 1) + }; + // Authorized READ. + assert_eq!( + call(&mut st, SYS_OBJECT_READ, [h, 0, 0]), + SyscallAction::Return(SEED_OBJECT_WORDS[0]) + ); + // WRITE through a READ-only handle: denied for authority, not handle. + assert_eq!( + call(&mut st, SYS_OBJECT_WRITE, [h, 0, 7]), + SyscallAction::Return(SYSCALL_DENIED) + ); + assert_eq!((st.write_denials, st.invalid_handle_denials), (1, 0)); + assert_eq!(st.object, SEED_OBJECT_WORDS, "denied write changed nothing"); + // Forged generation, never-issued slot, zero handle: invalid handles. + for forged in [h ^ (1 << 32), (1u64 << 32) | 1, 0] { + assert_eq!( + call(&mut st, SYS_OBJECT_READ, [forged, 0, 0]), + SyscallAction::Return(SYSCALL_DENIED) + ); + } + assert_eq!(st.invalid_handle_denials, 3); + // Out of the grant's range: a bounds denial, not an invalid handle. + assert_eq!( + call(&mut st, SYS_OBJECT_READ, [h, 32, 0]), + SyscallAction::Return(SYSCALL_DENIED) + ); + assert_eq!( + ( + st.denials, + st.write_denials, + st.invalid_handle_denials, + st.object_reads_ok + ), + (5, 1, 3, 1) + ); + let outcome = st.outcome(ExecutionStatus::Exited(0), 5); + assert_eq!( + ( + outcome.denials, + outcome.write_denials, + outcome.invalid_handle_denials + ), + (5, 1, 3) + ); + } + fn read( state: &mut RuntimeState, caps: &CapTable<TASK_CAPABILITIES>, diff --git a/scripts/qemu_artifact_test.sh b/scripts/qemu_artifact_test.sh index 57d0c666..863cef84 100755 --- a/scripts/qemu_artifact_test.sh +++ b/scripts/qemu_artifact_test.sh @@ -10,11 +10,17 @@ # P25WX admitted, killed by a W^X permission fault on its code page # P25SPIN admitted, killed when its admitted time budget runs out # P25TAMP one payload byte flipped after signing: rejected BadSignature +# P26SEED first SEED-0B capability artifact: READ granted and used, +# WRITE through the READ handle denied, forged/never-issued/ +# zero handles denied, read past the grant denied, exits 0 # 2. ordinary build (empty production trust set): every candidate rejected # UntrustedSigner. Production trust fails closed. # # Every candidate must end with reclaimed=yes (all frames returned, no live -# capabilities). No physical hardware is touched. +# capabilities). Every candidate also emits an unsigned Admission Receipt v0 +# on the console; the host checks it binds the artifact it supplied, signs +# it with the TEST ONLY SEED-0B receipt key, and verifies the signed record. +# No physical hardware is touched. # # Needs qemu-system-aarch64 and AAVMF (Ubuntu: qemu-system-arm qemu-efi-aarch64). set -euo pipefail @@ -28,6 +34,7 @@ command -v qemu-system-aarch64 >/dev/null || { echo "qemu-system-aarch64 not ins [[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; exit 2; } fixtures="crates/aienos-artifact-tool/fixtures/p2_5" +seed_fixtures="crates/aienos-artifact-tool/fixtures/p2_6" work="$(mktemp -d)" trap 'rm -rf "${work}"' EXIT failed=0 @@ -47,6 +54,12 @@ if command -v "${as_bin}" >/dev/null; then fail "${probe} code.bin differs from probe.S" fi done + "${seed_fixtures}/assemble.sh" "${work}/asm" + if cmp -s "${work}/asm/p26seed/code.bin" "${seed_fixtures}/p26seed/code.bin"; then + pass "p26seed code.bin is exactly what probe.S assembles to" + else + fail "p26seed code.bin differs from probe.S" + fi else echo "NOTE no AArch64 assembler; using committed probe bytes unchecked" fi @@ -56,6 +69,7 @@ cargo build --quiet -p aienos-artifact-tool --features seed0b-test-signing tool="target/debug/aienos-artifact-tool" mkdir -p "${work}/esp/EFI/BOOT" "${work}/esp/EFI/AIENOS/ARTIFACTS" "${fixtures}/pack.sh" "${tool}" "${work}/esp/EFI/AIENOS/ARTIFACTS" +"${seed_fixtures}/pack.sh" "${tool}" "${work}/esp/EFI/AIENOS/ARTIFACTS" mv "${work}/esp/EFI/AIENOS/ARTIFACTS/ids.txt" "${work}/ids.txt" touch "${work}/esp/EFI/AIENOS/BOOTREPORT.TXT" id_prefix() { # name -> first 16 hex digits of its ArtifactId @@ -102,9 +116,50 @@ common_checks() { # serial 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" "firmware read four artifact candidates" "artifact_candidates: 4$" + check "$1" "firmware read five artifact candidates" "artifact_candidates: 5$" check "$1" "final report reached the console" "report_kind: final" if has "$1" "report_kind: (panic|fault)"; then fail "panic or fault reported"; 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 +} + +# receipt_check SERIAL NAME PATTERN: the kernel's unsigned receipt for NAME +# must decode, bind the supplied artifact, match PATTERN, carry the digest +# the host recomputes, and sign/verify with the TEST ONLY receipt key. +receipt_check() { + 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}") + "${tool}" receipt from-hex "${record}" "${work}/${name}.receipt" >/dev/null + if ! out=$("${tool}" receipt check "${work}/${name}.receipt" "${work}/esp/EFI/AIENOS/ARTIFACTS/${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 + "${tool}" receipt sign-test "${work}/${name}.receipt" "${work}/${name}.receipt.signed" >/dev/null + if "${tool}" receipt verify "${work}/${name}.receipt.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 } # ---- boot 1: qualification build -------------------------------------------- @@ -122,8 +177,16 @@ check "${qual}" "P25SPIN admitted then killed at its time budget, reclaimed" \ "artifact: P25SPIN\.AIEN admitted id=$(id_prefix P25SPIN.AIEN) tier=seed0b-test exec=timeout .*wx=enforced caps=0 revoked=yes reclaimed=yes frames=[0-9]+ syscalls=0 reads=0 denials=0$" check "${qual}" "P25TAMP (payload byte flipped after signing) rejected BadSignature, reclaimed" \ "artifact: P25TAMP\.AIEN rejected stage=(received|staged|verified) reason=BadSignature reclaimed=yes" -check "${qual}" "final report summarises three admitted, one rejected" \ - "artifacts: candidates=4 admitted=3 rejected=1" +check "${qual}" "P26SEED (first SEED-0B capability artifact) read through its grant, WRITE and forged authority denied, exit 0, reclaimed" \ + "artifact: P26SEED\.AIEN admitted id=$(id_prefix P26SEED.AIEN) tier=seed0b-test exec=exited:0x0 bytes=identified=verified=admitted=mapped=executed wx=enforced caps=1 revoked=yes reclaimed=yes frames=[0-9]+ syscalls=9 reads=3 denials=5$" +check "${qual}" "final report summarises four admitted, one rejected" \ + "artifacts: candidates=5 admitted=4 rejected=1" +check "${qual}" "receipts carry the SEED-0B-QEMU tier" "^artifact_receipt_tier: SEED-0B-QEMU$" +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$" +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$" # ---- boot 2: ordinary build, empty production trust ------------------------- prod="${work}/production.txt" @@ -132,19 +195,20 @@ common_checks "${prod}" if has "${prod}" "seed0b-test qualification build"; then fail "ordinary build must not carry the qualification label" fi -for name in P25EXEC P25WX P25SPIN P25TAMP; do +for name in P25EXEC P25WX P25SPIN P25TAMP P26SEED; do reason=UntrustedSigner # The tampered file may fail its signature check before or after signer # lookup; either way it must be rejected, never run. [[ "${name}" != P25TAMP ]] || reason="(UntrustedSigner|BadSignature)" check "${prod}" "ordinary build rejects ${name} (${reason}), reclaimed" \ "artifact: ${name}\.AIEN rejected stage=[a-z]+ reason=${reason} reclaimed=yes" + receipt_check "${prod}" "${name}.AIEN" "decision=Rejected .* stage=3 reason=0x11 status=NotRun .* flags=0x04$" done if has "${prod}" "artifact: [A-Z0-9]+\.AIEN admitted"; then fail "ordinary build admitted an artifact" fi check "${prod}" "final report summarises zero admitted" \ - "artifacts: candidates=4 admitted=0 rejected=4" + "artifacts: candidates=5 admitted=0 rejected=5" if [[ -n "${AIENOS_LOG_DIR:-}" ]]; then cp "${qual}" "${AIENOS_LOG_DIR}/qemu_artifact_qualification_serial.log"