Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/crates/aienos-kernel/src/artifact_loader.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / crates / aienos-kernel / src / artifact_loader.rs` 1714 lines · 62114 bytes Raw Blame History 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2026 Drake Stapleton (AIEN / aien-dev) 3 // 4 // Licensed under the Apache License, Version 2.0 (the "License"); 5 // you may not use this file except in compliance with the License. 6 // You may obtain a copy of the License at 7 // 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 //! Binary Artifact v0 loader: the only path from authenticated artifact bytes 17 //! to a runnable EL0 task (ADR 0014 §5). 18 //! 19 //! The pipeline is fixed and fail-closed: 20 //! 21 //! ```text 22 //! stage bytes (contiguous NX kernel frames, never mapped into the task) 23 //! -> parse + ArtifactId + Ed25519 against local anchors (Verified) 24 //! -> deterministic admission policy (Authorized) 25 //! -> scheduler slot + every frame, reserved up front (Reserved) 26 //! -> private tables; exact code/data copy via the NX alias (Mapped) 27 //! -> SHA-256 of bytes read back from the private pages (Hashed) 28 //! -> I-cache sync, code EL0 RX, EL1 alias read-only, audit (Sealed) 29 //! -> policy grants installed in the task's M3 CapTable (CapsInstalled) 30 //! -> LoadedTask (Admitted) 31 //! ``` 32 //! 33 //! Any failure scrubs and releases every frame and scheduler slot taken so 34 //! far; nothing partially admitted survives. After the task ends for any 35 //! reason its code pages are hashed again (executed bytes), its capabilities 36 //! are revoked, and every page is scrubbed and returned. 37 //! 38 //! No translation regime active while the task lives maps a code frame 39 //! writable: its user mapping is EL0 read-only/executable, and the task's 40 //! private copy of the kernel identity map marks the same frames read-only 41 //! (EL1 alias). The kernel's own root keeps the RW+NX alias, which is used 42 //! only before sealing and after the task has left the CPU. 43 //! 44 //! Hardware access goes through [`LoaderPlatform`] so the whole pipeline, 45 //! including every rollback, runs under host tests. 46 47 use aienos_artifact::capability::{CapabilityRequest, MAX_CAPABILITIES, RESOURCE_KIND_OBJECT}; 48 use aienos_artifact::error::ArtifactError; 49 pub use aienos_artifact::receipt::QualificationTier; 50 use aienos_artifact::receipt::{ 51 receipt_digest, receipt_nonce, validate as validate_receipt, ExecutionStatusCode, Receipt, 52 ReceiptDecision, RECEIPT_SIZE, RESULT_CANARY_PASSED, RESULT_EXECUTED_BYTES_MATCH, 53 RESULT_FORGED_DENIED, RESULT_MAPPED_BYTES_MATCH, RESULT_READ_OK, RESULT_RECLAIMED, 54 RESULT_WRITE_DENIED, RESULT_WX_SEALED, 55 }; 56 use aienos_artifact::resource::{ 57 ResourceEnvelope, MAX_CODE_PAGES, MAX_CPU_TICKS, MAX_DATA_PAGES, MAX_ELAPSED_TICKS, 58 MAX_STACK_PAGES, MAX_SYSCALLS, 59 }; 60 use aienos_artifact::signature::{ArtifactVerifier, TrustTier}; 61 use aienos_artifact::ArtifactId; 62 use aienos_crypto::sha256::{Digest, Sha256}; 63 64 use crate::abi::Handle; 65 use crate::admission::{AdmissionLimits, AdmissionPolicy, AvailableResources, GrantedCapability}; 66 use crate::caps::{CapTable, Rights}; 67 use crate::mem::pagetable::{page_descriptor, MapFlags, MemoryAttribute}; 68 use crate::mem::{FrameBatch, PhysAddr, MAX_BATCH_FRAMES}; 69 use crate::scheduler::{Scheduler, TaskPriority}; 70 use crate::task_runtime::{ 71 ExecutionStatus, TaskBudget, TaskContext, TaskOutcome, SEED_OBJECT_ID, TASK_CAPABILITIES, 72 }; 73 74 /// Candidate lifecycle (ADR 0014 §5). Only `Admitted` tasks ever run. 75 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 76 pub enum CandidateState { 77 Received, 78 Staged, 79 Verified, 80 Authorized, 81 Reserved, 82 Mapped, 83 Hashed, 84 Sealed, 85 CapsInstalled, 86 Admitted, 87 Running, 88 Rejected, 89 Destroyed, 90 } 91 92 impl CandidateState { 93 pub const fn name(self) -> &'static str { 94 match self { 95 Self::Received => "received", 96 Self::Staged => "staged", 97 Self::Verified => "verified", 98 Self::Authorized => "authorized", 99 Self::Reserved => "reserved", 100 Self::Mapped => "mapped", 101 Self::Hashed => "hashed", 102 Self::Sealed => "sealed", 103 Self::CapsInstalled => "caps", 104 Self::Admitted => "admitted", 105 Self::Running => "running", 106 Self::Rejected => "rejected", 107 Self::Destroyed => "destroyed", 108 } 109 } 110 } 111 112 /// Every reason a candidate can be refused or torn down. 113 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 114 pub enum LoadError { 115 Artifact(ArtifactError), 116 NoFrames, 117 StagingTooLarge, 118 Mapping, 119 MappedDigestMismatch, 120 WxAudit, 121 CapabilityInstall, 122 SchedulerFull, 123 ExecutedDigestMismatch, 124 Reclaim, 125 /// Firmware could not provide the candidate's bytes (handoff-level). 126 FirmwareRead, 127 } 128 129 impl LoadError { 130 /// Stable ADR 0014 §7.3 reason code. 131 pub const fn reason_code(self) -> u16 { 132 match self { 133 Self::Artifact(e) => e as u16, 134 Self::NoFrames => 0x101, 135 Self::StagingTooLarge => 0x102, 136 Self::Mapping => 0x103, 137 Self::MappedDigestMismatch => 0x104, 138 Self::WxAudit => 0x105, 139 Self::CapabilityInstall => 0x106, 140 Self::SchedulerFull => 0x107, 141 Self::ExecutedDigestMismatch => 0x108, 142 Self::Reclaim => 0x109, 143 Self::FirmwareRead => 0x10a, 144 } 145 } 146 } 147 148 impl CandidateState { 149 /// Stable ADR 0014 §7.3 stage code; `0` for states that are not a 150 /// rejection point. 151 pub const fn stage_code(self) -> u16 { 152 match self { 153 Self::Received => 1, 154 Self::Staged => 2, 155 Self::Verified => 3, 156 Self::Authorized => 4, 157 Self::Reserved => 5, 158 Self::Mapped => 6, 159 Self::Hashed => 7, 160 Self::Sealed => 8, 161 Self::CapsInstalled => 9, 162 _ => 0, 163 } 164 } 165 } 166 167 /// Identity and check results the loader actually computed, recorded as 168 /// each stage passes. A field stays zero/false unless its stage completed, 169 /// so a rejection receipt never carries a value the kernel did not derive. 170 #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] 171 pub struct ReceiptBindings { 172 pub artifact_id: Digest, 173 pub payload_digest: Digest, 174 pub artifact_signer_fingerprint: Digest, 175 pub policy_digest: Digest, 176 pub requested_capability_digest: Digest, 177 pub granted_capability_digest: Digest, 178 pub resource_envelope_digest: Digest, 179 /// SHA-256 of the bytes read back from private pages == admitted digest. 180 pub mapped_bytes_matched: bool, 181 /// `audit_wx` passed on the sealed task root. 182 pub wx_sealed: bool, 183 } 184 185 impl From for LoadError { 186 fn from(error: ArtifactError) -> Self { 187 Self::Artifact(error) 188 } 189 } 190 191 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 192 pub enum Decision { 193 Admitted, 194 Rejected, 195 } 196 197 /// What one boot candidate did, for the boot report and QEMU checks. 198 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 199 pub struct CandidateReport { 200 pub decision: Decision, 201 pub failed_stage: Option, 202 pub error: Option, 203 pub artifact_id: Option, 204 pub trust_tier: Option, 205 pub frames_reserved: usize, 206 pub frames_free_before: usize, 207 pub frames_free_after: usize, 208 pub caps_installed: usize, 209 pub caps_live_after: usize, 210 /// identified == verified == admitted == mapped == executed. 211 pub byte_chain: bool, 212 pub wx_enforced: bool, 213 pub outcome: TaskOutcome, 214 pub code_base: u64, 215 pub code_end: u64, 216 /// Mapped RW+NX data and stack ranges, `[base, end)`, for fault classification. 217 pub data_base: u64, 218 pub data_end: u64, 219 pub stack_base: u64, 220 pub stack_end: u64, 221 pub bindings: ReceiptBindings, 222 /// Grants installed in the task's capability table, in grant order. 223 pub granted: [Option; MAX_CAPABILITIES], 224 } 225 226 impl CandidateReport { 227 pub const fn reclaimed(&self) -> bool { 228 self.frames_free_after == self.frames_free_before && self.caps_live_after == 0 229 } 230 } 231 232 // --------------------------------------------------------------------------- 233 // Platform contract 234 // --------------------------------------------------------------------------- 235 236 pub const PAGE: usize = 4096; 237 const PAGE_U64: u64 = PAGE as u64; 238 const ENTRIES: usize = 512; 239 /// Private user-window tables: L0 (copy of the kernel root), L1, L2, L3. 240 pub const TABLE_FRAMES: usize = 4; 241 /// Largest staged artifact: the admitted maximum payload fits in 130 pages. 242 pub const MAX_STAGING_FRAMES: usize = MAX_BATCH_FRAMES; 243 /// Loaded artifact tasks that may hold a scheduler slot at once. 244 pub const LOADED_TASK_SLOTS: usize = 4; 245 pub type LoaderScheduler = Scheduler<1, LOADED_TASK_SLOTS>; 246 247 const ADDRESS_MASK: u64 = 0x0000_ffff_ffff_f000; 248 const ATTR_MASK: u64 = 0xffff_0000_0000_0ffc; 249 const BLOCK_1G_MASK: u64 = 0x0000_ffff_c000_0000; 250 const BLOCK_2M_MASK: u64 = 0x0000_ffff_ffe0_0000; 251 const DESC_TYPE: u64 = 0b11; 252 const DESC_TABLE: u64 = 0b11; 253 const DESC_BLOCK: u64 = 0b01; 254 /// AP[2]: read-only at every EL that can access the page. 255 pub const AP_READ_ONLY: u64 = 1 << 7; 256 /// AP[1]: EL0 accessible. 257 pub const AP_EL0: u64 = 1 << 6; 258 pub const PXN: u64 = 1 << 53; 259 pub const UXN: u64 = 1 << 54; 260 261 pub const USER_CODE: MapFlags = MapFlags { 262 attribute: MemoryAttribute::NormalWriteBack, 263 writable: false, 264 user: true, 265 executable: true, 266 shareable: true, 267 global: false, 268 }; 269 pub const USER_DATA: MapFlags = MapFlags { 270 writable: true, 271 executable: false, 272 ..USER_CODE 273 }; 274 275 /// Physical memory and frame ownership as the loader needs them. On AArch64 276 /// the kernel identity map makes a physical address directly addressable; 277 /// host tests supply an arena. 278 pub trait LoaderPlatform { 279 fn kernel_root(&self) -> u64; 280 fn free_frames(&self) -> usize; 281 /// All-or-nothing reservation of `count` frames. 282 fn reserve_batch(&mut self, count: usize) -> Option; 283 fn release_batch(&mut self, batch: FrameBatch) -> bool; 284 fn reserve_contiguous(&mut self, count: usize) -> Option; 285 fn release_contiguous(&mut self, start: u64, count: usize) -> bool; 286 fn bytes(&self, pa: u64, len: usize) -> &[u8]; 287 /// Only ever called on frames the loader currently owns. 288 fn bytes_mut(&mut self, pa: u64, len: usize) -> &mut [u8]; 289 fn copy(&mut self, src: u64, dst: u64, len: usize); 290 /// Make table writes visible to the translation walker. 291 fn clean_dcache(&mut self, pa: u64, len: usize); 292 /// Clean D-cache to PoU and invalidate I-cache for freshly written code. 293 fn sync_icache(&mut self, pa: u64, len: usize); 294 } 295 296 /// Runs a sealed task. The hardware implementation enters EL0. 297 pub trait TaskExecutor { 298 fn execute(&mut self, task: TaskContext<'_>, platform: &mut P) -> TaskOutcome; 299 } 300 301 fn read_entry(p: &P, table: u64, index: usize) -> u64 { 302 let b = p.bytes(table + (index as u64) * 8, 8); 303 u64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]) 304 } 305 306 fn write_entry(p: &mut P, table: u64, index: usize, value: u64) { 307 p.bytes_mut(table + (index as u64) * 8, 8) 308 .copy_from_slice(&value.to_le_bytes()); 309 } 310 311 const fn table_index(va: u64, level: usize) -> usize { 312 ((va >> (39 - 9 * level)) & 511) as usize 313 } 314 315 // --------------------------------------------------------------------------- 316 // Task layout 317 // --------------------------------------------------------------------------- 318 319 /// The private 2 MiB EL0 window, one L3 table, page by page: 320 /// guard | code | guard | data | guard | stack | guard. 321 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 322 pub struct TaskLayout { 323 pub window_index: usize, 324 pub base: u64, 325 pub code_pages: usize, 326 pub data_pages: usize, 327 pub stack_pages: usize, 328 pub code_len: usize, 329 pub data_len: usize, 330 pub data_memory_len: usize, 331 pub entry_offset: u64, 332 } 333 334 impl TaskLayout { 335 pub fn new( 336 window_index: usize, 337 resources: &ResourceEnvelope, 338 code_len: usize, 339 data_len: usize, 340 data_memory_len: usize, 341 entry_offset: u32, 342 ) -> Result { 343 let layout = Self { 344 window_index, 345 base: (window_index as u64) << 39, 346 code_pages: resources.code_pages as usize, 347 data_pages: resources.data_pages as usize, 348 stack_pages: resources.stack_pages as usize, 349 code_len, 350 data_len, 351 data_memory_len, 352 entry_offset: u64::from(entry_offset), 353 }; 354 let fits = |len: usize, pages: usize| len <= pages.saturating_mul(PAGE); 355 if !(1..256).contains(&window_index) 356 || layout.code_pages == 0 357 || layout.code_pages > MAX_CODE_PAGES as usize 358 || layout.data_pages == 0 359 || layout.data_pages > MAX_DATA_PAGES as usize 360 || layout.stack_pages == 0 361 || layout.stack_pages > MAX_STACK_PAGES as usize 362 || code_len == 0 363 || !fits(code_len, layout.code_pages) 364 || data_len > data_memory_len 365 || !fits(data_memory_len, layout.data_pages) 366 || !layout.entry_offset.is_multiple_of(4) 367 || layout.entry_offset + 4 > code_len as u64 368 || layout.window_pages() > ENTRIES 369 { 370 return Err(LoadError::Artifact(ArtifactError::ResourceLimit)); 371 } 372 Ok(layout) 373 } 374 375 pub const fn content_frames(&self) -> usize { 376 self.code_pages + self.data_pages + self.stack_pages 377 } 378 pub const fn total_frames(&self) -> usize { 379 self.content_frames() + TABLE_FRAMES 380 } 381 const fn code_first(&self) -> usize { 382 1 383 } 384 const fn data_first(&self) -> usize { 385 self.code_first() + self.code_pages + 1 386 } 387 const fn stack_first(&self) -> usize { 388 self.data_first() + self.data_pages + 1 389 } 390 const fn window_pages(&self) -> usize { 391 self.stack_first() + self.stack_pages + 1 392 } 393 pub const fn code_base(&self) -> u64 { 394 self.base + (self.code_first() * PAGE) as u64 395 } 396 pub const fn code_end(&self) -> u64 { 397 self.code_base() + (self.code_pages * PAGE) as u64 398 } 399 pub const fn data_base(&self) -> u64 { 400 self.base + (self.data_first() * PAGE) as u64 401 } 402 pub const fn data_end(&self) -> u64 { 403 self.data_base() + (self.data_pages * PAGE) as u64 404 } 405 pub const fn stack_base(&self) -> u64 { 406 self.base + (self.stack_first() * PAGE) as u64 407 } 408 pub const fn stack_top(&self) -> u64 { 409 self.stack_base() + (self.stack_pages * PAGE) as u64 410 } 411 pub const fn entry_pc(&self) -> u64 { 412 self.code_base() + self.entry_offset 413 } 414 415 /// Expected L3 descriptor at window page `index`, given the task frames. 416 fn expected_leaf(&self, index: usize, frames: &[PhysAddr]) -> u64 { 417 let (d, s) = (self.data_first(), self.stack_first()); 418 if (1..1 + self.code_pages).contains(&index) { 419 page_descriptor(frames[index - 1], USER_CODE) 420 } else if (d..d + self.data_pages).contains(&index) { 421 page_descriptor(frames[self.code_pages + index - d], USER_DATA) 422 } else if (s..s + self.stack_pages).contains(&index) { 423 page_descriptor( 424 frames[self.code_pages + self.data_pages + index - s], 425 USER_DATA, 426 ) 427 } else { 428 0 429 } 430 } 431 } 432 433 // --------------------------------------------------------------------------- 434 // Loaded task 435 // --------------------------------------------------------------------------- 436 437 /// Frames owned by one task: content frames then its four window tables, plus 438 /// the private shadow of the kernel identity map that makes code read-only. 439 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 440 pub struct TaskAddressSpace { 441 pub root: u64, 442 pub layout: TaskLayout, 443 frames: FrameBatch, 444 shadow: FrameBatch, 445 shadow_used: usize, 446 } 447 448 impl TaskAddressSpace { 449 pub fn frames(&self) -> &[PhysAddr] { 450 self.frames.as_slice() 451 } 452 pub fn code_frames(&self) -> &[PhysAddr] { 453 &self.frames.as_slice()[..self.layout.code_pages] 454 } 455 pub fn shadow_frames(&self) -> &[PhysAddr] { 456 &self.shadow.as_slice()[..self.shadow_used] 457 } 458 pub fn frames_reserved(&self) -> usize { 459 self.frames.len() + self.shadow.len() 460 } 461 } 462 463 /// A sealed, admitted task: the only thing the scheduler/runtime receives. 464 pub struct LoadedTask { 465 pub artifact_id: ArtifactId, 466 pub trust_tier: TrustTier, 467 pub payload_digest: Digest, 468 /// SHA-256 of the exact code bytes read back from the private pages. 469 pub code_digest: Digest, 470 pub address_space: TaskAddressSpace, 471 pub entry_pc: u64, 472 pub stack_pointer: u64, 473 pub handle_array: u64, 474 pub capabilities: CapTable, 475 pub handles: [Option; TASK_CAPABILITIES], 476 pub grants: [Option; MAX_CAPABILITIES], 477 pub grant_count: usize, 478 pub resource_budget: ResourceEnvelope, 479 pub scheduler_id: u32, 480 pub state: CandidateState, 481 } 482 483 impl LoadedTask { 484 pub fn args(&self) -> [u64; 4] { 485 [ 486 self.handle_array, 487 self.grant_count as u64, 488 self.address_space.layout.data_base(), 489 self.address_space.layout.data_memory_len as u64, 490 ] 491 } 492 493 pub fn budget(&self) -> TaskBudget { 494 TaskBudget { 495 cpu_ticks: self.resource_budget.cpu_ticks, 496 elapsed_ticks: self.resource_budget.elapsed_ticks, 497 syscalls: self.resource_budget.syscall_count, 498 } 499 } 500 } 501 502 /// What teardown observed. 503 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 504 pub struct Teardown { 505 pub executed_bytes_match: bool, 506 pub caps_live_after: usize, 507 pub released: bool, 508 } 509 510 // --------------------------------------------------------------------------- 511 // Policy and resources 512 // --------------------------------------------------------------------------- 513 514 /// The local SEED-0B admission policy: READ on the SEED object only, no IPC, 515 /// signers limited to `signers` (empty in production builds). 516 pub fn boot_policy(signers: &[Digest]) -> Result { 517 let mut policy = AdmissionPolicy::new(AdmissionLimits { 518 code_pages: MAX_CODE_PAGES, 519 data_pages: MAX_DATA_PAGES, 520 stack_pages: MAX_STACK_PAGES, 521 max_capabilities: MAX_CAPABILITIES as u32, 522 ipc_messages: 0, 523 ipc_bytes: 0, 524 cpu_ticks: MAX_CPU_TICKS, 525 elapsed_ticks: MAX_ELAPSED_TICKS, 526 syscall_count: MAX_SYSCALLS, 527 })?; 528 policy.add_resource_rule(CapabilityRequest { 529 resource_kind: RESOURCE_KIND_OBJECT, 530 resource_id: SEED_OBJECT_ID, 531 rights: u32::from(Rights::READ.bits()), 532 bounds_kind: 1, 533 max_operations: 16, 534 max_bytes: 32, 535 byte_offset: 0, 536 byte_length: 32, 537 })?; 538 for signer in signers { 539 policy.allow_signer(*signer)?; 540 } 541 Ok(policy) 542 } 543 544 /// Snapshot of what the kernel could reserve right now. 545 pub fn available_resources(free_frames: usize, free_task_slots: usize) -> AvailableResources { 546 let frames = if free_task_slots == 0 { 547 0 548 } else { 549 u32::try_from(free_frames.saturating_sub(TABLE_FRAMES)).unwrap_or(u32::MAX) 550 }; 551 AvailableResources { 552 code_pages: frames, 553 data_pages: frames, 554 stack_pages: frames, 555 capability_slots: TASK_CAPABILITIES as u32, 556 ipc_messages: 0, 557 ipc_bytes: 0, 558 cpu_ticks: MAX_CPU_TICKS, 559 elapsed_ticks: MAX_ELAPSED_TICKS, 560 syscall_count: MAX_SYSCALLS, 561 } 562 } 563 564 // --------------------------------------------------------------------------- 565 // Pipeline 566 // --------------------------------------------------------------------------- 567 568 type Failure = (CandidateState, LoadError); 569 570 /// Everything reserved so far, released as a unit on failure. 571 struct Reservation { 572 scheduler_id: Option, 573 frames: Option, 574 shadow: Option, 575 } 576 577 impl Reservation { 578 fn release( 579 &mut self, 580 platform: &mut P, 581 scheduler: &mut LoaderScheduler, 582 ) -> bool { 583 let mut ok = true; 584 for batch in [self.frames.take(), self.shadow.take()] 585 .into_iter() 586 .flatten() 587 { 588 for frame in batch.as_slice() { 589 platform.bytes_mut(frame.0 as u64, PAGE).fill(0); 590 } 591 ok &= platform.release_batch(batch); 592 } 593 if let Some(id) = self.scheduler_id.take() { 594 ok &= scheduler.remove(id).is_ok(); 595 } 596 ok 597 } 598 } 599 600 /// Verify, admit, reserve, map, hash, seal and install capabilities for the 601 /// artifact already staged at `staged_pa..staged_pa + staged_len`. 602 pub fn load( 603 platform: &mut P, 604 staged_pa: u64, 605 staged_len: usize, 606 verifier: &V, 607 policy: &AdmissionPolicy, 608 scheduler: &mut LoaderScheduler, 609 task_id: u32, 610 ) -> Result 611 where 612 P: LoaderPlatform, 613 V: ArtifactVerifier, 614 { 615 let mut bindings = ReceiptBindings::default(); 616 load_bound( 617 platform, 618 staged_pa, 619 staged_len, 620 verifier, 621 policy, 622 scheduler, 623 task_id, 624 &mut bindings, 625 ) 626 } 627 628 /// [`load`], also recording in `bindings` what each completed stage derived. 629 #[allow(clippy::too_many_arguments)] 630 pub fn load_bound( 631 platform: &mut P, 632 staged_pa: u64, 633 staged_len: usize, 634 verifier: &V, 635 policy: &AdmissionPolicy, 636 scheduler: &mut LoaderScheduler, 637 task_id: u32, 638 bindings: &mut ReceiptBindings, 639 ) -> Result 640 where 641 P: LoaderPlatform, 642 V: ArtifactVerifier, 643 { 644 bindings.policy_digest = policy.digest(); 645 // ---- Verified + Authorized: pure decisions over the staged bytes. 646 let free_slots = LOADED_TASK_SLOTS.saturating_sub(occupied_slots(scheduler)); 647 let (admission, code_src, data_src, code_len, data_len, data_memory_len) = { 648 let bytes = platform.bytes(staged_pa, staged_len); 649 // Identity is derivable from structure alone, before authentication. 650 if let Ok(identified) = aienos_artifact::verify::parse_and_identify(bytes) { 651 bindings.artifact_id = *identified.artifact_id.as_bytes(); 652 bindings.payload_digest = identified.payload_digest; 653 bindings.requested_capability_digest = 654 aienos_artifact::canonical::requested_capability_digest( 655 identified.artifact.capability_request_bytes, 656 ); 657 bindings.resource_envelope_digest = 658 aienos_artifact::canonical::resource_envelope_digest( 659 identified.artifact.resource_envelope_bytes, 660 ); 661 } 662 let verified = verifier 663 .verify(bytes) 664 .map_err(|e| (CandidateState::Verified, e.into()))?; 665 bindings.artifact_signer_fingerprint = *verified.signer_fingerprint(); 666 let available = available_resources(platform.free_frames(), free_slots); 667 let admission = policy 668 .evaluate(&verified, available) 669 .map_err(|e| (CandidateState::Authorized, e.into()))?; 670 bindings.granted_capability_digest = admission.granted_capability_digest; 671 let identified = verified.identified(); 672 if admission.artifact_id != identified.artifact_id 673 || admission.payload_digest != identified.payload_digest 674 { 675 return Err((CandidateState::Authorized, LoadError::MappedDigestMismatch)); 676 } 677 let artifact = &identified.artifact; 678 let offset_of = |slice: &[u8]| slice.as_ptr() as u64 - bytes.as_ptr() as u64; 679 ( 680 admission, 681 staged_pa + offset_of(artifact.code_bytes()), 682 staged_pa + offset_of(artifact.data_bytes()), 683 artifact.code_bytes().len(), 684 artifact.data_bytes().len(), 685 artifact.sections[1].memory_length as usize, 686 ) 687 }; 688 if admission.capability_count() > TASK_CAPABILITIES { 689 return Err(( 690 CandidateState::Authorized, 691 LoadError::Artifact(ArtifactError::ResourceLimit), 692 )); 693 } 694 let kernel_root = platform.kernel_root(); 695 let window_index = (1..256) 696 .find(|&index| read_entry(platform, kernel_root, index) == 0) 697 .ok_or((CandidateState::Reserved, LoadError::Mapping))?; 698 let layout = TaskLayout::new( 699 window_index, 700 &admission.resources, 701 code_len, 702 data_len, 703 data_memory_len, 704 admission.entry_offset, 705 ) 706 .map_err(|e| (CandidateState::Authorized, e))?; 707 708 // ---- Reserved: scheduler slot, content+table frames, shadow frames. 709 let mut reservation = Reservation { 710 scheduler_id: None, 711 frames: None, 712 shadow: None, 713 }; 714 macro_rules! fail { 715 ($stage:expr, $error:expr) => {{ 716 reservation.release(platform, scheduler); 717 return Err(($stage, $error)); 718 }}; 719 } 720 if scheduler.enqueue(task_id, TaskPriority::Normal).is_err() { 721 fail!(CandidateState::Reserved, LoadError::SchedulerFull); 722 } 723 reservation.scheduler_id = Some(task_id); 724 if layout.total_frames() > MAX_BATCH_FRAMES { 725 fail!(CandidateState::Reserved, LoadError::NoFrames); 726 } 727 let Some(frames) = platform.reserve_batch(layout.total_frames()) else { 728 fail!(CandidateState::Reserved, LoadError::NoFrames); 729 }; 730 reservation.frames = Some(frames); 731 let all = frames.as_slice(); 732 let code_frames = &all[..layout.code_pages]; 733 let shadow_need = match shadow_frames_needed(platform, kernel_root, code_frames) { 734 Ok(n) => n, 735 Err(e) => fail!(CandidateState::Reserved, e), 736 }; 737 if shadow_need > MAX_BATCH_FRAMES { 738 fail!(CandidateState::Reserved, LoadError::NoFrames); 739 } 740 let Some(shadow) = platform.reserve_batch(shadow_need) else { 741 fail!(CandidateState::Reserved, LoadError::NoFrames); 742 }; 743 reservation.shadow = Some(shadow); 744 745 // ---- Mapped: private tables, exact bytes copied through the NX alias. 746 let content = layout.content_frames(); 747 let (l0, l1, l2, l3) = ( 748 all[content].0 as u64, 749 all[content + 1].0 as u64, 750 all[content + 2].0 as u64, 751 all[content + 3].0 as u64, 752 ); 753 for frame in all.iter().chain(shadow.as_slice()) { 754 platform.bytes_mut(frame.0 as u64, PAGE).fill(0); 755 } 756 platform.copy(kernel_root, l0, PAGE); 757 write_entry(platform, l0, window_index, (l1 & ADDRESS_MASK) | DESC_TABLE); 758 write_entry(platform, l1, 0, (l2 & ADDRESS_MASK) | DESC_TABLE); 759 write_entry(platform, l2, 0, (l3 & ADDRESS_MASK) | DESC_TABLE); 760 for index in layout.data_first()..layout.window_pages() { 761 let leaf = layout.expected_leaf(index, all); 762 if leaf != 0 { 763 write_entry(platform, l3, index, leaf); 764 } 765 } 766 copy_section(platform, code_src, code_len, code_frames); 767 copy_section( 768 platform, 769 data_src, 770 data_len, 771 &all[layout.code_pages..layout.code_pages + layout.data_pages], 772 ); 773 774 // ---- Hashed: identified/verified/admitted == mapped. 775 let (payload, code_digest) = hash_loaded(platform, &layout, all); 776 if payload != admission.payload_digest { 777 fail!(CandidateState::Hashed, LoadError::MappedDigestMismatch); 778 } 779 bindings.mapped_bytes_matched = true; 780 781 // ---- Sealed: code becomes EL0 RX; its EL1 alias read-only in this root. 782 for frame in code_frames { 783 platform.sync_icache(frame.0 as u64, PAGE); 784 } 785 let shadow_used = match shadow_code_alias(platform, l0, code_frames, shadow.as_slice()) { 786 Ok(n) => n, 787 Err(e) => fail!(CandidateState::Sealed, e), 788 }; 789 for index in 1..1 + layout.code_pages { 790 write_entry(platform, l3, index, layout.expected_leaf(index, all)); 791 } 792 for table in all[content..] 793 .iter() 794 .chain(&shadow.as_slice()[..shadow_used]) 795 { 796 platform.clean_dcache(table.0 as u64, PAGE); 797 } 798 let address_space = TaskAddressSpace { 799 root: l0, 800 layout, 801 frames, 802 shadow, 803 shadow_used, 804 }; 805 if !audit_wx(platform, &address_space) { 806 fail!(CandidateState::Sealed, LoadError::WxAudit); 807 } 808 bindings.wx_sealed = true; 809 810 // ---- CapsInstalled: exactly the policy grants, in grant order. 811 let mut capabilities = CapTable::new(0x5441_0000 | (task_id & 0xffff)); 812 let mut handles = [None; TASK_CAPABILITIES]; 813 let mut grants = [None; MAX_CAPABILITIES]; 814 let grant_count = admission.capability_count(); 815 for (index, grant) in admission.capabilities().iter().enumerate() { 816 let Some(grant) = grant else { 817 fail!(CandidateState::CapsInstalled, LoadError::CapabilityInstall); 818 }; 819 match capabilities.insert(index as u32, grant.rights) { 820 Ok(handle) => handles[index] = Some(handle), 821 Err(_) => fail!(CandidateState::CapsInstalled, LoadError::CapabilityInstall), 822 } 823 grants[index] = Some(*grant); 824 } 825 let handle_array = layout.stack_top() - (grant_count as u64) * 8; 826 let top_frame = all[content - 1].0 as u64; 827 for (index, handle) in handles[..grant_count].iter().enumerate() { 828 let va = handle_array + (index as u64) * 8; 829 let offset = va - (layout.stack_top() - PAGE_U64); 830 let raw = handle.map_or(0, Handle::to_raw); 831 platform 832 .bytes_mut(top_frame + offset, 8) 833 .copy_from_slice(&raw.to_le_bytes()); 834 } 835 platform.clean_dcache(top_frame, PAGE); 836 837 Ok(LoadedTask { 838 artifact_id: admission.artifact_id, 839 trust_tier: admission.trust_tier, 840 payload_digest: payload, 841 code_digest, 842 address_space, 843 entry_pc: layout.entry_pc(), 844 stack_pointer: handle_array & !15, 845 handle_array, 846 capabilities, 847 handles, 848 grants, 849 grant_count, 850 resource_budget: admission.resources, 851 scheduler_id: task_id, 852 state: CandidateState::Admitted, 853 }) 854 } 855 856 fn occupied_slots(scheduler: &LoaderScheduler) -> usize { 857 scheduler.queue_len(0).unwrap_or(LOADED_TASK_SLOTS) 858 } 859 860 fn copy_section(p: &mut P, src: u64, len: usize, frames: &[PhysAddr]) { 861 for (index, frame) in frames.iter().enumerate() { 862 let start = index * PAGE; 863 if start >= len { 864 break; 865 } 866 let n = (len - start).min(PAGE); 867 p.copy(src + start as u64, frame.0 as u64, n); 868 } 869 } 870 871 /// SHA-256(code || data) and SHA-256(code), read back from private pages. 872 fn hash_loaded( 873 p: &P, 874 layout: &TaskLayout, 875 frames: &[PhysAddr], 876 ) -> (Digest, Digest) { 877 let mut payload = Sha256::new(); 878 let mut code = Sha256::new(); 879 for (index, frame) in frames[..layout.code_pages].iter().enumerate() { 880 let start = index * PAGE; 881 if start >= layout.code_len { 882 break; 883 } 884 let bytes = p.bytes(frame.0 as u64, (layout.code_len - start).min(PAGE)); 885 payload.update(bytes); 886 code.update(bytes); 887 } 888 let data = &frames[layout.code_pages..layout.code_pages + layout.data_pages]; 889 for (index, frame) in data.iter().enumerate() { 890 let start = index * PAGE; 891 if start >= layout.data_len { 892 break; 893 } 894 payload.update(p.bytes(frame.0 as u64, (layout.data_len - start).min(PAGE))); 895 } 896 (payload.finalize(), code.finalize()) 897 } 898 899 /// SHA-256 of the code bytes currently in a task's code frames. 900 pub fn code_digest(p: &P, space: &TaskAddressSpace) -> Digest { 901 let mut code = Sha256::new(); 902 for (index, frame) in space.code_frames().iter().enumerate() { 903 let start = index * PAGE; 904 if start >= space.layout.code_len { 905 break; 906 } 907 code.update(p.bytes(frame.0 as u64, (space.layout.code_len - start).min(PAGE))); 908 } 909 code.finalize() 910 } 911 912 // --------------------------------------------------------------------------- 913 // Read-only shadow of the kernel identity map for code frames 914 // --------------------------------------------------------------------------- 915 916 /// Distinct (L0), (L0,L1), (L0,L1,L2) prefixes covering `frames`: one private 917 /// L1, L2 and L3 table per prefix. Fails if the identity map does not reach 918 /// a frame through L0 table → L1 table/1 GiB block → L2 table/2 MiB block → L3 919 /// page. 920 fn shadow_frames_needed( 921 p: &P, 922 kernel_root: u64, 923 frames: &[PhysAddr], 924 ) -> Result { 925 let mut prefixes: [[u64; 3]; MAX_CODE_PAGES as usize] = 926 [[u64::MAX; 3]; MAX_CODE_PAGES as usize]; 927 let mut count = 0usize; 928 for (n, frame) in frames.iter().enumerate() { 929 let pa = frame.0 as u64; 930 kernel_translation(p, kernel_root, pa).ok_or(LoadError::Mapping)?; 931 let keys = [pa >> 39, pa >> 30, pa >> 21]; 932 for level in 0..3 { 933 if !prefixes[..n].iter().any(|k| k[level] == keys[level]) { 934 count += 1; 935 } 936 } 937 prefixes[n] = keys; 938 } 939 Ok(count) 940 } 941 942 /// Walk `root` for `va`; returns (leaf descriptor, level) of a valid leaf. 943 fn kernel_translation(p: &P, root: u64, va: u64) -> Option<(u64, usize)> { 944 let mut table = root; 945 for level in 0..4 { 946 let entry = read_entry(p, table, table_index(va, level)); 947 match (level, entry & DESC_TYPE) { 948 (3, DESC_TABLE) => return Some((entry, 3)), 949 (1 | 2, DESC_BLOCK) => return Some((entry, level)), 950 (0..=2, DESC_TABLE) => table = entry & ADDRESS_MASK, 951 _ => return None, 952 } 953 } 954 None 955 } 956 957 /// Privatise the path to every code frame in the task root and mark its 958 /// identity-map leaf read-only. Returns shadow frames used. 959 fn shadow_code_alias( 960 p: &mut P, 961 task_root: u64, 962 frames: &[PhysAddr], 963 shadow: &[PhysAddr], 964 ) -> Result { 965 let mut used = 0usize; 966 for frame in frames { 967 let pa = frame.0 as u64; 968 let mut table = task_root; 969 for level in 0..3 { 970 let index = table_index(pa, level); 971 let entry = read_entry(p, table, index); 972 let child = entry & ADDRESS_MASK; 973 let private = shadow[..used].iter().any(|f| f.0 as u64 == child); 974 let next = if entry & DESC_TYPE == DESC_TABLE && private { 975 child 976 } else { 977 let fresh = shadow.get(used).ok_or(LoadError::Mapping)?.0 as u64; 978 used += 1; 979 match (level, entry & DESC_TYPE) { 980 (_, DESC_TABLE) => p.copy(child, fresh, PAGE), 981 (1, DESC_BLOCK) => { 982 let attrs = entry & ATTR_MASK; 983 let base = entry & BLOCK_1G_MASK; 984 for k in 0..ENTRIES as u64 { 985 write_entry( 986 p, 987 fresh, 988 k as usize, 989 (base + (k << 21)) | attrs | DESC_BLOCK, 990 ); 991 } 992 } 993 (2, DESC_BLOCK) => { 994 let attrs = entry & ATTR_MASK; 995 let base = entry & BLOCK_2M_MASK; 996 for k in 0..ENTRIES as u64 { 997 write_entry( 998 p, 999 fresh, 1000 k as usize, 1001 (base + (k << 12)) | attrs | DESC_TABLE, 1002 ); 1003 } 1004 } 1005 _ => return Err(LoadError::Mapping), 1006 } 1007 write_entry( 1008 p, 1009 table, 1010 index, 1011 (entry & !ADDRESS_MASK & !DESC_TYPE) | fresh | DESC_TABLE, 1012 ); 1013 fresh 1014 }; 1015 table = next; 1016 } 1017 let index = table_index(pa, 3); 1018 let leaf = read_entry(p, table, index); 1019 if leaf & DESC_TYPE != DESC_TABLE || leaf & ADDRESS_MASK != pa { 1020 return Err(LoadError::Mapping); 1021 } 1022 write_entry(p, table, index, leaf | AP_READ_ONLY | PXN | UXN); 1023 } 1024 Ok(used) 1025 } 1026 1027 /// Fail-closed W^X audit of the sealed task root: 1028 /// - the user window holds exactly the expected leaves (code EL0 RO+X, data 1029 /// and stack EL0 RW+NX, guards unmapped) and nothing else; 1030 /// - every code frame's identity alias is read-only and never executable; 1031 /// - no user-window leaf is both writable and executable. 1032 pub fn audit_wx(p: &P, space: &TaskAddressSpace) -> bool { 1033 let layout = &space.layout; 1034 let root = space.root; 1035 let frames = space.frames(); 1036 let l0e = read_entry(p, root, layout.window_index); 1037 let l1 = l0e & ADDRESS_MASK; 1038 let content = layout.content_frames(); 1039 if l0e != (frames[content + 1].0 as u64 & ADDRESS_MASK) | DESC_TABLE { 1040 return false; 1041 } 1042 for index in 1..ENTRIES { 1043 if read_entry(p, l1, index) != 0 { 1044 return false; 1045 } 1046 } 1047 let l2 = read_entry(p, l1, 0) & ADDRESS_MASK; 1048 if l2 != frames[content + 2].0 as u64 { 1049 return false; 1050 } 1051 for index in 1..ENTRIES { 1052 if read_entry(p, l2, index) != 0 { 1053 return false; 1054 } 1055 } 1056 let l3 = read_entry(p, l2, 0) & ADDRESS_MASK; 1057 if l3 != frames[content + 3].0 as u64 { 1058 return false; 1059 } 1060 for index in 0..ENTRIES { 1061 let leaf = read_entry(p, l3, index); 1062 if leaf != layout.expected_leaf(index, frames) { 1063 return false; 1064 } 1065 let writable = leaf & AP_READ_ONLY == 0; 1066 let executable = leaf & UXN == 0 || leaf & PXN == 0; 1067 if leaf != 0 && writable && executable { 1068 return false; 1069 } 1070 } 1071 for frame in space.code_frames() { 1072 let pa = frame.0 as u64; 1073 match kernel_translation(p, root, pa) { 1074 Some((leaf, 3)) => { 1075 if leaf & ADDRESS_MASK != pa 1076 || leaf & AP_READ_ONLY == 0 1077 || leaf & PXN == 0 1078 || leaf & UXN == 0 1079 { 1080 return false; 1081 } 1082 } 1083 _ => return false, 1084 } 1085 } 1086 true 1087 } 1088 1089 // --------------------------------------------------------------------------- 1090 // Run and teardown 1091 // --------------------------------------------------------------------------- 1092 1093 /// Hand the task to the scheduler and run it when the scheduler selects it. 1094 pub fn run_task( 1095 task: &mut LoadedTask, 1096 platform: &mut P, 1097 scheduler: &mut LoaderScheduler, 1098 executor: &mut E, 1099 ) -> TaskOutcome 1100 where 1101 P: LoaderPlatform, 1102 E: TaskExecutor

, 1103 { 1104 let not_run = TaskOutcome::not_run(); 1105 if scheduler.tick(0) != Ok(Some(task.scheduler_id)) { 1106 return not_run; 1107 } 1108 task.state = CandidateState::Running; 1109 let args = task.args(); 1110 let budget = task.budget(); 1111 let context = TaskContext { 1112 root: task.address_space.root, 1113 entry_pc: task.entry_pc, 1114 stack_pointer: task.stack_pointer, 1115 args, 1116 capabilities: &mut task.capabilities, 1117 grants: &task.grants[..task.grant_count], 1118 budget, 1119 }; 1120 executor.execute(context, platform) 1121 } 1122 1123 /// Re-hash executed code, revoke every capability, scrub and release every 1124 /// frame, and free the scheduler slot. Always completes. 1125 pub fn destroy( 1126 mut task: LoadedTask, 1127 platform: &mut P, 1128 scheduler: &mut LoaderScheduler, 1129 ) -> Teardown { 1130 let executed_bytes_match = code_digest(platform, &task.address_space) == task.code_digest; 1131 for handle in task.handles.iter_mut() { 1132 if let Some(h) = handle.take() { 1133 let _ = task.capabilities.remove(h); 1134 } 1135 } 1136 let caps_live_after = task.capabilities.live_count(); 1137 let mut reservation = Reservation { 1138 scheduler_id: Some(task.scheduler_id), 1139 frames: Some(task.address_space.frames), 1140 shadow: Some(task.address_space.shadow), 1141 }; 1142 let released = reservation.release(platform, scheduler); 1143 Teardown { 1144 executed_bytes_match, 1145 caps_live_after, 1146 released, 1147 } 1148 } 1149 1150 /// Stage, verify, admit, load, run and destroy one candidate on `platform`. 1151 pub fn process_candidate( 1152 bytes: &[u8], 1153 platform: &mut P, 1154 verifier: &V, 1155 policy: &AdmissionPolicy, 1156 scheduler: &mut LoaderScheduler, 1157 executor: &mut E, 1158 task_id: u32, 1159 ) -> CandidateReport 1160 where 1161 P: LoaderPlatform, 1162 V: ArtifactVerifier, 1163 E: TaskExecutor

, 1164 { 1165 let free_before = platform.free_frames(); 1166 let mut report = empty_report(free_before); 1167 let reject = |mut report: CandidateReport, stage, error, free_after| { 1168 report.decision = Decision::Rejected; 1169 report.failed_stage = Some(stage); 1170 report.error = Some(error); 1171 report.frames_free_after = free_after; 1172 report 1173 }; 1174 let pages = bytes.len().div_ceil(PAGE); 1175 if bytes.is_empty() || pages > MAX_STAGING_FRAMES { 1176 return reject( 1177 report, 1178 CandidateState::Received, 1179 LoadError::StagingTooLarge, 1180 platform.free_frames(), 1181 ); 1182 } 1183 let Some(staged) = platform.reserve_contiguous(pages) else { 1184 return reject( 1185 report, 1186 CandidateState::Staged, 1187 LoadError::NoFrames, 1188 platform.free_frames(), 1189 ); 1190 }; 1191 platform.bytes_mut(staged, pages * PAGE).fill(0); 1192 platform 1193 .bytes_mut(staged, bytes.len()) 1194 .copy_from_slice(bytes); 1195 let loaded = load_bound( 1196 platform, 1197 staged, 1198 bytes.len(), 1199 verifier, 1200 policy, 1201 scheduler, 1202 task_id, 1203 &mut report.bindings, 1204 ); 1205 // The task owns its own copy; staging is scrubbed and returned now. 1206 platform.bytes_mut(staged, pages * PAGE).fill(0); 1207 let staging_released = platform.release_contiguous(staged, pages); 1208 let mut task = match loaded { 1209 Ok(task) => task, 1210 Err((stage, error)) => { 1211 let error = if staging_released { 1212 error 1213 } else { 1214 LoadError::Reclaim 1215 }; 1216 return reject(report, stage, error, platform.free_frames()); 1217 } 1218 }; 1219 report.artifact_id = Some(task.artifact_id); 1220 report.trust_tier = Some(task.trust_tier); 1221 report.frames_reserved = task.address_space.frames_reserved(); 1222 report.caps_installed = task.grant_count; 1223 report.granted = task.grants; 1224 report.code_base = task.address_space.layout.code_base(); 1225 report.code_end = task.address_space.layout.code_end(); 1226 report.data_base = task.address_space.layout.data_base(); 1227 report.data_end = task.address_space.layout.data_end(); 1228 report.stack_base = task.address_space.layout.stack_base(); 1229 report.stack_end = task.address_space.layout.stack_top(); 1230 report.wx_enforced = report.bindings.wx_sealed; 1231 report.outcome = run_task(&mut task, platform, scheduler, executor); 1232 let teardown = destroy(task, platform, scheduler); 1233 report.decision = Decision::Admitted; 1234 report.byte_chain = report.bindings.mapped_bytes_matched && teardown.executed_bytes_match; 1235 report.caps_live_after = teardown.caps_live_after; 1236 report.frames_free_after = platform.free_frames(); 1237 if !teardown.executed_bytes_match { 1238 report.error = Some(LoadError::ExecutedDigestMismatch); 1239 } else if !teardown.released || !staging_released { 1240 report.error = Some(LoadError::Reclaim); 1241 } 1242 report 1243 } 1244 1245 fn empty_report(free_before: usize) -> CandidateReport { 1246 CandidateReport { 1247 decision: Decision::Rejected, 1248 failed_stage: None, 1249 error: None, 1250 artifact_id: None, 1251 trust_tier: None, 1252 frames_reserved: 0, 1253 frames_free_before: free_before, 1254 frames_free_after: free_before, 1255 caps_installed: 0, 1256 caps_live_after: 0, 1257 byte_chain: false, 1258 wx_enforced: false, 1259 outcome: TaskOutcome::not_run(), 1260 code_base: 0, 1261 code_end: 0, 1262 data_base: 0, 1263 data_end: 0, 1264 stack_base: 0, 1265 stack_end: 0, 1266 bindings: ReceiptBindings::default(), 1267 granted: [None; MAX_CAPABILITIES], 1268 } 1269 } 1270 1271 // --------------------------------------------------------------------------- 1272 // Boot platform (early allocator + identity map) 1273 // --------------------------------------------------------------------------- 1274 1275 /// The early-boot platform: frames from `boot`'s allocator, memory through 1276 /// the kernel identity map. 1277 pub struct EarlyPlatform { 1278 kernel_root: u64, 1279 } 1280 1281 impl LoaderPlatform for EarlyPlatform { 1282 fn kernel_root(&self) -> u64 { 1283 self.kernel_root 1284 } 1285 fn free_frames(&self) -> usize { 1286 crate::boot::early_free_frames() 1287 } 1288 fn reserve_batch(&mut self, count: usize) -> Option { 1289 crate::boot::reserve_early_frames(count) 1290 } 1291 fn release_batch(&mut self, batch: FrameBatch) -> bool { 1292 crate::boot::release_early_frames(batch) 1293 } 1294 fn reserve_contiguous(&mut self, count: usize) -> Option { 1295 crate::boot::reserve_early_contiguous(count).map(|pa| pa.0 as u64) 1296 } 1297 fn release_contiguous(&mut self, start: u64, count: usize) -> bool { 1298 crate::boot::release_early_contiguous(PhysAddr(start as usize), count) 1299 } 1300 fn bytes(&self, pa: u64, len: usize) -> &[u8] { 1301 // SAFETY: the kernel identity map covers RAM and page-table pools. 1302 unsafe { core::slice::from_raw_parts(pa as usize as *const u8, len) } 1303 } 1304 fn bytes_mut(&mut self, pa: u64, len: usize) -> &mut [u8] { 1305 // SAFETY: the loader only writes frames it reserved. 1306 unsafe { core::slice::from_raw_parts_mut(pa as usize as *mut u8, len) } 1307 } 1308 fn copy(&mut self, src: u64, dst: u64, len: usize) { 1309 // SAFETY: distinct frames owned by or staged for the loader. 1310 unsafe { 1311 core::ptr::copy_nonoverlapping(src as usize as *const u8, dst as usize as *mut u8, len) 1312 } 1313 } 1314 fn clean_dcache(&mut self, pa: u64, len: usize) { 1315 cache_maintenance(pa as usize, len, false); 1316 } 1317 fn sync_icache(&mut self, pa: u64, len: usize) { 1318 cache_maintenance(pa as usize, len, true); 1319 } 1320 } 1321 1322 #[cfg(target_arch = "aarch64")] 1323 fn cache_maintenance(address: usize, length: usize, instructions: bool) { 1324 let ctr: u64; 1325 // SAFETY: CTR_EL0 read and cache maintenance by VA on owned memory. 1326 unsafe { 1327 core::arch::asm!("mrs {0}, ctr_el0", out(reg) ctr, options(nomem, nostack)); 1328 let dline = 4usize << ((ctr >> 16) & 0xf); 1329 let iline = 4usize << (ctr & 0xf); 1330 for at in (address & !(dline - 1)..address + length).step_by(dline) { 1331 core::arch::asm!("dc cvau, {0}", in(reg) at, options(nostack)); 1332 } 1333 core::arch::asm!("dsb ish", options(nostack)); 1334 if instructions { 1335 for at in (address & !(iline - 1)..address + length).step_by(iline) { 1336 core::arch::asm!("ic ivau, {0}", in(reg) at, options(nostack)); 1337 } 1338 core::arch::asm!("dsb ish", "isb", options(nostack)); 1339 } 1340 } 1341 } 1342 1343 #[cfg(not(target_arch = "aarch64"))] 1344 fn cache_maintenance(_address: usize, _length: usize, _instructions: bool) {} 1345 1346 /// Enters EL0 through [`crate::task_runtime::run`]. 1347 pub struct El0Executor { 1348 kernel_root: usize, 1349 } 1350 1351 impl TaskExecutor for El0Executor { 1352 fn execute(&mut self, task: TaskContext<'_>, _platform: &mut EarlyPlatform) -> TaskOutcome { 1353 // SAFETY: caller of `run_boot_candidate` guarantees the EL1 context. 1354 unsafe { crate::task_runtime::run(task, self.kernel_root) } 1355 } 1356 } 1357 1358 static BOOT_SCHEDULER: crate::sync::spinlock::SpinLock = 1359 crate::sync::spinlock::SpinLock::new(Scheduler::new([0])); 1360 static NEXT_TASK_ID: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(1); 1361 1362 static NEXT_RECEIPT_SEQUENCE: core::sync::atomic::AtomicU64 = core::sync::atomic::AtomicU64::new(1); 1363 1364 /// A candidate refused by the boot handoff before the kernel saw its bytes. 1365 pub fn firmware_rejection(error: LoadError) -> CandidateReport { 1366 let free = crate::boot::early_free_frames(); 1367 let mut report = empty_report(free); 1368 report.failed_stage = Some(CandidateState::Received); 1369 report.error = Some(error); 1370 report.bindings.policy_digest = boot_policy_digest(); 1371 report 1372 } 1373 1374 /// Next boot-scoped receipt sequence (from 1) and the candidate's unsigned 1375 /// canonical receipt. `None` only if the report violates §7, which would be 1376 /// a loader bug; callers report it rather than emit a malformed record. 1377 pub fn boot_receipt( 1378 report: &CandidateReport, 1379 context: &ReceiptContext, 1380 ) -> (u64, Option<[u8; RECEIPT_SIZE]>) { 1381 let sequence = NEXT_RECEIPT_SEQUENCE.fetch_add(1, core::sync::atomic::Ordering::Relaxed); 1382 let record = build_receipt(report, context, sequence) 1383 .ok() 1384 .map(|receipt| aienos_artifact::receipt::encode(&receipt)); 1385 (sequence, record) 1386 } 1387 1388 /// Digest of the local boot admission policy (ADR 0014 §5). 1389 pub fn boot_policy_digest() -> Digest { 1390 boot_policy(&boot_signers()).map_or([0; 32], |policy| policy.digest()) 1391 } 1392 1393 /// Verifier identity digest for this build (ADR 0014 §7.1). 1394 pub fn boot_verifier_identity(commit: &str) -> Digest { 1395 let feature = u8::from(cfg!(feature = "seed0b-test-anchor")); 1396 match aienos_artifact::receipt::verifier_identity_bytes( 1397 commit.as_bytes(), 1398 aienos_artifact::format::TARGET_AARCH64_LE, 1399 aienos_artifact::format::ABI_V1, 1400 feature, 1401 ) { 1402 Some(bytes) => aienos_artifact::canonical::verifier_identity_digest(&bytes), 1403 None => aienos_artifact::canonical::verifier_identity_digest(b"unpinned-build"), 1404 } 1405 } 1406 1407 fn boot_signers() -> [Digest; BOOT_SIGNERS] { 1408 #[cfg(feature = "seed0b-test-anchor")] 1409 { 1410 [aienos_artifact::signature::signer_fingerprint( 1411 &aienos_artifact::signature::seed0b_test_anchor::PUBLIC_KEY, 1412 )] 1413 } 1414 #[cfg(not(feature = "seed0b-test-anchor"))] 1415 { 1416 [] 1417 } 1418 } 1419 1420 #[cfg(feature = "seed0b-test-anchor")] 1421 const BOOT_SIGNERS: usize = 1; 1422 #[cfg(not(feature = "seed0b-test-anchor"))] 1423 const BOOT_SIGNERS: usize = 0; 1424 1425 /// Stage, verify, admit, load, run and destroy one candidate. 1426 /// 1427 /// # Safety 1428 /// EL1, single core, after `boot::early_kernel_enter` initialised the frame 1429 /// allocator and after exception vectors, GIC and timer are set up. 1430 pub unsafe fn run_boot_candidate(bytes: &[u8], kernel_root: usize) -> CandidateReport { 1431 #[cfg(feature = "seed0b-test-anchor")] 1432 let anchors = aienos_artifact::signature::seed0b_test_anchor::Seed0bTestAnchorSet; 1433 #[cfg(not(feature = "seed0b-test-anchor"))] 1434 let anchors = aienos_artifact::ProductionTrustAnchorSet::default(); 1435 let signers = boot_signers(); 1436 let verifier = aienos_artifact::ConfiguredArtifactVerifier::new( 1437 &anchors, 1438 aienos_artifact::Ed25519Verifier, 1439 ); 1440 let mut platform = EarlyPlatform { 1441 kernel_root: kernel_root as u64, 1442 }; 1443 let Ok(policy) = boot_policy(&signers) else { 1444 let mut report = empty_report(platform.free_frames()); 1445 report.failed_stage = Some(CandidateState::Authorized); 1446 report.error = Some(LoadError::Artifact(ArtifactError::ResourceLimit)); 1447 return report; 1448 }; 1449 let mut executor = El0Executor { kernel_root }; 1450 let task_id = NEXT_TASK_ID.fetch_add(1, core::sync::atomic::Ordering::Relaxed); 1451 let mut scheduler = BOOT_SCHEDULER.lock(); 1452 process_candidate( 1453 bytes, 1454 &mut platform, 1455 &verifier, 1456 &policy, 1457 &mut scheduler, 1458 &mut executor, 1459 task_id, 1460 ) 1461 } 1462 1463 // --------------------------------------------------------------------------- 1464 // Admission Receipt v0 emission (ADR 0014 §7) 1465 // --------------------------------------------------------------------------- 1466 1467 /// Verifier-context facts a receipt binds that the loader does not derive. 1468 #[derive(Clone, Copy, Debug, Eq, PartialEq)] 1469 pub struct ReceiptContext { 1470 pub verifier_identity: Digest, 1471 pub tier: QualificationTier, 1472 } 1473 1474 /// Build the unsigned canonical receipt for one candidate from what the 1475 /// loader and runtime observed. Every record passes the strict §7 rules 1476 /// before it is returned; nothing is filled from expectations. 1477 pub fn build_receipt( 1478 report: &CandidateReport, 1479 context: &ReceiptContext, 1480 sequence: u64, 1481 ) -> Result { 1482 let b = &report.bindings; 1483 let admitted = report.decision == Decision::Admitted; 1484 let o = &report.outcome; 1485 let (execution_status, exit_status) = if admitted { 1486 match o.status { 1487 ExecutionStatus::NotRun => (ExecutionStatusCode::NotRun, 0), 1488 ExecutionStatus::Exited(code) => (ExecutionStatusCode::Exited, code as u32 as i32), 1489 ExecutionStatus::Timeout => (ExecutionStatusCode::Timeout, 0), 1490 ExecutionStatus::Fault { .. } => (ExecutionStatusCode::Fault, 0), 1491 ExecutionStatus::BadSyscall(_) => (ExecutionStatusCode::BadSyscall, 0), 1492 ExecutionStatus::ResourceOverrun => (ExecutionStatusCode::ResourceOverrun, 0), 1493 } 1494 } else { 1495 (ExecutionStatusCode::NotRun, 0) 1496 }; 1497 let mut result_flags = 0; 1498 let mut set = |on: bool, flag: u32| { 1499 if on { 1500 result_flags |= flag; 1501 } 1502 }; 1503 set(report.reclaimed(), RESULT_RECLAIMED); 1504 if admitted { 1505 set(o.object_reads_ok > 0, RESULT_READ_OK); 1506 set(o.write_denials > 0, RESULT_WRITE_DENIED); 1507 set(o.invalid_handle_denials > 0, RESULT_FORGED_DENIED); 1508 set( 1509 execution_status == ExecutionStatusCode::Exited && exit_status == 0, 1510 RESULT_CANARY_PASSED, 1511 ); 1512 set(b.mapped_bytes_matched, RESULT_MAPPED_BYTES_MATCH); 1513 set(report.byte_chain, RESULT_EXECUTED_BYTES_MATCH); 1514 set(b.wx_sealed, RESULT_WX_SEALED); 1515 } 1516 let (rejection_stage, rejection_reason) = if admitted { 1517 (0, 0) 1518 } else { 1519 ( 1520 report.failed_stage.map_or(0, CandidateState::stage_code), 1521 report.error.map_or(0, LoadError::reason_code), 1522 ) 1523 }; 1524 let counter = |v: u32| if admitted { v } else { 0 }; 1525 let receipt = Receipt { 1526 flags: 0, 1527 decision: if admitted { 1528 ReceiptDecision::Admitted 1529 } else { 1530 ReceiptDecision::Rejected 1531 }, 1532 tier: context.tier, 1533 sequence, 1534 nonce: receipt_nonce(&context.verifier_identity, sequence), 1535 observed_time_ns: 0, 1536 execution_status, 1537 exit_status, 1538 result_flags, 1539 rejection_stage, 1540 rejection_reason, 1541 syscalls: counter(o.syscalls), 1542 object_reads_ok: counter(o.object_reads_ok), 1543 denials: counter(o.denials), 1544 frames_reserved: u32::try_from(report.frames_reserved).unwrap_or(u32::MAX), 1545 artifact_id: b.artifact_id, 1546 payload_digest: b.payload_digest, 1547 artifact_signer_fingerprint: b.artifact_signer_fingerprint, 1548 policy_digest: b.policy_digest, 1549 requested_capability_digest: b.requested_capability_digest, 1550 granted_capability_digest: b.granted_capability_digest, 1551 resource_envelope_digest: b.resource_envelope_digest, 1552 verifier_identity: context.verifier_identity, 1553 machine_id_digest: [0; 32], 1554 generation: 0, 1555 context_id: 0, 1556 }; 1557 validate_receipt(&receipt)?; 1558 Ok(receipt) 1559 } 1560 1561 /// One `grant:` line per capability the task actually received, so the 1562 /// evidence shows granted ⊆ requested directly. 1563 pub fn write_grant_lines(out: &mut impl core::fmt::Write, name: &str, r: &CandidateReport) { 1564 for (index, grant) in r.granted.iter().enumerate() { 1565 let Some(g) = grant else { continue }; 1566 let kind = match g.resource.kind() { 1567 crate::abi::ResourceKind::Object => "object", 1568 crate::abi::ResourceKind::Channel => "channel", 1569 _ => "other", 1570 }; 1571 let _ = writeln!( 1572 out, 1573 "grant: {name}[{index}] kind={kind} id={} rights={:#x} bounds={}+{} max_ops={} max_bytes={}", 1574 g.resource.id(), 1575 g.rights.bits(), 1576 g.bounds.byte_offset, 1577 g.bounds.byte_length, 1578 g.bounds.max_operations, 1579 g.bounds.max_bytes, 1580 ); 1581 } 1582 } 1583 1584 /// `receipt: NAME seq=N digest=HEX64 record=HEX1024` — the unsigned record 1585 /// the host qualification harness checks, signs and verifies. 1586 pub fn write_receipt_line( 1587 out: &mut impl core::fmt::Write, 1588 name: &str, 1589 sequence: u64, 1590 record: &[u8; RECEIPT_SIZE], 1591 ) { 1592 let _ = write!(out, "receipt: {name} seq={sequence} digest="); 1593 for byte in receipt_digest(record) { 1594 let _ = write!(out, "{byte:02x}"); 1595 } 1596 let _ = write!(out, " record="); 1597 for byte in record { 1598 let _ = write!(out, "{byte:02x}"); 1599 } 1600 let _ = writeln!(out); 1601 } 1602 1603 /// Names an EL0 fault from its ESR and FAR. A label that claims a W^X or NX 1604 /// property requires both the architectural fault kind and the address range 1605 /// that property is about, so a wild or unmapped access can never prove it. 1606 fn classify_fault(r: &CandidateReport, esr: u64, far: u64) -> &'static str { 1607 let ec = (esr >> 26) & 0x3f; 1608 // ISS[5:2] of the IFSC/DFSC: 0b0011 = permission fault, 0b0001 = 1609 // translation fault (any level). 1610 let status = (esr >> 2) & 0xf; 1611 let permission = status == 0b0011; 1612 let translation = status == 0b0001; 1613 let within = |base: u64, end: u64| far >= base && far < end; 1614 let in_data_or_stack = within(r.data_base, r.data_end) || within(r.stack_base, r.stack_end); 1615 match ec { 1616 // Data abort from EL0 with ISS.WnR set: a write. 1617 0x24 if esr & (1 << 6) != 0 && permission && within(r.code_base, r.code_end) => { 1618 "code-write" 1619 } 1620 // Instruction abort from EL0. 1621 0x20 if permission && in_data_or_stack => "exec-nx", 1622 0x20 if translation => "exec-unmapped", 1623 _ => "other", 1624 } 1625 } 1626 1627 /// One stable report line per candidate. Formats (QEMU checks grep these): 1628 /// 1629 /// `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` 1630 /// `artifact: NAME rejected stage=STAGE reason=REASON reclaimed=yes` 1631 /// 1632 /// EXEC is `exited:0x..`, `timeout`, `fault:code-write`, `fault:exec-nx`, 1633 /// `fault:exec-unmapped`, `fault:other`, `bad-syscall:N`, `resource-overrun`, 1634 /// or `not-run`. 1635 pub fn write_candidate_line(out: &mut impl core::fmt::Write, name: &str, r: &CandidateReport) { 1636 let yes_no = |b: bool| if b { "yes" } else { "no" }; 1637 match r.decision { 1638 Decision::Rejected => { 1639 let stage = r.failed_stage.map_or("unknown", CandidateState::name); 1640 let _ = write!(out, "artifact: {name} rejected stage={stage} reason="); 1641 match r.error { 1642 Some(LoadError::Artifact(e)) => { 1643 let _ = write!(out, "{e:?}"); 1644 } 1645 Some(e) => { 1646 let _ = write!(out, "{e:?}"); 1647 } 1648 None => { 1649 let _ = write!(out, "unknown"); 1650 } 1651 } 1652 let _ = writeln!(out, " reclaimed={}", yes_no(r.reclaimed())); 1653 } 1654 Decision::Admitted => { 1655 let _ = write!(out, "artifact: {name} admitted id="); 1656 if let Some(id) = r.artifact_id { 1657 for byte in &id.as_bytes()[..8] { 1658 let _ = write!(out, "{byte:02x}"); 1659 } 1660 } 1661 let tier = match r.trust_tier { 1662 Some(TrustTier::Seed0bQualification) => "seed0b-test", 1663 Some(TrustTier::Production) => "production", 1664 None => "none", 1665 }; 1666 let _ = write!(out, " tier={tier} exec="); 1667 match r.outcome.status { 1668 ExecutionStatus::NotRun => { 1669 let _ = write!(out, "not-run"); 1670 } 1671 ExecutionStatus::Exited(code) => { 1672 let _ = write!(out, "exited:{code:#x}"); 1673 } 1674 ExecutionStatus::Timeout => { 1675 let _ = write!(out, "timeout"); 1676 } 1677 ExecutionStatus::Fault { esr, far, .. } => { 1678 let _ = write!(out, "fault:{}", classify_fault(r, esr, far)); 1679 } 1680 ExecutionStatus::BadSyscall(n) => { 1681 let _ = write!(out, "bad-syscall:{n}"); 1682 } 1683 ExecutionStatus::ResourceOverrun => { 1684 let _ = write!(out, "resource-overrun"); 1685 } 1686 } 1687 let _ = writeln!( 1688 out, 1689 " bytes={} wx={} caps={} revoked={} reclaimed={} frames={} syscalls={} reads={} denials={}", 1690 if r.byte_chain { 1691 "identified=verified=admitted=mapped=executed" 1692 } else { 1693 "mismatch" 1694 }, 1695 if r.wx_enforced { 1696 "enforced" 1697 } else { 1698 "violated" 1699 }, 1700 r.caps_installed, 1701 yes_no(r.caps_live_after == 0), 1702 yes_no(r.reclaimed()), 1703 r.frames_reserved, 1704 r.outcome.syscalls, 1705 r.outcome.object_reads_ok, 1706 r.outcome.denials, 1707 ); 1708 } 1709 } 1710 } 1711 1712 #[cfg(test)] 1713 #[path = "artifact_loader_tests.rs"] 1714 mod tests;