// K2165 guest experiment: A/B read-only version slots (`update_slots.slots`) in // the product kernel runtime. Active slot A (v1, 48 bytes) is initialized as // ActiveReadOnly with its domain-separated `TurkOS/ELF-PROGRAM/v1\0` SHA-256 // digest. An EL0 negative actor (`k2165-attacker`) attempts to stage/write/ // finalize on active slot A (refused with ActiveSlotReadOnly = 1) and attempts // to finalize an incomplete 16-byte update on slot B (refused with // IncompleteUpdate = 7 and rolled back to Empty with zero leases). Then EL0 // `k2165-updater` stages a complete 56-byte v2 candidate image into inactive // slot B across three sequential chunks, finalizes slot B to StagedReady, and // confirms active slot A's SHA-256 digest remains constant while all user-space // frames are returned (`free_after == free_before`). use super::feature_el0 as el0; use turkos_kernel::runtime::update_slots_slots::{ digest_prefix_u64, program_digest, Error, SlotId, SlotManager, SlotPhase, SlotPlan, }; use core::arch::asm; use core::ptr::{addr_of, addr_of_mut, read_volatile, write_volatile}; #[unsafe(no_mangle)] static mut OS_K2165_EVIDENCE: [u64; 64] = [0; 64]; #[unsafe(no_mangle)] static mut OS_K2165_CAPTURE_GATE: u8 = 0; static ATTACKER: &[u8] = include_bytes!("k2165-attacker.bin"); static UPDATER: &[u8] = include_bytes!("k2165-updater.bin"); const MAGIC: u64 = 0x4b32_3136_355f_534c; // "K2165_SL" const SYS_EXIT: u64 = 1; const SYS_BEGIN_STAGING: u64 = 16; const SYS_WRITE_CHUNK: u64 = 17; const SYS_FINALIZE: u64 = 18; const SYS_ABORT: u64 = 19; const SYS_VERIFY_ACTIVE: u64 = 20; const REFUSED: u64 = 1 << 63; const ACTIVE_ENTRY: u64 = 0x8000_0000; const ACTIVE_CODE: &[u8] = b"TURKOS-SLOT-A-CODE-V1-READONLY!!"; const ACTIVE_DATA: &[u8] = b"SLOT-A-CONFIG-V1"; const NEXT_ENTRY: u64 = 0x8000_1000; const NEXT_CODE: &[u8] = b"TURKOS-SLOT-B-CODE-V2-CANDIDATE!"; const NEXT_DATA: &[u8] = b"SLOT-B-CONFIG-V2-PAYLOAD"; const ATTACKER_ID: el0::Identity = el0::Identity { pid: 9, generation: 0x2165_0009, }; const UPDATER_ID: el0::Identity = el0::Identity { pid: 1, generation: 0x2165_0001, }; struct State { mgr: Option, user: Option, expected_a: [u8; 32], expected_b: [u8; 32], calls: usize, base: usize, } static mut STATE: State = State { mgr: None, user: None, expected_a: [0; 32], expected_b: [0; 32], calls: 0, base: 0, }; fn state() -> &'static mut State { unsafe { &mut *addr_of_mut!(STATE) } } fn word(i: usize, v: u64) { unsafe { write_volatile( addr_of_mut!(OS_K2165_EVIDENCE).cast::().add(i), v, ) } } #[inline(never)] fn checkpoint(stage: u64) { word(1, stage); unsafe { write_volatile(addr_of_mut!(OS_K2165_CAPTURE_GATE), 0) }; el0::write_fields("TURKOS/OS/K2165: CAPTURE", &[("STAGE", stage)]); while unsafe { read_volatile(addr_of!(OS_K2165_CAPTURE_GATE)) } == 0 { unsafe { asm!("yield", options(nomem, nostack, preserves_flags)) } } } fn slot_from_arg(arg: u64) -> Result { match arg { 0 => Ok(SlotId::A), 1 => Ok(SlotId::B), _ => Err(Error::InvalidConfig), } } #[inline(never)] fn setup_stage() -> Result<(u64, u64), &'static str> { let expected_a = program_digest(ACTIVE_ENTRY, ACTIVE_CODE, ACTIVE_DATA); let expected_b = program_digest(NEXT_ENTRY, NEXT_CODE, NEXT_DATA); let mgr = SlotManager::new(SlotId::A, 1, ACTIVE_ENTRY, ACTIVE_CODE, ACTIVE_DATA) .map_err(|_| "k2165-init")?; let s = mgr.status(); let pref_a = digest_prefix_u64(&s.active_digest); let pref_b = digest_prefix_u64(&expected_b); for (j, v) in [ s.active_slot as u64, s.inactive_slot as u64, s.active_phase as u64, s.inactive_phase as u64, s.active_version, s.active_bytes as u64, pref_a, pref_b, ] .into_iter() .enumerate() { word(4 + j, v); } let st = state(); st.expected_a = expected_a; st.expected_b = expected_b; st.mgr = Some(mgr); Ok((pref_a, pref_b)) } fn dispatch(_caller: el0::Identity, frame: &mut el0::Frame) -> el0::Step { let st = state(); let expected_b = st.expected_b; let mgr = st.mgr.as_mut().unwrap(); let r = match frame.number() { SYS_BEGIN_STAGING => match slot_from_arg(frame.arg(0)) { Ok(slot) => { let plan = SlotPlan { version: frame.arg(1), entry: NEXT_ENTRY, code_len: NEXT_CODE.len(), data_len: NEXT_DATA.len(), expected_digest: expected_b, }; match mgr.begin_staging(slot, plan) { Ok(()) => 0, Err(e) => REFUSED | (e as u64), } } Err(e) => REFUSED | (e as u64), }, SYS_WRITE_CHUNK => match slot_from_arg(frame.arg(0)) { Ok(slot) => { let offset = frame.arg(1) as usize; let chunk: &[u8] = match frame.arg(2) { 0 => &NEXT_CODE[..16], 1 => &NEXT_CODE[16..], 2 => NEXT_DATA, _ => b"", }; match mgr.write_chunk(slot, offset, chunk) { Ok(written) => written as u64, Err(e) => REFUSED | (e as u64), } } Err(e) => REFUSED | (e as u64), }, SYS_FINALIZE => match slot_from_arg(frame.arg(0)) { Ok(slot) => match mgr.finalize_staging(slot) { Ok(digest) => digest_prefix_u64(&digest), Err(e) => REFUSED | (e as u64), }, Err(e) => REFUSED | (e as u64), }, SYS_ABORT => match slot_from_arg(frame.arg(0)) { Ok(slot) => match mgr.abort_staging(slot) { Ok(()) => 0, Err(e) => REFUSED | (e as u64), }, Err(e) => REFUSED | (e as u64), }, SYS_VERIFY_ACTIVE => match mgr.verify_active_intact() { Ok(digest) => digest_prefix_u64(&digest), Err(e) => REFUSED | (e as u64), }, SYS_EXIT => return el0::Step::Exit(frame.arg(0)), _ => return el0::Step::Exit(0xbad), }; if st.calls < 8 { word(st.base + st.calls, r); st.calls += 1; } frame.ret(r); el0::Step::Resume } #[inline(never)] fn run_program( allocator: &mut super::memory::FrameAllocator, tables: &super::mmu::Tables, boot: &super::BootData, id: el0::Identity, image: &[u8], args: [u64; 2], base: usize, ) -> Result { let st = state(); st.user = Some( unsafe { tables.build_user_space(allocator, boot.hardware.ram_base, boot.hardware.ram_size) } .map_err(|_| "k2165-user")?, ); let user = st.user.as_ref().unwrap(); if !user.contract_valid(tables.root) { return Err("k2165-user-contract"); } unsafe { el0::load(user, image) }?; st.calls = 0; st.base = base; let mut handler = dispatch; let outcome = unsafe { el0::run(st.user.as_ref().unwrap(), id, args, &mut handler) }; let user = st.user.take().unwrap(); unsafe { user.release_after_tlbi(allocator, tables.root) }.map_err(|_| "k2165-release")?; Ok(outcome) } #[inline(never)] fn record_attacker(attacker: &el0::Outcome) { let s = state().mgr.as_ref().unwrap().status(); for (j, v) in [ attacker.exit, attacker.syscalls, attacker.fault, s.inactive_phase as u64, s.staging_leases, s.active_write_refusals, s.incomplete_refusals, digest_prefix_u64(&s.active_digest), ] .into_iter() .enumerate() { word(20 + j, v); } } #[inline(never)] fn finish_stage( attacker: &el0::Outcome, updater: &el0::Outcome, free_before: u64, free_after: u64, pref_a: u64, pref_b: u64, ) -> Result<(), &'static str> { let mgr = state().mgr.as_ref().unwrap(); let verified_a = mgr.verify_active_intact().map_err(|_| "k2165-active-corrupted")?; let s = mgr.status(); let act_pref = digest_prefix_u64(&verified_a); let stg_pref = digest_prefix_u64(&s.staged_digest); for (j, v) in [ updater.exit, updater.syscalls, updater.fault, s.active_slot as u64, s.active_phase as u64, s.inactive_phase as u64, s.active_version, s.staged_version, s.active_bytes as u64, s.staged_bytes as u64, act_pref, stg_pref, s.staging_leases, s.chunks_written, s.committed_updates, s.rejected, ] .into_iter() .enumerate() { word(36 + j, v); } word(3, free_after); if free_after != free_before { return Err("k2165-frame-accounting"); } if attacker.exit != 0x2164 || updater.exit != 56 || s.active_phase != SlotPhase::ActiveReadOnly || s.inactive_phase != SlotPhase::StagedReady || act_pref != pref_a || stg_pref != pref_b || s.staging_leases != 0 || s.active_write_refusals != 3 || s.incomplete_refusals != 1 || s.committed_updates != 1 { return Err("k2165-outcome"); } checkpoint(3); el0::write_fields( "TURKOS/OS/K2165-UPDATE-SLOTS:", &[ ("ACTIVE_SLOT", s.active_slot as u64), ("STAGED_SLOT", s.inactive_slot as u64), ("ACTIVE_HASH", act_pref), ("STAGED_HASH", stg_pref), ("STAGED_BYTES", s.staged_bytes as u64), ("REFUSED_ACTIVE", s.active_write_refusals), ("REFUSED_INCOMPLETE", s.incomplete_refusals), ("FREE_EQUAL", 1), ], ); Ok(()) } #[inline(never)] fn run_inner( runtime: &mut super::OsK660Runtime, tables: &super::mmu::Tables, boot: &super::BootData, ) -> Result<(), &'static str> { let allocator = &mut runtime.memory_mut().map_err(|_| "k2165-memory")?.allocator; let free_before = allocator.remaining_pages() as u64; word(0, MAGIC); word(2, free_before); let (pref_a, pref_b) = setup_stage()?; checkpoint(1); let attacker = run_program( allocator, tables, boot, ATTACKER_ID, ATTACKER, [pref_a, pref_b], 12, )?; record_attacker(&attacker); checkpoint(2); let updater = run_program( allocator, tables, boot, UPDATER_ID, UPDATER, [pref_a, pref_b], 28, )?; let free_after = allocator.remaining_pages() as u64; finish_stage(&attacker, &updater, free_before, free_after, pref_a, pref_b) } extern "C" fn entry( runtime: *mut super::OsK660Runtime, tables: *const super::mmu::Tables, boot: *const super::BootData, out: *mut Result<(), &'static str>, ) { unsafe { *out = run_inner(&mut *runtime, &*tables, &*boot) } } #[inline(never)] pub fn run( runtime: &mut super::OsK660Runtime, tables: &super::mmu::Tables, boot: &super::BootData, ) -> Result<(), &'static str> { let mut out: Result<(), &'static str> = Ok(()); let top = (addr_of!(super::OS_K900_STACK) as u64 + 4096 + 65536 - 16) & !15; unsafe { asm!( "mov x9, sp", "mov sp, x4", "stp x9, x30, [sp, #-16]!", "blr x5", "ldp x9, x30, [sp], #16", "mov sp, x9", in("x0") runtime as *mut _, in("x1") tables as *const _, in("x2") boot as *const _, in("x3") &mut out as *mut _, in("x4") top, in("x5") entry as usize, clobber_abi("C"), ) }; out }