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#122 (code only)
Fetch it
curl -fsSL https://interplane.io/drakestapleton/aienux/patches/19c709630ad5e6da.bundle -o 19c709630ad5e6da.bundle git fetch 19c709630ad5e6da.bundle refs/pull/122/head
Provenance
github-import 1
aien-dev/aienux
122
504141f2916ca72fb0825ab1dfa39cea61e99f4d
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":122,"url":"https://github.com/aien-dev/aienux/pull/122","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:35:46Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/Cargo.lock b/Cargo.lock index 9631fc5b..f120d17c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -93,6 +93,7 @@ dependencies = [ "aienos-accel", "aienos-artifact", "aienos-crypto", + "ed25519-dalek", ] [[package]] diff --git a/ROADMAP.md b/ROADMAP.md index b23ec07a..c44ce6c1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -102,9 +102,13 @@ can be built and tested in QEMU on any machine. Good places to start: small, self-contained changes. - [`help wanted`](https://github.com/aien-dev/aienos/labels/help%20wanted): kernel, boot, evidence and tooling work that is ready for a contributor. -- Phase 2 executable identity (Binary Artifact v0, admission receipts, - SEED-0B loader) is the next large body of work, and the QEMU parts run - in the emulator. M3 kernel isolation is done; see the M3 row above. +- Phase 2 executable identity: Binary Artifact v0, Ed25519 trust, admission + policy and the P2-5 loader (signed artifact -> exact-byte W^X EL0 task, + full rollback) are done in QEMU; see + [evidence/p2_5_artifact_loader_qemu_2026-09-25.md](evidence/p2_5_artifact_loader_qemu_2026-09-25.md). + Next: admission receipts, the first SEED-0B capability artifact (P2-6), + and the hostile-input matrix (P2-7). M3 kernel isolation is done; see the + M3 row above. Work labelled [`needs-hardware`](https://github.com/aien-dev/aienos/labels/needs-hardware) runs on Machine 1; maintainers execute it and publish the evidence. Read diff --git a/crates/aienos-artifact-tool/fixtures/p2_5/assemble.sh b/crates/aienos-artifact-tool/fixtures/p2_5/assemble.sh new file mode 100755 index 00000000..632c2887 --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_5/assemble.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Reassemble every P2-5 probe from probe.S into OUT_DIR/<probe>/code.bin. +# The committed code.bin files are the qualification inputs; this script +# only exists to prove they are exactly what probe.S assembles to. +# Needs an AArch64 GNU `as` and `objcopy` (native on the Spark). +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 p25exec p25wx p25spin; do + mkdir -p "${out}/${probe}" + "${as_bin}" -o "${out}/${probe}/probe.o" "${here}/${probe}/probe.S" + # A probe must be fully resolved: no relocations, so the bytes the kernel + # authenticates are the bytes that execute, with no loader fix-ups. + 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_5/p25exec/code.bin b/crates/aienos-artifact-tool/fixtures/p2_5/p25exec/code.bin new file mode 100644 index 00000000..d444223d Binary files /dev/null and b/crates/aienos-artifact-tool/fixtures/p2_5/p25exec/code.bin differ diff --git a/crates/aienos-artifact-tool/fixtures/p2_5/p25exec/data.bin b/crates/aienos-artifact-tool/fixtures/p2_5/p25exec/data.bin new file mode 100644 index 00000000..e35c2043 Binary files /dev/null and b/crates/aienos-artifact-tool/fixtures/p2_5/p25exec/data.bin differ diff --git a/crates/aienos-artifact-tool/fixtures/p2_5/p25exec/manifest.json b/crates/aienos-artifact-tool/fixtures/p2_5/p25exec/manifest.json new file mode 100644 index 00000000..f2a6992e --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_5/p25exec/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_5/p25exec/probe.S b/crates/aienos-artifact-tool/fixtures/p2_5/p25exec/probe.S new file mode 100644 index 00000000..2739dc93 --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_5/p25exec/probe.S @@ -0,0 +1,83 @@ +// P2-5 execution probe: AArch64 EL0, position independent, no relocations. +// Entry (task_runtime ABI): x0 = handle array VA, x1 = handle count, +// x2 = data base VA, x3 = data memory length. All other registers zero. +// Exit code 0 means every check passed; otherwise each set bit names one +// failed check: +// 0x01 handle count != 1 0x02 data word mismatch +// 0x04 data write/readback 0x08 stack write/readback +// 0x10 object read via handle 0x20 forged handle 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 + + // 0x01: exactly one granted handle + cmp x20, #1 + b.eq 1f + orr x22, x22, #0x01 +1: + // 0x02: first data word is "CEXE5-2P" = 0x50322d3545584543 + ldr x9, [x21] + movz x10, #0x4543 + movk x10, #0x4558, lsl #16 + movk x10, #0x2d35, lsl #32 + movk x10, #0x5032, lsl #48 + cmp x9, x10 + b.eq 2f + orr x22, x22, #0x02 +2: + // 0x04: data is writable + movz x11, #0xbeef + movk x11, #0xdead, lsl #16 + str x11, [x21, #8] + ldr x12, [x21, #8] + cmp x11, x12 + b.eq 3f + orr x22, x22, #0x04 +3: + // 0x08: stack is writable + sub sp, sp, #16 + str x11, [sp] + ldr x12, [sp] + add sp, sp, #16 + cmp x11, x12 + b.eq 4f + orr x22, x22, #0x08 +4: + // No handle: both capability checks fail without touching the array. + cbnz x20, 5f + orr x22, x22, #0x30 + b 7f +5: + // 0x10: SYS_OBJECT_READ(handle[0], 0) == SEED_OBJECT_WORDS[0] + ldr x23, [x19] + mov x0, x23 + mov x1, #0 + mov x8, #6 + svc #0 + movz x10, #0x0001 + movk x10, #0x5eed, lsl #32 + movk x10, #0xa1e0, lsl #48 + cmp x0, x10 + b.eq 6f + orr x22, x22, #0x10 +6: + // 0x20: a forged generation must be denied (SYSCALL_DENIED = u64::MAX) + 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, #0x20 +7: + // SYS_EXIT(bitmask) + mov x0, x22 + mov x8, #2 + svc #0 +8: b 8b diff --git a/crates/aienos-artifact-tool/fixtures/p2_5/p25spin/code.bin b/crates/aienos-artifact-tool/fixtures/p2_5/p25spin/code.bin new file mode 100644 index 00000000..c917f76c Binary files /dev/null and b/crates/aienos-artifact-tool/fixtures/p2_5/p25spin/code.bin differ diff --git a/crates/aienos-artifact-tool/fixtures/p2_5/p25spin/data.bin b/crates/aienos-artifact-tool/fixtures/p2_5/p25spin/data.bin new file mode 100644 index 00000000..a92509ec --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_5/p25spin/data.bin @@ -0,0 +1 @@ +P25SPIND \ No newline at end of file diff --git a/crates/aienos-artifact-tool/fixtures/p2_5/p25spin/manifest.json b/crates/aienos-artifact-tool/fixtures/p2_5/p25spin/manifest.json new file mode 100644 index 00000000..bdd45f64 --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_5/p25spin/manifest.json @@ -0,0 +1,15 @@ +{ + "entry_offset": 0, + "capabilities": [], + "resources": { + "code_pages": 1, + "data_pages": 1, + "stack_pages": 1, + "max_capabilities": 0, + "ipc_messages": 0, + "ipc_bytes": 0, + "cpu_ticks": 6250000, + "elapsed_ticks": 6250000, + "syscall_count": 1 + } +} diff --git a/crates/aienos-artifact-tool/fixtures/p2_5/p25spin/probe.S b/crates/aienos-artifact-tool/fixtures/p2_5/p25spin/probe.S new file mode 100644 index 00000000..05fa911c --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_5/p25spin/probe.S @@ -0,0 +1,6 @@ +// P2-5 runaway probe: never yields and never makes a syscall. Only the +// kernel's admitted elapsed/CPU budget can end it (timer IRQ from EL0). + .text + .global _start +_start: +0: b 0b diff --git a/crates/aienos-artifact-tool/fixtures/p2_5/p25wx/code.bin b/crates/aienos-artifact-tool/fixtures/p2_5/p25wx/code.bin new file mode 100644 index 00000000..1e1446bb Binary files /dev/null and b/crates/aienos-artifact-tool/fixtures/p2_5/p25wx/code.bin differ diff --git a/crates/aienos-artifact-tool/fixtures/p2_5/p25wx/data.bin b/crates/aienos-artifact-tool/fixtures/p2_5/p25wx/data.bin new file mode 100644 index 00000000..b090c553 --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_5/p25wx/data.bin @@ -0,0 +1 @@ +P25WXDAT \ No newline at end of file diff --git a/crates/aienos-artifact-tool/fixtures/p2_5/p25wx/manifest.json b/crates/aienos-artifact-tool/fixtures/p2_5/p25wx/manifest.json new file mode 100644 index 00000000..af3633c7 --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_5/p25wx/manifest.json @@ -0,0 +1,15 @@ +{ + "entry_offset": 0, + "capabilities": [], + "resources": { + "code_pages": 1, + "data_pages": 1, + "stack_pages": 1, + "max_capabilities": 0, + "ipc_messages": 0, + "ipc_bytes": 0, + "cpu_ticks": 100000000, + "elapsed_ticks": 100000000, + "syscall_count": 4 + } +} diff --git a/crates/aienos-artifact-tool/fixtures/p2_5/p25wx/probe.S b/crates/aienos-artifact-tool/fixtures/p2_5/p25wx/probe.S new file mode 100644 index 00000000..82dbd425 --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_5/p25wx/probe.S @@ -0,0 +1,12 @@ +// P2-5 W^X probe: stores to its own code page. Code is mapped EL0 RX, so +// the store must take a permission fault and the kernel must terminate and +// reclaim the task. Reaching SYS_EXIT(0x57) would mean W^X was violated. + .text + .global _start +_start: + adr x9, 0f +0: str x9, [x9] + mov x0, #0x57 + mov x8, #2 + svc #0 +1: b 1b diff --git a/crates/aienos-artifact-tool/fixtures/p2_5/pack.sh b/crates/aienos-artifact-tool/fixtures/p2_5/pack.sh new file mode 100755 index 00000000..2510bfb5 --- /dev/null +++ b/crates/aienos-artifact-tool/fixtures/p2_5/pack.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Pack and sign the P2-5 probes with the TEST ONLY SEED-0B identity into +# OUT_DIR as P25EXEC.AIEN, P25WX.AIEN, P25SPIN.AIEN, and P25TAMP.AIEN +# (P25EXEC with one payload byte flipped after signing). Also writes +# OUT_DIR/ids.txt: "NAME ARTIFACT_ID" per signed probe. +# +# 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}" +: >"${out}/ids.txt" + +pack_one() { # probe, output name + local probe="$1" name="$2" + "${tool}" pack "${here}/${probe}/manifest.json" "${here}/${probe}/code.bin" \ + "${here}/${probe}/data.bin" "${out}/${probe}.unsigned.aien" >/dev/null + "${tool}" sign "${out}/${probe}.unsigned.aien" "${out}/${name}" >/dev/null + rm -f "${out}/${probe}.unsigned.aien" + "${tool}" verify "${out}/${name}" >/dev/null + echo "${name} $("${tool}" id "${out}/${name}")" >>"${out}/ids.txt" +} + +pack_one p25exec P25EXEC.AIEN +pack_one p25wx P25WX.AIEN +pack_one p25spin P25SPIN.AIEN + +# Tamper: flip the low bit of the first payload byte (first code byte) of +# the signed P25EXEC. Its ArtifactId changes, so the signature must fail. +cp "${out}/P25EXEC.AIEN" "${out}/P25TAMP.AIEN" +payload_offset=$(od -An -tu4 -j56 -N4 "${out}/P25TAMP.AIEN" | tr -d ' ') +byte=$(od -An -tu1 -j"${payload_offset}" -N1 "${out}/P25TAMP.AIEN" | tr -d ' ') +printf "$(printf '\\%03o' $((byte ^ 1)))" | + dd of="${out}/P25TAMP.AIEN" bs=1 seek="${payload_offset}" conv=notrunc status=none +if "${tool}" verify "${out}/P25TAMP.AIEN" >/dev/null 2>&1; then + echo "FAIL tampered probe still verifies" >&2 + exit 1 +fi +if cmp -s "${out}/P25EXEC.AIEN" "${out}/P25TAMP.AIEN"; then + echo "FAIL tampering did not change the file" >&2 + exit 1 +fi diff --git a/crates/aienos-boot/Cargo.toml b/crates/aienos-boot/Cargo.toml index bb08f0dc..7ad13d94 100644 --- a/crates/aienos-boot/Cargo.toml +++ b/crates/aienos-boot/Cargo.toml @@ -18,6 +18,11 @@ handoff = ["uefi-base", "dep:aienos-kernel", "dep:aienos-accel", "uefi/alloc"] # SEED-0A candidate: polled USB keyboard after firmware exit (ADR 0012). # Only the QEMU keyboard test enables it; hardware staging never does. usb-keyboard = ["handoff"] +# SEED-0B qualification build (ADR 0014 §6): the kernel trusts the public, +# TEST ONLY RFC 8032 qualification key in addition to the (empty) production +# set, and every report says so. Without it, every artifact candidate is +# rejected with UntrustedSigner. scripts/qemu_artifact_test.sh enables it. +seed0b-qualification = ["handoff", "aienos-kernel/seed0b-test-anchor"] # Marks an image built for Machine 1 (native hardware) staging. # scripts/stage_one_time_boot.sh builds with it. It adds no code; it exists so # unsafe debug features refuse to compile into a hardware image. diff --git a/crates/aienos-boot/src/handoff.rs b/crates/aienos-boot/src/handoff.rs index 0fe929ff..320ac312 100644 --- a/crates/aienos-boot/src/handoff.rs +++ b/crates/aienos-boot/src/handoff.rs @@ -1100,6 +1100,218 @@ fn save_report_file(text: &str) -> uefi::Result { file.flush() } +/// Most signed-artifact candidates firmware reads from `\EFI\AIENOS\ARTIFACTS`. +const MAX_ARTIFACT_CANDIDATES: usize = 8; +/// Largest candidate firmware will read. Bigger files are refused unread. +const MAX_ARTIFACT_FILE_BYTES: u64 = 640 * 1024; +const ARTIFACT_NAME_BYTES: usize = 32; + +/// One candidate file: a name plus the firmware-allocated bytes holding it. +/// Firmware is only a byte provider (ADR 0014 §1); it never parses or judges +/// the contents. The kernel copies these bytes to staging before parsing. +#[derive(Clone, Copy)] +struct ArtifactCandidate { + name: [u8; ARTIFACT_NAME_BYTES], + name_len: usize, + size: u64, + /// Physical (identity) address of the LOADER_DATA copy; 0 when unread. + base: usize, + len: usize, +} + +impl ArtifactCandidate { + const EMPTY: Self = Self { + name: [0; ARTIFACT_NAME_BYTES], + name_len: 0, + size: 0, + base: 0, + len: 0, + }; + + fn name(&self) -> &str { + core::str::from_utf8(&self.name[..self.name_len]).unwrap_or("?") + } + + fn oversize(&self) -> bool { + self.size > MAX_ARTIFACT_FILE_BYTES + } + + /// The bytes firmware read, or `None` if the file was refused or failed. + fn bytes(&self) -> Option<&'static [u8]> { + (self.base != 0 && self.len as u64 == self.size) + .then(|| unsafe { core::slice::from_raw_parts(self.base as *const u8, self.len) }) + } +} + +struct ArtifactCandidates { + entries: [ArtifactCandidate; MAX_ARTIFACT_CANDIDATES], + count: usize, + /// `.AIEN` files beyond the bound, not read. + ignored: usize, +} + +/// ASCII name of a directory entry, if printable and within the bound. +fn artifact_name(name: &CStr16) -> Option<([u8; ARTIFACT_NAME_BYTES], usize)> { + let mut out = [0u8; ARTIFACT_NAME_BYTES]; + let mut len = 0; + for c in name.iter() { + let unit = u16::from(*c); + if !(0x21..=0x7e).contains(&unit) || len == ARTIFACT_NAME_BYTES { + return None; + } + out[len] = unit as u8; + len += 1; + } + let suffix = b".aien"; + (len > suffix.len() && out[len - suffix.len()..len].eq_ignore_ascii_case(suffix)) + .then_some((out, len)) +} + +/// Read every `.AIEN` file in `\EFI\AIENOS\ARTIFACTS` (at most eight, sorted +/// by name bytes) into its own LOADER_DATA pages before firmware exit. A +/// missing directory means no candidates. Must run while boot services live. +fn read_artifact_candidates() -> ArtifactCandidates { + let mut out = ArtifactCandidates { + entries: [ArtifactCandidate::EMPTY; MAX_ARTIFACT_CANDIDATES], + count: 0, + ignored: 0, + }; + let Ok(mut fs) = uefi::boot::get_image_file_system(uefi::boot::image_handle()) else { + return out; + }; + let Ok(mut root) = fs.open_volume() else { + return out; + }; + let Some(mut dir) = root + .open( + cstr16!("\\EFI\\AIENOS\\ARTIFACTS"), + FileMode::Read, + FileAttribute::empty(), + ) + .ok() + .and_then(|handle| handle.into_directory()) + else { + return out; + }; + while let Ok(Some(info)) = dir.read_entry_boxed() { + if info.is_directory() { + continue; + } + let Some((name, name_len)) = artifact_name(info.file_name()) else { + continue; + }; + let entry = ArtifactCandidate { + name, + name_len, + size: info.file_size(), + ..ArtifactCandidate::EMPTY + }; + // Keep the eight smallest names in sorted order. + let key = &entry.name[..entry.name_len]; + let at = out.entries[..out.count] + .iter() + .position(|e| key < &e.name[..e.name_len]) + .unwrap_or(out.count); + if at == MAX_ARTIFACT_CANDIDATES { + out.ignored += 1; + continue; + } + if out.count == MAX_ARTIFACT_CANDIDATES { + out.ignored += 1; + } else { + out.count += 1; + } + for index in (at + 1..out.count).rev() { + out.entries[index] = out.entries[index - 1]; + } + out.entries[at] = entry; + } + for entry in out.entries[..out.count].iter_mut() { + if entry.oversize() || entry.size == 0 { + continue; + } + let Ok(name) = core::str::from_utf8(&entry.name[..entry.name_len]) else { + continue; + }; + let mut wide = [0u16; ARTIFACT_NAME_BYTES + 1]; + let Ok(path) = CStr16::from_str_with_buf(name, &mut wide) else { + continue; + }; + let Some(mut file) = dir + .open(path, FileMode::Read, FileAttribute::empty()) + .ok() + .and_then(|handle| handle.into_regular_file()) + else { + continue; + }; + let size = entry.size as usize; + let Ok(pages) = uefi::boot::allocate_pages( + uefi::boot::AllocateType::AnyPages, + MemoryType::LOADER_DATA, + size.div_ceil(4096), + ) else { + continue; + }; + let buffer = unsafe { core::slice::from_raw_parts_mut(pages.as_ptr(), size) }; + let mut read = 0; + while read < size { + match file.read(&mut buffer[read..]) { + Ok(0) | Err(_) => break, + Ok(n) => read += n, + } + } + entry.base = pages.as_ptr() as usize; + entry.len = read; + } + 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. +fn run_artifact_candidates(candidates: &ArtifactCandidates, kernel_root: usize) -> (usize, usize) { + let mut record = Report::new(); + header(&mut record, "artifacts"); + #[cfg(feature = "seed0b-qualification")] + let _ = writeln!( + record, + "artifact_trust: seed0b-test qualification build — TEST ONLY" + ); + let _ = writeln!(record, "artifact_candidates: {}", candidates.count); + 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 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, + } + aienos_kernel::artifact_loader::write_candidate_line(&mut record, name, &result); + } + if record.truncated() { + let _ = writeln!(record, "truncated: yes"); + } + send_to_console(record.as_str()); + (admitted, rejected) +} + fn wait_seconds(seconds: u64) { let frequency_hz = FREQUENCY_HZ.load(Ordering::SeqCst); let start = counter_ticks(); @@ -1300,6 +1512,9 @@ fn main() -> Status { .expect("post-exit heap allocation failed") .as_ptr() as usize; POST_EXIT_HEAP.store(post_exit_heap as u64, Ordering::Release); + // Candidate artifact bytes must be read while boot services still live; + // they are judged only by the kernel after firmware exit. + let artifact_candidates = read_artifact_candidates(); #[cfg(feature = "usb-keyboard")] let xhci = usb_keyboard::find_xhci(); @@ -1349,6 +1564,16 @@ fn main() -> Status { let _ = writeln!(pre, "framebuffer: unavailable"); } } + let _ = writeln!( + pre, + "artifact_candidates: {}{}", + artifact_candidates.count, + if artifact_candidates.ignored == 0 { + "" + } else { + " (more ignored)" + } + ); let _ = writeln!(pre, "exiting firmware boot services"); uefi::println!("{}", pre.as_str()); let pre_file = save_report_file(pre.as_str()).map_err(|e| e.status()); @@ -1593,6 +1818,20 @@ fn main() -> Status { "accepted" }, ); + // P2-5: every firmware-provided candidate goes through the kernel's one + // admission path. The per-candidate lines are their own record so they + // never push the bounded final report past its NVRAM size. + let (admitted, rejected) = run_artifact_candidates(&artifact_candidates, kernel_root); + #[cfg(feature = "seed0b-qualification")] + let _ = writeln!( + report, + "artifact_trust: seed0b-test qualification build — TEST ONLY" + ); + let _ = writeln!( + report, + "artifacts: candidates={} admitted={admitted} rejected={rejected}", + artifact_candidates.count + ); let _ = writeln!( report, "runtime_code: {}", diff --git a/crates/aienos-kernel/Cargo.toml b/crates/aienos-kernel/Cargo.toml index 5e4667cb..c19a7d07 100644 --- a/crates/aienos-kernel/Cargo.toml +++ b/crates/aienos-kernel/Cargo.toml @@ -16,3 +16,6 @@ seed0b-test-anchor = ["aienos-artifact/seed0b-test-anchor"] aienos-accel = { path = "../aienos-accel" } aienos-artifact = { path = "../aienos-artifact" } aienos-crypto = { path = "../aienos-crypto" } + +[dev-dependencies] +ed25519-dalek = { version = "=2.2.0", default-features = false, features = ["fast"] } diff --git a/crates/aienos-kernel/src/artifact_loader.rs b/crates/aienos-kernel/src/artifact_loader.rs new file mode 100644 index 00000000..dc27c5e1 --- /dev/null +++ b/crates/aienos-kernel/src/artifact_loader.rs @@ -0,0 +1,1360 @@ +//! Binary Artifact v0 loader: the only path from authenticated artifact bytes +//! to a runnable EL0 task (ADR 0014 §5). +//! +//! The pipeline is fixed and fail-closed: +//! +//! ```text +//! stage bytes (contiguous NX kernel frames, never mapped into the task) +//! -> parse + ArtifactId + Ed25519 against local anchors (Verified) +//! -> deterministic admission policy (Authorized) +//! -> scheduler slot + every frame, reserved up front (Reserved) +//! -> private tables; exact code/data copy via the NX alias (Mapped) +//! -> SHA-256 of bytes read back from the private pages (Hashed) +//! -> I-cache sync, code EL0 RX, EL1 alias read-only, audit (Sealed) +//! -> policy grants installed in the task's M3 CapTable (CapsInstalled) +//! -> LoadedTask (Admitted) +//! ``` +//! +//! Any failure scrubs and releases every frame and scheduler slot taken so +//! far; nothing partially admitted survives. After the task ends for any +//! reason its code pages are hashed again (executed bytes), its capabilities +//! are revoked, and every page is scrubbed and returned. +//! +//! No translation regime active while the task lives maps a code frame +//! writable: its user mapping is EL0 read-only/executable, and the task's +//! private copy of the kernel identity map marks the same frames read-only +//! (EL1 alias). The kernel's own root keeps the RW+NX alias, which is used +//! only before sealing and after the task has left the CPU. +//! +//! Hardware access goes through [`LoaderPlatform`] so the whole pipeline, +//! including every rollback, runs under host tests. + +use aienos_artifact::capability::{CapabilityRequest, MAX_CAPABILITIES, RESOURCE_KIND_OBJECT}; +use aienos_artifact::error::ArtifactError; +use aienos_artifact::resource::{ + ResourceEnvelope, MAX_CODE_PAGES, MAX_CPU_TICKS, MAX_DATA_PAGES, MAX_ELAPSED_TICKS, + MAX_STACK_PAGES, MAX_SYSCALLS, +}; +use aienos_artifact::signature::{ArtifactVerifier, TrustTier}; +use aienos_artifact::ArtifactId; +use aienos_crypto::sha256::{Digest, Sha256}; + +use crate::abi::Handle; +use crate::admission::{AdmissionLimits, AdmissionPolicy, AvailableResources, GrantedCapability}; +use crate::caps::{CapTable, Rights}; +use crate::mem::pagetable::{page_descriptor, MapFlags, MemoryAttribute}; +use crate::mem::{FrameBatch, PhysAddr, MAX_BATCH_FRAMES}; +use crate::scheduler::{Scheduler, TaskPriority}; +use crate::task_runtime::{ + ExecutionStatus, TaskBudget, TaskContext, TaskOutcome, SEED_OBJECT_ID, TASK_CAPABILITIES, +}; + +/// Candidate lifecycle (ADR 0014 §5). Only `Admitted` tasks ever run. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum CandidateState { + Received, + Staged, + Verified, + Authorized, + Reserved, + Mapped, + Hashed, + Sealed, + CapsInstalled, + Admitted, + Running, + Rejected, + Destroyed, +} + +impl CandidateState { + pub const fn name(self) -> &'static str { + match self { + Self::Received => "received", + Self::Staged => "staged", + Self::Verified => "verified", + Self::Authorized => "authorized", + Self::Reserved => "reserved", + Self::Mapped => "mapped", + Self::Hashed => "hashed", + Self::Sealed => "sealed", + Self::CapsInstalled => "caps", + Self::Admitted => "admitted", + Self::Running => "running", + Self::Rejected => "rejected", + Self::Destroyed => "destroyed", + } + } +} + +/// Every reason a candidate can be refused or torn down. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum LoadError { + Artifact(ArtifactError), + NoFrames, + StagingTooLarge, + Mapping, + MappedDigestMismatch, + WxAudit, + CapabilityInstall, + SchedulerFull, + ExecutedDigestMismatch, + Reclaim, +} + +impl From<ArtifactError> for LoadError { + fn from(error: ArtifactError) -> Self { + Self::Artifact(error) + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Decision { + Admitted, + Rejected, +} + +/// What one boot candidate did, for the boot report and QEMU checks. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct CandidateReport { + pub decision: Decision, + pub failed_stage: Option<CandidateState>, + pub error: Option<LoadError>, + pub artifact_id: Option<ArtifactId>, + pub trust_tier: Option<TrustTier>, + pub frames_reserved: usize, + pub frames_free_before: usize, + pub frames_free_after: usize, + pub caps_installed: usize, + pub caps_live_after: usize, + /// identified == verified == admitted == mapped == executed. + pub byte_chain: bool, + pub wx_enforced: bool, + pub outcome: TaskOutcome, + pub code_base: u64, + pub code_end: u64, +} + +impl CandidateReport { + pub const fn reclaimed(&self) -> bool { + self.frames_free_after == self.frames_free_before && self.caps_live_after == 0 + } +} + +// --------------------------------------------------------------------------- +// Platform contract +// --------------------------------------------------------------------------- + +pub const PAGE: usize = 4096; +const PAGE_U64: u64 = PAGE as u64; +const ENTRIES: usize = 512; +/// Private user-window tables: L0 (copy of the kernel root), L1, L2, L3. +pub const TABLE_FRAMES: usize = 4; +/// Largest staged artifact: the admitted maximum payload fits in 130 pages. +pub const MAX_STAGING_FRAMES: usize = MAX_BATCH_FRAMES; +/// Loaded artifact tasks that may hold a scheduler slot at once. +pub const LOADED_TASK_SLOTS: usize = 4; +pub type LoaderScheduler = Scheduler<1, LOADED_TASK_SLOTS>; + +const ADDRESS_MASK: u64 = 0x0000_ffff_ffff_f000; +const ATTR_MASK: u64 = 0xffff_0000_0000_0ffc; +const BLOCK_1G_MASK: u64 = 0x0000_ffff_c000_0000; +const BLOCK_2M_MASK: u64 = 0x0000_ffff_ffe0_0000; +const DESC_TYPE: u64 = 0b11; +const DESC_TABLE: u64 = 0b11; +const DESC_BLOCK: u64 = 0b01; +/// AP[2]: read-only at every EL that can access the page. +pub const AP_READ_ONLY: u64 = 1 << 7; +/// AP[1]: EL0 accessible. +pub const AP_EL0: u64 = 1 << 6; +pub const PXN: u64 = 1 << 53; +pub const UXN: u64 = 1 << 54; + +pub const USER_CODE: MapFlags = MapFlags { + attribute: MemoryAttribute::NormalWriteBack, + writable: false, + user: true, + executable: true, + shareable: true, + global: false, +}; +pub const USER_DATA: MapFlags = MapFlags { + writable: true, + executable: false, + ..USER_CODE +}; + +/// Physical memory and frame ownership as the loader needs them. On AArch64 +/// the kernel identity map makes a physical address directly addressable; +/// host tests supply an arena. +pub trait LoaderPlatform { + fn kernel_root(&self) -> u64; + fn free_frames(&self) -> usize; + /// All-or-nothing reservation of `count` frames. + fn reserve_batch(&mut self, count: usize) -> Option<FrameBatch>; + fn release_batch(&mut self, batch: FrameBatch) -> bool; + fn reserve_contiguous(&mut self, count: usize) -> Option<u64>; + fn release_contiguous(&mut self, start: u64, count: usize) -> bool; + fn bytes(&self, pa: u64, len: usize) -> &[u8]; + /// Only ever called on frames the loader currently owns. + fn bytes_mut(&mut self, pa: u64, len: usize) -> &mut [u8]; + fn copy(&mut self, src: u64, dst: u64, len: usize); + /// Make table writes visible to the translation walker. + fn clean_dcache(&mut self, pa: u64, len: usize); + /// Clean D-cache to PoU and invalidate I-cache for freshly written code. + fn sync_icache(&mut self, pa: u64, len: usize); +} + +/// Runs a sealed task. The hardware implementation enters EL0. +pub trait TaskExecutor<P: LoaderPlatform> { + fn execute(&mut self, task: TaskContext<'_>, platform: &mut P) -> TaskOutcome; +} + +fn read_entry<P: LoaderPlatform>(p: &P, table: u64, index: usize) -> u64 { + let b = p.bytes(table + (index as u64) * 8, 8); + u64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) +} + +fn write_entry<P: LoaderPlatform>(p: &mut P, table: u64, index: usize, value: u64) { + p.bytes_mut(table + (index as u64) * 8, 8) + .copy_from_slice(&value.to_le_bytes()); +} + +const fn table_index(va: u64, level: usize) -> usize { + ((va >> (39 - 9 * level)) & 511) as usize +} + +// --------------------------------------------------------------------------- +// Task layout +// --------------------------------------------------------------------------- + +/// The private 2 MiB EL0 window, one L3 table, page by page: +/// guard | code | guard | data | guard | stack | guard. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct TaskLayout { + pub window_index: usize, + pub base: u64, + pub code_pages: usize, + pub data_pages: usize, + pub stack_pages: usize, + pub code_len: usize, + pub data_len: usize, + pub data_memory_len: usize, + pub entry_offset: u64, +} + +impl TaskLayout { + pub fn new( + window_index: usize, + resources: &ResourceEnvelope, + code_len: usize, + data_len: usize, + data_memory_len: usize, + entry_offset: u32, + ) -> Result<Self, LoadError> { + let layout = Self { + window_index, + base: (window_index as u64) << 39, + code_pages: resources.code_pages as usize, + data_pages: resources.data_pages as usize, + stack_pages: resources.stack_pages as usize, + code_len, + data_len, + data_memory_len, + entry_offset: u64::from(entry_offset), + }; + let fits = |len: usize, pages: usize| len <= pages.saturating_mul(PAGE); + if !(1..256).contains(&window_index) + || layout.code_pages == 0 + || layout.code_pages > MAX_CODE_PAGES as usize + || layout.data_pages == 0 + || layout.data_pages > MAX_DATA_PAGES as usize + || layout.stack_pages == 0 + || layout.stack_pages > MAX_STACK_PAGES as usize + || code_len == 0 + || !fits(code_len, layout.code_pages) + || data_len > data_memory_len + || !fits(data_memory_len, layout.data_pages) + || !layout.entry_offset.is_multiple_of(4) + || layout.entry_offset + 4 > code_len as u64 + || layout.window_pages() > ENTRIES + { + return Err(LoadError::Artifact(ArtifactError::ResourceLimit)); + } + Ok(layout) + } + + pub const fn content_frames(&self) -> usize { + self.code_pages + self.data_pages + self.stack_pages + } + pub const fn total_frames(&self) -> usize { + self.content_frames() + TABLE_FRAMES + } + const fn code_first(&self) -> usize { + 1 + } + const fn data_first(&self) -> usize { + self.code_first() + self.code_pages + 1 + } + const fn stack_first(&self) -> usize { + self.data_first() + self.data_pages + 1 + } + const fn window_pages(&self) -> usize { + self.stack_first() + self.stack_pages + 1 + } + pub const fn code_base(&self) -> u64 { + self.base + (self.code_first() * PAGE) as u64 + } + pub const fn code_end(&self) -> u64 { + self.code_base() + (self.code_pages * PAGE) as u64 + } + pub const fn data_base(&self) -> u64 { + self.base + (self.data_first() * PAGE) as u64 + } + pub const fn stack_base(&self) -> u64 { + self.base + (self.stack_first() * PAGE) as u64 + } + pub const fn stack_top(&self) -> u64 { + self.stack_base() + (self.stack_pages * PAGE) as u64 + } + pub const fn entry_pc(&self) -> u64 { + self.code_base() + self.entry_offset + } + + /// Expected L3 descriptor at window page `index`, given the task frames. + fn expected_leaf(&self, index: usize, frames: &[PhysAddr]) -> u64 { + let (d, s) = (self.data_first(), self.stack_first()); + if (1..1 + self.code_pages).contains(&index) { + page_descriptor(frames[index - 1], USER_CODE) + } else if (d..d + self.data_pages).contains(&index) { + page_descriptor(frames[self.code_pages + index - d], USER_DATA) + } else if (s..s + self.stack_pages).contains(&index) { + page_descriptor( + frames[self.code_pages + self.data_pages + index - s], + USER_DATA, + ) + } else { + 0 + } + } +} + +// --------------------------------------------------------------------------- +// Loaded task +// --------------------------------------------------------------------------- + +/// Frames owned by one task: content frames then its four window tables, plus +/// the private shadow of the kernel identity map that makes code read-only. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct TaskAddressSpace { + pub root: u64, + pub layout: TaskLayout, + frames: FrameBatch, + shadow: FrameBatch, + shadow_used: usize, +} + +impl TaskAddressSpace { + pub fn frames(&self) -> &[PhysAddr] { + self.frames.as_slice() + } + pub fn code_frames(&self) -> &[PhysAddr] { + &self.frames.as_slice()[..self.layout.code_pages] + } + pub fn shadow_frames(&self) -> &[PhysAddr] { + &self.shadow.as_slice()[..self.shadow_used] + } + pub fn frames_reserved(&self) -> usize { + self.frames.len() + self.shadow.len() + } +} + +/// A sealed, admitted task: the only thing the scheduler/runtime receives. +pub struct LoadedTask { + pub artifact_id: ArtifactId, + pub trust_tier: TrustTier, + pub payload_digest: Digest, + /// SHA-256 of the exact code bytes read back from the private pages. + pub code_digest: Digest, + pub address_space: TaskAddressSpace, + pub entry_pc: u64, + pub stack_pointer: u64, + pub handle_array: u64, + pub capabilities: CapTable<TASK_CAPABILITIES>, + pub handles: [Option<Handle>; TASK_CAPABILITIES], + pub grants: [Option<GrantedCapability>; MAX_CAPABILITIES], + pub grant_count: usize, + pub resource_budget: ResourceEnvelope, + pub scheduler_id: u32, + pub state: CandidateState, +} + +impl LoadedTask { + pub fn args(&self) -> [u64; 4] { + [ + self.handle_array, + self.grant_count as u64, + self.address_space.layout.data_base(), + self.address_space.layout.data_memory_len as u64, + ] + } + + pub fn budget(&self) -> TaskBudget { + TaskBudget { + cpu_ticks: self.resource_budget.cpu_ticks, + elapsed_ticks: self.resource_budget.elapsed_ticks, + syscalls: self.resource_budget.syscall_count, + } + } +} + +/// What teardown observed. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Teardown { + pub executed_bytes_match: bool, + pub caps_live_after: usize, + pub released: bool, +} + +// --------------------------------------------------------------------------- +// Policy and resources +// --------------------------------------------------------------------------- + +/// The local SEED-0B admission policy: READ on the SEED object only, no IPC, +/// signers limited to `signers` (empty in production builds). +pub fn boot_policy(signers: &[Digest]) -> Result<AdmissionPolicy, ArtifactError> { + let mut policy = AdmissionPolicy::new(AdmissionLimits { + code_pages: MAX_CODE_PAGES, + data_pages: MAX_DATA_PAGES, + stack_pages: MAX_STACK_PAGES, + max_capabilities: MAX_CAPABILITIES as u32, + ipc_messages: 0, + ipc_bytes: 0, + cpu_ticks: MAX_CPU_TICKS, + elapsed_ticks: MAX_ELAPSED_TICKS, + syscall_count: MAX_SYSCALLS, + })?; + policy.add_resource_rule(CapabilityRequest { + resource_kind: RESOURCE_KIND_OBJECT, + resource_id: SEED_OBJECT_ID, + rights: u32::from(Rights::READ.bits()), + bounds_kind: 1, + max_operations: 16, + max_bytes: 32, + byte_offset: 0, + byte_length: 32, + })?; + for signer in signers { + policy.allow_signer(*signer)?; + } + Ok(policy) +} + +/// Snapshot of what the kernel could reserve right now. +pub fn available_resources(free_frames: usize, free_task_slots: usize) -> AvailableResources { + let frames = if free_task_slots == 0 { + 0 + } else { + u32::try_from(free_frames.saturating_sub(TABLE_FRAMES)).unwrap_or(u32::MAX) + }; + AvailableResources { + code_pages: frames, + data_pages: frames, + stack_pages: frames, + capability_slots: TASK_CAPABILITIES as u32, + ipc_messages: 0, + ipc_bytes: 0, + cpu_ticks: MAX_CPU_TICKS, + elapsed_ticks: MAX_ELAPSED_TICKS, + syscall_count: MAX_SYSCALLS, + } +} + +// --------------------------------------------------------------------------- +// Pipeline +// --------------------------------------------------------------------------- + +type Failure = (CandidateState, LoadError); + +/// Everything reserved so far, released as a unit on failure. +struct Reservation { + scheduler_id: Option<u32>, + frames: Option<FrameBatch>, + shadow: Option<FrameBatch>, +} + +impl Reservation { + fn release<P: LoaderPlatform>( + &mut self, + platform: &mut P, + scheduler: &mut LoaderScheduler, + ) -> bool { + let mut ok = true; + for batch in [self.frames.take(), self.shadow.take()] + .into_iter() + .flatten() + { + for frame in batch.as_slice() { + platform.bytes_mut(frame.0 as u64, PAGE).fill(0); + } + ok &= platform.release_batch(batch); + } + if let Some(id) = self.scheduler_id.take() { + ok &= scheduler.remove(id).is_ok(); + } + ok + } +} + +/// Verify, admit, reserve, map, hash, seal and install capabilities for the +/// artifact already staged at `staged_pa..staged_pa + staged_len`. +pub fn load<P, V>( + platform: &mut P, + staged_pa: u64, + staged_len: usize, + verifier: &V, + policy: &AdmissionPolicy, + scheduler: &mut LoaderScheduler, + task_id: u32, +) -> Result<LoadedTask, Failure> +where + P: LoaderPlatform, + V: ArtifactVerifier, +{ + // ---- 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); + let verified = verifier + .verify(bytes) + .map_err(|e| (CandidateState::Verified, e.into()))?; + let available = available_resources(platform.free_frames(), free_slots); + let admission = policy + .evaluate(&verified, available) + .map_err(|e| (CandidateState::Authorized, e.into()))?; + let identified = verified.identified(); + if admission.artifact_id != identified.artifact_id + || admission.payload_digest != identified.payload_digest + { + return Err((CandidateState::Authorized, LoadError::MappedDigestMismatch)); + } + let artifact = &identified.artifact; + let offset_of = |slice: &[u8]| slice.as_ptr() as u64 - bytes.as_ptr() as u64; + ( + admission, + staged_pa + offset_of(artifact.code_bytes()), + staged_pa + offset_of(artifact.data_bytes()), + artifact.code_bytes().len(), + artifact.data_bytes().len(), + artifact.sections[1].memory_length as usize, + ) + }; + if admission.capability_count() > TASK_CAPABILITIES { + return Err(( + CandidateState::Authorized, + LoadError::Artifact(ArtifactError::ResourceLimit), + )); + } + let kernel_root = platform.kernel_root(); + let window_index = (1..256) + .find(|&index| read_entry(platform, kernel_root, index) == 0) + .ok_or((CandidateState::Reserved, LoadError::Mapping))?; + let layout = TaskLayout::new( + window_index, + &admission.resources, + code_len, + data_len, + data_memory_len, + admission.entry_offset, + ) + .map_err(|e| (CandidateState::Authorized, e))?; + + // ---- Reserved: scheduler slot, content+table frames, shadow frames. + let mut reservation = Reservation { + scheduler_id: None, + frames: None, + shadow: None, + }; + macro_rules! fail { + ($stage:expr, $error:expr) => {{ + reservation.release(platform, scheduler); + return Err(($stage, $error)); + }}; + } + if scheduler.enqueue(task_id, TaskPriority::Normal).is_err() { + fail!(CandidateState::Reserved, LoadError::SchedulerFull); + } + reservation.scheduler_id = Some(task_id); + if layout.total_frames() > MAX_BATCH_FRAMES { + fail!(CandidateState::Reserved, LoadError::NoFrames); + } + let Some(frames) = platform.reserve_batch(layout.total_frames()) else { + fail!(CandidateState::Reserved, LoadError::NoFrames); + }; + reservation.frames = Some(frames); + let all = frames.as_slice(); + let code_frames = &all[..layout.code_pages]; + let shadow_need = match shadow_frames_needed(platform, kernel_root, code_frames) { + Ok(n) => n, + Err(e) => fail!(CandidateState::Reserved, e), + }; + if shadow_need > MAX_BATCH_FRAMES { + fail!(CandidateState::Reserved, LoadError::NoFrames); + } + let Some(shadow) = platform.reserve_batch(shadow_need) else { + fail!(CandidateState::Reserved, LoadError::NoFrames); + }; + reservation.shadow = Some(shadow); + + // ---- Mapped: private tables, exact bytes copied through the NX alias. + let content = layout.content_frames(); + let (l0, l1, l2, l3) = ( + all[content].0 as u64, + all[content + 1].0 as u64, + all[content + 2].0 as u64, + all[content + 3].0 as u64, + ); + for frame in all.iter().chain(shadow.as_slice()) { + platform.bytes_mut(frame.0 as u64, PAGE).fill(0); + } + platform.copy(kernel_root, l0, PAGE); + write_entry(platform, l0, window_index, (l1 & ADDRESS_MASK) | DESC_TABLE); + write_entry(platform, l1, 0, (l2 & ADDRESS_MASK) | DESC_TABLE); + write_entry(platform, l2, 0, (l3 & ADDRESS_MASK) | DESC_TABLE); + for index in layout.data_first()..layout.window_pages() { + let leaf = layout.expected_leaf(index, all); + if leaf != 0 { + write_entry(platform, l3, index, leaf); + } + } + copy_section(platform, code_src, code_len, code_frames); + copy_section( + platform, + data_src, + data_len, + &all[layout.code_pages..layout.code_pages + layout.data_pages], + ); + + // ---- Hashed: identified/verified/admitted == mapped. + let (payload, code_digest) = hash_loaded(platform, &layout, all); + if payload != admission.payload_digest { + fail!(CandidateState::Hashed, LoadError::MappedDigestMismatch); + } + + // ---- Sealed: code becomes EL0 RX; its EL1 alias read-only in this root. + for frame in code_frames { + platform.sync_icache(frame.0 as u64, PAGE); + } + let shadow_used = match shadow_code_alias(platform, l0, code_frames, shadow.as_slice()) { + Ok(n) => n, + Err(e) => fail!(CandidateState::Sealed, e), + }; + for index in 1..1 + layout.code_pages { + write_entry(platform, l3, index, layout.expected_leaf(index, all)); + } + for table in all[content..] + .iter() + .chain(&shadow.as_slice()[..shadow_used]) + { + platform.clean_dcache(table.0 as u64, PAGE); + } + let address_space = TaskAddressSpace { + root: l0, + layout, + frames, + shadow, + shadow_used, + }; + if !audit_wx(platform, &address_space) { + fail!(CandidateState::Sealed, LoadError::WxAudit); + } + + // ---- CapsInstalled: exactly the policy grants, in grant order. + let mut capabilities = CapTable::new(0x5441_0000 | (task_id & 0xffff)); + let mut handles = [None; TASK_CAPABILITIES]; + let mut grants = [None; MAX_CAPABILITIES]; + let grant_count = admission.capability_count(); + for (index, grant) in admission.capabilities().iter().enumerate() { + let Some(grant) = grant else { + fail!(CandidateState::CapsInstalled, LoadError::CapabilityInstall); + }; + match capabilities.insert(index as u32, grant.rights) { + Ok(handle) => handles[index] = Some(handle), + Err(_) => fail!(CandidateState::CapsInstalled, LoadError::CapabilityInstall), + } + grants[index] = Some(*grant); + } + let handle_array = layout.stack_top() - (grant_count as u64) * 8; + let top_frame = all[content - 1].0 as u64; + for (index, handle) in handles[..grant_count].iter().enumerate() { + let va = handle_array + (index as u64) * 8; + let offset = va - (layout.stack_top() - PAGE_U64); + let raw = handle.map_or(0, Handle::to_raw); + platform + .bytes_mut(top_frame + offset, 8) + .copy_from_slice(&raw.to_le_bytes()); + } + platform.clean_dcache(top_frame, PAGE); + + Ok(LoadedTask { + artifact_id: admission.artifact_id, + trust_tier: admission.trust_tier, + payload_digest: payload, + code_digest, + address_space, + entry_pc: layout.entry_pc(), + stack_pointer: handle_array & !15, + handle_array, + capabilities, + handles, + grants, + grant_count, + resource_budget: admission.resources, + scheduler_id: task_id, + state: CandidateState::Admitted, + }) +} + +fn occupied_slots(scheduler: &LoaderScheduler) -> usize { + scheduler.queue_len(0).unwrap_or(LOADED_TASK_SLOTS) +} + +fn copy_section<P: LoaderPlatform>(p: &mut P, src: u64, len: usize, frames: &[PhysAddr]) { + for (index, frame) in frames.iter().enumerate() { + let start = index * PAGE; + if start >= len { + break; + } + let n = (len - start).min(PAGE); + p.copy(src + start as u64, frame.0 as u64, n); + } +} + +/// SHA-256(code || data) and SHA-256(code), read back from private pages. +fn hash_loaded<P: LoaderPlatform>( + p: &P, + layout: &TaskLayout, + frames: &[PhysAddr], +) -> (Digest, Digest) { + let mut payload = Sha256::new(); + let mut code = Sha256::new(); + for (index, frame) in frames[..layout.code_pages].iter().enumerate() { + let start = index * PAGE; + if start >= layout.code_len { + break; + } + let bytes = p.bytes(frame.0 as u64, (layout.code_len - start).min(PAGE)); + payload.update(bytes); + code.update(bytes); + } + let data = &frames[layout.code_pages..layout.code_pages + layout.data_pages]; + for (index, frame) in data.iter().enumerate() { + let start = index * PAGE; + if start >= layout.data_len { + break; + } + payload.update(p.bytes(frame.0 as u64, (layout.data_len - start).min(PAGE))); + } + (payload.finalize(), code.finalize()) +} + +/// SHA-256 of the code bytes currently in a task's code frames. +pub fn code_digest<P: LoaderPlatform>(p: &P, space: &TaskAddressSpace) -> Digest { + let mut code = Sha256::new(); + for (index, frame) in space.code_frames().iter().enumerate() { + let start = index * PAGE; + if start >= space.layout.code_len { + break; + } + code.update(p.bytes(frame.0 as u64, (space.layout.code_len - start).min(PAGE))); + } + code.finalize() +} + +// --------------------------------------------------------------------------- +// Read-only shadow of the kernel identity map for code frames +// --------------------------------------------------------------------------- + +/// Distinct (L0), (L0,L1), (L0,L1,L2) prefixes covering `frames`: one private +/// L1, L2 and L3 table per prefix. Fails if the identity map does not reach +/// a frame through L0 table → L1 table/1 GiB block → L2 table/2 MiB block → L3 +/// page. +fn shadow_frames_needed<P: LoaderPlatform>( + p: &P, + kernel_root: u64, + frames: &[PhysAddr], +) -> Result<usize, LoadError> { + let mut prefixes: [[u64; 3]; MAX_CODE_PAGES as usize] = + [[u64::MAX; 3]; MAX_CODE_PAGES as usize]; + let mut count = 0usize; + for (n, frame) in frames.iter().enumerate() { + let pa = frame.0 as u64; + kernel_translation(p, kernel_root, pa).ok_or(LoadError::Mapping)?; + let keys = [pa >> 39, pa >> 30, pa >> 21]; + for level in 0..3 { + if !prefixes[..n].iter().any(|k| k[level] == keys[level]) { + count += 1; + } + } + prefixes[n] = keys; + } + Ok(count) +} + +/// Walk `root` for `va`; returns (leaf descriptor, level) of a valid leaf. +fn kernel_translation<P: LoaderPlatform>(p: &P, root: u64, va: u64) -> Option<(u64, usize)> { + let mut table = root; + for level in 0..4 { + let entry = read_entry(p, table, table_index(va, level)); + match (level, entry & DESC_TYPE) { + (3, DESC_TABLE) => return Some((entry, 3)), + (1 | 2, DESC_BLOCK) => return Some((entry, level)), + (0..=2, DESC_TABLE) => table = entry & ADDRESS_MASK, + _ => return None, + } + } + None +} + +/// Privatise the path to every code frame in the task root and mark its +/// identity-map leaf read-only. Returns shadow frames used. +fn shadow_code_alias<P: LoaderPlatform>( + p: &mut P, + task_root: u64, + frames: &[PhysAddr], + shadow: &[PhysAddr], +) -> Result<usize, LoadError> { + let mut used = 0usize; + for frame in frames { + let pa = frame.0 as u64; + let mut table = task_root; + for level in 0..3 { + let index = table_index(pa, level); + let entry = read_entry(p, table, index); + let child = entry & ADDRESS_MASK; + let private = shadow[..used].iter().any(|f| f.0 as u64 == child); + let next = if entry & DESC_TYPE == DESC_TABLE && private { + child + } else { + let fresh = shadow.get(used).ok_or(LoadError::Mapping)?.0 as u64; + used += 1; + match (level, entry & DESC_TYPE) { + (_, DESC_TABLE) => p.copy(child, fresh, PAGE), + (1, DESC_BLOCK) => { + let attrs = entry & ATTR_MASK; + let base = entry & BLOCK_1G_MASK; + for k in 0..ENTRIES as u64 { + write_entry( + p, + fresh, + k as usize, + (base + (k << 21)) | attrs | DESC_BLOCK, + ); + } + } + (2, DESC_BLOCK) => { + let attrs = entry & ATTR_MASK; + let base = entry & BLOCK_2M_MASK; + for k in 0..ENTRIES as u64 { + write_entry( + p, + fresh, + k as usize, + (base + (k << 12)) | attrs | DESC_TABLE, + ); + } + } + _ => return Err(LoadError::Mapping), + } + write_entry( + p, + table, + index, + (entry & !ADDRESS_MASK & !DESC_TYPE) | fresh | DESC_TABLE, + ); + fresh + }; + table = next; + } + let index = table_index(pa, 3); + let leaf = read_entry(p, table, index); + if leaf & DESC_TYPE != DESC_TABLE || leaf & ADDRESS_MASK != pa { + return Err(LoadError::Mapping); + } + write_entry(p, table, index, leaf | AP_READ_ONLY | PXN | UXN); + } + Ok(used) +} + +/// Fail-closed W^X audit of the sealed task root: +/// - the user window holds exactly the expected leaves (code EL0 RO+X, data +/// and stack EL0 RW+NX, guards unmapped) and nothing else; +/// - every code frame's identity alias is read-only and never executable; +/// - no user-window leaf is both writable and executable. +pub fn audit_wx<P: LoaderPlatform>(p: &P, space: &TaskAddressSpace) -> bool { + let layout = &space.layout; + let root = space.root; + let frames = space.frames(); + let l0e = read_entry(p, root, layout.window_index); + let l1 = l0e & ADDRESS_MASK; + let content = layout.content_frames(); + if l0e != (frames[content + 1].0 as u64 & ADDRESS_MASK) | DESC_TABLE { + return false; + } + for index in 1..ENTRIES { + if read_entry(p, l1, index) != 0 { + return false; + } + } + let l2 = read_entry(p, l1, 0) & ADDRESS_MASK; + if l2 != frames[content + 2].0 as u64 { + return false; + } + for index in 1..ENTRIES { + if read_entry(p, l2, index) != 0 { + return false; + } + } + let l3 = read_entry(p, l2, 0) & ADDRESS_MASK; + if l3 != frames[content + 3].0 as u64 { + return false; + } + for index in 0..ENTRIES { + let leaf = read_entry(p, l3, index); + if leaf != layout.expected_leaf(index, frames) { + return false; + } + let writable = leaf & AP_READ_ONLY == 0; + let executable = leaf & UXN == 0 || leaf & PXN == 0; + if leaf != 0 && writable && executable { + return false; + } + } + for frame in space.code_frames() { + let pa = frame.0 as u64; + match kernel_translation(p, root, pa) { + Some((leaf, 3)) => { + if leaf & ADDRESS_MASK != pa + || leaf & AP_READ_ONLY == 0 + || leaf & PXN == 0 + || leaf & UXN == 0 + { + return false; + } + } + _ => return false, + } + } + true +} + +// --------------------------------------------------------------------------- +// Run and teardown +// --------------------------------------------------------------------------- + +/// Hand the task to the scheduler and run it when the scheduler selects it. +pub fn run_task<P, E>( + task: &mut LoadedTask, + platform: &mut P, + scheduler: &mut LoaderScheduler, + executor: &mut E, +) -> TaskOutcome +where + P: LoaderPlatform, + E: TaskExecutor<P>, +{ + let not_run = TaskOutcome { + status: ExecutionStatus::NotRun, + syscalls: 0, + object_reads_ok: 0, + denials: 0, + elapsed_ticks: 0, + }; + if scheduler.tick(0) != Ok(Some(task.scheduler_id)) { + return not_run; + } + task.state = CandidateState::Running; + let args = task.args(); + let budget = task.budget(); + let context = TaskContext { + root: task.address_space.root, + entry_pc: task.entry_pc, + stack_pointer: task.stack_pointer, + args, + capabilities: &mut task.capabilities, + grants: &task.grants[..task.grant_count], + budget, + }; + executor.execute(context, platform) +} + +/// Re-hash executed code, revoke every capability, scrub and release every +/// frame, and free the scheduler slot. Always completes. +pub fn destroy<P: LoaderPlatform>( + mut task: LoadedTask, + platform: &mut P, + scheduler: &mut LoaderScheduler, +) -> Teardown { + let executed_bytes_match = code_digest(platform, &task.address_space) == task.code_digest; + for handle in task.handles.iter_mut() { + if let Some(h) = handle.take() { + let _ = task.capabilities.remove(h); + } + } + let caps_live_after = task.capabilities.live_count(); + let mut reservation = Reservation { + scheduler_id: Some(task.scheduler_id), + frames: Some(task.address_space.frames), + shadow: Some(task.address_space.shadow), + }; + let released = reservation.release(platform, scheduler); + Teardown { + executed_bytes_match, + caps_live_after, + released, + } +} + +/// Stage, verify, admit, load, run and destroy one candidate on `platform`. +pub fn process_candidate<P, V, E>( + bytes: &[u8], + platform: &mut P, + verifier: &V, + policy: &AdmissionPolicy, + scheduler: &mut LoaderScheduler, + executor: &mut E, + task_id: u32, +) -> CandidateReport +where + P: LoaderPlatform, + V: ArtifactVerifier, + E: TaskExecutor<P>, +{ + let free_before = platform.free_frames(); + let mut report = empty_report(free_before); + let reject = |mut report: CandidateReport, stage, error, free_after| { + report.decision = Decision::Rejected; + report.failed_stage = Some(stage); + report.error = Some(error); + report.frames_free_after = free_after; + report + }; + let pages = bytes.len().div_ceil(PAGE); + if bytes.is_empty() || pages > MAX_STAGING_FRAMES { + return reject( + report, + CandidateState::Received, + LoadError::StagingTooLarge, + platform.free_frames(), + ); + } + let Some(staged) = platform.reserve_contiguous(pages) else { + return reject( + report, + CandidateState::Staged, + LoadError::NoFrames, + platform.free_frames(), + ); + }; + platform.bytes_mut(staged, pages * PAGE).fill(0); + platform + .bytes_mut(staged, bytes.len()) + .copy_from_slice(bytes); + let loaded = load( + platform, + staged, + bytes.len(), + verifier, + policy, + scheduler, + task_id, + ); + // The task owns its own copy; staging is scrubbed and returned now. + platform.bytes_mut(staged, pages * PAGE).fill(0); + let staging_released = platform.release_contiguous(staged, pages); + let mut task = match loaded { + Ok(task) => task, + Err((stage, error)) => { + let error = if staging_released { + error + } else { + LoadError::Reclaim + }; + return reject(report, stage, error, platform.free_frames()); + } + }; + report.artifact_id = Some(task.artifact_id); + report.trust_tier = Some(task.trust_tier); + report.frames_reserved = task.address_space.frames_reserved(); + 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.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.caps_live_after = teardown.caps_live_after; + report.frames_free_after = platform.free_frames(); + if !teardown.executed_bytes_match { + report.error = Some(LoadError::ExecutedDigestMismatch); + } else if !teardown.released || !staging_released { + report.error = Some(LoadError::Reclaim); + } + report +} + +fn empty_report(free_before: usize) -> CandidateReport { + CandidateReport { + decision: Decision::Rejected, + failed_stage: None, + error: None, + artifact_id: None, + trust_tier: None, + frames_reserved: 0, + frames_free_before: free_before, + frames_free_after: free_before, + caps_installed: 0, + 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, + }, + code_base: 0, + code_end: 0, + } +} + +// --------------------------------------------------------------------------- +// Boot platform (early allocator + identity map) +// --------------------------------------------------------------------------- + +/// The early-boot platform: frames from `boot`'s allocator, memory through +/// the kernel identity map. +pub struct EarlyPlatform { + kernel_root: u64, +} + +impl LoaderPlatform for EarlyPlatform { + fn kernel_root(&self) -> u64 { + self.kernel_root + } + fn free_frames(&self) -> usize { + crate::boot::early_free_frames() + } + fn reserve_batch(&mut self, count: usize) -> Option<FrameBatch> { + crate::boot::reserve_early_frames(count) + } + fn release_batch(&mut self, batch: FrameBatch) -> bool { + crate::boot::release_early_frames(batch) + } + fn reserve_contiguous(&mut self, count: usize) -> Option<u64> { + crate::boot::reserve_early_contiguous(count).map(|pa| pa.0 as u64) + } + fn release_contiguous(&mut self, start: u64, count: usize) -> bool { + crate::boot::release_early_contiguous(PhysAddr(start as usize), count) + } + fn bytes(&self, pa: u64, len: usize) -> &[u8] { + // SAFETY: the kernel identity map covers RAM and page-table pools. + unsafe { core::slice::from_raw_parts(pa as usize as *const u8, len) } + } + fn bytes_mut(&mut self, pa: u64, len: usize) -> &mut [u8] { + // SAFETY: the loader only writes frames it reserved. + unsafe { core::slice::from_raw_parts_mut(pa as usize as *mut u8, len) } + } + fn copy(&mut self, src: u64, dst: u64, len: usize) { + // SAFETY: distinct frames owned by or staged for the loader. + unsafe { + core::ptr::copy_nonoverlapping(src as usize as *const u8, dst as usize as *mut u8, len) + } + } + fn clean_dcache(&mut self, pa: u64, len: usize) { + cache_maintenance(pa as usize, len, false); + } + fn sync_icache(&mut self, pa: u64, len: usize) { + cache_maintenance(pa as usize, len, true); + } +} + +#[cfg(target_arch = "aarch64")] +fn cache_maintenance(address: usize, length: usize, instructions: bool) { + let ctr: u64; + // SAFETY: CTR_EL0 read and cache maintenance by VA on owned memory. + unsafe { + core::arch::asm!("mrs {0}, ctr_el0", out(reg) ctr, options(nomem, nostack)); + let dline = 4usize << ((ctr >> 16) & 0xf); + let iline = 4usize << (ctr & 0xf); + for at in (address & !(dline - 1)..address + length).step_by(dline) { + core::arch::asm!("dc cvau, {0}", in(reg) at, options(nostack)); + } + core::arch::asm!("dsb ish", options(nostack)); + if instructions { + for at in (address & !(iline - 1)..address + length).step_by(iline) { + core::arch::asm!("ic ivau, {0}", in(reg) at, options(nostack)); + } + core::arch::asm!("dsb ish", "isb", options(nostack)); + } + } +} + +#[cfg(not(target_arch = "aarch64"))] +fn cache_maintenance(_address: usize, _length: usize, _instructions: bool) {} + +/// Enters EL0 through [`crate::task_runtime::run`]. +pub struct El0Executor { + kernel_root: usize, +} + +impl TaskExecutor<EarlyPlatform> for El0Executor { + fn execute(&mut self, task: TaskContext<'_>, _platform: &mut EarlyPlatform) -> TaskOutcome { + // SAFETY: caller of `run_boot_candidate` guarantees the EL1 context. + unsafe { crate::task_runtime::run(task, self.kernel_root) } + } +} + +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); + +/// Stage, verify, admit, load, run and destroy one candidate. +/// +/// # Safety +/// EL1, single core, after `boot::early_kernel_enter` initialised the frame +/// 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)], + ) + }; + #[cfg(not(feature = "seed0b-test-anchor"))] + let (anchors, signers): (aienos_artifact::ProductionTrustAnchorSet, [Digest; 0]) = + (aienos_artifact::ProductionTrustAnchorSet::default(), []); + let verifier = aienos_artifact::ConfiguredArtifactVerifier::new( + &anchors, + aienos_artifact::Ed25519Verifier, + ); + let mut platform = EarlyPlatform { + kernel_root: kernel_root as u64, + }; + let Ok(policy) = boot_policy(&signers) else { + let mut report = empty_report(platform.free_frames()); + report.failed_stage = Some(CandidateState::Authorized); + report.error = Some(LoadError::Artifact(ArtifactError::ResourceLimit)); + return report; + }; + let mut executor = El0Executor { kernel_root }; + let task_id = NEXT_TASK_ID.fetch_add(1, core::sync::atomic::Ordering::Relaxed); + let mut scheduler = BOOT_SCHEDULER.lock(); + process_candidate( + bytes, + &mut platform, + &verifier, + &policy, + &mut scheduler, + &mut executor, + task_id, + ) +} + +/// 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` +/// `artifact: NAME rejected stage=STAGE reason=REASON reclaimed=yes` +/// +/// EXEC is `exited:0x..`, `timeout`, `fault:code-write`, `fault:other`, +/// `bad-syscall:N`, `resource-overrun`, or `not-run`. +pub fn write_candidate_line(out: &mut impl core::fmt::Write, name: &str, r: &CandidateReport) { + let yes_no = |b: bool| if b { "yes" } else { "no" }; + match r.decision { + Decision::Rejected => { + let stage = r.failed_stage.map_or("unknown", CandidateState::name); + let _ = write!(out, "artifact: {name} rejected stage={stage} reason="); + match r.error { + Some(LoadError::Artifact(e)) => { + let _ = write!(out, "{e:?}"); + } + Some(e) => { + let _ = write!(out, "{e:?}"); + } + None => { + let _ = write!(out, "unknown"); + } + } + let _ = writeln!(out, " reclaimed={}", yes_no(r.reclaimed())); + } + Decision::Admitted => { + let _ = write!(out, "artifact: {name} admitted id="); + if let Some(id) = r.artifact_id { + for byte in &id.as_bytes()[..8] { + let _ = write!(out, "{byte:02x}"); + } + } + let tier = match r.trust_tier { + Some(TrustTier::Seed0bQualification) => "seed0b-test", + Some(TrustTier::Production) => "production", + None => "none", + }; + let _ = write!(out, " tier={tier} exec="); + match r.outcome.status { + ExecutionStatus::NotRun => { + let _ = write!(out, "not-run"); + } + ExecutionStatus::Exited(code) => { + let _ = write!(out, "exited:{code:#x}"); + } + ExecutionStatus::Timeout => { + let _ = write!(out, "timeout"); + } + ExecutionStatus::Fault { esr, far, .. } => { + // EC 0x24 data abort from EL0, ISS.WnR (bit 6) set. + let write_abort = (esr >> 26) & 0x3f == 0x24 && esr & (1 << 6) != 0; + if write_abort && far >= r.code_base && far < r.code_end { + let _ = write!(out, "fault:code-write"); + } else { + let _ = write!(out, "fault:other"); + } + } + ExecutionStatus::BadSyscall(n) => { + let _ = write!(out, "bad-syscall:{n}"); + } + ExecutionStatus::ResourceOverrun => { + let _ = write!(out, "resource-overrun"); + } + } + let _ = writeln!( + out, + " bytes={} wx={} caps={} revoked={} reclaimed={} frames={} syscalls={} reads={} denials={}", + if r.byte_chain { + "identified=verified=admitted=mapped=executed" + } else { + "mismatch" + }, + if r.wx_enforced { + "enforced" + } else { + "violated" + }, + r.caps_installed, + yes_no(r.caps_live_after == 0), + yes_no(r.reclaimed()), + r.frames_reserved, + r.outcome.syscalls, + r.outcome.object_reads_ok, + r.outcome.denials, + ); + } + } +} + +#[cfg(test)] +#[path = "artifact_loader_tests.rs"] +mod tests; diff --git a/crates/aienos-kernel/src/artifact_loader_tests.rs b/crates/aienos-kernel/src/artifact_loader_tests.rs new file mode 100644 index 00000000..6e25c213 --- /dev/null +++ b/crates/aienos-kernel/src/artifact_loader_tests.rs @@ -0,0 +1,1311 @@ +//! Host tests for the Binary Artifact v0 loader over a mock physical memory. +//! +//! The mock kernel identity map covers the arena at `ARENA_BASE` in one of +//! three shapes (1 GiB block, 2 MiB blocks, 4 KiB pages) so the read-only +//! shadow of code frames is exercised at every level. + +use super::*; + +use std::collections::BTreeSet; +use std::string::String; +use std::vec; +use std::vec::Vec; + +use aienos_artifact::capability::{RESOURCE_KIND_CHANNEL, RIGHT_READ, RIGHT_WRITE}; +use aienos_artifact::signature::{ + artifact_signature_message, signer_fingerprint, ConfiguredArtifactVerifier, Ed25519Verifier, + TrustAnchorSet, TrustedSigner, +}; +use aienos_artifact::verify::parse_and_identify; +use ed25519_dalek::{Signer, SigningKey}; + +use crate::caps::CapError; +use crate::mem::BitmapFrameAllocator; + +// --------------------------------------------------------------------------- +// Mock platform +// --------------------------------------------------------------------------- + +const ARENA_BASE: u64 = 0x4000_0000; +const ARENA_FRAMES: usize = 1100; +/// Frames 0..KERNEL_RESERVED hold the mock kernel tables; the rest is managed. +const KERNEL_RESERVED: usize = 8; +const MANAGED: usize = ARENA_FRAMES - KERNEL_RESERVED; +const WORDS: usize = MANAGED.div_ceil(64); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum KernelMap { + Block1G, + Blocks2M, + Pages4K, +} + +struct MockPlatform { + arena: Vec<u8>, + allocator: BitmapFrameAllocator<WORDS>, + kernel_frames: usize, + handed_out: BTreeSet<u64>, + batch_calls: usize, + fail_batch_nth: Option<usize>, + fail_contiguous: bool, + copy_calls: usize, + corrupt_after_copy: Option<usize>, + release_calls: usize, +} + +const KERNEL_ATTRS: u64 = { + // Normal WB, EL1 RW, inner shareable, AF, global, PXN|UXN. + (0b11 << 8) | (1 << 10) | PXN | UXN +}; + +impl MockPlatform { + fn new(map: KernelMap) -> Self { + let mut p = Self { + arena: vec![0u8; ARENA_FRAMES * PAGE], + allocator: BitmapFrameAllocator::new( + PhysAddr((ARENA_BASE as usize) + KERNEL_RESERVED * PAGE), + MANAGED, + ), + kernel_frames: 0, + handed_out: BTreeSet::new(), + batch_calls: 0, + fail_batch_nth: None, + fail_contiguous: false, + copy_calls: 0, + corrupt_after_copy: None, + release_calls: 0, + }; + let frame = |i: usize| ARENA_BASE + (i * PAGE) as u64; + let (l0, l1, l2) = (frame(0), frame(1), frame(2)); + p.put(l0, 0, (l1 & ADDRESS_MASK) | DESC_TABLE); + // An unrelated kernel mapping in L1[0] (below RAM) as a 1 GiB block. + p.put(l1, 0, KERNEL_ATTRS | DESC_BLOCK); + match map { + KernelMap::Block1G => { + p.put(l1, 1, ARENA_BASE | KERNEL_ATTRS | DESC_BLOCK); + p.kernel_frames = 2; + } + KernelMap::Blocks2M => { + p.put(l1, 1, l2 | DESC_TABLE); + for k in 0..512u64 { + p.put( + l2, + k as usize, + (ARENA_BASE + (k << 21)) | KERNEL_ATTRS | DESC_BLOCK, + ); + } + p.kernel_frames = 3; + } + KernelMap::Pages4K => { + p.put(l1, 1, l2 | DESC_TABLE); + let l3_tables = (ARENA_FRAMES * PAGE).div_ceil(1 << 21); + assert!(3 + l3_tables <= KERNEL_RESERVED); + for k in 0..512u64 { + let region = ARENA_BASE + (k << 21); + if (k as usize) < l3_tables { + let l3 = frame(3 + k as usize); + p.put(l2, k as usize, l3 | DESC_TABLE); + for j in 0..512u64 { + p.put( + l3, + j as usize, + (region + (j << 12)) | KERNEL_ATTRS | DESC_TABLE, + ); + } + } else { + p.put(l2, k as usize, region | KERNEL_ATTRS | DESC_BLOCK); + } + } + p.kernel_frames = 3 + l3_tables; + } + } + p + } + + fn offset(&self, pa: u64, len: usize) -> usize { + assert!( + pa >= ARENA_BASE && pa + len as u64 <= ARENA_BASE + self.arena.len() as u64, + "access outside arena: {pa:#x}+{len}" + ); + (pa - ARENA_BASE) as usize + } + + fn put(&mut self, table: u64, index: usize, value: u64) { + let o = self.offset(table + index as u64 * 8, 8); + self.arena[o..o + 8].copy_from_slice(&value.to_le_bytes()); + } + + fn get(&self, table: u64, index: usize) -> u64 { + read_entry(self, table, index) + } + + fn kernel_snapshot(&self) -> Vec<u8> { + self.arena[..self.kernel_frames * PAGE].to_vec() + } + + fn all_handed_out_zero(&self) -> bool { + self.handed_out.iter().all(|pa| { + let o = self.offset(*pa, PAGE); + self.arena[o..o + PAGE].iter().all(|b| *b == 0) + }) + } +} + +impl LoaderPlatform for MockPlatform { + fn kernel_root(&self) -> u64 { + ARENA_BASE + } + fn free_frames(&self) -> usize { + self.allocator.free_count() + } + fn reserve_batch(&mut self, count: usize) -> Option<FrameBatch> { + self.batch_calls += 1; + if self.fail_batch_nth == Some(self.batch_calls) { + return None; + } + let batch = self.allocator.allocate_batch(count)?; + for f in batch.as_slice() { + self.handed_out.insert(f.0 as u64); + } + Some(batch) + } + fn release_batch(&mut self, batch: FrameBatch) -> bool { + self.release_calls += 1; + self.allocator.release_batch(batch) + } + fn reserve_contiguous(&mut self, count: usize) -> Option<u64> { + if self.fail_contiguous { + return None; + } + let start = self.allocator.allocate_contiguous(count)?.0 as u64; + for i in 0..count { + self.handed_out.insert(start + (i * PAGE) as u64); + } + Some(start) + } + fn release_contiguous(&mut self, start: u64, count: usize) -> bool { + self.release_calls += 1; + let mut ok = true; + for i in 0..count { + ok &= self + .allocator + .deallocate_frame(PhysAddr(start as usize + i * PAGE)); + } + ok + } + fn bytes(&self, pa: u64, len: usize) -> &[u8] { + let o = self.offset(pa, len); + &self.arena[o..o + len] + } + fn bytes_mut(&mut self, pa: u64, len: usize) -> &mut [u8] { + let o = self.offset(pa, len); + &mut self.arena[o..o + len] + } + fn copy(&mut self, src: u64, dst: u64, len: usize) { + let (s, d) = (self.offset(src, len), self.offset(dst, len)); + self.arena.copy_within(s..s + len, d); + self.copy_calls += 1; + if self.corrupt_after_copy == Some(self.copy_calls) && len > 0 { + self.arena[d] ^= 0x5a; + } + } + fn clean_dcache(&mut self, _pa: u64, _len: usize) {} + fn sync_icache(&mut self, _pa: u64, _len: usize) {} +} + +// --------------------------------------------------------------------------- +// Artifact fixtures +// --------------------------------------------------------------------------- + +/// RFC 8032 TEST 1 seed: the SEED-0B qualification signer. TEST ONLY. +const TEST_SEED: [u8; 32] = [ + 0x9d, 0x61, 0xb1, 0x9d, 0xef, 0xfd, 0x5a, 0x60, 0xba, 0x84, 0x4a, 0xf4, 0x92, 0xec, 0x2c, 0xc4, + 0x44, 0x49, 0xc5, 0x69, 0x7b, 0x32, 0x69, 0x19, 0x70, 0x3b, 0xac, 0x03, 0x1c, 0xae, 0x7f, 0x60, +]; +const OTHER_SEED: [u8; 32] = [0x42; 32]; + +struct Res { + code_pages: u32, + data_pages: u32, + stack_pages: u32, + max_capabilities: u16, + ipc_messages: u32, + ipc_bytes: u32, + cpu_ticks: u64, + elapsed_ticks: u64, + syscall_count: u32, +} + +impl Default for Res { + fn default() -> Self { + Self { + code_pages: 1, + data_pages: 1, + stack_pages: 1, + max_capabilities: 1, + ipc_messages: 0, + ipc_bytes: 0, + cpu_ticks: 1_000_000, + elapsed_ticks: 1_000_000, + syscall_count: 16, + } + } +} + +struct Spec { + entry: u32, + caps: Vec<CapabilityRequest>, + res: Res, + code: Vec<u8>, + data: Vec<u8>, +} + +fn seed_read(rights: u32, id: u32) -> CapabilityRequest { + CapabilityRequest { + resource_kind: RESOURCE_KIND_OBJECT, + resource_id: id, + rights, + bounds_kind: 1, + max_operations: 4, + max_bytes: 32, + byte_offset: 0, + byte_length: 32, + } +} + +fn code_words(n: usize) -> Vec<u8> { + // Deterministic distinct instruction-sized words; content is never run. + (0..n as u32) + .flat_map(|i| (0xd503_201f_u32 ^ (i.wrapping_mul(0x9e37_79b9))).to_le_bytes()) + .collect() +} + +fn spec() -> Spec { + Spec { + entry: 4, + caps: vec![seed_read(RIGHT_READ, SEED_OBJECT_ID)], + res: Res::default(), + code: code_words(16), + data: b"P2-5EXEC data section bytes".to_vec(), + } +} + +fn put16(b: &mut [u8], o: usize, v: u16) { + b[o..o + 2].copy_from_slice(&v.to_le_bytes()); +} +fn put32(b: &mut [u8], o: usize, v: u32) { + b[o..o + 4].copy_from_slice(&v.to_le_bytes()); +} +fn put64(b: &mut [u8], o: usize, v: u64) { + b[o..o + 8].copy_from_slice(&v.to_le_bytes()); +} + +/// Mirror of `aienos-artifact-tool pack`, then Ed25519-sign with `seed`. +fn pack_signed(s: &Spec, seed: &[u8; 32]) -> Vec<u8> { + let cap_off = 192usize; + let res_off = cap_off + s.caps.len() * 48; + let payload_off = (res_off + 48 + 15) & !15; + let payload_len = s.code.len() + s.data.len(); + let sig_off = payload_off + payload_len; + let total = sig_off + 100; + let mut b = vec![0u8; total]; + b[0..8].copy_from_slice(b"AIENART\0"); + put16(&mut b, 10, 128); + put16(&mut b, 12, 1); + put16(&mut b, 14, 1); + put32(&mut b, 20, total as u32); + put32(&mut b, 24, 128); + put16(&mut b, 28, 2); + put16(&mut b, 30, 32); + put32(&mut b, 36, s.entry); + put32(&mut b, 40, cap_off as u32); + put16(&mut b, 44, s.caps.len() as u16); + put16(&mut b, 46, 48); + put32(&mut b, 48, res_off as u32); + put16(&mut b, 52, 48); + put32(&mut b, 56, payload_off as u32); + put32(&mut b, 60, payload_len as u32); + put32(&mut b, 64, sig_off as u32); + put16(&mut b, 68, 100); + put16(&mut b, 70, 1); + let section = |b: &mut [u8], o: usize, kind: u16, perm: u16, rel: u32, len: u32, mem: u32| { + put16(b, o, kind); + put16(b, o + 2, perm); + put32(b, o + 8, rel); + put32(b, o + 12, len); + put32(b, o + 16, mem); + put32(b, o + 20, 4096); + }; + let code_len = s.code.len() as u32; + section(&mut b, 128, 1, 5, 0, code_len, code_len); + section( + &mut b, + 160, + 2, + 3, + code_len, + s.data.len() as u32, + s.res.data_pages * 4096, + ); + for (i, c) in s.caps.iter().enumerate() { + b[cap_off + i * 48..cap_off + (i + 1) * 48].copy_from_slice(&c.to_bytes()); + } + let r = &s.res; + put32(&mut b, res_off, r.code_pages); + put32(&mut b, res_off + 4, r.data_pages); + put32(&mut b, res_off + 8, r.stack_pages); + put16(&mut b, res_off + 12, r.max_capabilities); + put32(&mut b, res_off + 16, r.ipc_messages); + put32(&mut b, res_off + 20, r.ipc_bytes); + put64(&mut b, res_off + 24, r.cpu_ticks); + put64(&mut b, res_off + 32, r.elapsed_ticks); + put32(&mut b, res_off + 40, r.syscall_count); + b[payload_off..payload_off + s.code.len()].copy_from_slice(&s.code); + b[payload_off + s.code.len()..sig_off].copy_from_slice(&s.data); + put16(&mut b, sig_off, 1); + let id = parse_and_identify(&b).expect("fixture parses").artifact_id; + let key = SigningKey::from_bytes(seed); + let signature = key.sign(&artifact_signature_message(&id)); + b[sig_off + 4..sig_off + 36] + .copy_from_slice(&signer_fingerprint(&key.verifying_key().to_bytes())); + b[sig_off + 36..sig_off + 100].copy_from_slice(&signature.to_bytes()); + b +} + +fn payload_offset(bytes: &[u8]) -> usize { + u32::from_le_bytes(bytes[56..60].try_into().unwrap()) as usize +} + +struct TestAnchors { + key: [u8; 32], +} + +impl TrustAnchorSet for TestAnchors { + fn find(&self, fingerprint: &Digest) -> Option<TrustedSigner> { + (signer_fingerprint(&self.key) == *fingerprint).then_some(TrustedSigner { + public_key: self.key, + tier: TrustTier::Seed0bQualification, + }) + } +} + +fn public(seed: &[u8; 32]) -> [u8; 32] { + SigningKey::from_bytes(seed).verifying_key().to_bytes() +} + +fn anchors() -> TestAnchors { + TestAnchors { + key: public(&TEST_SEED), + } +} + +fn policy() -> AdmissionPolicy { + boot_policy(&[signer_fingerprint(&public(&TEST_SEED))]).unwrap() +} + +// --------------------------------------------------------------------------- +// Executors +// --------------------------------------------------------------------------- + +struct FnExec<F>(F); + +impl<F> TaskExecutor<MockPlatform> for FnExec<F> +where + F: FnMut(TaskContext<'_>, &mut MockPlatform) -> TaskOutcome, +{ + fn execute(&mut self, task: TaskContext<'_>, platform: &mut MockPlatform) -> TaskOutcome { + (self.0)(task, platform) + } +} + +fn exec<F>(f: F) -> FnExec<F> +where + F: FnMut(TaskContext<'_>, &mut MockPlatform) -> TaskOutcome, +{ + FnExec(f) +} + +fn outcome(status: ExecutionStatus) -> TaskOutcome { + TaskOutcome { + status, + syscalls: 1, + object_reads_ok: 0, + denials: 0, + elapsed_ticks: 10, + } +} + +fn exits_zero() -> FnExec<impl FnMut(TaskContext<'_>, &mut MockPlatform) -> TaskOutcome> { + exec(|_, _| outcome(ExecutionStatus::Exited(0))) +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +/// Walk `root` for `va`; returns (output page PA, leaf attributes) of the 4 KiB +/// page containing `va`, whatever the leaf level. +fn effective(p: &MockPlatform, root: u64, va: u64) -> Option<(u64, u64)> { + let (leaf, level) = kernel_translation(p, root, va)?; + let page = va & !0xfff; + let pa = match level { + 1 => (leaf & BLOCK_1G_MASK) + (page & ((1 << 30) - 1)), + 2 => (leaf & BLOCK_2M_MASK) + (page & ((1 << 21) - 1)), + _ => leaf & ADDRESS_MASK, + }; + Some((pa, leaf & ATTR_MASK)) +} + +struct Run { + platform: MockPlatform, + scheduler: LoaderScheduler, + kernel_before: Vec<u8>, + free_before: usize, +} + +impl Run { + fn new(map: KernelMap) -> Self { + let platform = MockPlatform::new(map); + Self { + kernel_before: platform.kernel_snapshot(), + free_before: platform.free_frames(), + platform, + scheduler: Scheduler::new([0]), + } + } + + fn candidate<E: TaskExecutor<MockPlatform>>( + &mut self, + bytes: &[u8], + verifier: &impl ArtifactVerifier, + policy: &AdmissionPolicy, + executor: &mut E, + task_id: u32, + ) -> CandidateReport { + process_candidate( + bytes, + &mut self.platform, + verifier, + policy, + &mut self.scheduler, + executor, + task_id, + ) + } + + /// Invariants every candidate, admitted or not, must leave behind. + fn assert_clean(&self, report: &CandidateReport) { + assert_eq!( + self.platform.free_frames(), + self.free_before, + "frames leaked" + ); + assert_eq!(report.frames_free_before, self.free_before); + assert_eq!(report.frames_free_after, self.free_before); + assert!(report.reclaimed(), "{report:?}"); + assert_eq!( + self.scheduler.queue_len(0), + Some(0), + "scheduler slot leaked" + ); + assert!(self.platform.all_handed_out_zero(), "unscrubbed frame"); + assert_eq!( + self.platform.kernel_snapshot(), + self.kernel_before, + "kernel tables modified" + ); + } +} + +fn verifier(a: &TestAnchors) -> ConfiguredArtifactVerifier<'_, TestAnchors, Ed25519Verifier> { + ConfiguredArtifactVerifier::new(a, Ed25519Verifier) +} + +fn assert_rejected(report: &CandidateReport, stage: CandidateState, error: LoadError) { + assert_eq!(report.decision, Decision::Rejected, "{report:?}"); + assert_eq!(report.failed_stage, Some(stage), "{report:?}"); + assert_eq!(report.error, Some(error), "{report:?}"); +} + +const MAPS: [KernelMap; 3] = [KernelMap::Block1G, KernelMap::Blocks2M, KernelMap::Pages4K]; + +// --------------------------------------------------------------------------- +// 1. Happy path +// --------------------------------------------------------------------------- + +#[test] +fn admitted_task_sees_exact_entry_state_and_is_fully_reclaimed() { + for map in MAPS { + let s = spec(); + let bytes = pack_signed(&s, &TEST_SEED); + let expected_id = parse_and_identify(&bytes).unwrap().artifact_id; + let a = anchors(); + let v = verifier(&a); + let pol = policy(); + let mut run = Run::new(map); + let mut seen = false; + let mut executor = exec(|ctx: TaskContext<'_>, p: &mut MockPlatform| { + seen = true; + let base = 1u64 << 39; + let code_base = base + PAGE_U64; + let data_base = base + 3 * PAGE_U64; + let stack_top = base + 5 * PAGE_U64 + PAGE_U64; + assert_eq!(ctx.entry_pc, code_base + 4); + assert_eq!(ctx.args[0], stack_top - 8, "handle array VA"); + assert_eq!(ctx.args[1], 1); + assert_eq!(ctx.args[2], data_base); + assert_eq!(ctx.args[3], 4096); + assert_eq!(ctx.stack_pointer % 16, 0); + assert!(ctx.stack_pointer <= ctx.args[0]); + assert!(ctx.args[0] - ctx.stack_pointer < 16); + assert_eq!(ctx.budget.syscalls, 16); + assert_eq!(ctx.grants.len(), 1); + let handle = Handle::new(0, 1).unwrap(); + assert_eq!(ctx.capabilities.lookup(handle, Rights::READ), Ok(0)); + assert_eq!( + ctx.capabilities.lookup(handle, Rights::WRITE), + Err(CapError::MissingRights) + ); + let (pa, _) = effective(p, ctx.root, ctx.args[0]).expect("handle array mapped"); + let raw = p.bytes(pa + (ctx.args[0] & 0xfff), 8); + assert_eq!( + u64::from_le_bytes(raw.try_into().unwrap()), + handle.to_raw(), + "handle array holds the installed handle" + ); + outcome(ExecutionStatus::Exited(0)) + }); + let report = run.candidate(&bytes, &v, &pol, &mut executor, 7); + assert!(seen, "executor never ran ({map:?})"); + assert_eq!(report.decision, Decision::Admitted, "{report:?}"); + assert_eq!(report.error, None); + assert_eq!(report.artifact_id, Some(expected_id)); + assert_eq!(report.trust_tier, Some(TrustTier::Seed0bQualification)); + assert!(report.byte_chain); + assert!(report.wx_enforced); + assert_eq!(report.caps_installed, 1); + assert_eq!(report.caps_live_after, 0); + assert_eq!(report.outcome.status, ExecutionStatus::Exited(0)); + assert_eq!(report.code_base, (1u64 << 39) + PAGE_U64); + assert_eq!(report.code_end, report.code_base + PAGE_U64); + // 3 content + 4 window tables + 3 shadow tables. + assert_eq!(report.frames_reserved, 10, "{map:?}"); + run.assert_clean(&report); + } +} + +// --------------------------------------------------------------------------- +// 2. Sealed address space, inspected while the task "runs" +// --------------------------------------------------------------------------- + +#[test] +fn sealed_address_space_is_wx_with_read_only_code_alias() { + for map in MAPS { + let mut s = spec(); + s.res.code_pages = 2; + s.res.data_pages = 2; + s.res.stack_pages = 2; + s.code = code_words(1100); // 4400 bytes: spans two code pages + s.data = (0..5000u32).map(|i| (i * 7) as u8).collect(); + let bytes = pack_signed(&s, &TEST_SEED); + let a = anchors(); + let v = verifier(&a); + let pol = policy(); + let mut run = Run::new(map); + let pages = bytes.len().div_ceil(PAGE); + let staged = run.platform.reserve_contiguous(pages).unwrap(); + run.platform + .bytes_mut(staged, bytes.len()) + .copy_from_slice(&bytes); + let mut task = load( + &mut run.platform, + staged, + bytes.len(), + &v, + &pol, + &mut run.scheduler, + 9, + ) + .expect("admitted"); + run.platform.bytes_mut(staged, pages * PAGE).fill(0); + assert!(run.platform.release_contiguous(staged, pages)); + assert_eq!(task.state, CandidateState::Admitted); + + let p = &run.platform; + let space = task.address_space; + assert!(audit_wx(p, &space), "{map:?}"); + let layout = space.layout; + let root = space.root; + + // User window: guard | code RX | guard | data RW NX | guard | stack RW NX | guard. + let base = layout.base; + let kinds: Vec<&str> = (0..10) + .map(|i| match effective(p, root, base + i * PAGE_U64) { + None => "guard", + Some((_, attrs)) => { + let el0 = attrs & AP_EL0 != 0; + let ro = attrs & AP_READ_ONLY != 0; + let user_x = attrs & UXN == 0; + let kernel_x = attrs & PXN == 0; + assert!(el0, "user window page not EL0"); + assert!(!kernel_x, "user page executable at EL1"); + match (ro, user_x) { + (true, true) => "rx", + (false, false) => "rw", + _ => "bad", + } + } + }) + .collect(); + assert_eq!( + kinds, + ["guard", "rx", "rx", "guard", "rw", "rw", "guard", "rw", "rw", "guard"] + ); + for i in 10..512 { + assert!(effective(p, root, base + i * PAGE_U64).is_none()); + } + + // Code aliases: read-only, never executable; other pages untouched. + let code_pas: Vec<u64> = space.code_frames().iter().map(|f| f.0 as u64).collect(); + for pa in &code_pas { + let (out, attrs) = effective(p, root, *pa).unwrap(); + assert_eq!(out, *pa); + assert_ne!(attrs & AP_READ_ONLY, 0, "code alias writable ({map:?})"); + assert_ne!(attrs & PXN, 0); + assert_ne!(attrs & UXN, 0); + assert_eq!(attrs & AP_EL0, 0, "code alias EL0-accessible"); + // Kernel root still has the original RW alias (used only after exit). + let (_, kattrs) = effective(p, ARENA_BASE, *pa).unwrap(); + assert_eq!(kattrs & AP_READ_ONLY, 0); + } + let region = code_pas[0] & !((1 << 21) - 1); + for page in (region..region + (1 << 21)).step_by(PAGE) { + if code_pas.contains(&page) || page >= ARENA_BASE + (ARENA_FRAMES * PAGE) as u64 { + continue; + } + assert_eq!( + effective(p, root, page), + effective(p, ARENA_BASE, page), + "neighbour {page:#x} changed ({map:?})" + ); + } + for frame in &space.frames()[layout.code_pages..] { + let pa = frame.0 as u64; + assert_eq!(effective(p, root, pa), effective(p, ARENA_BASE, pa)); + } + // Mappings outside RAM (kernel L1[0]) are shared, not copied. + assert_eq!(effective(p, root, 0x1000), effective(p, ARENA_BASE, 0x1000)); + + // Exact bytes, zero tails, zero stack (except the handle array). + let read_va = |va: u64, len: usize| -> Vec<u8> { + (0..len as u64) + .map(|i| { + let (pa, _) = effective(p, root, va + i).unwrap(); + p.bytes(pa + ((va + i) & 0xfff), 1)[0] + }) + .collect() + }; + assert_eq!(read_va(layout.code_base(), s.code.len()), s.code); + assert!(read_va( + layout.code_base() + s.code.len() as u64, + 2 * PAGE - s.code.len() + ) + .iter() + .all(|b| *b == 0)); + assert_eq!(read_va(layout.data_base(), s.data.len()), s.data); + assert!(read_va( + layout.data_base() + s.data.len() as u64, + 2 * PAGE - s.data.len() + ) + .iter() + .all(|b| *b == 0)); + let stack = read_va(layout.stack_base(), 2 * PAGE); + assert!(stack[..2 * PAGE - 8].iter().all(|b| *b == 0)); + assert_eq!( + u64::from_le_bytes(stack[2 * PAGE - 8..].try_into().unwrap()), + task.handles[0].unwrap().to_raw() + ); + assert_eq!(code_digest(p, &space), task.code_digest); + + let outcome = run_task( + &mut task, + &mut run.platform, + &mut run.scheduler, + &mut exits_zero(), + ); + assert_eq!(outcome.status, ExecutionStatus::Exited(0)); + let teardown = destroy(task, &mut run.platform, &mut run.scheduler); + assert_eq!( + teardown, + Teardown { + executed_bytes_match: true, + caps_live_after: 0, + released: true, + } + ); + assert_eq!(run.platform.free_frames(), run.free_before); + assert!(run.platform.all_handed_out_zero()); + assert_eq!(run.platform.kernel_snapshot(), run.kernel_before); + } +} + +#[test] +fn audit_rejects_writable_code_and_writable_alias() { + let bytes = pack_signed(&spec(), &TEST_SEED); + let a = anchors(); + let v = verifier(&a); + let pol = policy(); + let mut run = Run::new(KernelMap::Blocks2M); + let pages = bytes.len().div_ceil(PAGE); + let staged = run.platform.reserve_contiguous(pages).unwrap(); + run.platform + .bytes_mut(staged, bytes.len()) + .copy_from_slice(&bytes); + let task = load( + &mut run.platform, + staged, + bytes.len(), + &v, + &pol, + &mut run.scheduler, + 3, + ) + .unwrap(); + let space = task.address_space; + assert!(audit_wx(&run.platform, &space)); + let l3 = space.frames()[space.layout.content_frames() + 3].0 as u64; + + // Code leaf made writable (RWX at EL0). + let good = run.platform.get(l3, 1); + run.platform.put(l3, 1, good & !AP_READ_ONLY); + assert!(!audit_wx(&run.platform, &space)); + run.platform.put(l3, 1, good); + // Data leaf made executable. + let data = run.platform.get(l3, 3); + run.platform.put(l3, 3, data & !UXN); + assert!(!audit_wx(&run.platform, &space)); + run.platform.put(l3, 3, data); + // A stray extra mapping in a guard slot. + run.platform.put(l3, 2, data); + assert!(!audit_wx(&run.platform, &space)); + run.platform.put(l3, 2, 0); + assert!(audit_wx(&run.platform, &space)); + // Code frame alias made writable again in the task root. + let pa = space.code_frames()[0].0 as u64; + let shadow_l3 = space.shadow_frames()[2].0 as u64; + let index = table_index(pa, 3); + let alias = run.platform.get(shadow_l3, index); + assert_ne!(alias & AP_READ_ONLY, 0); + run.platform.put(shadow_l3, index, alias & !AP_READ_ONLY); + assert!(!audit_wx(&run.platform, &space)); + run.platform.put(shadow_l3, index, alias); + assert!(audit_wx(&run.platform, &space)); + + let teardown = destroy(task, &mut run.platform, &mut run.scheduler); + assert!(teardown.released); + run.platform.bytes_mut(staged, pages * PAGE).fill(0); + assert!(run.platform.release_contiguous(staged, pages)); + assert_eq!(run.platform.free_frames(), run.free_before); +} + +// --------------------------------------------------------------------------- +// 3. Rejections +// --------------------------------------------------------------------------- + +fn reject_case( + map: KernelMap, + bytes: &[u8], + a: &TestAnchors, + pol: &AdmissionPolicy, + setup: impl FnOnce(&mut Run), +) -> (CandidateReport, Run) { + let mut run = Run::new(map); + setup(&mut run); + let mut ran = false; + let mut executor = exec(|_, _| { + ran = true; + outcome(ExecutionStatus::Exited(0)) + }); + let report = run.candidate(bytes, &verifier(a), pol, &mut executor, 11); + assert!(!ran, "rejected candidate executed"); + (report, run) +} + +#[test] +fn tampered_payload_is_rejected_before_any_task_frame() { + let mut bytes = pack_signed(&spec(), &TEST_SEED); + let at = payload_offset(&bytes); + bytes[at] ^= 1; + let (report, run) = reject_case(KernelMap::Block1G, &bytes, &anchors(), &policy(), |_| {}); + assert_rejected( + &report, + CandidateState::Verified, + LoadError::Artifact(ArtifactError::BadSignature), + ); + assert_eq!( + run.platform.batch_calls, 0, + "task frames reserved before verification" + ); + run.assert_clean(&report); +} + +#[test] +fn unknown_signer_rejected_by_anchors_and_by_policy() { + let bytes = pack_signed(&spec(), &OTHER_SEED); + let (report, run) = reject_case(KernelMap::Block1G, &bytes, &anchors(), &policy(), |_| {}); + assert_rejected( + &report, + CandidateState::Verified, + LoadError::Artifact(ArtifactError::UntrustedSigner), + ); + run.assert_clean(&report); + + // Anchors know the key but local policy does not allow it. + let bytes = pack_signed(&spec(), &TEST_SEED); + let empty_policy = boot_policy(&[]).unwrap(); + let (report, run) = reject_case( + KernelMap::Block1G, + &bytes, + &anchors(), + &empty_policy, + |_| {}, + ); + assert_rejected( + &report, + CandidateState::Authorized, + LoadError::Artifact(ArtifactError::UntrustedSigner), + ); + run.assert_clean(&report); +} + +#[test] +fn ipc_request_exceeds_policy_and_is_rejected() { + let mut s = spec(); + s.res.ipc_messages = 1; + let bytes = pack_signed(&s, &TEST_SEED); + let (report, run) = reject_case(KernelMap::Block1G, &bytes, &anchors(), &policy(), |_| {}); + assert_rejected( + &report, + CandidateState::Authorized, + LoadError::Artifact(ArtifactError::ResourceLimit), + ); + assert_eq!(run.platform.batch_calls, 0); + run.assert_clean(&report); +} + +#[test] +fn empty_and_oversized_inputs_are_refused_before_staging() { + for bytes in [Vec::new(), vec![0u8; (MAX_STAGING_FRAMES + 1) * PAGE]] { + let (report, run) = reject_case(KernelMap::Block1G, &bytes, &anchors(), &policy(), |_| {}); + assert_rejected( + &report, + CandidateState::Received, + LoadError::StagingTooLarge, + ); + assert!(run.platform.handed_out.is_empty()); + run.assert_clean(&report); + } + // Exactly MAX_STAGING_FRAMES pages is staged (then fails parsing). + let bytes = vec![0u8; MAX_STAGING_FRAMES * PAGE]; + let (report, run) = reject_case(KernelMap::Block1G, &bytes, &anchors(), &policy(), |_| {}); + assert_rejected( + &report, + CandidateState::Verified, + LoadError::Artifact(ArtifactError::BadMagic), + ); + run.assert_clean(&report); +} + +#[test] +fn staging_reservation_failure() { + let bytes = pack_signed(&spec(), &TEST_SEED); + let (report, run) = reject_case(KernelMap::Block1G, &bytes, &anchors(), &policy(), |r| { + r.platform.fail_contiguous = true; + }); + assert_rejected(&report, CandidateState::Staged, LoadError::NoFrames); + run.assert_clean(&report); +} + +#[test] +fn main_and_shadow_batch_failures_roll_back() { + for nth in [1, 2] { + for map in MAPS { + let bytes = pack_signed(&spec(), &TEST_SEED); + let (report, run) = reject_case(map, &bytes, &anchors(), &policy(), |r| { + r.platform.fail_batch_nth = Some(nth); + }); + assert_rejected(&report, CandidateState::Reserved, LoadError::NoFrames); + assert_eq!(run.platform.batch_calls, nth); + run.assert_clean(&report); + } + } +} + +#[test] +fn full_scheduler_fails_closed_at_admission() { + // With every loaded-task slot taken, the resource snapshot offers no + // pages, so admission refuses before anything is reserved. + let bytes = pack_signed(&spec(), &TEST_SEED); + let (report, run) = reject_case(KernelMap::Block1G, &bytes, &anchors(), &policy(), |r| { + for id in 0..LOADED_TASK_SLOTS as u32 { + r.scheduler + .enqueue(1000 + id, TaskPriority::Normal) + .unwrap(); + } + }); + assert_rejected( + &report, + CandidateState::Authorized, + LoadError::Artifact(ArtifactError::ResourceLimit), + ); + assert_eq!(run.platform.free_frames(), run.free_before); + assert_eq!(run.scheduler.queue_len(0), Some(LOADED_TASK_SLOTS)); + assert!(run.platform.all_handed_out_zero()); +} + +#[test] +fn scheduler_refusal_at_reservation_rolls_back() { + // A duplicate task id passes admission but the scheduler refuses the slot. + let bytes = pack_signed(&spec(), &TEST_SEED); + let (report, run) = reject_case(KernelMap::Block1G, &bytes, &anchors(), &policy(), |r| { + r.scheduler.enqueue(11, TaskPriority::Normal).unwrap(); + }); + assert_rejected(&report, CandidateState::Reserved, LoadError::SchedulerFull); + assert_eq!(run.platform.batch_calls, 0); + assert_eq!(run.platform.free_frames(), run.free_before); + // The pre-existing entry is untouched; nothing of ours remains. + assert_eq!(run.scheduler.queue_len(0), Some(1)); + assert!(run.platform.all_handed_out_zero()); +} + +#[test] +fn kernel_root_without_free_window_is_a_mapping_failure() { + let bytes = pack_signed(&spec(), &TEST_SEED); + let (report, run) = reject_case(KernelMap::Block1G, &bytes, &anchors(), &policy(), |r| { + for index in 1..256 { + r.platform.put(ARENA_BASE, index, 0x2); + } + r.kernel_before = r.platform.kernel_snapshot(); + }); + assert_rejected(&report, CandidateState::Reserved, LoadError::Mapping); + run.assert_clean(&report); +} + +#[test] +fn corrupted_mapped_bytes_fail_the_read_back_hash() { + for map in MAPS { + // Copy #1 is the kernel L0; #2 the first code page; #3 the data page. + for k in [2, 3] { + let bytes = pack_signed(&spec(), &TEST_SEED); + let (report, run) = reject_case(map, &bytes, &anchors(), &policy(), |r| { + r.platform.corrupt_after_copy = Some(k); + }); + assert_rejected( + &report, + CandidateState::Hashed, + LoadError::MappedDigestMismatch, + ); + run.assert_clean(&report); + } + } +} + +// --------------------------------------------------------------------------- +// 4. Executed-bytes check +// --------------------------------------------------------------------------- + +#[test] +fn code_modified_during_execution_breaks_the_byte_chain() { + let bytes = pack_signed(&spec(), &TEST_SEED); + let a = anchors(); + let mut run = Run::new(KernelMap::Pages4K); + let mut executor = exec(|ctx: TaskContext<'_>, p: &mut MockPlatform| { + // Simulate a W^X hole: something writes the code frame. + 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, 5); + assert_eq!(report.decision, Decision::Admitted); + assert!(!report.byte_chain); + assert_eq!(report.error, Some(LoadError::ExecutedDigestMismatch)); + let mut line = String::new(); + write_candidate_line(&mut line, "X.AIEN", &report); + assert!(line.contains(" bytes=mismatch "), "{line}"); + run.assert_clean(&report); +} + +// --------------------------------------------------------------------------- +// 5. Granted ⊆ requested +// --------------------------------------------------------------------------- + +fn installed_rights(caps: Vec<CapabilityRequest>) -> (CandidateReport, Vec<(bool, bool)>) { + let mut s = spec(); + s.res.max_capabilities = caps.len() as u16; + s.caps = caps; + let bytes = pack_signed(&s, &TEST_SEED); + let a = anchors(); + let mut run = Run::new(KernelMap::Block1G); + let mut rights = Vec::new(); + let mut executor = exec(|ctx: TaskContext<'_>, _p: &mut MockPlatform| { + for index in 0..ctx.args[1] as u32 { + let h = Handle::new(index, 1).unwrap(); + rights.push(( + ctx.capabilities.lookup(h, Rights::READ).is_ok(), + ctx.capabilities.lookup(h, Rights::WRITE).is_ok(), + )); + } + assert_eq!(ctx.grants.len() as u64, ctx.args[1]); + outcome(ExecutionStatus::Exited(0)) + }); + let report = run.candidate(&bytes, &verifier(&a), &policy(), &mut executor, 21); + run.assert_clean(&report); + (report, rights) +} + +#[test] +fn grants_never_exceed_requests_or_policy() { + let (report, rights) = + installed_rights(vec![seed_read(RIGHT_READ | RIGHT_WRITE, SEED_OBJECT_ID)]); + assert_eq!(report.decision, Decision::Admitted); + assert_eq!(report.caps_installed, 1); + assert_eq!( + rights, + [(true, false)], + "READ|WRITE request must reduce to READ" + ); + + let (report, rights) = installed_rights(vec![seed_read(RIGHT_WRITE, SEED_OBJECT_ID)]); + assert_eq!(report.decision, Decision::Admitted); + assert_eq!(report.caps_installed, 0); + assert!(rights.is_empty()); + + let (report, rights) = installed_rights(vec![seed_read(RIGHT_READ, SEED_OBJECT_ID + 1)]); + assert_eq!(report.decision, Decision::Admitted); + assert_eq!(report.caps_installed, 0, "resource absent from policy"); + assert!(rights.is_empty()); + + let channel = CapabilityRequest { + resource_kind: RESOURCE_KIND_CHANNEL, + resource_id: 1, + rights: RIGHT_READ, + bounds_kind: 2, + max_operations: 1, + max_bytes: 8, + byte_offset: 0, + byte_length: 0, + }; + let (report, _) = installed_rights(vec![channel, seed_read(RIGHT_READ, SEED_OBJECT_ID)]); + assert_eq!(report.caps_installed, 1, "only the policy-allowed object"); +} + +// --------------------------------------------------------------------------- +// 6. Envelope extremes and layout bounds +// --------------------------------------------------------------------------- + +#[test] +fn largest_envelope_loads_in_one_l3_table() { + for map in MAPS { + let mut s = spec(); + s.res.code_pages = 64; + s.res.data_pages = 64; + s.res.stack_pages = 16; + s.code = code_words(64 * 1024); // exactly 64 pages + s.data = vec![0xa5; 64 * PAGE]; + let bytes = pack_signed(&s, &TEST_SEED); + let a = anchors(); + let mut run = Run::new(map); + let mut executor = exec(|ctx: TaskContext<'_>, p: &mut MockPlatform| { + let base = 1u64 << 39; + // 1 + 64 + 1 + 64 + 1 + 16 + 1 = 148 window pages. + assert!(effective(p, ctx.root, base + 147 * PAGE_U64).is_none()); + assert!(effective(p, ctx.root, base + 146 * PAGE_U64).is_some()); + assert!(effective(p, ctx.root, base + 64 * PAGE_U64).is_some()); + assert!(effective(p, ctx.root, base + 65 * PAGE_U64).is_none()); + outcome(ExecutionStatus::Exited(0)) + }); + let report = run.candidate(&bytes, &verifier(&a), &policy(), &mut executor, 31); + assert_eq!(report.decision, Decision::Admitted, "{report:?}"); + assert!(report.byte_chain); + assert!(report.frames_reserved >= 148 + 3); + run.assert_clean(&report); + } +} + +#[test] +fn task_layout_rejects_every_bound_violation() { + let res = |c: u32, d: u32, st: u32| ResourceEnvelope { + code_pages: c, + data_pages: d, + stack_pages: st, + max_capabilities: 0, + ipc_messages: 0, + ipc_bytes: 0, + cpu_ticks: 1, + elapsed_ticks: 1, + syscall_count: 1, + }; + let ok = |w, r: &ResourceEnvelope, code, data, mem, entry| { + TaskLayout::new(w, r, code, data, mem, entry) + }; + let limit = Err(LoadError::Artifact(ArtifactError::ResourceLimit)); + let r = res(1, 1, 1); + assert!(ok(1, &r, 8, 4, 4096, 4).is_ok()); + assert!(ok(255, &r, 8, 4, 4096, 0).is_ok()); + assert!(ok(1, &res(64, 64, 16), 64 * PAGE, 1, 64 * PAGE, 0).is_ok()); + assert_eq!(ok(0, &r, 8, 4, 4096, 0), limit); + assert_eq!(ok(256, &r, 8, 4, 4096, 0), limit); + for bad in [ + res(0, 1, 1), + res(65, 1, 1), + res(1, 0, 1), + res(1, 65, 1), + res(1, 1, 0), + res(1, 1, 17), + ] { + assert_eq!(ok(1, &bad, 8, 4, 4096, 0), limit, "{bad:?}"); + } + assert_eq!(ok(1, &r, 0, 4, 4096, 0), limit, "empty code"); + assert_eq!( + ok(1, &r, PAGE + 1, 4, 4096, 0), + limit, + "code overflows pages" + ); + assert_eq!(ok(1, &r, 8, 5, 4, 0), limit, "data longer than memory"); + assert_eq!( + ok(1, &r, 8, 4, PAGE + 1, 0), + limit, + "data memory overflows pages" + ); + assert_eq!(ok(1, &r, 8, 4, 4096, 2), limit, "unaligned entry"); + assert_eq!(ok(1, &r, 8, 4, 4096, 8), limit, "entry at code end"); + assert_eq!(ok(1, &r, 8, 4, 4096, 12), limit, "entry past code"); +} + +// --------------------------------------------------------------------------- +// 7. Report lines +// --------------------------------------------------------------------------- + +fn admitted_report(status: ExecutionStatus) -> CandidateReport { + let mut r = empty_report(100); + r.decision = Decision::Admitted; + r.artifact_id = Some(ArtifactId([0xab; 32])); + r.trust_tier = Some(TrustTier::Seed0bQualification); + r.frames_reserved = 10; + r.caps_installed = 1; + r.byte_chain = true; + r.wx_enforced = true; + r.outcome = TaskOutcome { + status, + syscalls: 3, + object_reads_ok: 2, + denials: 1, + elapsed_ticks: 10, + }; + r.code_base = 0x80_0000_1000; + r.code_end = 0x80_0000_2000; + r +} + +fn line(r: &CandidateReport) -> String { + let mut s = String::new(); + write_candidate_line(&mut s, "P25EXEC.AIEN", r); + s +} + +#[test] +fn candidate_lines_are_stable() { + let tail = "bytes=identified=verified=admitted=mapped=executed wx=enforced caps=1 revoked=yes reclaimed=yes frames=10 syscalls=3 reads=2 denials=1\n"; + let head = "artifact: P25EXEC.AIEN admitted id=abababababababab tier=seed0b-test exec="; + assert_eq!( + line(&admitted_report(ExecutionStatus::Exited(0))), + std::format!("{head}exited:0x0 {tail}") + ); + assert_eq!( + line(&admitted_report(ExecutionStatus::Timeout)), + std::format!("{head}timeout {tail}") + ); + // EC 0x24 (EL0 data abort), IL, WnR, permission fault level 3. + let write_abort = 0x9200_004f; + let code_write = ExecutionStatus::Fault { + esr: write_abort, + far: 0x80_0000_1008, + elr: 0x80_0000_1004, + }; + assert_eq!( + line(&admitted_report(code_write)), + std::format!("{head}fault:code-write {tail}") + ); + let outside = ExecutionStatus::Fault { + esr: write_abort, + far: 0x80_0000_3008, + elr: 0x80_0000_1004, + }; + assert_eq!( + line(&admitted_report(outside)), + std::format!("{head}fault:other {tail}") + ); + let read_abort = ExecutionStatus::Fault { + esr: 0x9200_000f, + far: 0x80_0000_1008, + elr: 0x80_0000_1004, + }; + assert_eq!( + line(&admitted_report(read_abort)), + std::format!("{head}fault:other {tail}") + ); + assert_eq!( + line(&admitted_report(ExecutionStatus::BadSyscall(9))), + std::format!("{head}bad-syscall:9 {tail}") + ); + assert_eq!( + line(&admitted_report(ExecutionStatus::ResourceOverrun)), + std::format!("{head}resource-overrun {tail}") + ); + + let mut rejected = empty_report(100); + rejected.failed_stage = Some(CandidateState::Verified); + rejected.error = Some(LoadError::Artifact(ArtifactError::BadSignature)); + assert_eq!( + line(&rejected), + "artifact: P25EXEC.AIEN rejected stage=verified reason=BadSignature reclaimed=yes\n" + ); + rejected.failed_stage = Some(CandidateState::Reserved); + rejected.error = Some(LoadError::NoFrames); + rejected.frames_free_after = 99; + assert_eq!( + line(&rejected), + "artifact: P25EXEC.AIEN rejected stage=reserved reason=NoFrames reclaimed=no\n" + ); +} + +// --------------------------------------------------------------------------- +// 8. Sequential candidates +// --------------------------------------------------------------------------- + +#[test] +fn sequential_candidates_reuse_resources_cleanly() { + let a = anchors(); + let pol = policy(); + let mut run = Run::new(KernelMap::Blocks2M); + let mut table_ids = Vec::new(); + for task_id in 1..=3u32 { + let mut s = spec(); + s.data.push(task_id as u8); // distinct artifacts + let bytes = pack_signed(&s, &TEST_SEED); + let mut executor = exec(|ctx: TaskContext<'_>, _p: &mut MockPlatform| { + table_ids.push(ctx.capabilities.id()); + outcome(ExecutionStatus::Exited(u64::from(task_id))) + }); + let report = run.candidate(&bytes, &verifier(&a), &pol, &mut executor, task_id); + assert_eq!(report.decision, Decision::Admitted); + assert_eq!( + report.outcome.status, + ExecutionStatus::Exited(u64::from(task_id)) + ); + run.assert_clean(&report); + } + table_ids.sort_unstable(); + table_ids.dedup(); + assert_eq!(table_ids.len(), 3, "task principals must be distinct"); +} diff --git a/crates/aienos-kernel/src/boot.rs b/crates/aienos-kernel/src/boot.rs index 5ec374a0..1994e872 100644 --- a/crates/aienos-kernel/src/boot.rs +++ b/crates/aienos-kernel/src/boot.rs @@ -7,7 +7,7 @@ use crate::arch::aarch64::{ counter_ticks, current_el, disable_interrupts, dsb, halt, isb, midr_el1, midr_part, EarlyUart, SPARK_16550_UART_BASE, }; -use crate::mem::{BitmapFrameAllocator, PhysAddr, PAGE_SIZE}; +use crate::mem::{BitmapFrameAllocator, FrameBatch, PhysAddr, PAGE_SIZE}; use crate::report::ReportBuf; use crate::sync::spinlock::SpinLock; use core::fmt::Write; @@ -22,6 +22,49 @@ pub fn allocate_early_frame() -> Option<PhysAddr> { EARLY_ALLOCATOR.lock().as_mut()?.allocate_frame() } +/// Atomically reserve every frame required by a candidate while holding the +/// early allocator lock once. The loader computes and checks the count before +/// calling; an allocation failure leaves the allocator unchanged. +pub fn reserve_early_frames(count: usize) -> Option<FrameBatch> { + EARLY_ALLOCATOR.lock().as_mut()?.allocate_batch(count) +} + +/// Release a prior candidate reservation after teardown or construction +/// failure. Capability revocation is the caller's responsibility and must +/// happen before this function is called. +pub fn release_early_frames(batch: FrameBatch) -> bool { + EARLY_ALLOCATOR + .lock() + .as_mut() + .is_some_and(|allocator| allocator.release_batch(batch)) +} + +/// Reserve a physically contiguous run of early frames (artifact staging). +pub fn reserve_early_contiguous(count: usize) -> Option<PhysAddr> { + EARLY_ALLOCATOR.lock().as_mut()?.allocate_contiguous(count) +} + +/// Release a run obtained from [`reserve_early_contiguous`]. +pub fn release_early_contiguous(start: PhysAddr, count: usize) -> bool { + let mut guard = EARLY_ALLOCATOR.lock(); + let Some(allocator) = guard.as_mut() else { + return false; + }; + let mut complete = true; + for index in 0..count { + complete &= allocator.deallocate_frame(start.offset(index * PAGE_SIZE)); + } + complete +} + +/// Free frames remaining in the early allocator (0 before initialisation). +pub fn early_free_frames() -> usize { + EARLY_ALLOCATOR + .lock() + .as_ref() + .map_or(0, |allocator| allocator.free_count()) +} + fn initialize_early_allocator(region: BootMemoryRegion) -> Option<(usize, PhysAddr)> { let mut allocator = EARLY_ALLOCATOR.lock(); if allocator.is_some() { diff --git a/crates/aienos-kernel/src/caps.rs b/crates/aienos-kernel/src/caps.rs index 44a44216..8fde38c6 100644 --- a/crates/aienos-kernel/src/caps.rs +++ b/crates/aienos-kernel/src/caps.rs @@ -89,6 +89,11 @@ impl<const N: usize> CapTable<N> { self.id } + /// Occupied slots, including tombstones kept for revocation. + pub fn live_count(&self) -> usize { + self.slots.iter().filter(|slot| slot.is_some()).count() + } + pub fn insert(&mut self, resource: u32, rights: Rights) -> Result<Handle, CapError> { self.allocate(resource, rights, None) } diff --git a/crates/aienos-kernel/src/fatal.rs b/crates/aienos-kernel/src/fatal.rs index 75cdf86a..f9fa7af2 100644 --- a/crates/aienos-kernel/src/fatal.rs +++ b/crates/aienos-kernel/src/fatal.rs @@ -254,8 +254,12 @@ mod vectors { "aienos_exception_vectors:", ".irp slot, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15", ".balign 128", + // Slot 5: IRQ at EL1h. Slot 9: IRQ from lower-EL AArch64 (EL0 tasks), + // which saves and restores the EL0 context through the same frame. ".if \\slot == 5", "b aienos_irq_trampoline", + ".elseif \\slot == 9", + "b aienos_irq_trampoline", ".elseif \\slot == 8", "b aienos_lower_el_sync_trampoline", ".else", diff --git a/crates/aienos-kernel/src/lib.rs b/crates/aienos-kernel/src/lib.rs index fe2569be..3acd1228 100644 --- a/crates/aienos-kernel/src/lib.rs +++ b/crates/aienos-kernel/src/lib.rs @@ -14,6 +14,7 @@ pub mod abi; pub mod acpi; pub mod admission; pub mod arch; +pub mod artifact_loader; pub mod block; pub mod boot; pub mod budget; @@ -40,6 +41,7 @@ pub mod shell; pub mod smmu; pub mod store; pub mod sync; +pub mod task_runtime; pub mod thread; pub mod timer; pub mod uefi; diff --git a/crates/aienos-kernel/src/mem/frame_allocator.rs b/crates/aienos-kernel/src/mem/frame_allocator.rs index ba85d7fa..c82caa9a 100644 --- a/crates/aienos-kernel/src/mem/frame_allocator.rs +++ b/crates/aienos-kernel/src/mem/frame_allocator.rs @@ -2,6 +2,37 @@ /// Physical Page Size on AArch64 (4 KiB standard). pub const PAGE_SIZE: usize = 4096; +pub const MAX_BATCH_FRAMES: usize = 160; + +/// Fixed-capacity ownership record for a reservation made under one allocator +/// lock. The addresses are explicit physical frame starts; no Rust layout is +/// persisted or passed across the firmware handoff. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FrameBatch { + frames: [PhysAddr; MAX_BATCH_FRAMES], + count: u16, +} + +impl FrameBatch { + pub const fn empty() -> Self { + Self { + frames: [PhysAddr(0); MAX_BATCH_FRAMES], + count: 0, + } + } + + pub fn as_slice(&self) -> &[PhysAddr] { + &self.frames[..usize::from(self.count)] + } + + pub const fn len(&self) -> usize { + self.count as usize + } + + pub const fn is_empty(&self) -> bool { + self.count == 0 + } +} /// Physical address wrapper. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -204,6 +235,39 @@ impl<const WORDS: usize> BitmapFrameAllocator<WORDS> { None } + + /// Reserve a bounded set of frames atomically from this allocator. On + /// exhaustion, every frame acquired by this call is returned before it + /// reports failure. + pub fn allocate_batch(&mut self, count: usize) -> Option<FrameBatch> { + if count == 0 || count > MAX_BATCH_FRAMES || count > self.free_count() { + return None; + } + let mut batch = FrameBatch::empty(); + for index in 0..count { + match self.allocate_frame() { + Some(frame) => { + batch.frames[index] = frame; + batch.count += 1; + } + None => { + self.release_batch(batch); + return None; + } + } + } + Some(batch) + } + + /// Return every frame owned by a prior batch. Invalid/double-freed entries + /// cause `false`; valid entries are still returned. + pub fn release_batch(&mut self, batch: FrameBatch) -> bool { + let mut complete = true; + for frame in batch.as_slice() { + complete &= self.deallocate_frame(*frame); + } + complete + } } #[cfg(test)] @@ -248,6 +312,26 @@ mod tests { assert!(alloc.deallocate_frame(frame)); } + #[test] + fn batch_reservation_is_bounded_and_released_as_a_unit() { + let mut alloc = BitmapFrameAllocator::<1>::new(PhysAddr(0x3000_0000), 8); + let batch = alloc.allocate_batch(6).unwrap(); + assert_eq!(batch.len(), 6); + assert_eq!(alloc.free_count(), 2); + assert!(alloc.release_batch(batch)); + assert_eq!(alloc.free_count(), 8); + assert!(alloc.allocate_batch(MAX_BATCH_FRAMES + 1).is_none()); + } + + #[test] + fn insufficient_batch_reservation_leaves_no_partial_allocations() { + let mut alloc = BitmapFrameAllocator::<1>::new(PhysAddr(0x4000_0000), 8); + assert!(alloc.allocate_frame().is_some()); + assert!(alloc.allocate_batch(8).is_none()); + assert_eq!(alloc.allocated_count(), 1); + assert_eq!(alloc.free_count(), 7); + } + #[test] #[should_panic(expected = "frame region exceeds bitmap capacity")] fn allocator_rejects_capacity_overflow() { diff --git a/crates/aienos-kernel/src/mem/mod.rs b/crates/aienos-kernel/src/mem/mod.rs index 13d78d30..ad778bf7 100644 --- a/crates/aienos-kernel/src/mem/mod.rs +++ b/crates/aienos-kernel/src/mem/mod.rs @@ -4,4 +4,6 @@ pub mod frame_allocator; pub mod map_plan; pub mod pagetable; -pub use frame_allocator::{BitmapFrameAllocator, Frame, PhysAddr, VirtAddr, PAGE_SIZE}; +pub use frame_allocator::{ + BitmapFrameAllocator, Frame, FrameBatch, PhysAddr, VirtAddr, MAX_BATCH_FRAMES, PAGE_SIZE, +}; diff --git a/crates/aienos-kernel/src/mem/pagetable.rs b/crates/aienos-kernel/src/mem/pagetable.rs index cc571378..edb71b46 100644 --- a/crates/aienos-kernel/src/mem/pagetable.rs +++ b/crates/aienos-kernel/src/mem/pagetable.rs @@ -391,6 +391,12 @@ fn indexes(va: u64) -> [usize; 4] { ] } +/// Level-3 page descriptor for `frame` with `flags` (same encoding as +/// [`PageTableBuilder::map`] leaves). +pub fn page_descriptor(frame: PhysAddr, flags: MapFlags) -> u64 { + (frame.0 as u64 & ADDRESS_MASK) | TABLE | leaf_attributes(flags) +} + fn leaf_attributes(flags: MapFlags) -> u64 { let attr = match flags.attribute { MemoryAttribute::NormalWriteBack => MAIR_NORMAL_WB, diff --git a/crates/aienos-kernel/src/task_runtime.rs b/crates/aienos-kernel/src/task_runtime.rs new file mode 100644 index 00000000..60191ec0 --- /dev/null +++ b/crates/aienos-kernel/src/task_runtime.rs @@ -0,0 +1,819 @@ +//! EL0 execution of one admitted, loaded artifact task. +//! +//! The loader (`artifact_loader`) builds the private address space and the +//! capability table; this module only enters EL0 with that state, dispatches +//! the task's syscalls against its own table, enforces the admitted CPU, +//! elapsed-time and syscall budgets, and returns control to the kernel on +//! exit, fault, timeout, bad syscall, or budget overrun. It has no parser, +//! signature, or policy responsibilities. +//! +//! Entry ABI (v0 loader, ABI v1 register forms): +//! - `x0` = VA of the task's handle array (u64 register-form handles, in +//! grant order) at the top of its stack; `x1` = handle count; +//! `x2` = data section base VA; `x3` = admitted data memory length. +//! - Every other general-purpose and SIMD/FP register is zero. +//! - `sp_el0` is 16-byte aligned below the handle array. +//! +//! Syscalls (`svc #0`, number in `x8`): +//! - `SYS_EXIT` (2): `x0` = exit code. Ends the task. +//! - `SYS_OBJECT_READ` (6): `x0` = handle, `x1` = byte offset (8-aligned). +//! Returns the u64 at that offset in `x0`, or `SYSCALL_DENIED`. +//! - `SYS_OBJECT_WRITE` (7): `x0` = handle, `x1` = offset, `x2` = value. +//! Returns 0 or `SYSCALL_DENIED`. +//! - Any other number terminates the task with `ExecutionStatus::BadSyscall`. +//! +//! A capability-table resource value is the task's grant index; kind, object +//! id, byte range and operation/byte budgets come from that grant. + +use crate::abi::{Handle, ResourceKind}; +use crate::admission::GrantedCapability; +use crate::caps::{CapTable, Rights}; +use core::sync::atomic::{AtomicBool, Ordering}; + +pub const SYS_EXIT: u64 = 2; +pub const SYS_OBJECT_READ: u64 = 6; +pub const SYS_OBJECT_WRITE: u64 = 7; +pub const SYSCALL_DENIED: u64 = u64::MAX; + +/// Capability slots per loaded task (== artifact v0 maximum). +pub const TASK_CAPABILITIES: usize = 16; + +/// Kernel-owned object reachable by SEED-0B qualification artifacts. +pub const SEED_OBJECT_ID: u32 = 1; +pub const SEED_OBJECT_WORDS: [u64; 4] = [ + 0xa1e0_5eed_0000_0001, + 0xa1e0_5eed_0000_0002, + 0xa1e0_5eed_0000_0003, + 0xa1e0_5eed_0000_0004, +]; +/// Size of the seed object in bytes. +pub const SEED_OBJECT_BYTES: u64 = (SEED_OBJECT_WORDS.len() * 8) as u64; + +/// ASID used for loaded artifact tasks (M3 demos use 1). +pub const TASK_ASID: u16 = 2; + +/// SPSR used when a termination returns control to EL1h with DAIF masked. +const SPSR_EL1H_MASKED: u64 = 0x3c5; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum ExecutionStatus { + NotRun, + Exited(u64), + Timeout, + Fault { esr: u64, far: u64, elr: u64 }, + BadSyscall(u64), + ResourceOverrun, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct TaskOutcome { + pub status: ExecutionStatus, + pub syscalls: u32, + pub object_reads_ok: u32, + pub denials: u32, + pub elapsed_ticks: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct TaskBudget { + pub cpu_ticks: u64, + pub elapsed_ticks: u64, + pub syscalls: u32, +} + +impl TaskBudget { + /// With one task on one core, CPU time never exceeds elapsed time, so the + /// tighter of the two budgets is the single wall-clock limit. + pub const fn tick_limit(self) -> u64 { + if self.cpu_ticks < self.elapsed_ticks { + self.cpu_ticks + } else { + self.elapsed_ticks + } + } +} + +/// Everything the runtime needs to run one task. Built by the loader. +pub struct TaskContext<'a> { + /// Physical address of the task's private L0 table. + pub root: u64, + pub entry_pc: u64, + pub stack_pointer: u64, + pub args: [u64; 4], + pub capabilities: &'a mut CapTable<TASK_CAPABILITIES>, + pub grants: &'a [Option<GrantedCapability>], + pub budget: TaskBudget, +} + +/// Counter ticks elapsed since `start`, correct across one counter wrap. +pub const fn elapsed_since(start: u64, now: u64) -> u64 { + now.wrapping_sub(start) +} + +/// True once `limit` ticks have passed since `start`. +pub const fn deadline_expired(start: u64, now: u64, limit: u64) -> bool { + elapsed_since(start, now) >= limit +} + +/// Consumption of one grant's operation and byte budgets. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct GrantUsage { + pub operations: u32, + pub bytes: u64, +} + +/// What the dispatcher must do with the trapped task after a syscall. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum SyscallAction { + /// Resume EL0 with this value in `x0`. + Return(u64), + /// End the task with this status. + Terminate(ExecutionStatus), +} + +/// Host-testable accounting and authority state of the running task. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct RuntimeState { + pub budget: TaskBudget, + pub start: u64, + pub syscalls: u32, + pub object_reads_ok: u32, + pub denials: u32, + pub usage: [GrantUsage; TASK_CAPABILITIES], + pub object: [u64; 4], +} + +impl RuntimeState { + pub const fn new(budget: TaskBudget, start: u64) -> Self { + Self { + budget, + start, + syscalls: 0, + object_reads_ok: 0, + denials: 0, + usage: [GrantUsage { + operations: 0, + bytes: 0, + }; TASK_CAPABILITIES], + object: SEED_OBJECT_WORDS, + } + } + + pub const fn expired(&self, now: u64) -> bool { + deadline_expired(self.start, now, self.budget.tick_limit()) + } + + /// Decide one `svc` from EL0. `imm` is the SVC immediate (ESR ISS[15:0]), + /// `number` is `x8`, `args` are `x0..x2`, `now` the counter value. + pub fn syscall( + &mut self, + caps: &CapTable<TASK_CAPABILITIES>, + grants: &[Option<GrantedCapability>], + imm: u16, + number: u64, + args: [u64; 3], + now: u64, + ) -> SyscallAction { + self.syscalls = self.syscalls.saturating_add(1); + if self.syscalls > self.budget.syscalls { + return SyscallAction::Terminate(ExecutionStatus::ResourceOverrun); + } + if self.expired(now) { + return SyscallAction::Terminate(ExecutionStatus::Timeout); + } + if imm != 0 { + return SyscallAction::Terminate(ExecutionStatus::BadSyscall(number)); + } + match number { + 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) => { + self.object_reads_ok = self.object_reads_ok.saturating_add(1); + SyscallAction::Return(self.object[word]) + } + None => self.deny(), + } + } + SYS_OBJECT_WRITE => { + match self.object_access(caps, grants, args[0], Rights::WRITE, args[1]) { + Some(word) => { + self.object[word] = args[2]; + SyscallAction::Return(0) + } + None => self.deny(), + } + } + other => SyscallAction::Terminate(ExecutionStatus::BadSyscall(other)), + } + } + + fn deny(&mut self) -> SyscallAction { + self.denials = self.denials.saturating_add(1); + SyscallAction::Return(SYSCALL_DENIED) + } + + /// Resolve and charge one 8-byte object access. Returns the object word + /// index, or `None` for any authority, bounds, or budget failure (in + /// which case nothing is charged). + fn object_access( + &mut self, + caps: &CapTable<TASK_CAPABILITIES>, + grants: &[Option<GrantedCapability>], + 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()?; + if grant.resource.kind() != ResourceKind::Object + || grant.resource.id() != SEED_OBJECT_ID + || !grant.rights.contains(right) + { + return None; + } + let end = offset.checked_add(8)?; + let grant_end = grant + .bounds + .byte_offset + .checked_add(grant.bounds.byte_length)?; + if offset & 7 != 0 + || offset < grant.bounds.byte_offset + || end > grant_end + || end > SEED_OBJECT_BYTES + { + return None; + } + let usage = self.usage.get_mut(index)?; + let bytes = usage.bytes.checked_add(8)?; + if usage.operations >= grant.bounds.max_operations || bytes > grant.bounds.max_bytes { + return None; + } + usage.operations += 1; + usage.bytes = bytes; + Some((offset / 8) as usize) + } + + fn outcome(&self, status: ExecutionStatus, now: u64) -> TaskOutcome { + TaskOutcome { + status, + syscalls: self.syscalls, + object_reads_ok: self.object_reads_ok, + denials: self.denials, + elapsed_ticks: elapsed_since(self.start, now), + } + } +} + +// ---- Active-task state (EL1, single core) --------------------------------- + +struct Active { + state: RuntimeState, + caps: *const CapTable<TASK_CAPABILITIES>, + grants: *const Option<GrantedCapability>, + grant_count: usize, + status: ExecutionStatus, +} + +static TASK_ACTIVE: AtomicBool = AtomicBool::new(false); +static mut ACTIVE: Option<Active> = None; + +/// True while a loaded task owns EL0. Exception dispatchers use this to route +/// EL0 exceptions here instead of the M3 demo paths. +pub fn is_active() -> bool { + TASK_ACTIVE.load(Ordering::Acquire) +} + +/// # Safety +/// EL1 only, single core; no other live reference to `ACTIVE`. +unsafe fn active() -> Option<&'static mut Active> { + unsafe { (*core::ptr::addr_of_mut!(ACTIVE)).as_mut() } +} + +fn terminate_frame(elr: &mut u64, spsr: &mut u64) { + *elr = task_resume_address(); + *spsr = SPSR_EL1H_MASKED; +} + +fn record_termination(active: &mut Active, status: ExecutionStatus) { + if active.status == ExecutionStatus::NotRun { + active.status = status; + } +} + +/// Lower-EL synchronous exception while a task is active. Called from +/// `user::aienos_lower_el_sync_dispatcher`. +/// +/// # Safety +/// Called only from the lower-EL synchronous trampoline with a complete frame. +pub unsafe fn dispatch_sync(frame: &mut crate::user::TrapFrame, esr: u64, far: u64) { + let Some(active) = (unsafe { active() }) else { + terminate_frame(&mut frame.elr_el1, &mut frame.spsr_el1); + return; + }; + let now = counter(); + let ec = (esr >> 26) & 0x3f; + let action = if ec == 0x15 { + let caps = unsafe { &*active.caps }; + let grants = unsafe { core::slice::from_raw_parts(active.grants, active.grant_count) }; + active.state.syscall( + caps, + grants, + (esr & 0xffff) as u16, + frame.x[8], + [frame.x[0], frame.x[1], frame.x[2]], + now, + ) + } else { + SyscallAction::Terminate(ExecutionStatus::Fault { + esr, + far, + elr: frame.elr_el1, + }) + }; + match action { + SyscallAction::Return(value) => frame.x[0] = value, + SyscallAction::Terminate(status) => { + record_termination(active, status); + terminate_frame(&mut frame.elr_el1, &mut frame.spsr_el1); + } + } +} + +/// Timer tick taken from EL0 while a task is active. Called from the IRQ +/// dispatcher after it acknowledged, re-armed and ended INTID 30. +/// +/// # Safety +/// Called only from the IRQ dispatcher with a complete frame. +pub unsafe fn on_timer_tick(frame: &mut crate::thread::TrapFrame) { + // Only an interrupted EL0 context (SPSR.M[3:0] == EL0t) is terminated. + if frame.spsr_el1 & 0xf != 0 { + return; + } + let Some(active) = (unsafe { active() }) else { + return; + }; + if active.state.expired(counter()) { + record_termination(active, ExecutionStatus::Timeout); + terminate_frame(&mut frame.elr_el1, &mut frame.spsr_el1); + } +} + +fn counter() -> u64 { + #[cfg(target_arch = "aarch64")] + { + crate::timer::TimerRegisters::counter(&crate::timer::Aarch64TimerRegisters) + } + #[cfg(not(target_arch = "aarch64"))] + { + 0 + } +} + +/// Enter EL0 with `task` and return when it ends for any reason. Restores +/// `kernel_root` in TTBR0, disables the timer and masks IRQs before returning. +/// +/// # Safety +/// EL1, single core, vectors installed, GIC/timer initialised; `task.root` +/// must be a complete private translation tree built by the loader. +pub unsafe fn run(task: TaskContext<'_>, kernel_root: usize) -> TaskOutcome { + #[cfg(target_arch = "aarch64")] + { + unsafe { run_inner(task, kernel_root) } + } + #[cfg(not(target_arch = "aarch64"))] + { + let _ = (task, kernel_root); + TaskOutcome { + status: ExecutionStatus::NotRun, + syscalls: 0, + object_reads_ok: 0, + denials: 0, + elapsed_ticks: 0, + } + } +} + +#[cfg(target_arch = "aarch64")] +unsafe fn run_inner(task: TaskContext<'_>, kernel_root: usize) -> TaskOutcome { + use crate::timer::{Aarch64TimerRegisters, TimerRegisters}; + + let grant_count = task.grants.len().min(TASK_CAPABILITIES); + let mut timer = Aarch64TimerRegisters; + let hz = timer.frequency(); + let interval = if hz >= 100 { hz / 100 } else { 625_000 }; + let start = timer.counter(); + unsafe { + *core::ptr::addr_of_mut!(ACTIVE) = Some(Active { + state: RuntimeState::new(task.budget, start), + caps: task.capabilities as *const _, + grants: task.grants.as_ptr(), + grant_count, + status: ExecutionStatus::NotRun, + }); + } + TASK_ACTIVE.store(true, Ordering::Release); + + unsafe { set_ttbr0(task.root | (u64::from(TASK_ASID) << 48)) }; + timer.set_compare(start.wrapping_add(interval)); + timer.enable_timer(true); + let args = task.args; + unsafe { aienos_task_enter(task.entry_pc, task.stack_pointer, args.as_ptr()) }; + // Back at EL1h with DAIF masked (SPSR 0x3c5 on every termination). + unsafe { core::arch::asm!("msr daifset, #2", "isb", options(nostack)) }; + timer.enable_timer(false); + unsafe { set_ttbr0(kernel_root as u64) }; + let now = timer.counter(); + + TASK_ACTIVE.store(false, Ordering::Release); + 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, + }, + } +} + +#[cfg(target_arch = "aarch64")] +unsafe fn set_ttbr0(value: u64) { + unsafe { + core::arch::asm!( + "dsb ish", + "msr ttbr0_el1, {0}", + "isb", + "tlbi vmalle1", + "dsb ish", + "isb", + in(reg) value, + options(nostack) + ); + } +} + +fn task_resume_address() -> u64 { + #[cfg(target_arch = "aarch64")] + { + core::ptr::addr_of!(aienos_task_resume) as u64 + } + #[cfg(not(target_arch = "aarch64"))] + { + 0 + } +} + +// Entry saves the callee-saved GPRs, d8-d15 and FPCR on SP_EL1, then enters +// EL0 with only x0-x3 carrying values: every other GPR, every SIMD/FP +// register, FPCR/FPSR and TPIDR_EL0 are zeroed so no kernel state leaks. +// Every termination returns to `aienos_task_resume` at EL1h with SP_EL1 back +// where entry left it, restoring the saved state. +#[cfg(target_arch = "aarch64")] +core::arch::global_asm!( + ".global aienos_task_enter", + ".global aienos_task_resume", + // x0 = entry, x1 = sp_el0, x2 = pointer to [u64; 4] initial x0..x3 + "aienos_task_enter:", + "sub sp, sp, #176", + "stp x19, x20, [sp, #0]", + "stp x21, x22, [sp, #16]", + "stp x23, x24, [sp, #32]", + "stp x25, x26, [sp, #48]", + "stp x27, x28, [sp, #64]", + "stp x29, x30, [sp, #80]", + "stp d8, d9, [sp, #96]", + "stp d10, d11, [sp, #112]", + "stp d12, d13, [sp, #128]", + "stp d14, d15, [sp, #144]", + "mrs x9, fpcr", + "str x9, [sp, #160]", + "msr sp_el0, x1", + "msr elr_el1, x0", + "msr spsr_el1, xzr", + "msr tpidr_el0, xzr", + "msr fpcr, xzr", + "msr fpsr, xzr", + "mov x9, x2", + "ldp x0, x1, [x9, #0]", + "ldp x2, x3, [x9, #16]", + "mov x4, xzr", + "mov x5, xzr", + "mov x6, xzr", + "mov x7, xzr", + "mov x8, xzr", + "mov x9, xzr", + "mov x10, xzr", + "mov x11, xzr", + "mov x12, xzr", + "mov x13, xzr", + "mov x14, xzr", + "mov x15, xzr", + "mov x16, xzr", + "mov x17, xzr", + "mov x18, xzr", + "mov x19, xzr", + "mov x20, xzr", + "mov x21, xzr", + "mov x22, xzr", + "mov x23, xzr", + "mov x24, xzr", + "mov x25, xzr", + "mov x26, xzr", + "mov x27, xzr", + "mov x28, xzr", + "mov x29, xzr", + "mov x30, xzr", + ".irp reg, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31", + "movi v\\reg\\().2d, #0", + ".endr", + "eret", + "aienos_task_resume:", + "ldr x9, [sp, #160]", + "msr fpcr, x9", + "msr fpsr, xzr", + "ldp d8, d9, [sp, #96]", + "ldp d10, d11, [sp, #112]", + "ldp d12, d13, [sp, #128]", + "ldp d14, d15, [sp, #144]", + "ldp x19, x20, [sp, #0]", + "ldp x21, x22, [sp, #16]", + "ldp x23, x24, [sp, #32]", + "ldp x25, x26, [sp, #48]", + "ldp x27, x28, [sp, #64]", + "ldp x29, x30, [sp, #80]", + "add sp, sp, #176", + "ret", +); + +#[cfg(target_arch = "aarch64")] +extern "C" { + fn aienos_task_enter(entry: u64, stack: u64, args: *const u64); + static aienos_task_resume: u8; +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::abi::ResourceId; + use aienos_artifact::capability::CapabilityRequest; + + const BUDGET: TaskBudget = TaskBudget { + cpu_ticks: 1_000, + elapsed_ticks: 2_000, + syscalls: 8, + }; + + fn grant(rights: Rights, offset: u64, length: u64, ops: u32, bytes: u64) -> GrantedCapability { + GrantedCapability { + resource: ResourceId::new(ResourceKind::Object, SEED_OBJECT_ID), + rights, + bounds: CapabilityRequest { + resource_kind: 3, + resource_id: SEED_OBJECT_ID, + rights: u32::from(rights.bits()), + bounds_kind: 1, + max_operations: ops, + max_bytes: bytes, + byte_offset: offset, + byte_length: length, + }, + } + } + + /// One READ grant installed at grant index 0; returns its raw handle. + fn setup( + g: GrantedCapability, + ) -> ( + CapTable<TASK_CAPABILITIES>, + [Option<GrantedCapability>; 1], + u64, + ) { + let mut caps = CapTable::new(0x5441_534b); + let handle = caps.insert(0, g.rights).unwrap(); + (caps, [Some(g)], handle.to_raw()) + } + + fn read( + state: &mut RuntimeState, + caps: &CapTable<TASK_CAPABILITIES>, + grants: &[Option<GrantedCapability>], + handle: u64, + offset: u64, + ) -> SyscallAction { + state.syscall(caps, grants, 0, SYS_OBJECT_READ, [handle, offset, 0], 10) + } + + #[test] + fn granted_read_returns_object_word_and_charges_budget() { + let (caps, grants, h) = setup(grant(Rights::READ, 0, 32, 4, 32)); + let mut s = RuntimeState::new(BUDGET, 0); + assert_eq!( + read(&mut s, &caps, &grants, h, 8), + SyscallAction::Return(SEED_OBJECT_WORDS[1]) + ); + assert_eq!(s.object_reads_ok, 1); + assert_eq!( + s.usage[0], + GrantUsage { + operations: 1, + bytes: 8 + } + ); + assert_eq!(s.denials, 0); + } + + #[test] + fn read_outside_grant_range_or_object_or_unaligned_is_denied() { + let (caps, grants, h) = setup(grant(Rights::READ, 8, 8, 8, 64)); + let mut s = RuntimeState::new(BUDGET, 0); + for offset in [0, 16, 12, 32, u64::MAX - 3] { + assert_eq!( + read(&mut s, &caps, &grants, h, offset), + SyscallAction::Return(SYSCALL_DENIED), + "offset {offset}" + ); + } + assert_eq!(s.denials, 5); + assert_eq!(s.usage[0], GrantUsage::default()); + // Range past the 32-byte object is denied even if the grant covers it. + let (caps, grants, h) = setup(grant(Rights::READ, 0, 64, 8, 64)); + let mut s = RuntimeState::new(BUDGET, 0); + assert_eq!( + read(&mut s, &caps, &grants, h, 32), + SyscallAction::Return(SYSCALL_DENIED) + ); + } + + #[test] + fn read_past_operation_budget_is_denied() { + let (caps, grants, h) = setup(grant(Rights::READ, 0, 32, 2, 32)); + let mut s = RuntimeState::new(BUDGET, 0); + assert!(matches!( + read(&mut s, &caps, &grants, h, 0), + SyscallAction::Return(v) if v != SYSCALL_DENIED + )); + assert!(matches!( + read(&mut s, &caps, &grants, h, 0), + SyscallAction::Return(v) if v != SYSCALL_DENIED + )); + assert_eq!( + read(&mut s, &caps, &grants, h, 0), + SyscallAction::Return(SYSCALL_DENIED) + ); + assert_eq!(s.object_reads_ok, 2); + } + + #[test] + fn read_past_byte_budget_is_denied() { + let (caps, grants, h) = setup(grant(Rights::READ, 0, 32, 8, 12)); + let mut s = RuntimeState::new(BUDGET, 0); + assert_eq!( + read(&mut s, &caps, &grants, h, 0), + SyscallAction::Return(SEED_OBJECT_WORDS[0]) + ); + assert_eq!( + read(&mut s, &caps, &grants, h, 8), + SyscallAction::Return(SYSCALL_DENIED) + ); + assert_eq!(s.usage[0].bytes, 8); + } + + #[test] + fn write_without_write_right_is_denied_and_object_unchanged() { + let (caps, grants, h) = setup(grant(Rights::READ, 0, 32, 8, 32)); + let mut s = RuntimeState::new(BUDGET, 0); + assert_eq!( + s.syscall(&caps, &grants, 0, SYS_OBJECT_WRITE, [h, 0, 0xbad], 10), + SyscallAction::Return(SYSCALL_DENIED) + ); + assert_eq!(s.denials, 1); + assert_eq!(s.object, SEED_OBJECT_WORDS); + } + + #[test] + fn write_with_write_right_updates_kernel_copy() { + let (caps, grants, h) = setup(grant(Rights::READ | Rights::WRITE, 0, 32, 8, 32)); + let mut s = RuntimeState::new(BUDGET, 0); + assert_eq!( + s.syscall(&caps, &grants, 0, SYS_OBJECT_WRITE, [h, 24, 0x77], 10), + SyscallAction::Return(0) + ); + assert_eq!(s.object[3], 0x77); + assert_eq!( + read(&mut s, &caps, &grants, h, 24), + SyscallAction::Return(0x77) + ); + } + + #[test] + fn forged_stale_and_unbacked_handles_are_denied() { + let (mut caps, grants, h) = setup(grant(Rights::READ, 0, 32, 8, 32)); + let mut s = RuntimeState::new(BUDGET, 0); + // Generation 0 never parses; wrong generation and wrong index fail lookup. + for forged in [0, h & 0xffff_ffff, h ^ (1 << 32), h + 1] { + assert_eq!( + read(&mut s, &caps, &grants, forged, 0), + SyscallAction::Return(SYSCALL_DENIED), + "forged {forged:#x}" + ); + } + // A handle whose resource names no grant is denied. + let orphan = caps.insert(5, Rights::READ).unwrap().to_raw(); + assert_eq!( + read(&mut s, &caps, &grants, orphan, 0), + SyscallAction::Return(SYSCALL_DENIED) + ); + // Revoked (removed) handle is stale. + caps.remove(Handle::from_raw(h).unwrap()).unwrap(); + assert_eq!( + read(&mut s, &caps, &grants, h, 0), + SyscallAction::Return(SYSCALL_DENIED) + ); + assert_eq!(s.denials, 6); + assert_eq!(s.object_reads_ok, 0); + } + + #[test] + fn non_object_or_other_object_grant_is_denied() { + let mut g = grant(Rights::READ, 0, 32, 8, 32); + g.resource = ResourceId::new(ResourceKind::Channel, SEED_OBJECT_ID); + let (caps, grants, h) = setup(g); + let mut s = RuntimeState::new(BUDGET, 0); + assert_eq!( + read(&mut s, &caps, &grants, h, 0), + SyscallAction::Return(SYSCALL_DENIED) + ); + let mut g = grant(Rights::READ, 0, 32, 8, 32); + g.resource = ResourceId::new(ResourceKind::Object, 99); + let (caps, grants, h) = setup(g); + assert_eq!( + read(&mut s, &caps, &grants, h, 0), + SyscallAction::Return(SYSCALL_DENIED) + ); + } + + #[test] + fn unknown_syscall_and_nonzero_immediate_terminate() { + let (caps, grants, _) = setup(grant(Rights::READ, 0, 32, 8, 32)); + let mut s = RuntimeState::new(BUDGET, 0); + assert_eq!( + s.syscall(&caps, &grants, 0, 99, [0; 3], 10), + SyscallAction::Terminate(ExecutionStatus::BadSyscall(99)) + ); + assert_eq!( + s.syscall(&caps, &grants, 1, SYS_EXIT, [0; 3], 10), + SyscallAction::Terminate(ExecutionStatus::BadSyscall(SYS_EXIT)) + ); + assert_eq!( + s.syscall(&caps, &grants, 0, SYS_EXIT, [0x5a, 0, 0], 10), + SyscallAction::Terminate(ExecutionStatus::Exited(0x5a)) + ); + } + + #[test] + fn syscall_budget_overrun_terminates() { + let (caps, grants, h) = setup(grant(Rights::READ, 0, 32, 100, 800)); + let budget = TaskBudget { + syscalls: 3, + ..BUDGET + }; + let mut s = RuntimeState::new(budget, 0); + for _ in 0..3 { + assert!(matches!( + read(&mut s, &caps, &grants, h, 0), + SyscallAction::Return(_) + )); + } + assert_eq!( + read(&mut s, &caps, &grants, h, 0), + SyscallAction::Terminate(ExecutionStatus::ResourceOverrun) + ); + } + + #[test] + fn syscall_after_deadline_times_out() { + let (caps, grants, _) = setup(grant(Rights::READ, 0, 32, 8, 32)); + let mut s = RuntimeState::new(BUDGET, 500); + assert_eq!( + s.syscall(&caps, &grants, 0, SYS_EXIT, [0; 3], 500 + 1_000), + SyscallAction::Terminate(ExecutionStatus::Timeout) + ); + } + + #[test] + fn deadline_uses_tighter_budget_and_survives_counter_wrap() { + assert_eq!(BUDGET.tick_limit(), 1_000); + let s = RuntimeState::new(BUDGET, u64::MAX - 100); + assert!(!s.expired(u64::MAX - 100)); + assert!(!s.expired(u64::MAX)); + assert!(!s.expired(898)); // 999 ticks after start, across the wrap + assert!(s.expired(899)); // exactly 1000 ticks + assert_eq!(elapsed_since(u64::MAX - 1, 1), 3); + assert!(deadline_expired(0, 5, 5)); + assert!(!deadline_expired(0, 4, 5)); + } +} diff --git a/crates/aienos-kernel/src/thread.rs b/crates/aienos-kernel/src/thread.rs index 137fafa0..6d79ba34 100644 --- a/crates/aienos-kernel/src/thread.rs +++ b/crates/aienos-kernel/src/thread.rs @@ -250,6 +250,13 @@ unsafe fn irq_dispatcher_inner(frame: *mut TrapFrame) -> *mut TrapFrame { return frame; } + // A loaded artifact task interrupted at EL0: enforce its time budget, + // possibly rewriting the frame to terminate it. + if crate::task_runtime::is_active() { + crate::task_runtime::on_timer_tick(&mut *frame); + return frame; + } + if !PREEMPT_DEMO_ACTIVE.load(Ordering::SeqCst) { return frame; } diff --git a/crates/aienos-kernel/src/user.rs b/crates/aienos-kernel/src/user.rs index dd7da9ef..c76ddc71 100644 --- a/crates/aienos-kernel/src/user.rs +++ b/crates/aienos-kernel/src/user.rs @@ -198,6 +198,21 @@ pub unsafe extern "C" fn aienos_lower_el_sync_dispatcher(frame: *mut TrapFrame) { esr = 0; } + // A loaded artifact task owns EL0: its syscalls and faults never reach + // the M3 demo paths below or the fatal handler. + if crate::task_runtime::is_active() { + let far: u64; + #[cfg(target_arch = "aarch64")] + unsafe { + core::arch::asm!("mrs {0}, far_el1", out(reg) far, options(nomem, nostack)); + } + #[cfg(not(target_arch = "aarch64"))] + { + far = 0; + } + unsafe { crate::task_runtime::dispatch_sync(frame, esr, far) }; + return; + } match (esr >> 26) & 0x3f { 0x15 if esr & 0xffff == 0 => { if IPC_ACTIVE.load(Ordering::Acquire) { diff --git a/evidence/p2_5_artifact_loader_qemu_2026-09-25.md b/evidence/p2_5_artifact_loader_qemu_2026-09-25.md new file mode 100644 index 00000000..60c0cc03 --- /dev/null +++ b/evidence/p2_5_artifact_loader_qemu_2026-09-25.md @@ -0,0 +1,116 @@ +# P2-5 evidence: Binary Artifact loader, exact-byte EL0 execution, W^X (QEMU) + +Date: 2026-09-25 · Commit: `e9defa69f4df472262cd1aadedeb396d8af9d936` (read back from the image: `aienos_commit:` line) · Host: DGX Spark (aarch64), QEMU `virt`, AAVMF, TCG single-thread · Scope: QEMU only. Machine 1 is P2-9. + +## Claim + +A cryptographically admitted external program executes as an isolated EL0 +principal from the exact bytes AIENOS authenticated: + +```text +identified bytes = verified bytes = admitted bytes = mapped bytes = executed bytes +``` + +## Pipeline under test (`crates/aienos-kernel/src/artifact_loader.rs`) + +Firmware reads `\EFI\AIENOS\ARTIFACTS\*.AIEN` into LOADER_DATA pages and does +not interpret them. After firmware exit the kernel: + +1. Stages the bytes into contiguous NX kernel frames. These are never mapped into the task. +2. Parses them, computes the ArtifactId, and checks Ed25519 against the local anchors. This is the `Verified` state. +3. Applies the deterministic admission policy: READ on SEED object 1 only, no IPC. This is `Authorized`. +4. Reserves the scheduler slot, every content and table frame, and the shadow table frames, all before mapping anything. This is `Reserved`. +5. Builds a private L0 (a copy of the kernel root) and a private L1/L2/L3 window laid out as guard | code | guard | data | guard | stack | guard. It copies the exact code and data through the RW+NX identity alias. +6. Hashes the code and data bytes read back from the private frames (SHA-256 of code‖data) and requires it to equal the admitted payload digest. This is `Hashed`. +7. Seals the task. It syncs the I-cache and maps code EL0 RX (PXN). In the task root's private shadow of the identity map, it marks each code frame's EL1 alias read-only+PXN+UXN. It then runs a fail-closed audit of the whole window and every code alias (`audit_wx`). This is `Sealed`. +8. Installs exactly the policy grants in the task's own M3 `CapTable`, with the resource value set to the grant index. It also writes the handle array at the stack top. +9. Produces a `LoadedTask`, hands it to the scheduler (`tick`), and runs it at EL0 through `task_runtime::run`. EL0 starts with zeroed GPRs and SIMD registers, TTBR0 set to the task root with ASID 2, and a timer enforcing min(cpu_ticks, elapsed_ticks). The runtime also enforces the syscall budget. +10. On any ending, it re-hashes the code frames (executed bytes), revokes every handle, scrubs and releases every frame, and frees the slot. + +## Artifacts (deterministic: two independent packs are byte-identical) + +| File | ArtifactId | File SHA-256 | +|---|---|---| +| P25EXEC.AIEN | `19429f616c5b531594a3495f6bb7dccf0b55f1cd497d748fe31a5a4abad8f26f` | `49c3621c190bf3fa8ea9ee4b7cd7f7b65472edc2a790d81aa4a29b43ffa56244` | +| P25WX.AIEN | `aa57bd141cf88fd07256bcf2233f8785e63b66692ab76e6d5c84bed3d8c1a09a` | `54a749077cdaf862b0d1410713529890c2bb7b0052f634809eee9129c31f2eb7` | +| P25SPIN.AIEN | `a683f56212ca600d21b529b8d336aad4674dc6a2bcb52d70359fca3959ca09ac` | `5589ef4256f29a2bf96d58a02f5d28c86ca49ba2fb3499bc6937eaf2cdcb9ff9` | +| P25TAMP.AIEN | (P25EXEC with one payload bit flipped after signing) | `069e10eda35bef104a8ff877cdb956724f0ccf8b2ecada3926bf89a61ffb3852` | + +The probe sources, code and data binaries, and manifests are in `crates/aienos-artifact-tool/fixtures/p2_5/`. `code.bin` is checked byte-for-byte against `probe.S` on every run. The signer is the SEED-0B test key (RFC 8032 TEST 1), used only in a debug host tool. + +## Raw serial: qualification build (`--features seed0b-qualification`) + +```text +aienos_commit: e9defa69f4df472262cd1aadedeb396d8af9d936 +artifact_candidates: 4 +artifact: P25EXEC.AIEN admitted id=19429f616c5b5315 tier=seed0b-test exec=exited:0x0 bytes=identified=verified=admitted=mapped=executed wx=enforced caps=1 revoked=yes reclaimed=yes frames=10 syscalls=3 reads=1 denials=1 +artifact: P25SPIN.AIEN admitted id=a683f56212ca600d tier=seed0b-test exec=timeout bytes=identified=verified=admitted=mapped=executed wx=enforced caps=0 revoked=yes reclaimed=yes frames=10 syscalls=0 reads=0 denials=0 +artifact: P25TAMP.AIEN rejected stage=verified reason=BadSignature reclaimed=yes +artifact: P25WX.AIEN admitted id=aa57bd141cf88fd0 tier=seed0b-test exec=fault:code-write bytes=identified=verified=admitted=mapped=executed wx=enforced caps=0 revoked=yes reclaimed=yes frames=10 syscalls=0 reads=0 denials=0 +artifacts: candidates=4 admitted=3 rejected=1 +artifact_trust: SEED-0B QUALIFICATION BUILD — TEST ONLY TRUST ANCHOR +artifact_trust: seed0b-test qualification build — TEST ONLY +``` + +- **P25EXEC:** exit 0 means every check in `probe.S` passed: + - exactly one handle; + - its authenticated data word read back at EL0; + - data and stack are writable; + - `OBJECT_READ` through the granted handle returned the SEED word; + - a forged-generation handle was denied. + + The runtime counters agree: 3 syscalls (read, forged read, exit), 1 successful read, 1 denial. +- **P25WX:** it stored to its own code page and got an EL0 write permission fault with FAR inside the code range. It was terminated, not resumed. +- **P25SPIN:** `b .` forever. It was killed by the timer IRQ from EL0 at its 6,250,000-tick budget. +- **P25TAMP:** the ArtifactId changed, so the signature failed before any task frame was reserved. +- **frames=10:** 3 content pages (1 code, 1 data, 1 stack), 4 window tables, and 3 shadow tables (a private L1, L2 and L3 on the path to the code frame). Every candidate reported `reclaimed=yes`, meaning allocator free count before equals free count after, and no live capability remained. + +## Raw serial: ordinary build (empty production trust) + +```text +artifact_candidates: 4 +artifact: P25EXEC.AIEN rejected stage=verified reason=UntrustedSigner reclaimed=yes +artifact: P25SPIN.AIEN rejected stage=verified reason=UntrustedSigner reclaimed=yes +artifact: P25TAMP.AIEN rejected stage=verified reason=UntrustedSigner reclaimed=yes +artifact: P25WX.AIEN rejected stage=verified reason=UntrustedSigner reclaimed=yes +artifacts: candidates=4 admitted=0 rejected=4 +artifact_trust: no production anchors enrolled +``` + +## Mutation control (audit is live) + +I temporarily removed `AP_READ_ONLY` from the shadow alias leaf, leaving the code frames' EL1 alias writable in the task root. The same QEMU run then produced: + +```text +artifact: P25EXEC.AIEN rejected stage=sealed reason=WxAudit reclaimed=yes +artifact: P25SPIN.AIEN rejected stage=sealed reason=WxAudit reclaimed=yes +artifact: P25TAMP.AIEN rejected stage=verified reason=BadSignature reclaimed=yes +artifact: P25WX.AIEN rejected stage=sealed reason=WxAudit reclaimed=yes +``` + +No task ran, and everything was reclaimed. The change was reverted before commit. + +## Gates run at this commit + +- `AIENOS_STRICT=1 ./scripts/verify_all.sh` exited 0 with 0 FAIL and 0 SKIPPED. That covers: + - fmt, 370 host tests, and `clippy -D warnings`; + - the aarch64 kernel build and both EFI images; + - `QEMU_BOOT: PASS` (M3 el0/ipc/preempt unchanged); + - `QEMU_KEYBOARD: PASS` (smmu + fail-closed) and the SMMU confinement run; + - `QEMU_ARTIFACT: PASS`; + - recovery tools. +- The host loader suite (`artifact_loader_tests.rs`, 19 tests) runs over a mock physical memory on three kernel-map shapes (1 GiB block, 2 MiB blocks, 4 KiB pages). It covers: + - every rejection stage and error, with full reclaim; + - kernel tables byte-identical after each load; + - zeroed frames; + - grants ⊆ requests; + - audit tamper detection; + - an executed-digest mismatch path. + +## Not covered here + +- Admission Receipt v0 encoding and signing is separate work, needed from P2-6 on. +- P2-6's first SEED-0B capability artifact, with a WRITE attempt through a READ handle and a receipt. +- The P2-7 full hostile-input matrix. +- Machine 1 (P2-9). +- The kernel root keeps its RW+NX alias of code frames; it is used only before sealing and after the task has left the CPU. While the task lives, the only active translation regime is the task root, where the alias is read-only. diff --git a/scripts/qemu_artifact_test.sh b/scripts/qemu_artifact_test.sh new file mode 100755 index 00000000..57d0c666 --- /dev/null +++ b/scripts/qemu_artifact_test.sh @@ -0,0 +1,159 @@ +#!/usr/bin/env bash +# P2-5 Binary Artifact loader qualification in QEMU AArch64 (UEFI, EL2 start). +# +# Firmware reads signed .AIEN files from \EFI\AIENOS\ARTIFACTS on the ESP and +# hands their bytes to the kernel, which stages, verifies, admits, loads and +# runs each one as an isolated EL0 task, then reclaims it. Two boots: +# +# 1. seed0b-qualification build (TEST ONLY qualification trust anchor): +# P25EXEC admitted, runs from the exact authenticated bytes, exits 0 +# 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 +# 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. +# +# Needs qemu-system-aarch64 and AAVMF (Ubuntu: qemu-system-arm qemu-efi-aarch64). +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "${repo_root}" + +code_fd="${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" +vars_fd="${AAVMF_VARS:-/usr/share/AAVMF/AAVMF_VARS.fd}" +command -v qemu-system-aarch64 >/dev/null || { echo "qemu-system-aarch64 not installed"; exit 2; } +[[ -r "${code_fd}" && -r "${vars_fd}" ]] || { echo "AAVMF firmware not found"; exit 2; } + +fixtures="crates/aienos-artifact-tool/fixtures/p2_5" +work="$(mktemp -d)" +trap 'rm -rf "${work}"' EXIT +failed=0 +pass() { echo "PASS $1"; } +fail() { echo "FAIL $1"; failed=1; } + +# The committed probe bytes are the qualification inputs. When an assembler +# is available, prove they are exactly what probe.S assembles to. +as_bin=as +[[ "$(uname -m)" == "aarch64" ]] || as_bin=aarch64-linux-gnu-as +if command -v "${as_bin}" >/dev/null; then + "${fixtures}/assemble.sh" "${work}/asm" + for probe in p25exec p25wx p25spin; do + if cmp -s "${work}/asm/${probe}/code.bin" "${fixtures}/${probe}/code.bin"; then + pass "${probe} code.bin is exactly what probe.S assembles to" + else + fail "${probe} code.bin differs from probe.S" + fi + done +else + echo "NOTE no AArch64 assembler; using committed probe bytes unchecked" +fi + +# Test-only signing: debug build by design (release refuses the feature). +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" +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 + awk -v n="$1" '$1 == n { print substr($2, 1, 16) }' "${work}/ids.txt" +} + +commit="$(git rev-parse HEAD 2>/dev/null || echo unknown)" +build_image() { # features, output + AIENOS_COMMIT="${commit}" AIENOS_RESTART_SECS=1 cargo build --quiet --release \ + -p aienos-boot --target aarch64-unknown-uefi --features "$1" --bin aienos-handoff + cp target/aarch64-unknown-uefi/release/aienos-handoff.efi "$2" +} +build_image seed0b-qualification "${work}/qualification.efi" +build_image handoff "${work}/production.efi" + +boot() { # image, serial text output + cp "$1" "${work}/esp/EFI/BOOT/BOOTAA64.EFI" + cp "${vars_fd}" "${work}/vars.fd" + local log="${work}/serial.log" started status + started=$(date +%s) + set +e + # Issue #61: single-threaded TCG; MTTCG hung in 1/40 soak boots. + timeout "${AIENOS_QEMU_TIMEOUT:-180}" qemu-system-aarch64 \ + -M virt,virtualization=on,gic-version=3 -accel tcg,thread=single -cpu max -smp 4 -m 2048 \ + -drive if=pflash,format=raw,readonly=on,file="${code_fd}" \ + -drive if=pflash,format=raw,file="${work}/vars.fd" \ + -drive if=none,id=esp,format=raw,file=fat:rw:"${work}/esp" \ + -device virtio-blk-pci,drive=esp \ + -device ramfb -display none -nic none \ + -serial file:"${log}" -no-reboot + status=$? + set -e + tr -d '\r' <"${log}" >"$2" + echo "qemu exit ${status} after $(( $(date +%s) - started )) s (commit ${commit:0:12})" + [[ "${status}" != 124 ]] || fail "QEMU timed out (no reset)" +} + +has() { grep -qE -- "$2" "$1"; } +check() { # serial, description, extended regex + if has "$1" "$3"; then pass "$2"; else fail "$2"; fi +} +common_checks() { # serial + check "$1" "left firmware and entered the kernel" "kernel: alive" + check "$1" "M3 cooperative threads unchanged" "threads: ok" + check "$1" "M3 EL0 isolation proof unchanged" "el0: ok write=granted forged=denied fault=contained exit=0" + check "$1" "M3 typed IPC proof unchanged" "ipc: ok message=delivered cap=delegated rights=attenuated forged=denied revoked=denied" + check "$1" "firmware read four artifact candidates" "artifact_candidates: 4$" + check "$1" "final report reached the console" "report_kind: final" + if has "$1" "report_kind: (panic|fault)"; then fail "panic or fault reported"; fi +} + +# ---- boot 1: qualification build -------------------------------------------- +qual="${work}/qualification.txt" +boot "${work}/qualification.efi" "${qual}" +common_checks "${qual}" +check "${qual}" "qualification build is labelled TEST ONLY" \ + "artifact_trust: seed0b-test qualification build — TEST ONLY" +exec_id="$(id_prefix P25EXEC.AIEN)" +check "${qual}" "P25EXEC admitted and executed its exact authenticated bytes, exit 0, caps revoked, reclaimed" \ + "artifact: P25EXEC\.AIEN admitted id=${exec_id} tier=seed0b-test exec=exited:0x0 bytes=identified=verified=admitted=mapped=executed wx=enforced caps=1 revoked=yes reclaimed=yes frames=[0-9]+ syscalls=3 reads=1 denials=1$" +check "${qual}" "P25WX admitted then killed by W^X fault on its code page, reclaimed" \ + "artifact: P25WX\.AIEN admitted id=$(id_prefix P25WX.AIEN) tier=seed0b-test exec=fault:code-write .*wx=enforced caps=0 revoked=yes reclaimed=yes frames=[0-9]+ syscalls=0 reads=0 denials=0$" +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" + +# ---- boot 2: ordinary build, empty production trust ------------------------- +prod="${work}/production.txt" +boot "${work}/production.efi" "${prod}" +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 + 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" +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" + +if [[ -n "${AIENOS_LOG_DIR:-}" ]]; then + cp "${qual}" "${AIENOS_LOG_DIR}/qemu_artifact_qualification_serial.log" + cp "${prod}" "${AIENOS_LOG_DIR}/qemu_artifact_production_serial.log" +fi +if [[ "${failed}" != 0 || -n "${AIENOS_QEMU_VERBOSE:-}" ]]; then + echo "---- serial console: qualification build ----" + cat "${qual}" + echo "---- serial console: ordinary build ----" + cat "${prod}" +fi +[[ "${failed}" == 0 ]] && echo "QEMU_ARTIFACT: PASS" || { echo "QEMU_ARTIFACT: FAIL"; exit 1; } diff --git a/scripts/verify_all.sh b/scripts/verify_all.sh index 9de8e562..31ef9ca0 100755 --- a/scripts/verify_all.sh +++ b/scripts/verify_all.sh @@ -87,6 +87,17 @@ else skipped "qemu-system-aarch64 or AAVMF firmware not present on host." fi +# Step 6a: P2-5 Binary Artifact loader. Signed candidates are staged, +# verified, admitted, run at EL0 from their exact authenticated bytes under +# W^X, and reclaimed; the ordinary build rejects every one (QEMU only). +echo "" +echo "--- [P2-5 Binary Artifact Loader in QEMU] ---" +if command -v qemu-system-aarch64 >/dev/null && [[ -r "${AAVMF_CODE:-/usr/share/AAVMF/AAVMF_CODE.no-secboot.fd}" ]]; then + ./scripts/qemu_artifact_test.sh +else + skipped "qemu-system-aarch64 or AAVMF firmware not present on host." +fi + # Step 6b: SEED-0A USB keyboard candidate, proven in QEMU only (ADR 0012). echo "" echo "--- [SEED-0A USB Keyboard in QEMU (input.keyboard.usb)] ---"