From b62bf9515e3fb2742256539f9de8076855889baa Mon Sep 17 00:00:00 2001 From: Quant-TheodoreFelix <53819958+Quant-TheodoreFelix@users.noreply.github.com> Date: Fri, 13 Nov 2026 05:32:24 +0900 Subject: [PATCH 1/2] Add serial console input and an operator terminal - Kernel receive path for PL011 and SBSA UART behind `console-input`, with the logic in a new host tested crate `k0-conin` - `CONSOLE_READ` with one waiter, timeouts and rights on the `Console` capability - Console interrupt number from the device tree or SPCR, shown in the platform line - Vault gets an operator role, `INIT` only delivers the seed and `KEYGEN` makes the key - New crate `k0-term` and a service stage in the root task behind `terminal` - `tools/term-test.py`, judge mode in the boot test and new matrix rows --- Cargo.lock | 13 + Cargo.toml | 3 + crates/k0-abi/src/lib.rs | 61 ++- crates/k0-abi/src/tests.rs | 18 +- crates/k0-arch/Cargo.toml | 4 + crates/k0-arch/src/conin.rs | 205 +++++++++ crates/k0-arch/src/earlycon.rs | 6 +- crates/k0-arch/src/earlycon/uart.rs | 11 +- crates/k0-arch/src/irq.rs | 333 ++++++++++++++- crates/k0-arch/src/lib.rs | 2 + crates/k0-boot/Cargo.toml | 4 + crates/k0-boot/build.rs | 4 + crates/k0-boot/src/platform.rs | 76 +++- crates/k0-boot/src/platform/tests.rs | 85 +++- crates/k0-boot/src/testing.rs | 1 + crates/k0-cap/Cargo.toml | 5 + crates/k0-cap/src/lib.rs | 44 +- crates/k0-cap/src/tests.rs | 73 +++- crates/k0-conin/Cargo.toml | 8 + crates/k0-conin/src/lib.rs | 345 +++++++++++++++ crates/k0-conin/src/tests.rs | 601 +++++++++++++++++++++++++++ crates/k0-efi/src/acpi.rs | 15 +- crates/k0-efi/src/synth.rs | 8 + crates/k0-efi/src/tests.rs | 48 ++- crates/k0-ipc/Cargo.toml | 3 + crates/k0-ipc/src/console.rs | 232 +++++++++++ crates/k0-ipc/src/lib.rs | 18 +- crates/k0-task/Cargo.toml | 2 + crates/k0-task/src/lib.rs | 4 + kernel/Cargo.toml | 7 + kernel/src/main.rs | 75 +++- kernel/src/syscall.rs | 97 ++++- tools/boot-matrix.sh | 102 +++++ tools/host-test.sh | 5 +- tools/qemu-boot-test.sh | 68 ++- tools/term-test.py | 328 +++++++++++++++ userspace/k0-term/Cargo.toml | 14 + userspace/k0-term/src/lib.rs | 550 ++++++++++++++++++++++++ userspace/k0-term/src/tests.rs | 563 +++++++++++++++++++++++++ userspace/k0-term/src/wire.rs | 148 +++++++ userspace/k0-vault/src/proto.rs | 192 ++++++++- userspace/k0-vault/src/server.rs | 128 +++++- userspace/k0-vault/src/tests.rs | 373 ++++++++++++++--- userspace/root-task/Cargo.toml | 10 +- userspace/root-task/src/main.rs | 237 ++++++++++- userspace/root-task/src/oracle.rs | 175 +++++--- userspace/root-task/src/service.rs | 398 ++++++++++++++++++ 47 files changed, 5464 insertions(+), 238 deletions(-) create mode 100644 crates/k0-arch/src/conin.rs create mode 100644 crates/k0-conin/Cargo.toml create mode 100644 crates/k0-conin/src/lib.rs create mode 100644 crates/k0-conin/src/tests.rs create mode 100644 crates/k0-ipc/src/console.rs create mode 100755 tools/term-test.py create mode 100644 userspace/k0-term/Cargo.toml create mode 100644 userspace/k0-term/src/lib.rs create mode 100644 userspace/k0-term/src/tests.rs create mode 100644 userspace/k0-term/src/wire.rs create mode 100644 userspace/root-task/src/service.rs diff --git a/Cargo.lock b/Cargo.lock index ad657a8..3d65e9b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -120,6 +120,7 @@ name = "k0-arch" version = "0.1.0" dependencies = [ "k0-abi", + "k0-conin", ] [[package]] @@ -133,6 +134,10 @@ dependencies = [ name = "k0-cap" version = "0.1.0" +[[package]] +name = "k0-conin" +version = "0.1.0" + [[package]] name = "k0-efi" version = "0.1.0" @@ -202,6 +207,13 @@ dependencies = [ "k0-mm", ] +[[package]] +name = "k0-term" +version = "0.1.0" +dependencies = [ + "k0-vault", +] + [[package]] name = "k0-vault" version = "0.1.0" @@ -240,6 +252,7 @@ name = "root-task" version = "0.1.0" dependencies = [ "k0-abi", + "k0-term", "k0-vault", ] diff --git a/Cargo.toml b/Cargo.toml index 4de7ed5..01efbac 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,8 +11,10 @@ members = [ "crates/k0-boot", "crates/k0-abi", "crates/k0-efi", + "crates/k0-conin", "userspace/root-task", "userspace/k0-vault", + "userspace/k0-term", "loader", ] # UEFI 로더는 타겟이 달라(aarch64-unknown-uefi) 기본 빌드 대상에서 뺌. @@ -28,6 +30,7 @@ default-members = [ "crates/k0-boot", "crates/k0-abi", "crates/k0-efi", + "crates/k0-conin", "userspace/root-task", ] diff --git a/crates/k0-abi/src/lib.rs b/crates/k0-abi/src/lib.rs index 3b2b87a..66050a9 100644 --- a/crates/k0-abi/src/lib.rs +++ b/crates/k0-abi/src/lib.rs @@ -34,9 +34,11 @@ pub const PA_CEILING: u64 = KERNEL_IMAGE_VA - KERNEL_VA_OFFSET; pub mod syscall { /// 바이트 하나를 커널 디버그 콘솔로 출력 /// - /// x0 = Console 슬롯, x1 = 바이트(하위 8비트만 사용). 출력 가능한 - /// ASCII(0x20-0x7E)와 개행만 그대로 나가고 그 외 바이트(터미널 제어 - /// 문자 등)는 `?`로 바뀝니다. 성공 시 x0 = 0, 실패 시 음수 에러 + /// x0 = Console 슬롯(쓰기 권한 W 필요), x1 = 바이트(하위 8비트만 사용). + /// 출력 가능한 ASCII(0x20-0x7E)와 개행만 그대로 나가고 그 외 바이트(터미널 + /// 제어 문자 등)는 `?`로 바뀝니다. `console-input`으로 빌드한 이미지에서 + /// 읽기 권한 R도 있는 케이퍼빌리티로 부르면 백스페이스(0x08)가 그대로 + /// 나갑니다(입력한 글자를 지우는 데 필요). 성공 시 x0 = 0, 실패 시 음수 에러 pub const DEBUG_PUTC: u64 = 0; /// 스케줄러 양보(준비된 다른 태스크가 없으면 즉시 복귀) pub const YIELD: u64 = 1; @@ -104,8 +106,8 @@ pub mod syscall { /// /// x0 = 원본 슬롯, x1 = 목적지 CNode를 가리키는 CNode 슬롯, x2 = 그 /// CNode 안의 빈 목적지 슬롯, x3 = 남길 권한 비트([super::rights]), - /// x4 = 배지(0 = 붙이지 않음). 권한은 줄일 수만 있고 Frame / Endpoint에만 - /// 적용됩니다. 배지는 배지가 없는 Endpoint에만 붙일 수 있습니다. 복사본은 + /// x4 = 배지(0 = 붙이지 않음). 권한은 줄일 수만 있고 Frame / Endpoint / + /// Console에만 적용됩니다. 배지는 배지가 없는 Endpoint에만 붙일 수 있습니다. 복사본은 /// 원본의 자식이라 원본을 회수하거나 삭제하면 함께 사라집니다. Untyped와 /// PageTable은 복사할 수 없습니다. 성공 시 x0 = 0 pub const CAP_COPY: u64 = 12; @@ -125,6 +127,34 @@ pub mod syscall { /// x0 = 슬롯. untyped를 회수하면 거기서 잘라낸 오브젝트가 전부 종료되고 /// 메모리를 다시 재분류할 수 있습니다. 성공 시 x0 = 0 pub const CAP_REVOKE: u64 = 15; + /// 콘솔 입력에서 바이트 하나를 읽음(커널을 `console-input`으로 빌드한 + /// 이미지에만 있음) + /// + /// x0 = Console 슬롯(읽기 권한 R 필요), x1 = 플래그([super::console]). + /// 받아 둔 바이트가 없으면 올 때까지 블록됩니다. 한 번에 한 태스크만 + /// 기다릴 수 있습니다. 성공 시 x0 = 0, x1 = 바이트, x2 = 이 바이트 바로 + /// 앞에서 입력이 유실됐으면 [super::console::LOST], 아니면 0. 커널은 + /// 바이트를 해석하지 않습니다. 기다리는 동안 그 케이퍼빌리티를 잃으면 + /// REVOKED로 깨어납니다 + pub const CONSOLE_READ: u64 = 16; +} + +/// CONSOLE_READ의 플래그(x1)와 결과(x2) 모듈입니다. +pub mod console { + /// 받아 둔 바이트가 없으면 블록 대신 WOULD_BLOCK으로 즉시 복귀 + pub const NONBLOCK: u64 = 1; + /// 읽기 전에, 지금까지 받아 둔 입력과 유실 표시를 전부 버림 + /// + /// 프롬프트를 내기 전에 들어온 입력이 명령으로 읽히지 않게 하는 데 + /// 씁니다. 버리는 양은 커널의 버퍼와 장치의 FIFO 크기로 묶여 있습니다 + pub const FLUSH: u64 = 2; + /// 플래그 레지스터에서 뜻이 정해지지 않은 비트. 하나라도 서 있으면 + /// BAD_FLAGS로 거부됩니다. 상위 32비트는 IPC와 같은 형식의 타임아웃입니다 + /// ([super::ipc::TIMEOUT_SHIFT]) + pub const RESERVED: u64 = 0xFFFF_FFFC; + /// 결과(x2): 이 바이트 바로 앞에서 입력이 유실됨(장치의 FIFO가 넘쳤거나 + /// 오류가 난 문자를 버렸음) + pub const LOST: u64 = 1; } /// IPC 플래그(x1) 모듈입니다. @@ -185,9 +215,9 @@ pub mod perm { /// 케이퍼빌리티 권한 비트 모듈입니다. (CAP_COPY의 x3) pub mod rights { - /// Frame: 읽기 매핑, Endpoint: 수신 + /// Frame: 읽기 매핑, Endpoint: 수신, Console: 입력 읽기 pub const R: u64 = 1; - /// Frame: 쓰기 매핑, Endpoint: 송신 + /// Frame: 쓰기 매핑, Endpoint: 송신, Console: 출력 pub const W: u64 = 2; /// Frame: 실행 매핑 pub const X: u64 = 4; @@ -231,7 +261,8 @@ pub mod err { pub const NO_REPLY: i64 = -15; /// 케이퍼빌리티에 이 연산에 필요한 권한 비트가 없음 pub const NO_RIGHTS: i64 = -16; - /// 대기하던 엔드포인트가 종료됨 + /// 대기하던 엔드포인트가 종료됨. 콘솔 입력을 기다리던 중이라면 그 + /// Console 케이퍼빌리티를 잃었음 pub const REVOKED: i64 = -17; /// 배지를 붙일 수 없는 케이퍼빌리티이거나 이미 다른 배지가 있음 pub const BAD_BADGE: i64 = -18; @@ -245,6 +276,10 @@ pub mod err { pub const REPLY_TIMEOUT: i64 = -21; /// IPC 플래그 레지스터에 뜻이 정해지지 않은 비트가 서 있음 pub const BAD_FLAGS: i64 = -22; + /// 다른 태스크가 이미 콘솔 입력을 기다리는 중임 + pub const BUSY: i64 = -23; + /// 이 이미지나 이 기계에 콘솔 입력 경로가 없거나, 커널이 그 경로를 껐음 + pub const NO_DEVICE: i64 = -24; } /// 커널이 루트 태스크에 RO로 매핑해 주는 bootinfo 페이지 모듈입니다. @@ -257,7 +292,10 @@ pub mod bootinfo { /// bootinfo 페이지의 사용자 VA(양 플랫폼 그래뉼 정렬) pub const VA: u64 = 0x0F00_0000; /// 레이아웃 버전(불일치 시 루트 태스크는 진행하면 안 됨) - pub const VERSION: u64 = 3; + /// + /// 버전 4부터 Console 케이퍼빌리티에 권한 비트가 있습니다(R = 입력 읽기, + /// W = 출력). 디스크립터의 `rights`가 그 값을 알립니다 + pub const VERSION: u64 = 4; /// 루트 태스크의 진입 레지스터 x4로 오는 시드 정보에서, 시드에 들어간 /// `rng-seed` 바이트 수를 담는 비트 @@ -301,8 +339,9 @@ pub mod bootinfo { /// /// untyped는 `base` / `size`가 물리 구간입니다. 루트 태스크 이미지의 /// Frame은 `base`가 그 프레임이 루트 주소 공간에 매핑된 VA, `size`가 - /// 프레임 크기, `rights`가 권한 비트([super::rights])입니다. 나머지 - /// 종류는 전부 0입니다(커널 내부 주소 노출 최소화). + /// 프레임 크기, `rights`가 권한 비트([super::rights])입니다. Console은 + /// `rights`만 채웁니다. 나머지 종류는 전부 0입니다(커널 내부 주소 노출 + /// 최소화). #[repr(C)] pub struct CapDesc { pub kind: u64, diff --git a/crates/k0-abi/src/tests.rs b/crates/k0-abi/src/tests.rs index 389192d..e6b6c81 100644 --- a/crates/k0-abi/src/tests.rs +++ b/crates/k0-abi/src/tests.rs @@ -29,6 +29,7 @@ fn syscall_numbers_are_unique_and_dense() { syscall::CAP_MOVE, syscall::CAP_DELETE, syscall::CAP_REVOKE, + syscall::CONSOLE_READ, ]; assert_unique(&nrs.map(i128::from)); for (i, nr) in nrs.iter().enumerate() { @@ -61,6 +62,8 @@ fn error_codes_are_unique_and_negative() { err::TIMEOUT, err::REPLY_TIMEOUT, err::BAD_FLAGS, + err::BUSY, + err::NO_DEVICE, ]; assert_unique(&errs.map(i128::from)); for e in errs { @@ -132,9 +135,22 @@ fn flag_register_bits_are_all_accounted_for() { assert_eq!(ipc::NONBLOCK | ipc::RESERVED | ipc::timeout(u32::MAX), u64::MAX); } +#[test] +fn console_read_flag_bits_are_all_accounted_for() { + assert_eq!(console::NONBLOCK & console::FLUSH, 0); + assert_eq!((console::NONBLOCK | console::FLUSH) & console::RESERVED, 0); + assert_eq!( + console::NONBLOCK | console::FLUSH | console::RESERVED | ipc::timeout(u32::MAX), + u64::MAX + ); + // 블록하지 않는 읽기는 IPC와 같은 비트를 씀 + assert_eq!(console::NONBLOCK, ipc::NONBLOCK); + assert_eq!(console::LOST, 1); +} + #[test] fn bootinfo_layout_is_stable() { - assert_eq!(bootinfo::VERSION, 3); + assert_eq!(bootinfo::VERSION, 4); assert_eq!(bootinfo::SEED_RNG_SEED_BYTES & bootinfo::SEED_RNDR, 0); assert_eq!(size_of::(), 32); assert_eq!(offset_of!(bootinfo::Header, version), 0); diff --git a/crates/k0-arch/Cargo.toml b/crates/k0-arch/Cargo.toml index e35d1ff..ba1c618 100644 --- a/crates/k0-arch/Cargo.toml +++ b/crates/k0-arch/Cargo.toml @@ -13,6 +13,10 @@ publish.workspace = true console-pl011 = [] # 16550 계열. 읽기만으로 확인할 식별 레지스터가 없음 console-16550 = [] +# 콘솔 입력의 수신 경로(UART 수신 인터럽트와 그 SPI 하나). 수신 드라이버는 +# PL011과 SBSA UART에만 있어서 console-pl011과 함께 골라야 입력이 생김 +console-input = ["dep:k0-conin"] [dependencies] k0-abi = { path = "../k0-abi" } +k0-conin = { path = "../k0-conin", optional = true } diff --git a/crates/k0-arch/src/conin.rs b/crates/k0-arch/src/conin.rs new file mode 100644 index 0000000..04de2ef --- /dev/null +++ b/crates/k0-arch/src/conin.rs @@ -0,0 +1,205 @@ +//! 콘솔 입력의 커널 쪽 접착부 모듈입니다. +//! +//! # Features +//! 수신 로직(링, 게이트, 유실 표시, 원인 없는 인터럽트의 차단)은 `k0-conin` +//! 크레이트에 있고 호스트에서 가짜 UART로 시험됩니다. 이 모듈은 그 로직을 실제 +//! UART의 레지스터와 커널의 static 하나에 잇기만 합니다. feature +//! `console-input`이 켜져 있을 때만 빌드되므로, 고르지 않은 이미지에는 UART에서 +//! 읽는 코드가 없습니다. +//! +//! 수신 드라이버는 PL011과 SBSA UART에만 있습니다(feature `console-pl011`). +//! 16550 콘솔에서는 [prepare]가 false를 돌려주고 입력이 없습니다. +//! +//! 수신 상태는 인터럽트 핸들러와 시스템 콜 경로가 함께 씁니다. 단일 코어이고 +//! 모든 접근이 인터럽트를 마스크한 구간 안에서 이루어지므로 서로 겹치지 +//! 않습니다. 핸들러는 링에 바이트를 옮기기만 하고 스케줄러는 건드리지 않습니다. +//! 기다리는 태스크를 깨우는 일은 커널이 자기 문맥에서 합니다. + +#[cfg(feature = "console-pl011")] +mod pl011 { + use core::cell::UnsafeCell; + use core::sync::atomic::{AtomicBool, Ordering}; + + use k0_conin::{Irq, Reg, Regs, Rx}; + + use crate::earlycon::{mask_irqs, pl011_base, restore_irqs}; + + /// 매핑된 UART 레지스터에 닿는 통로입니다. + struct Mmio(usize); + + impl Regs for Mmio { + fn read(&mut self, reg: Reg) -> u32 { + // SAFETY: prepare의 계약대로 매핑된 PL011 레지스터에 대한 volatile 접근 + unsafe { core::ptr::read_volatile((self.0 + reg.offset()) as *const u32) } + } + + fn write(&mut self, reg: Reg, value: u32) { + // SAFETY: prepare의 계약대로 매핑된 PL011 레지스터에 대한 volatile 접근 + unsafe { core::ptr::write_volatile((self.0 + reg.offset()) as *mut u32, value) } + } + } + + struct Cell(UnsafeCell); + + // SAFETY: 단일 코어이고 모든 접근이 with 안에서 인터럽트를 마스크한 채 + // 이루어지므로 동시에 두 곳에서 접근하지 않음 + unsafe impl Sync for Cell {} + + static RX: Cell = Cell(UnsafeCell::new(Rx::new(true))); + /// prepare가 끝나 수신 경로가 준비됐는지 + static READY: AtomicBool = AtomicBool::new(false); + + /// 인터럽트를 마스크한 채 수신 상태에 접근하는 함수입니다. 수신 경로가 + /// 준비되지 않았으면 `None`입니다. + fn with(f: impl FnOnce(&mut Rx, &mut Mmio) -> R) -> Option { + if !READY.load(Ordering::Relaxed) { + return None; + } + let base = pl011_base()?; + let daif = mask_irqs(); + // SAFETY: 인터럽트가 마스크된 단일 코어 구간이라 이 가변 참조는 유일함. + // 핸들러 안에서 불려도 그 핸들러가 끊은 코드는 이 구간 밖에 있음 + let r = f(unsafe { &mut *RX.0.get() }, &mut Mmio(base)); + restore_irqs(daif); + Some(r) + } + + pub unsafe fn prepare(has_cr: bool) -> bool { + let Some(base) = pl011_base() else { + return false; + }; + let daif = mask_irqs(); + // SAFETY: 인터럽트가 마스크된 단일 코어 구간이고, 아직 READY가 아니라 + // 다른 경로는 이 상태에 접근하지 않음 + unsafe { *RX.0.get() = Rx::new(has_cr) }; + Rx::quiesce(&mut Mmio(base)); + READY.store(true, Ordering::Relaxed); + restore_irqs(daif); + true + } + + pub fn available() -> bool { + with(|rx, _| !rx.is_off()).unwrap_or(false) + } + + pub fn open() { + with(|rx, regs| rx.open(regs)); + } + + pub fn pop() -> Option<(u8, bool)> { + with(|rx, regs| rx.pop(regs)).flatten() + } + + pub fn flush() { + with(|rx, regs| rx.flush(regs)); + } + + pub fn poll() { + with(|rx, regs| rx.poll(regs)); + } + + pub fn has_data() -> bool { + with(|rx, _| rx.has_data()).unwrap_or(false) + } + + pub fn shut() { + with(|rx, regs| rx.turn_off(regs)); + } + + pub(crate) fn interrupt() -> Irq { + with(|rx, regs| rx.interrupt(regs)).unwrap_or(Irq::Spurious) + } +} + +/// 수신 드라이버가 없는 빌드(16550만 고른 커널)에서 자리를 채우는 모듈입니다. +/// 이 빌드에는 UART에서 읽는 코드가 없습니다. +#[cfg(not(feature = "console-pl011"))] +mod pl011 { + pub unsafe fn prepare(_has_cr: bool) -> bool { + false + } + + pub fn available() -> bool { + false + } + + pub fn open() {} + + pub fn pop() -> Option<(u8, bool)> { + None + } + + pub fn flush() {} + + pub fn poll() {} + + pub fn has_data() -> bool { + false + } + + pub fn shut() {} + + pub(crate) fn interrupt() -> k0_conin::Irq { + k0_conin::Irq::Spurious + } +} + +/// 붙어 있는 콘솔에 수신 경로를 준비하는 함수입니다. UART의 인터럽트를 전부 +/// 막아 두기만 하고 켜지는 않습니다(켜는 것은 [open]). +/// +/// 인터럽트 컨트롤러에서 콘솔의 선을 켜기 전에 불러야 합니다. 수신 드라이버가 +/// 없는 UART면 false를 돌려줍니다. +/// +/// # Arguments +/// `has_cr` - 제어 레지스터가 있는 UART(PL011)면 true, SBSA UART면 false +/// +/// # Safety +/// 콘솔이 [crate::earlycon::attach]로 붙어 있어야 하고, 그 레지스터 프레임에서 +/// 수신 로직이 쓰는 범위(오프셋 0x48 미만)가 Device로 매핑돼 있어야 합니다. +pub unsafe fn prepare(has_cr: bool) -> bool { + // SAFETY: 함수 계약을 그대로 전달 + unsafe { pl011::prepare(has_cr) } +} + +/// 입력 경로가 있고 꺼지지 않았는지 알려 주는 함수입니다. +pub fn available() -> bool { + pl011::available() +} + +/// 입력을 쓰기 시작하는 함수입니다. 그동안 장치에 쌓인 바이트를 버리고 수신 +/// 인터럽트를 켭니다. 이미 열린 경로에는 아무 일도 하지 않습니다. +pub fn open() { + pl011::open(); +} + +/// 받아 둔 바이트 하나를 꺼내는 함수입니다. 둘째 값은 이 바이트 바로 앞에서 +/// 입력이 유실됐는지입니다. +pub fn pop() -> Option<(u8, bool)> { + pl011::pop() +} + +/// 받아 둔 입력과 유실 표시를 전부 버리는 함수입니다. +pub fn flush() { + pl011::flush(); +} + +/// 인터럽트 없이 장치의 FIFO를 들여다보는 함수입니다. 틱마다, 그리고 읽는 +/// 태스크가 잠들기 직전에 부릅니다. +pub fn poll() { + pl011::poll(); +} + +/// 꺼낼 바이트가 있는지 알려 주는 함수입니다. +pub fn has_data() -> bool { + pl011::has_data() +} + +/// 입력 경로를 끄는 함수입니다. 되돌리지 않습니다. +pub fn shut() { + pl011::shut(); +} + +/// 콘솔 인터럽트 하나를 처리하는 함수입니다. +pub(crate) fn interrupt() -> k0_conin::Irq { + pl011::interrupt() +} diff --git a/crates/k0-arch/src/earlycon.rs b/crates/k0-arch/src/earlycon.rs index 74d1119..87f7a6b 100644 --- a/crates/k0-arch/src/earlycon.rs +++ b/crates/k0-arch/src/earlycon.rs @@ -38,6 +38,8 @@ pub use uart::{Uart, attach, attached}; #[cfg(any(feature = "console-pl011", feature = "console-16550"))] use uart::hw_put; +#[cfg(all(feature = "console-pl011", feature = "console-input"))] +pub(crate) use uart::pl011_base; /// 드라이버가 하나도 없는 빌드에서 UART 송신 자리를 채우는 함수입니다. /// 아무것도 하지 않으며, 이 빌드에는 UART에 접근하는 코드가 없습니다. @@ -123,14 +125,14 @@ fn log_push(b: u8, user: bool) { restore_irqs(daif); } -fn mask_irqs() -> u64 { +pub(crate) fn mask_irqs() -> u64 { let daif: u64; // SAFETY: DAIF를 읽고 전부 마스크함, 호출자가 restore_irqs로 되돌림 unsafe { asm!("mrs {}, daif", "msr daifset, #0xf", out(reg) daif, options(nostack)) }; daif } -fn restore_irqs(daif: u64) { +pub(crate) fn restore_irqs(daif: u64) { // SAFETY: mask_irqs가 읽어 둔 값을 그대로 복원함 unsafe { asm!("msr daif, {}", in(reg) daif, options(nostack)) }; } diff --git a/crates/k0-arch/src/earlycon/uart.rs b/crates/k0-arch/src/earlycon/uart.rs index e74340f..13c8e48 100644 --- a/crates/k0-arch/src/earlycon/uart.rs +++ b/crates/k0-arch/src/earlycon/uart.rs @@ -1,7 +1,9 @@ //! 콘솔 UART 송신 드라이버 모듈입니다. //! //! # Features -//! 커널이 기계 밖으로 출력을 내보내는 유일한 경로입니다. 송신만 합니다. +//! 커널이 기계 밖으로 출력을 내보내는 유일한 경로입니다. 송신만 합니다(수신은 +//! feature `console-input`을 고른 빌드에서 [crate::conin]이 같은 레지스터 +//! 프레임으로 따로 합니다). //! 초기화 쓰기와 보율 설정은 하지 않고 부트로더가 켜 둔 상태를 그대로 씁니다. //! 송신 가능 대기에는 시간 상한이 있어서, 응답 없는 UART가 인터럽트를 막은 채 //! 커널을 붙잡지 못합니다. @@ -188,6 +190,13 @@ pub unsafe fn attach(uart: Uart, base: usize, counter_hz: u64) { } } +/// 붙어 있는 콘솔이 PL011(또는 SBSA UART)이면 그 레지스터 0의 주소를 주는 +/// 함수입니다. 수신 경로가 같은 레지스터 프레임을 씁니다. +#[cfg(all(feature = "console-pl011", feature = "console-input"))] +pub(crate) fn pl011_base() -> Option { + (KIND.load(Ordering::Relaxed) == KIND_PL011).then(|| BASE.load(Ordering::Relaxed)) +} + /// 콘솔이 붙어 있는지 알려 주는 함수입니다. pub fn attached() -> bool { KIND.load(Ordering::Relaxed) != KIND_NONE diff --git a/crates/k0-arch/src/irq.rs b/crates/k0-arch/src/irq.rs index 2567ed7..e49befc 100644 --- a/crates/k0-arch/src/irq.rs +++ b/crates/k0-arch/src/irq.rs @@ -9,6 +9,10 @@ //! 정리한 뒤, 타이머 PPI 하나만 켭니다. 가상 타이머를 쓰는 이유는 하이퍼바이저 //! 게스트에서도 항상 쓸 수 있는 타이머가 그것뿐이기 때문입니다. //! +//! feature `console-input`을 고른 빌드에서는 콘솔 UART의 SPI 하나를 더 받을 수 +//! 있습니다([enable_console_irq]). 그 번호는 DTB가 알려 준 것이라 틀릴 수 있고, +//! 틀린 번호가 선을 붙들면 수신 로직이 몇 번 만에 그 선을 끕니다([crate::conin]). +//! //! 설계상 발생할 수 없는 FIQ와 미지의 `INTID`는 fail-secure로 정지합니다. //! //! 틱 주기는 1초입니다. 틱은 선점 신호이면서 IPC 타임아웃의 단위이고, EL0가 @@ -62,6 +66,15 @@ pub enum IrqError { NoFrequency, /// 타이머의 INTID가 PPI 범위(16..=31) 밖 BadIntid, + /// 콘솔 인터럽트 번호가 이 컨트롤러의 SPI 범위 밖임 + #[cfg(feature = "console-input")] + SpiOutOfRange, + /// 콘솔의 SPI를 레벨 트리거로 둘 수 없음 + #[cfg(feature = "console-input")] + SpiNotLevel, + /// 콘솔의 SPI가 이 보안 상태의 것이 아님(켜기 비트가 서지 않음) + #[cfg(feature = "console-input")] + SpiNotOwned, } const KIND_NONE: u8 = 0; @@ -74,6 +87,18 @@ static GICC: AtomicUsize = AtomicUsize::new(0); static TIMER_INTID: AtomicU32 = AtomicU32::new(0); static TIMER_HZ: AtomicU64 = AtomicU64::new(0); static TICKS: AtomicU64 = AtomicU64::new(0); +/// 디스트리뷰터 레지스터의 가상 주소(콘솔의 SPI를 켜고 끄는 데 씀) +#[cfg(feature = "console-input")] +static GICD: AtomicUsize = AtomicUsize::new(0); +/// 이 컨트롤러가 구현한 INTID의 수(1020을 넘지 않게 묶음) +#[cfg(feature = "console-input")] +static INTID_LIMIT: AtomicU32 = AtomicU32::new(0); +/// 콘솔의 INTID. 켠 적이 없으면 어떤 INTID와도 같지 않은 값 +#[cfg(feature = "console-input")] +static CONSOLE_INTID: AtomicU32 = AtomicU32::new(u32::MAX); +/// 주기적인 틱 줄을 멈췄는지 +#[cfg(feature = "console-input")] +static QUIET_TICKS: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false); /// 로그에 남기는 틱 줄의 수. 이후의 틱은 콘솔에만 찍음 const LOGGED_TICKS: u64 = 4; @@ -137,10 +162,33 @@ pub mod gicv3 { use super::*; const GICD_CTLR: usize = 0x0000; - const GICD_TYPER: usize = 0x0004; + pub(super) const GICD_TYPER: usize = 0x0004; + #[cfg(feature = "console-input")] + const GICD_IGROUPR: usize = 0x0080; + #[cfg(feature = "console-input")] + const GICD_ISENABLER: usize = 0x0100; const GICD_ICENABLER: usize = 0x0180; const GICD_ICPENDR: usize = 0x0280; const GICD_ICACTIVER: usize = 0x0380; + #[cfg(feature = "console-input")] + const GICD_IPRIORITYR: usize = 0x0400; + #[cfg(feature = "console-input")] + const GICD_ICFGR: usize = 0x0C00; + #[cfg(feature = "console-input")] + const GICD_IGRPMODR: usize = 0x0D00; + #[cfg(feature = "console-input")] + const GICD_IROUTER: u64 = 0x6000; + + /// SPI의 라우팅 레지스터(GICD_IROUTER)가 디스트리뷰터 프레임 안에서 놓이는 + /// 위치를 주는 함수입니다. 초기화에 쓰는 첫 페이지 밖에 있어서, 콘솔의 + /// SPI를 켜려면 호출자가 그 페이지를 따로 매핑해야 합니다. + /// + /// # Arguments + /// `intid` - SPI의 INTID + #[cfg(feature = "console-input")] + pub const fn router_offset(intid: u32) -> u64 { + GICD_IROUTER + 8 * intid as u64 + } /// 식별 레지스터 PIDR2가 프레임 안에서 놓이는 위치 pub const PIDR2: u64 = 0xFFE8; pub const GICR_TYPER: u64 = 0x0008; @@ -379,6 +427,59 @@ pub mod gicv3 { Ok(()) } + /// SPI 하나를 이 코어로 오게 구성하고 켜는 함수입니다. + /// + /// 비보안 Group 1, 타이머와 같은 우선순위, 레벨 트리거로 두고 이 코어의 + /// 어피니티로 보냅니다. 보안 상태가 소유한 SPI는 비보안에서 쓰기가 + /// 무시되므로 켜기 비트를 읽어 보아 가립니다. + /// + /// # Safety + /// `dist`는 [init]이 초기화를 마친 디스트리뷰터 프레임의 매핑된 주소, + /// `router`는 이 SPI의 라우팅 레지스터([router_offset])가 매핑된 주소여야 + /// 하고, `intid`는 이 컨트롤러가 구현한 SPI여야 합니다. + #[cfg(feature = "console-input")] + pub(super) unsafe fn enable_spi(dist: usize, router: usize, intid: u32) -> Result<(), IrqError> { + let n = intid as usize; + let (word, bit) = (4 * (n / 32), 1u32 << (n % 32)); + let mpidr: u64; + // SAFETY: MPIDR_EL1 읽기는 부작용이 없음 + unsafe { asm!("mrs {}, mpidr_el1", out(reg) mpidr, options(nomem, nostack)) }; + // GICD_IROUTER의 어피니티 배치는 MPIDR과 같음(Aff3이 비트 39..32). 비트 + // 31(아무 코어로나 보내기)은 0으로 둠 + let route = mpidr & 0xFF_00FF_FFFF; + // SAFETY: 함수 계약대로 매핑된 디스트리뷰터 레지스터에 대한 접근 + unsafe { + write32(dist + GICD_IGROUPR + word, read32(dist + GICD_IGROUPR + word) | bit); + write32(dist + GICD_IGRPMODR + word, read32(dist + GICD_IGRPMODR + word) & !bit); + write8(dist + GICD_IPRIORITYR + n, PRIORITY as u8); + // 설정은 꺼진 동안에만 바꿀 수 있음. init이 SPI를 전부 꺼 두었음 + let cfg = dist + GICD_ICFGR + 4 * (n / 16); + let cfg_bit = 1u32 << (2 * (n % 16) + 1); + write32(cfg, read32(cfg) & !cfg_bit); + if read32(cfg) & cfg_bit != 0 { + return Err(IrqError::SpiNotLevel); + } + core::ptr::write_volatile(router as *mut u64, route); + write32(dist + GICD_ISENABLER + word, bit); + wait_clear(dist + GICD_CTLR, CTLR_RWP, IrqError::GicRwpTimeout)?; + if read32(dist + GICD_ISENABLER + word) & bit == 0 { + return Err(IrqError::SpiNotOwned); + } + } + Ok(()) + } + + /// SPI 하나를 끄는 함수입니다. + /// + /// # Safety + /// [enable_spi]와 같습니다. + #[cfg(feature = "console-input")] + pub(super) unsafe fn disable_spi(dist: usize, intid: u32) { + let n = intid as usize; + // SAFETY: 함수 계약대로 매핑된 디스트리뷰터 레지스터에 대한 접근 + unsafe { write32(dist + GICD_ICENABLER + 4 * (n / 32), 1u32 << (n % 32)) }; + } + pub(super) fn ack() -> u64 { let iar: u64; // SAFETY: ICC_IAR1_EL1 읽기는 최고 우선순위 대기 인터럽트를 승인함 @@ -397,13 +498,15 @@ pub mod gicv2 { use super::*; const GICD_CTLR: usize = 0x000; - const GICD_TYPER: usize = 0x004; + pub(super) const GICD_TYPER: usize = 0x004; const GICD_IGROUPR: usize = 0x080; const GICD_ISENABLER: usize = 0x100; const GICD_ICENABLER: usize = 0x180; const GICD_ICPENDR: usize = 0x280; const GICD_ICACTIVER: usize = 0x380; const GICD_IPRIORITYR: usize = 0x400; + #[cfg(feature = "console-input")] + const GICD_ITARGETSR: usize = 0x800; const GICD_ICFGR: usize = 0xC00; const GICD_PIDR2: usize = 0xFE8; const GICC_CTLR: usize = 0x00; @@ -481,6 +584,55 @@ pub mod gicv2 { } Ok(()) } + + /// SPI 하나를 이 코어로 오게 구성하고 켜는 함수입니다. + /// + /// # Safety + /// `dist`는 [init]이 초기화를 마친 디스트리뷰터 프레임의 매핑된 주소여야 + /// 하고, `intid`는 이 컨트롤러가 구현한 SPI여야 합니다. + #[cfg(feature = "console-input")] + pub(super) unsafe fn enable_spi(dist: usize, intid: u32) -> Result<(), IrqError> { + let n = intid as usize; + let (word, bit) = (4 * (n / 32), 1u32 << (n % 32)); + // SAFETY: 함수 계약대로 매핑된 디스트리뷰터 레지스터에 대한 접근 + unsafe { + // 타이머와 같은 그룹에 둠. 보안 확장이 있으면 이 레지스터는 + // 비보안에서 읽기 0 / 쓰기 무시임 + if read32(dist + GICD_TYPER) & (1 << 10) == 0 { + write32(dist + GICD_IGROUPR + word, read32(dist + GICD_IGROUPR + word) & !bit); + } + write8(dist + GICD_IPRIORITYR + n, PRIORITY as u8); + let cfg = dist + GICD_ICFGR + 4 * (n / 16); + let cfg_bit = 1u32 << (2 * (n % 16) + 1); + write32(cfg, read32(cfg) & !cfg_bit); + if read32(cfg) & cfg_bit != 0 { + return Err(IrqError::SpiNotLevel); + } + // 이 CPU 인터페이스의 마스크는 ITARGETSR0의 첫 바이트로 읽힘. CPU가 + // 하나뿐인 구현에서는 이 레지스터가 읽기 0 / 쓰기 무시이고 모든 + // 인터럽트가 그 CPU로 가므로, 0이면 쓰지 않음 + let me = read32(dist + GICD_ITARGETSR) & 0xFF; + if me != 0 { + write8(dist + GICD_ITARGETSR + n, me as u8); + } + write32(dist + GICD_ISENABLER + word, bit); + if read32(dist + GICD_ISENABLER + word) & bit == 0 { + return Err(IrqError::SpiNotOwned); + } + } + Ok(()) + } + + /// SPI 하나를 끄는 함수입니다. + /// + /// # Safety + /// [enable_spi]와 같습니다. + #[cfg(feature = "console-input")] + pub(super) unsafe fn disable_spi(dist: usize, intid: u32) { + let n = intid as usize; + // SAFETY: 함수 계약대로 매핑된 디스트리뷰터 레지스터에 대한 접근 + unsafe { write32(dist + GICD_ICENABLER + 4 * (n / 32), 1u32 << (n % 32)) }; + } } /// 초기화할 인터럽트 컨트롤러와 그 레지스터의 가상 주소입니다. @@ -524,8 +676,20 @@ fn timer_arm(interval: u64) { fn timer_tick() { let n = TICKS.load(Ordering::Relaxed) + 1; TICKS.store(n, Ordering::Relaxed); + // 수신 인터럽트가 오지 않는 UART(수신 타임아웃이 없거나 번호가 조용히 + // 틀린 경우)에서도 입력이 늦게나마 도착하게 틱마다 한 번 들여다봄. 닫혀 + // 있는 동안에는 아무 일도 하지 않음 + #[cfg(feature = "console-input")] + crate::conin::poll(); + // 태스크가 콘솔 입력을 쓰기 시작한 뒤에는 틱 줄을 내지 않음(입력하는 줄 + // 사이에 끼어들지 않게). 틱과 타임아웃은 그대로 동작함 + #[cfg(feature = "console-input")] + let quiet = QUIET_TICKS.load(Ordering::Relaxed); + #[cfg(not(feature = "console-input"))] + let quiet = false; // 틱은 끝없이 이어지므로 처음 몇 줄만 로그에 남김 - if n <= LOGGED_TICKS { + if quiet { + } else if n <= LOGGED_TICKS { let _ = writeln!(EarlyCon, "k0: tick {n}"); } else { // 콘솔 드라이버가 없는 빌드에는 쓸 곳이 없으므로 서식 작업도 하지 않음 @@ -543,6 +707,100 @@ pub fn ticks() -> u64 { TICKS.load(Ordering::Relaxed) } +/// 주기적인 틱 줄을 멈추는 함수입니다. 처음 불렸으면 true를 돌려줍니다. +/// +/// 태스크가 콘솔 입력을 쓰기 시작할 때 커널이 부릅니다. 틱 자체와 IPC +/// 타임아웃은 그대로 동작합니다. +#[cfg(feature = "console-input")] +pub fn quiet_ticks() -> bool { + !QUIET_TICKS.swap(true, Ordering::Relaxed) +} + +/// 콘솔 UART의 SPI를 이 코어로 오게 구성하고 켜는 함수입니다. +/// +/// UART 쪽의 인터럽트는 [crate::conin::prepare]가 먼저 전부 막아 두었어야 +/// 합니다. 그래야 여기서 선을 켜도 태스크가 입력을 쓰기 전까지는 인터럽트가 +/// 오지 않습니다. +/// +/// # Arguments +/// `_irq` - 컨트롤러가 초기화됐음을 증명하는 토큰 +/// `intid` - DTB가 알려 준 콘솔의 INTID +/// `router` - GICv3에서 이 SPI의 라우팅 레지스터([gicv3::router_offset])가 +/// 매핑된 주소. GICv2에서는 쓰지 않음 +/// +/// # Safety +/// [init]에 넘긴 디스트리뷰터의 매핑이 그대로 살아 있어야 하고, GICv3라면 +/// `router`가 Device로 매핑된 그 레지스터의 주소여야 합니다. +/// +/// # Errors +/// 번호가 이 컨트롤러의 SPI가 아니거나 타이머의 번호이면 `SpiOutOfRange`, +/// 레벨 트리거로 둘 수 없으면 `SpiNotLevel`, 켜기 비트가 서지 않으면 +/// `SpiNotOwned`. 어느 경우든 잃는 것은 콘솔 입력뿐이고 부팅은 계속됩니다 +#[cfg(feature = "console-input")] +pub unsafe fn enable_console_irq(_irq: &Irq, intid: u32, router: Option) -> Result<(), IrqError> { + let limit = INTID_LIMIT.load(Ordering::Relaxed); + if !(32..limit).contains(&intid) || intid == TIMER_INTID.load(Ordering::Relaxed) { + return Err(IrqError::SpiOutOfRange); + } + let dist = GICD.load(Ordering::Relaxed); + // 켜자마자 인터럽트가 올 수 있으므로 분배기가 알아볼 번호를 먼저 적어 둠 + CONSOLE_INTID.store(intid, Ordering::Relaxed); + // SAFETY: 함수 계약대로 매핑된 디스트리뷰터이고 번호는 위에서 확인한 SPI임 + let r = unsafe { + match KIND.load(Ordering::Relaxed) { + KIND_V3 => match router { + Some(router) => gicv3::enable_spi(dist, router, intid), + None => Err(IrqError::ProbeFailed), + }, + KIND_V2 => gicv2::enable_spi(dist, intid), + _ => Err(IrqError::WrongGic), + } + }; + if r.is_err() { + // 반쯤 구성된 선은 꺼 둠. 번호는 그대로 두어, 이미 전달돼 있던 + // 인터럽트가 "미지의 INTID"로 커널을 멈추지 않게 함 + // SAFETY: 위와 같음 + unsafe { disable_console_irq() }; + } + r +} + +/// 콘솔의 SPI를 끄는 함수입니다. +/// +/// # Safety +/// [enable_console_irq]와 같습니다. +#[cfg(feature = "console-input")] +unsafe fn disable_console_irq() { + let (dist, intid) = (GICD.load(Ordering::Relaxed), CONSOLE_INTID.load(Ordering::Relaxed)); + if intid == u32::MAX { + return; + } + // SAFETY: 함수 계약을 그대로 전달 + unsafe { + match KIND.load(Ordering::Relaxed) { + KIND_V3 => gicv3::disable_spi(dist, intid), + KIND_V2 => gicv2::disable_spi(dist, intid), + _ => {} + } + } +} + +/// 콘솔 인터럽트 하나를 처리하는 함수입니다. +/// +/// 수신 로직이 원인 없는 인터럽트가 이어진다고 판단하면(DTB가 다른 장치의 +/// 번호를 준 경우) 컨트롤러에서 그 선을 끄고 한 줄을 남깁니다. 커널은 계속 +/// 실행되고 입력만 없어집니다. +#[cfg(feature = "console-input")] +fn console_irq() { + if crate::conin::interrupt() == k0_conin::Irq::CutOff { + // SAFETY: 이 인터럽트가 왔다는 것은 enable_console_irq가 선을 켰다는 + // 뜻이고, 그 계약대로 디스트리뷰터가 매핑돼 있음 + unsafe { disable_console_irq() }; + let intid = CONSOLE_INTID.load(Ordering::Relaxed); + let _ = writeln!(EarlyCon, "k0: console input off (interrupt {intid} fired without a uart cause)"); + } +} + /// 실행할 태스크가 없을 때 다음 인터럽트까지 코어를 재우고 그 인터럽트를 /// 처리하는 함수입니다. /// @@ -596,12 +854,16 @@ pub unsafe fn init(_vectors: &Vectors, gic: &Gic, intid: u32, hz: u64) -> Result Gic::V3(frames) => unsafe { gicv3::init(frames, intid)?; KIND.store(KIND_V3, Ordering::Relaxed); + #[cfg(feature = "console-input")] + remember_distributor(frames.dist, read32(frames.dist + gicv3::GICD_TYPER)); }, // SAFETY: 함수 계약을 그대로 전달 Gic::V2 { dist, cpu } => unsafe { gicv2::init(*dist, *cpu, intid)?; GICC.store(*cpu, Ordering::Relaxed); KIND.store(KIND_V2, Ordering::Relaxed); + #[cfg(feature = "console-input")] + remember_distributor(*dist, read32(*dist + gicv2::GICD_TYPER)); }, } TIMER_INTID.store(intid, Ordering::Relaxed); @@ -614,6 +876,15 @@ pub unsafe fn init(_vectors: &Vectors, gic: &Gic, intid: u32, hz: u64) -> Result Ok(Irq { _sealed: () }) } +/// 콘솔의 SPI를 켤 때 쓸 디스트리뷰터 주소와 INTID의 상한을 적어 두는 +/// 함수입니다. 상한은 GICD_TYPER의 ITLinesNumber에서 나오고, 1020부터는 특수 +/// 번호라 넘지 않게 묶습니다. +#[cfg(feature = "console-input")] +fn remember_distributor(dist: usize, typer: u32) { + GICD.store(dist, Ordering::Relaxed); + INTID_LIMIT.store((32 * ((typer & 0x1F) + 1)).min(1020), Ordering::Relaxed); +} + /// 설계상 발생할 수 없는 인터럽트를 fail-secure로 정지시키는 함수입니다. /// /// # Arguments @@ -637,13 +908,32 @@ unsafe extern "C" { /// EL0에서 진입한 IRQ/FIQ 컨텍스트에서 벡터가 사용자 컨텍스트 저장을 /// 마친 뒤에만 호출됩니다. fn k0_preempt(); + + /// 콘솔 입력이 도착했을 때 기다리는 태스크를 깨우는 정책, 커널 바이너리가 + /// 정의함 (링크 계약) + /// + /// # Safety + /// [k0_preempt]와 같습니다. + #[cfg(feature = "console-input")] + fn k0_console_event(); } +/// 분배 결과: 타이머 틱이었음(EL0 경로의 선점 판단용) +const EV_TICK: u8 = 1; +/// 분배 결과: 콘솔 인터럽트였음(기다리는 태스크를 깨울지 커널이 판단) +#[cfg(feature = "console-input")] +const EV_CONSOLE: u8 = 2; + /// EL1과 EL0 양쪽 IRQ 벡터가 공유하는 실제 분배 함수입니다. /// -/// 타이머 틱이었으면 true를 반환합니다(EL0 경로의 선점 판단용). -fn dispatch_irq() -> bool { +/// 무슨 인터럽트였는지를 `EV_` 비트로 돌려줍니다. 콘솔 인터럽트의 가지는 그 +/// 선을 끈 뒤에도 남겨 둡니다. 끄기 전에 이미 CPU로 전달돼 있던 인터럽트가 +/// 미지의 INTID로 취급되어 커널을 멈추면 안 되기 때문입니다(그때의 수신 +/// 로직은 레지스터를 건드리지 않고 돌아옴). +fn dispatch_irq() -> u8 { let timer = u64::from(TIMER_INTID.load(Ordering::Relaxed)); + #[cfg(feature = "console-input")] + let console = u64::from(CONSOLE_INTID.load(Ordering::Relaxed)); match KIND.load(Ordering::Relaxed) { KIND_V3 => { let iar = gicv3::ack(); @@ -651,9 +941,15 @@ fn dispatch_irq() -> bool { id if id == timer => { timer_tick(); gicv3::eoi(iar); - true + EV_TICK } - 1020..=1023 => false, // 스퓨리어스: 승인 없이 복귀 + #[cfg(feature = "console-input")] + id if id == console => { + console_irq(); + gicv3::eoi(iar); + EV_CONSOLE + } + 1020..=1023 => 0, // 스퓨리어스: 승인 없이 복귀 other => unexpected("irq", other), } } @@ -666,9 +962,16 @@ fn dispatch_irq() -> bool { timer_tick(); // SAFETY: 승인에서 받은 값 그대로 완료 통지 unsafe { write32(cpu + gicv2::GICC_EOIR, iar) }; - true + EV_TICK } - 1020..=1023 => false, + #[cfg(feature = "console-input")] + id if id == console => { + console_irq(); + // SAFETY: 승인에서 받은 값 그대로 완료 통지 + unsafe { write32(cpu + gicv2::GICC_EOIR, iar) }; + EV_CONSOLE + } + 1020..=1023 => 0, other => unexpected("irq", other), } } @@ -680,7 +983,7 @@ fn dispatch_irq() -> bool { /// /// 커널은 모든 인터럽트를 IRQ로만 받으므로 FIQ는 설계상 없고, 들어오면 /// fail-secure로 정지합니다. -fn dispatch_fiq() -> bool { +fn dispatch_fiq() -> u8 { unexpected("fiq", 0) } @@ -705,7 +1008,13 @@ extern "C" fn fiq_current() { /// 복원하며 수행합니다. #[unsafe(no_mangle)] extern "C" fn irq_lower(_ctx: &mut crate::usermode::Context) { - if dispatch_irq() { + let events = dispatch_irq(); + #[cfg(feature = "console-input")] + if events & EV_CONSOLE != 0 { + // SAFETY: 벡터가 사용자 컨텍스트 저장을 마친 EL0 IRQ 경로임 + unsafe { k0_console_event() }; + } + if events & EV_TICK != 0 { // SAFETY: 벡터가 사용자 컨텍스트 저장을 마친 EL0 IRQ 경로임 unsafe { k0_preempt() }; } @@ -714,7 +1023,7 @@ extern "C" fn irq_lower(_ctx: &mut crate::usermode::Context) { /// 사용자 공간(EL0) 실행 중 FIQ 벡터가 사용하는 디스패처 함수입니다. #[unsafe(no_mangle)] extern "C" fn fiq_lower(_ctx: &mut crate::usermode::Context) { - if dispatch_fiq() { + if dispatch_fiq() & EV_TICK != 0 { // SAFETY: 벡터가 사용자 컨텍스트 저장을 마친 EL0 FIQ 경로임 unsafe { k0_preempt() }; } diff --git a/crates/k0-arch/src/lib.rs b/crates/k0-arch/src/lib.rs index 52d44b9..a87afeb 100644 --- a/crates/k0-arch/src/lib.rs +++ b/crates/k0-arch/src/lib.rs @@ -7,6 +7,8 @@ #![no_std] +#[cfg(feature = "console-input")] +pub mod conin; pub mod earlycon; pub mod hardening; pub mod irq; diff --git a/crates/k0-boot/Cargo.toml b/crates/k0-boot/Cargo.toml index 49853ec..73b1087 100644 --- a/crates/k0-boot/Cargo.toml +++ b/crates/k0-boot/Cargo.toml @@ -13,6 +13,10 @@ roottask = [] # 보고 루트 태스크의 빌드에 같은 이름의 feature를 넘김 vault = ["roottask"] vault-ed25519 = ["vault"] +# 콘솔 입력: 루트 태스크의 자가 검증에 입력 시스템 콜의 시험을 넣음 +console-input = ["roottask"] +# 운영자 터미널: 자가 검증 뒤에 서비스(볼트가 있으면 볼트와 터미널)를 시작함 +terminal = ["console-input"] # 테스트용 DTB 빌더와 퍼즈 도우미를 다른 크레이트의 테스트에 공개함(std 필요) test-support = [] diff --git a/crates/k0-boot/build.rs b/crates/k0-boot/build.rs index d19ed2f..8e12e32 100644 --- a/crates/k0-boot/build.rs +++ b/crates/k0-boot/build.rs @@ -152,6 +152,8 @@ fn main() { for (var, name) in [ ("CARGO_FEATURE_VAULT", "vault"), ("CARGO_FEATURE_VAULT_ED25519", "vault-ed25519"), + ("CARGO_FEATURE_CONSOLE_INPUT", "console-input"), + ("CARGO_FEATURE_TERMINAL", "terminal"), ] { if env::var_os(var).is_some() { features.push(name); @@ -252,6 +254,8 @@ fn main() { "userspace/root-task/src", "userspace/k0-vault/src", "userspace/k0-vault/Cargo.toml", + "userspace/k0-term/src", + "userspace/k0-term/Cargo.toml", "Cargo.lock", "userspace/root-task/Cargo.toml", "userspace/root-task/build.rs", diff --git a/crates/k0-boot/src/platform.rs b/crates/k0-boot/src/platform.rs index f64f06f..037de83 100644 --- a/crates/k0-boot/src/platform.rs +++ b/crates/k0-boot/src/platform.rs @@ -65,6 +65,10 @@ pub struct Console { pub span: u64, /// DTB가 선언한 레지스터 구간 전체 (겹침 검사용) pub reg: Region, + /// 콘솔의 인터럽트 번호(INTID). 노드에 없거나, 발견한 인터럽트 컨트롤러의 + /// SPI 하나로 읽히지 않으면 `None`이고 그때는 콘솔 입력이 없습니다. + /// 인터럽트를 못 읽는 것은 부팅 거부 사유가 아닙니다. + pub irq: Option, } /// 인터럽트 컨트롤러를 나타내는 열거형입니다. @@ -240,12 +244,13 @@ pub fn discover_blob(blob: &[u8]) -> Result { return Err(DiscoverError::DuplicatePhandle); } let (intc, interrupt_cells) = intc.ok_or(DiscoverError::IntcNotFound)??; + let timer_parent = timer.parent; let timer = Timer { intid: timer_intid(&timer, interrupt_cells)?, clock_hz: timer.clock.unwrap_or(0), }; - let (console, no_console) = match find_console(&fdt, stdout)? { + let (console, no_console) = match find_console(&fdt, stdout, Some((timer_parent, interrupt_cells)))? { Ok(c) => (Some(c), None), Err(why) => (None, Some(why)), }; @@ -531,7 +536,15 @@ fn read_intc(levels: &Levels<'_>, node: &Node<'_>, depth: usize) -> Result<(Intc /// /// 콘솔을 못 찾는 경우는 전부 안쪽 `Err(NoConsole)`이고, 바깥 `Err`는 DTB /// 구조 위반뿐입니다. -fn find_console(fdt: &Fdt<'_>, stdout: Option<&[u8]>) -> Result, BootError> { +/// +/// `gic`는 발견한 인터럽트 컨트롤러의 phandle과 `#interrupt-cells`입니다. 주면 +/// 콘솔의 인터럽트도 읽고, `None`이면(컨트롤러를 찾기 전의 조기 콘솔 탐색) +/// 인터럽트 없이 돌려줍니다. +fn find_console( + fdt: &Fdt<'_>, + stdout: Option<&[u8]>, + gic: Option<(u32, u32)>, +) -> Result, BootError> { let Some(value) = stdout else { return Ok(Err(NoConsole::NoStdoutPath)); }; @@ -569,7 +582,10 @@ fn find_console(fdt: &Fdt<'_>, stdout: Option<&[u8]>) -> Result, stdout: Option<&[u8]>) -> Result, node: &Node<'_>, depth: usize, gic: u32, cells: u32) -> Option { + if node.has(P::InterruptsExtended) { + return None; + } + let spec = node.get(P::Interrupts)?; + let mut parent = node.u32(P::InterruptParent).ok()?; + let mut k = depth; + while parent.is_none() && k > 1 { + k -= 1; + if levels[k].has_interrupt_cells { + return None; + } + parent = levels[k].interrupt_parent().ok()?; + } + if parent? != gic || cells != 3 || spec.len() != 12 { + return None; + } + let cell = |i: usize| read_cells(&spec[i * 4..i * 4 + 4]); + // SPI 번호의 상한 987은 INTID 1019(1020부터는 특수 번호) + if cell(0) != 0 || cell(1) > 987 || cell(2) != 4 { + return None; + } + Some(32 + cell(1) as u32) +} + fn read_console(levels: &Levels<'_>, node: &Node<'_>, depth: usize) -> Result { if !usable(levels, node, depth) { return Err(NoConsole::Disabled); @@ -651,6 +700,7 @@ fn read_console(levels: &Levels<'_>, node: &Node<'_>, depth: usize) -> Result Option { Ok(Flow::Continue) }) .ok()?; - find_console(&fdt, stdout).ok()?.ok() + find_console(&fdt, stdout, None).ok()?.ok() } impl fmt::Display for Platform { @@ -808,13 +858,19 @@ impl fmt::Display for Platform { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.console { None => write!(f, "con=none")?, - Some(c) => match c.kind { - ConsoleKind::Pl011 => write!(f, "con=pl011@{:#x}", c.base)?, - ConsoleKind::SbsaUart => write!(f, "con=sbsa@{:#x}", c.base)?, - ConsoleKind::Ns16550 { reg_shift, io_width } => { - write!(f, "con=ns16550@{:#x},s{reg_shift},w{io_width}", c.base)?; + Some(c) => { + match c.kind { + ConsoleKind::Pl011 => write!(f, "con=pl011@{:#x}", c.base)?, + ConsoleKind::SbsaUart => write!(f, "con=sbsa@{:#x}", c.base)?, + ConsoleKind::Ns16550 { reg_shift, io_width } => { + write!(f, "con=ns16550@{:#x},s{reg_shift},w{io_width}", c.base)?; + } } - }, + // 커널이 켜는 인터럽트이므로 플랫폼 줄(고정 모드의 대조 대상)에 넣음 + if let Some(irq) = c.irq { + write!(f, ",irq{irq}")?; + } + } } match &self.intc { Intc::GicV2 { dist, cpu } => write!(f, " gic=v2@{:#x} cpu={:#x}", dist.base, cpu.base)?, diff --git a/crates/k0-boot/src/platform/tests.rs b/crates/k0-boot/src/platform/tests.rs index 6c7c5fc..89d42f4 100644 --- a/crates/k0-boot/src/platform/tests.rs +++ b/crates/k0-boot/src/platform/tests.rs @@ -36,6 +36,7 @@ fn qemu_virt_gicv3_is_discovered() { base: 0x900_0000, span: 0x1C, reg: Region { base: 0x900_0000, size: 0x1000 }, + irq: Some(33), }), intc: Intc::GicV3 { dist: Region { base: 0x800_0000, size: 0x1_0000 }, @@ -48,7 +49,7 @@ fn qemu_virt_gicv3_is_discovered() { ); assert_eq!( d.platform.to_string(), - "con=pl011@0x9000000 gic=v3@0x8000000 rd=0x80a0000+0xf60000 tmr=27" + "con=pl011@0x9000000,irq33 gic=v3@0x8000000 rd=0x80a0000+0xf60000 tmr=27" ); } @@ -65,7 +66,7 @@ fn qemu_virt_gicv2_is_discovered() { assert_eq!(d.platform.timer.intid, 27); assert_eq!( d.platform.to_string(), - "con=pl011@0x9000000 gic=v2@0x8000000 cpu=0x8010000 tmr=27" + "con=pl011@0x9000000,irq33 gic=v2@0x8000000 cpu=0x8010000 tmr=27" ); } @@ -79,6 +80,7 @@ fn raspberry_pi_4_shape_is_translated_through_soc_ranges() { base: 0xfe21_5040, span: 24, reg: Region { base: 0xfe21_5040, size: 0x40 }, + irq: None, }) ); assert_eq!( @@ -104,12 +106,89 @@ fn rk3399_shape_uses_four_cell_specifiers_and_a_shifted_uart() { base: 0xff1a_0000, span: 24, reg: Region { base: 0xff1a_0000, size: 0x100 }, + irq: None, }) ); assert_eq!(d.platform.intc.redist(), &[Region { base: 0xfef0_0000, size: 0xc_0000 }]); assert_eq!(d.platform.timer.intid, 27); } +#[test] +fn the_console_interrupt_is_one_level_high_spi_of_the_discovered_controller() { + let irq = |t: &N| ok(t).platform.console.unwrap().irq; + assert_eq!(irq(&virt3()), Some(33)); + assert_eq!(irq(&virt2()), Some(33)); + + // 가장 큰 SPI 번호는 INTID 1019 + let mut t = virt3(); + t.kid("pl011@9000000").set("interrupts", cells(&[0, 987, 4])); + assert_eq!(irq(&t), Some(1019)); + assert!(ok(&t).platform.to_string().starts_with("con=pl011@0x9000000,irq1019 ")); + + // 받지 않는 모양은 전부 "인터럽트 없음"이고 부팅 거부가 아님 + let bad: [&[u32]; 9] = [ + &[0, 988, 4], // 특수 INTID에 닿는 번호 + &[1, 1, 4], // PPI + &[2, 1, 4], // 모르는 종류 + &[0, 1, 1], // 에지 트리거 + &[0, 1, 8], // 액티브 로우 + &[0, 1, 0x104], // 플래그에 다른 비트 + &[0, 1], // 셀이 모자람 + &[0, 1, 4, 0], // 셀이 남음 + &[0, 1, 4, 0, 2, 4], // 항목이 둘 + ]; + for spec in bad { + let mut t = virt3(); + t.kid("pl011@9000000").set("interrupts", cells(spec)); + let d = ok(&t); + assert_eq!(d.platform.console.unwrap().irq, None, "{spec:?}"); + assert!(d.platform.to_string().starts_with("con=pl011@0x9000000 gic="), "{spec:?}"); + } + + // 속성이 없는 콘솔, interrupts-extended를 쓰는 콘솔 + let mut t = virt3(); + t.kid("pl011@9000000").del("interrupts"); + assert_eq!(irq(&t), None); + let mut t = virt3(); + t.kid("pl011@9000000").set("interrupts-extended", cells(&[GIC_PHANDLE, 0, 1, 4])); + assert_eq!(irq(&t), None); + + // 인터럽트 부모가 발견한 컨트롤러가 아니면 읽지 않음 + let mut t = virt3(); + t.kid("pl011@9000000").set("interrupt-parent", cells(&[GIC_PHANDLE + 1])); + assert_eq!(irq(&t), None); + // 노드 자신의 interrupt-parent가 그 컨트롤러면 읽음 + let mut t = virt3(); + t.kid("pl011@9000000").set("interrupt-parent", cells(&[GIC_PHANDLE])); + assert_eq!(irq(&t), Some(33)); +} + +#[test] +fn a_controller_with_four_cell_specifiers_gives_no_console_interrupt() { + // rk3399 모양: 컨트롤러의 #interrupt-cells가 4라서 셀 셋짜리 지정자를 + // 추측해 읽지 않음 + let mut t = rk3399(); + let d = ok(&t); + assert_eq!(d.platform.console.unwrap().irq, None); + // 지정자를 넷으로 맞춰 줘도 받지 않음(받는 모양은 셀 셋뿐) + fn uart(n: &mut N) -> Option<&mut N> { + if n.name.starts_with("serial@") { + return Some(n); + } + n.kids.iter_mut().find_map(uart) + } + if let Some(u) = uart(&mut t) { + u.set("interrupts", cells(&[0, 100, 4, 0])); + } + assert_eq!(ok(&t).platform.console.unwrap().irq, None); +} + +#[test] +fn early_console_discovery_does_not_read_the_interrupt() { + // 컨트롤러를 찾기 전의 조기 탐색은 출력만 쓰므로 인터럽트를 읽지 않음 + assert_eq!(console_of(&virt3().blob()).unwrap().irq, None); +} + #[test] fn the_virtual_timer_number_comes_from_the_tree() { // Qualcomm sdm845: <1 1>, <1 2>, <1 3>, <1 0> @@ -217,7 +296,7 @@ fn console_nodes_are_checked_before_use() { let mut t = virt3(); t.kid("pl011@9000000").set("compatible", strs(&["arm,sbsa-uart"])); assert_eq!(ok(&t).platform.console.map(|c| c.kind), Some(ConsoleKind::SbsaUart)); - assert!(ok(&t).platform.to_string().starts_with("con=sbsa@0x9000000 ")); + assert!(ok(&t).platform.to_string().starts_with("con=sbsa@0x9000000,irq33 ")); } #[test] diff --git a/crates/k0-boot/src/testing.rs b/crates/k0-boot/src/testing.rs index 7a7da70..3c8be64 100644 --- a/crates/k0-boot/src/testing.rs +++ b/crates/k0-boot/src/testing.rs @@ -237,6 +237,7 @@ pub fn pl011() -> N { N::new("pl011@9000000") .p("compatible", strs(&["arm,pl011", "arm,primecell"])) .p("reg", cells(&[0, 0x900_0000, 0, 0x1000])) + .p("interrupts", cells(&[0, 1, 4])) } pub fn gicv3() -> N { diff --git a/crates/k0-cap/Cargo.toml b/crates/k0-cap/Cargo.toml index b200c33..06d36e7 100644 --- a/crates/k0-cap/Cargo.toml +++ b/crates/k0-cap/Cargo.toml @@ -5,4 +5,9 @@ edition.workspace = true license.workspace = true publish.workspace = true +# 루트 CNode를 1024슬롯으로 만듦. 자가 검증 뒤에 서비스를 새로 띄우는 이미지 +# (터미널)가 켬. 주지 않으면 512슬롯 그대로임 +[features] +root-cnode-1024 = [] + [dependencies] diff --git a/crates/k0-cap/src/lib.rs b/crates/k0-cap/src/lib.rs index f808044..237e471 100644 --- a/crates/k0-cap/src/lib.rs +++ b/crates/k0-cap/src/lib.rs @@ -38,7 +38,14 @@ use core::ptr; pub const SLOT_SIZE: usize = 64; /// 루트 CNode의 슬롯 수 +/// +/// 자가 검증 뒤에 서비스(볼트와 터미널)를 새로 띄우는 이미지는 주소 공간 둘을 +/// 더 만들 슬롯이 필요하므로 feature `root-cnode-1024`로 두 배를 받습니다. +/// 그 밖의 이미지는 그대로입니다. +#[cfg(not(feature = "root-cnode-1024"))] pub const ROOT_CNODE_SLOTS: usize = 512; +#[cfg(feature = "root-cnode-1024")] +pub const ROOT_CNODE_SLOTS: usize = 1024; /// 파생 깊이 상한, 초과하는 복사는 거부됩니다 pub const MAX_DEPTH: u64 = 1 << 32; @@ -46,7 +53,8 @@ pub const MAX_DEPTH: u64 = 1 << 32; /// 케이퍼빌리티 권한 비트 모듈입니다. /// /// Frame은 R/W/X를 매핑 권한의 상한으로 쓰고, Endpoint는 R을 수신, W를 -/// 송신으로 씁니다. 다른 종류는 권한 비트를 갖지 않습니다. +/// 송신으로, Console은 R을 입력 읽기, W를 출력으로 씁니다. 다른 종류는 권한 +/// 비트를 갖지 않습니다. pub mod rights { pub const R: u8 = 1; pub const W: u8 = 2; @@ -123,8 +131,9 @@ pub enum Cap { CNode { base: u64, slots: u64 }, /// 사용자 주소 공간(TTBR0 루트 테이블) AddrSpace { root_pa: u64, asid: u64 }, - /// 커널 디버그 콘솔 출력 권한(오브젝트 없음) - Console, + /// 커널 콘솔에 대한 권한(오브젝트 없음), `rights`의 W가 출력이고 R이 + /// 입력 읽기 + Console { rights: u8 }, } /// 재분류로 만들 수 있는 커널 오브젝트 종류를 나타내는 열거형입니다. @@ -270,7 +279,7 @@ fn encode(cap: &Cap) -> [u64; 4] { ], Cap::CNode { base, slots } => [base | KIND_CNODE, *slots, 0, 0], Cap::AddrSpace { root_pa, asid } => [root_pa | KIND_ADDR_SPACE, *asid, 0, 0], - Cap::Console => [KIND_CONSOLE, 0, 0, 0], + Cap::Console { rights } => [KIND_CONSOLE | (u64::from(*rights) << RIGHTS_SHIFT), 0, 0, 0], } } @@ -387,11 +396,11 @@ fn decode(w: &[u64; 4]) -> Result, CapError> { } } KIND_CONSOLE => { - plain(w[1] == 0 && w[2] == 0 && w[3] == 0)?; - if base != 0 { + let tail_zero = w[1] == 0 && w[2] == 0 && w[3] == 0; + if rights == 0 || rights & rights::X != 0 || mapped || base != 0 || !tail_zero { return Err(CapError::Corrupt); } - Cap::Console + Cap::Console { rights } } _ => return Err(CapError::Corrupt), }; @@ -801,6 +810,17 @@ unsafe fn plan_copy( badge, } } + Cap::Console { rights } => { + if badge != 0 { + return Err(CapError::BadBadge); + } + // 입력을 읽을 권한(R)은 복사로 줄일 수만 있음 + let rights = rights & mask; + if rights == 0 { + return Err(CapError::NoRights); + } + Cap::Console { rights } + } other => { // 배지는 엔드포인트 전용. 다른 종류의 워드에 사용자 값이 섞이면 // asid나 매핑 기록을 위조하는 길이 됨 @@ -1093,6 +1113,9 @@ pub struct BootObjects { pub addr_space_asid: u64, /// 루트 CNode 자신의 PA pub cnode: u64, + /// 루트 태스크의 Console 케이퍼빌리티가 갖는 권한. 출력(W)은 항상 있고, + /// 입력 읽기(R)는 커널에 콘솔 입력 경로가 있는 이미지에서만 줌 + pub console_rights: u8, } /// 루트 CNode를 구성하는 부트스트랩 함수입니다. @@ -1135,7 +1158,12 @@ pub unsafe fn bootstrap( asid: objs.addr_space_asid, }, ), - (boot_slot::CONSOLE, Cap::Console), + ( + boot_slot::CONSOLE, + Cap::Console { + rights: objs.console_rights, + }, + ), ( boot_slot::CNODE, Cap::CNode { diff --git a/crates/k0-cap/src/tests.rs b/crates/k0-cap/src/tests.rs index 8ef4d92..688cbb2 100644 --- a/crates/k0-cap/src/tests.rs +++ b/crates/k0-cap/src/tests.rs @@ -9,6 +9,7 @@ const BOOT: BootObjects = BootObjects { addr_space_root: 0x7000_1000, addr_space_asid: 1, cnode: 0x7000_2000, + console_rights: rights::R | rights::W, }; fn r(base: u64, size: u64) -> PhysRegion { @@ -151,7 +152,10 @@ fn every_kind_round_trips_through_the_raw_words() { root_pa: 0x4000_6000, asid: 200, }, - Cap::Console, + Cap::Console { rights: rights::W }, + Cap::Console { + rights: rights::R | rights::W, + }, ]; for cap in caps { for flags in [0, FLAG_ORIGINAL, FLAG_BOUND, FLAG_ORIGINAL | FLAG_BOUND] { @@ -245,7 +249,12 @@ fn fixed_slots_come_first() { asid: 1 } ); - assert_eq!(cap_at(c, 3), Cap::Console); + assert_eq!( + cap_at(c, 3), + Cap::Console { + rights: rights::R | rights::W + } + ); assert_eq!( cap_at(c, 4), Cap::CNode { @@ -613,6 +622,60 @@ fn random_retypes_never_overlap() { } } +#[test] +fn console_rights_only_shrink() { + let (c, _) = filled(&[r(0x4000_0000, 16 * G)], &[]); + let both = Cap::Console { + rights: rights::R | rights::W, + }; + unsafe { + assert_eq!(cap_at(c, 3), both); + // 다 사라지는 복사, 콘솔에 없는 권한만 남기는 복사, 배지를 붙이는 복사는 거부 + assert_eq!(copy(c.add(3), c.add(30), 0, 0, false), Err(CapError::NoRights)); + assert_eq!(copy(c.add(3), c.add(30), rights::X, 0, false), Err(CapError::NoRights)); + assert_eq!(copy(c.add(3), c.add(30), rights::ALL, 5, false), Err(CapError::BadBadge)); + assert_eq!(get(c, 30), None); + // 출력만 남긴 복사본에서는 입력 권한을 되살릴 수 없음 + copy(c.add(3), c.add(30), rights::W, 0, false).unwrap(); + assert_eq!(cap_at(c, 30), Cap::Console { rights: rights::W }); + copy(c.add(30), c.add(31), rights::ALL, 0, false).unwrap(); + assert_eq!(cap_at(c, 31), Cap::Console { rights: rights::W }); + assert_eq!(copy(c.add(30), c.add(32), rights::R, 0, false), Err(CapError::NoRights)); + // 입력만 남긴 복사본도 마찬가지 + copy(c.add(3), c.add(32), rights::R, 0, false).unwrap(); + assert_eq!(cap_at(c, 32), Cap::Console { rights: rights::R }); + assert_eq!(copy(c.add(32), c.add(33), rights::W, 0, false), Err(CapError::NoRights)); + // 전부 남기는 복사와 이동은 권한을 그대로 옮김 + copy(c.add(3), c.add(33), rights::ALL, 0, false).unwrap(); + assert_eq!(cap_at(c, 33), both); + move_cap(c.add(33), c.add(34)).unwrap(); + assert_eq!(cap_at(c, 34), both); + // 원본을 회수하면 복사본이 전부 사라짐 + let mut log = Log::default(); + revoke(c.add(3), &mut log).unwrap(); + for i in 30..35 { + assert_eq!(get(c, i), None); + } + assert_eq!(cap_at(c, 3), both); + } +} + +#[test] +fn a_console_word_without_rights_or_with_execute_is_corrupt() { + for rights in [0u64, 4, 5, 6, 7] { + assert_eq!(decode(&[KIND_CONSOLE | rights << RIGHTS_SHIFT, 0, 0, 0]), Err(CapError::Corrupt)); + } + for rights in [1u64, 2, 3] { + let w = [KIND_CONSOLE | rights << RIGHTS_SHIFT, 0, 0, 0]; + assert_eq!(decode(&w).unwrap().unwrap().cap, Cap::Console { rights: rights as u8 }); + // 콘솔에는 오브젝트도 매핑 기록도 꼬리 워드도 없음 + assert_eq!(decode(&[w[0] | 0x1000, 0, 0, 0]), Err(CapError::Corrupt)); + assert_eq!(decode(&[w[0] | FLAG_MAPPED, 0, 0, 0]), Err(CapError::Corrupt)); + assert_eq!(decode(&[w[0], 1, 0, 0]), Err(CapError::Corrupt)); + assert_eq!(decode(&[w[0], 0, 0, 1]), Err(CapError::Corrupt)); + } +} + #[test] fn copy_rules_per_kind() { let (c, next) = filled(&[r(0x4000_0000, 16 * G)], &[]); @@ -1039,7 +1102,7 @@ fn a_very_deep_derivation_chain_is_deleted_iteratively() { let c = node(N + 8); let mut log = Log::default(); unsafe { - insert_root(c.add(1), Cap::Console).unwrap(); + insert_root(c.add(1), Cap::Console { rights: rights::W }).unwrap(); for i in 1..N { copy(c.add(i), c.add(i + 1), rights::ALL, 0, false).unwrap(); } @@ -1096,7 +1159,7 @@ const TCB_N: usize = 3; fn ident(cap: &Cap) -> (u8, u64) { match *cap { Cap::Untyped { base, .. } => (0, base), - Cap::Console => (1, 0), + Cap::Console { .. } => (1, 0), Cap::Frame { base, .. } | Cap::PageTable { base, .. } | Cap::Tcb { base } @@ -1108,7 +1171,7 @@ fn ident(cap: &Cap) -> (u8, u64) { fn cap_rights(cap: &Cap) -> u8 { match *cap { - Cap::Frame { rights, .. } | Cap::Endpoint { rights, .. } => rights, + Cap::Frame { rights, .. } | Cap::Endpoint { rights, .. } | Cap::Console { rights } => rights, _ => 0, } } diff --git a/crates/k0-conin/Cargo.toml b/crates/k0-conin/Cargo.toml new file mode 100644 index 0000000..828bfed --- /dev/null +++ b/crates/k0-conin/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "k0-conin" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] diff --git a/crates/k0-conin/src/lib.rs b/crates/k0-conin/src/lib.rs new file mode 100644 index 0000000..3241095 --- /dev/null +++ b/crates/k0-conin/src/lib.rs @@ -0,0 +1,345 @@ +//! 콘솔 입력의 수신 로직을 담는 크레이트입니다. +//! +//! # Features +//! PL011과 SBSA UART에서 바이트를 받아 고정 크기 링에 담는 상태 기계([Rx]) +//! 입니다. 하드웨어에는 직접 닿지 않고 레지스터 접근을 트레이트([Regs])로 +//! 받으므로, 커널에서는 MMIO로, 호스트 테스트에서는 가짜 UART로 같은 코드를 +//! 돌립니다. QEMU의 UART는 넘침도 수신 타임아웃도 흉내 내지 않아서, 그 경로는 +//! 가짜 UART로만 시험됩니다. +//! +//! 지키는 성질은 다음과 같습니다. +//! +//! - 바이트를 해석하지 않습니다. 옮기기만 합니다. +//! - 인터럽트 한 번의 일은 링의 빈자리로 묶여 있습니다. 링이 가득 차면 UART의 +//! 수신 인터럽트를 스스로 막고(게이트), 읽는 쪽이 자리를 비운 뒤에 다시 +//! 엽니다. 그래서 외부가 아무리 빨리 보내도 인터럽트는 읽는 쪽의 소비 +//! 속도만큼만 들어옵니다. +//! - 수신 원인은 지우지 않고 FIFO를 비워서 가라앉힙니다. FIFO에 남은 바이트를 +//! 새 인터럽트가 알려 주리라고 기대하지 않고, 게이트를 열 때와 틱마다 직접 +//! 들여다봅니다. +//! - 유실은 유실된 자리의 바이트에 표시합니다. 장치의 FIFO가 넘쳤으면 그때 +//! FIFO에 있던 바이트와 그 뒤의 첫 바이트까지 모두 표시합니다(넘친 자리는 +//! FIFO에 있던 바이트들의 뒤이지만 정확한 경계는 알 수 없음). +//! - 원인 없는 인터럽트가 이어지면 입력 경로를 끕니다. 디바이스 트리가 엉뚱한 +//! 인터럽트 번호를 주었을 때 잃는 것은 입력뿐입니다. +//! +//! # Examples +//! ```rust,ignore +//! let mut rx = Rx::new(true); +//! Rx::quiesce(&mut regs); +//! rx.open(&mut regs); +//! while let Some((byte, lost)) = rx.pop(&mut regs) { /* ... */ } +//! ``` + +#![cfg_attr(not(test), no_std)] +#![forbid(unsafe_code)] + +#[cfg(test)] +mod tests; + +/// 수신 로직이 건드리는 레지스터입니다. PL011과 SBSA UART에 공통인 것들이고 +/// [Reg::Cr]만 PL011 전용입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Reg { + /// 데이터(UARTDR) + Dr, + /// 플래그(UARTFR) + Fr, + /// 제어(UARTCR), SBSA UART에는 없음 + Cr, + /// 인터럽트 마스크(UARTIMSC) + Imsc, + /// 마스크를 거친 인터럽트 상태(UARTMIS) + Mis, + /// 인터럽트 지우기(UARTICR) + Icr, +} + +impl Reg { + /// 레지스터 0으로부터의 바이트 오프셋을 주는 함수입니다. + pub const fn offset(self) -> usize { + match self { + Reg::Dr => 0x00, + Reg::Fr => 0x18, + Reg::Cr => 0x30, + Reg::Imsc => 0x38, + Reg::Mis => 0x40, + Reg::Icr => 0x44, + } + } +} + +/// UART 레지스터에 닿는 통로입니다. +pub trait Regs { + /// 레지스터를 32비트로 읽는 함수입니다. + fn read(&mut self, reg: Reg) -> u32; + /// 레지스터에 32비트를 쓰는 함수입니다. + fn write(&mut self, reg: Reg, value: u32); +} + +/// 링이 담는 바이트 수 +pub const RING: usize = 256; +/// 원인 없는 인터럽트가 이만큼 이어지면 입력 경로를 끔 +pub const SPURIOUS_MAX: u8 = 8; +/// FIFO를 한 번 비울 때 데이터 레지스터를 읽는 횟수의 상한. 오류가 난 문자는 +/// 링의 자리를 쓰지 않고 버려지므로 링의 빈자리와 따로 묶어 둠 +const DRAIN_MAX: usize = RING + 64; +/// 버릴 때 장치의 FIFO에서 꺼내는 횟수의 상한(PL011의 FIFO는 32칸) +const FLUSH_MAX: usize = 64; + +const FR_RXFE: u32 = 1 << 4; +const DR_FE: u32 = 1 << 8; +const DR_PE: u32 = 1 << 9; +const DR_BE: u32 = 1 << 10; +const DR_OE: u32 = 1 << 11; +const CR_UARTEN: u32 = 1 << 0; +const CR_RXE: u32 = 1 << 9; +/// 수신, 수신 타임아웃, 넘침 인터럽트 +const INT_RX: u32 = 1 << 4; +const INT_RT: u32 = 1 << 6; +const INT_OE: u32 = 1 << 10; +const INT_OURS: u32 = INT_RX | INT_RT | INT_OE; +/// UARTICR에 쓸 수 있는 모든 비트 +const INT_ALL: u32 = 0x7FF; +/// 링 항목에서 "이 바이트 바로 앞에서 유실이 있었음"을 뜻하는 비트 +const GAP: u16 = 1 << 8; + +/// 인터럽트 하나를 처리한 결과입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Irq { + /// UART가 원인이었고 FIFO를 비웠음(링에 바이트가 있을 수 있음) + Served, + /// UART에 원인이 없었음 + Spurious, + /// 원인 없는 인터럽트가 이어져 입력 경로를 껐음. 호출자는 인터럽트 + /// 컨트롤러에서 이 선을 꺼야 함 + CutOff, +} + +/// 수신 상태를 담는 구조체입니다. +/// +/// 커널의 static 하나에 놓이고, 인터럽트 핸들러와 시스템 콜 경로가 번갈아 +/// 씁니다(둘이 겹치지 않게 하는 것은 호출자의 몫). +pub struct Rx { + ring: [u16; RING], + head: usize, + len: usize, + /// UARTCR이 있는 UART인지(PL011은 있고 SBSA UART는 없음) + has_cr: bool, + /// 태스크가 입력을 쓰기 시작해 수신 인터럽트를 켠 상태인지 + open: bool, + /// 입력 경로가 꺼졌는지(되돌리지 않음) + off: bool, + /// 링이 가득 차 UART의 수신 인터럽트를 막아 둔 상태인지 + gated: bool, + /// 다음에 넣는 바이트에 유실 표시를 붙일지 + gap: bool, + /// 장치의 FIFO가 넘쳤고 그 FIFO를 아직 끝까지 비우지 못했는지 + overrun: bool, + spurious: u8, +} + +impl Rx { + /// 닫힌 상태의 수신 로직을 만드는 함수입니다. + /// + /// # Arguments + /// `has_cr` - UARTCR이 있는 UART(PL011)면 true, SBSA UART면 false + pub const fn new(has_cr: bool) -> Self { + Self { + ring: [0; RING], + head: 0, + len: 0, + has_cr, + open: false, + off: false, + gated: false, + gap: false, + overrun: false, + spurious: 0, + } + } + + /// UART의 인터럽트를 전부 막고 남은 원인을 지우는 함수입니다. + /// + /// 부팅 때, 인터럽트 컨트롤러에서 콘솔의 선을 켜기 전에 부릅니다. + /// 펌웨어가 켜 둔 인터럽트(송신 인터럽트 등)가 선을 붙들지 않게 합니다. + pub fn quiesce(regs: &mut impl Regs) { + regs.write(Reg::Imsc, 0); + regs.write(Reg::Icr, INT_ALL); + } + + /// 입력을 쓰기 시작하는 함수입니다. 그동안 장치에 쌓인 바이트를 버리고 + /// 수신 인터럽트를 켭니다. 이미 열렸거나 꺼진 경로에는 아무 일도 하지 + /// 않습니다. + pub fn open(&mut self, regs: &mut impl Regs) { + if self.open || self.off { + return; + } + if self.has_cr { + // 선로 설정은 건드리지 않고 UART와 수신기가 켜져 있게만 함 + let cr = regs.read(Reg::Cr); + if cr & (CR_UARTEN | CR_RXE) != CR_UARTEN | CR_RXE { + regs.write(Reg::Cr, cr | CR_UARTEN | CR_RXE); + } + } + self.open = true; + self.flush(regs); + } + + /// 입력이 열려 있는지 알려 주는 함수입니다. + pub fn is_open(&self) -> bool { + self.open + } + + /// 입력 경로가 꺼졌는지 알려 주는 함수입니다. + pub fn is_off(&self) -> bool { + self.off + } + + /// 링에 꺼낼 바이트가 있는지 알려 주는 함수입니다. + pub fn has_data(&self) -> bool { + self.len > 0 + } + + /// 입력 경로를 끄는 함수입니다. UART의 인터럽트를 막고 받아 둔 것을 + /// 버립니다. + pub fn turn_off(&mut self, regs: &mut impl Regs) { + regs.write(Reg::Imsc, 0); + self.off = true; + self.open = false; + self.gated = false; + self.len = 0; + } + + /// 받아 둔 입력과 유실 표시를 전부 버리는 함수입니다. + /// + /// 링을 비우고 장치의 FIFO에서도 정해진 횟수까지 꺼내 버립니다. 그 뒤에도 + /// 들어오는 바이트는 평소대로 받습니다. + pub fn flush(&mut self, regs: &mut impl Regs) { + if !self.open { + return; + } + // 버리는 동안에는 인터럽트를 막아 두고, 끝에서 FIFO의 상태에 맞춰 다시 엶 + regs.write(Reg::Imsc, 0); + self.gated = true; + self.head = 0; + self.len = 0; + for _ in 0..FLUSH_MAX { + if regs.read(Reg::Fr) & FR_RXFE != 0 { + break; + } + let _ = regs.read(Reg::Dr); + } + regs.write(Reg::Icr, INT_ALL); + self.gap = false; + self.overrun = false; + self.service(regs); + } + + /// 인터럽트 하나를 처리하는 함수입니다. + pub fn interrupt(&mut self, regs: &mut impl Regs) -> Irq { + if self.off { + // 선을 끈 뒤에 이미 전달돼 있던 인터럽트. 레지스터를 건드리지 않음 + return Irq::Spurious; + } + let mis = regs.read(Reg::Mis); + if mis & INT_OURS != 0 && self.open { + let full = self.len == RING; + if mis & INT_OE != 0 { + // 넘침은 FIFO를 비워도 가라앉지 않으므로 지움 + self.overrun = true; + regs.write(Reg::Icr, INT_OE); + } + // 바이트를 꺼냈거나, 넘침 알림이었거나, 링이 가득 차 게이트를 닫은 + // 경우가 제대로 된 원인임 + if self.service(regs) > 0 || mis & INT_OE != 0 || full { + self.spurious = 0; + return Irq::Served; + } + } + // 원인이 없거나, 원인이 있다는데 꺼낼 바이트가 없었음. 다른 장치의 + // 선이거나 고장 난 장치면 선이 내려가지 않으므로 횟수를 세어 끊음 + self.spurious += 1; + if self.spurious >= SPURIOUS_MAX { + self.turn_off(regs); + return Irq::CutOff; + } + Irq::Spurious + } + + /// 인터럽트 없이 FIFO를 들여다보는 함수입니다. + /// + /// 틱마다, 그리고 읽는 태스크가 잠들기 직전에 부릅니다. 수신 타임아웃 + /// 인터럽트가 없는 UART나 조용히 틀린 인터럽트 번호에서도 입력이 (늦게나마) + /// 도착하게 하는 보조 경로입니다. + pub fn poll(&mut self, regs: &mut impl Regs) { + if self.open && !self.off && self.service(regs) > 0 { + self.spurious = 0; + } + } + + /// 링에서 바이트 하나를 꺼내는 함수입니다. 둘째 값은 이 바이트 바로 앞에서 + /// 입력이 유실됐는지입니다. + pub fn pop(&mut self, regs: &mut impl Regs) -> Option<(u8, bool)> { + if self.len == 0 { + return None; + } + let e = self.ring[self.head]; + self.head = (self.head + 1) % RING; + self.len -= 1; + // 게이트는 링이 절반 비었을 때 다시 엶. 한 바이트마다 열면 홍수 때 + // 꺼낼 때마다 장치를 건드리게 됨 + if self.gated && self.len <= RING / 2 { + self.service(regs); + } + Some((e as u8, e & GAP != 0)) + } + + /// FIFO를 링으로 옮기고 게이트를 맞추는 함수입니다. 옮긴(또는 버린) 문자 + /// 수를 돌려줍니다. + fn service(&mut self, regs: &mut impl Regs) -> usize { + let mut taken = 0; + let mut empty = false; + for _ in 0..DRAIN_MAX { + if regs.read(Reg::Fr) & FR_RXFE != 0 { + empty = true; + break; + } + if self.len == RING { + break; + } + let d = regs.read(Reg::Dr); + taken += 1; + if d & DR_OE != 0 { + self.overrun = true; + } + if d & (DR_FE | DR_PE | DR_BE) != 0 { + // 오류가 난 문자는 버리고 다음 바이트에 표시함 + self.gap = true; + continue; + } + let mark = if self.gap || self.overrun { GAP } else { 0 }; + self.gap = false; + self.ring[(self.head + self.len) % RING] = (d & 0xFF) as u16 | mark; + self.len += 1; + } + if empty { + if self.overrun { + // 넘친 자리는 지금까지 FIFO에 있던 바이트들의 뒤임. 다음에 + // 오는 첫 바이트까지 표시함 + self.overrun = false; + self.gap = true; + } + if self.gated { + self.gated = false; + regs.write(Reg::Imsc, INT_OURS); + } + } else if !self.gated { + // FIFO에 남은 것이 있는데 받을 자리가 없음. 선이 내려가지 않으므로 + // UART 쪽에서 막고, 자리가 나면 pop이 다시 들여다봄 + self.gated = true; + regs.write(Reg::Imsc, 0); + } + taken + } +} diff --git a/crates/k0-conin/src/tests.rs b/crates/k0-conin/src/tests.rs new file mode 100644 index 0000000..9f68350 --- /dev/null +++ b/crates/k0-conin/src/tests.rs @@ -0,0 +1,601 @@ +//! 수신 로직을 가짜 UART로 검증하는 테스트 모듈입니다. +//! +//! 가짜 UART는 두 가지로 돕니다. 하나는 QEMU의 PL011처럼 FIFO가 차면 바이트를 +//! 받지 않고 기다리게 하는 것(넘침 없음, 수신 타임아웃 없음)이고, 다른 하나는 +//! 실제 하드웨어처럼 FIFO가 차면 바이트를 잃고 넘침을 알리는 것입니다. + +use std::collections::VecDeque; + +use super::*; + +const BREAK: u32 = DR_BE | DR_FE; + +struct Fake { + fifo: VecDeque, + depth: usize, + /// FIFO가 이만큼 차는 순간 수신 인터럽트가 섬 + trigger: usize, + /// FIFO가 차면 바이트를 거절하는지(QEMU), 아니면 잃는지(하드웨어) + backpressure: bool, + has_cr: bool, + ris: u32, + imsc: u32, + cr: u32, + /// 넘친 뒤 다음 데이터 읽기에 넘침 비트를 실을지 + overrun: bool, + accesses: usize, + dr_reads: usize, + cr_writes: usize, +} + +impl Fake { + fn new(depth: usize, trigger: usize, backpressure: bool) -> Self { + Self { + fifo: VecDeque::new(), + depth, + trigger, + backpressure, + has_cr: true, + ris: 0, + imsc: 0, + cr: 0x300, + overrun: false, + accesses: 0, + dr_reads: 0, + cr_writes: 0, + } + } + + fn line(&self) -> bool { + self.ris & self.imsc != 0 + } + + /// 선로에서 문자 하나가 도착함. 받았으면 true, 거절했거나 잃었으면 false + fn offer(&mut self, entry: u32) -> bool { + if self.fifo.len() == self.depth { + if !self.backpressure { + self.ris |= INT_OE; + self.overrun = true; + } + return false; + } + self.fifo.push_back(entry); + if self.fifo.len() == self.trigger { + self.ris |= INT_RX; + } + true + } + + /// 선로가 한동안 조용했음(수신 타임아웃) + fn idle(&mut self) { + if !self.fifo.is_empty() && !self.backpressure { + self.ris |= INT_RT; + } + } +} + +impl Regs for Fake { + fn read(&mut self, reg: Reg) -> u32 { + self.accesses += 1; + match reg { + Reg::Dr => { + self.dr_reads += 1; + let mut d = self.fifo.pop_front().unwrap_or(0); + if self.overrun { + d |= DR_OE; + self.overrun = false; + } + if self.fifo.len() < self.trigger { + self.ris &= !INT_RX; + } + if self.fifo.is_empty() { + self.ris &= !INT_RT; + } + d + } + Reg::Fr => { + if self.fifo.is_empty() { + FR_RXFE + } else { + 0 + } + } + Reg::Cr => { + assert!(self.has_cr, "the SBSA UART has no control register"); + self.cr + } + Reg::Imsc => self.imsc, + Reg::Mis => self.ris & self.imsc, + Reg::Icr => 0, + } + } + + fn write(&mut self, reg: Reg, value: u32) { + self.accesses += 1; + match reg { + Reg::Imsc => self.imsc = value, + Reg::Icr => self.ris &= !value, + Reg::Cr => { + assert!(self.has_cr, "the SBSA UART has no control register"); + self.cr = value; + self.cr_writes += 1; + } + other => panic!("write to {other:?}"), + } + } +} + +/// 고정된 씨앗의 의사 난수입니다(xorshift64). +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + fn below(&mut self, n: u64) -> u64 { + self.next() % n + } +} + +/// UART, 수신 로직, 인터럽트 컨트롤러의 선 하나, 읽는 태스크를 묶은 모형입니다. +struct Sim { + uart: Fake, + rx: Rx, + /// 인터럽트 컨트롤러에서 이 선이 켜져 있는지 + enabled: bool, + /// 선로에 내보냈지만 UART가 아직 받지 않은 것(QEMU 모형에서만 쌓임) + waiting: VecDeque, + /// 보낸 순서 번호를 붙인, UART가 받은 바이트 + accepted: Vec<(usize, u8)>, + sent: usize, + got: Vec<(u8, bool)>, + entries: usize, +} + +impl Sim { + fn new(uart: Fake) -> Self { + let mut s = Self { + rx: Rx::new(uart.has_cr), + uart, + enabled: true, + waiting: VecDeque::new(), + accepted: Vec::new(), + sent: 0, + got: Vec::new(), + entries: 0, + }; + Rx::quiesce(&mut s.uart); + s.rx.open(&mut s.uart); + s + } + + /// 선이 서 있는 동안 핸들러를 부름. 핸들러가 돌아온 뒤에도 선이 서 있으면 + /// 곧바로 다시 들어오는 것이고, 그런 재진입은 끊기 전까지의 횟수로 묶여야 함 + fn irqs(&mut self) { + let mut again = 0; + while self.enabled && self.uart.line() { + self.entries += 1; + again += 1; + assert!(again <= SPURIOUS_MAX as usize, "the handler returned with the line still up, again and again"); + if self.rx.interrupt(&mut self.uart) == Irq::CutOff { + self.enabled = false; + } + } + } + + /// 기다리던 문자를 UART에 밀어 넣고 인터럽트를 돌림 + fn pump(&mut self) { + loop { + self.irqs(); + let Some(&e) = self.waiting.front() else { break }; + let index = self.sent; + if self.uart.offer(e) { + self.waiting.pop_front(); + self.sent += 1; + if e & BREAK == 0 { + self.accepted.push((index, e as u8)); + } + } else if self.uart.backpressure { + self.irqs(); + break; + } else { + // 하드웨어 모형: 받지 못한 문자는 사라짐 + self.waiting.pop_front(); + self.sent += 1; + } + } + self.irqs(); + } + + fn send(&mut self, bytes: &[u8]) { + self.waiting.extend(bytes.iter().map(|b| u32::from(*b))); + self.pump(); + } + + fn pop(&mut self) -> bool { + let r = self.rx.pop(&mut self.uart); + if let Some(e) = r { + self.got.push(e); + } + self.pump(); + r.is_some() + } + + fn tick(&mut self) { + self.rx.poll(&mut self.uart); + self.pump(); + } + + /// 더 올 것이 없을 때까지 읽는 쪽을 돌림(읽는 태스크는 잠들기 전에 한 번 + /// 들여다보고, 틱마다 커널이 한 번 더 들여다봄) + fn settle(&mut self) { + for _ in 0..10_000 { + self.uart.idle(); + self.pump(); + if self.pop() { + continue; + } + self.tick(); + if !self.rx.has_data() && self.waiting.is_empty() && self.uart.fifo.is_empty() { + return; + } + } + panic!("input never drained: {} waiting, {} in the fifo", self.waiting.len(), self.uart.fifo.len()); + } + + /// 받은 것이 UART가 받아들인 것과 순서까지 같고, 빠진 자리 뒤의 첫 + /// 바이트에는 유실 표시가 있어야 함 + fn check(&self) { + let bytes: Vec = self.got.iter().map(|e| e.0).collect(); + let want: Vec = self.accepted.iter().map(|e| e.1).collect(); + assert_eq!(bytes, want); + let mut last = None; + for (k, (index, _)) in self.accepted.iter().enumerate() { + let hole = match last { + None => *index != 0, + Some(prev) => *index != prev + 1, + }; + if hole { + assert!(self.got[k].1, "byte {k} follows a hole and carries no mark"); + } + last = Some(*index); + } + } +} + +#[test] +fn quiesce_masks_everything_and_open_asks_only_for_receive() { + let mut uart = Fake::new(16, 1, true); + uart.imsc = 0x7FF; + uart.ris = 1 << 5; + Rx::quiesce(&mut uart); + assert_eq!((uart.imsc, uart.ris), (0, 0)); + assert!(!uart.line()); + + // 열기 전에 온 바이트는 버려지고, UART와 수신기가 켜지며, 수신 관련 + // 인터럽트만 요청함 + for b in b"typed during boot" { + uart.offer(u32::from(*b)); + } + let mut rx = Rx::new(true); + assert!(!rx.is_open()); + rx.open(&mut uart); + assert!(rx.is_open() && !rx.has_data() && uart.fifo.is_empty()); + assert_eq!(uart.cr, 0x301); + assert_eq!(uart.imsc, INT_RX | INT_RT | INT_OE); + assert_eq!(rx.pop(&mut uart), None); + + // 이미 켜져 있으면 제어 레지스터에 쓰지 않고, 두 번 여는 것은 아무 일도 아님 + let mut uart = Fake::new(16, 1, true); + uart.cr = 0x301; + let mut rx = Rx::new(true); + rx.open(&mut uart); + let after = uart.accesses; + rx.open(&mut uart); + assert_eq!((uart.cr_writes, uart.accesses), (0, after)); +} + +#[test] +fn the_sbsa_uart_is_never_asked_for_a_control_register() { + let mut uart = Fake::new(32, 16, false); + uart.has_cr = false; + let mut sim = Sim::new(uart); + sim.send(b"hello over an sbsa uart, longer than the fifo trigger"); + sim.settle(); + sim.check(); + assert_eq!(sim.got.len(), sim.accepted.len()); +} + +#[test] +fn a_byte_arrives_through_one_interrupt() { + let mut sim = Sim::new(Fake::new(1, 1, true)); + sim.send(b"a"); + assert_eq!(sim.entries, 1); + assert!(!sim.uart.line()); + assert_eq!(sim.rx.pop(&mut sim.uart), Some((b'a', false))); + assert_eq!(sim.rx.pop(&mut sim.uart), None); +} + +#[test] +fn a_flood_fills_the_ring_closes_the_gate_and_resumes_when_the_reader_catches_up() { + // 설계 검토가 찾은 경우: 링이 가득 찬 뒤 게이트가 열릴 때 FIFO에 남은 + // 바이트를 가져올 인터럽트가 다시 오지 않으면 입력이 영영 멈춤 + for (depth, trigger) in [(1, 1), (16, 1), (32, 16)] { + let mut sim = Sim::new(Fake::new(depth, trigger, true)); + let flood: Vec = (0..5000u32).map(|i| (i % 251) as u8).collect(); + sim.send(&flood); + // 읽는 쪽이 멈춰 있으면 링이 차고 선이 내려감. 그때까지의 진입 횟수는 + // 링 크기를 넘지 않음 + assert!(sim.rx.has_data()); + assert!(!sim.uart.line()); + assert!(sim.entries <= RING + 1, "{} entries", sim.entries); + assert_eq!(sim.uart.imsc, 0, "the gate is closed at the uart"); + let quiet = sim.entries; + for _ in 0..50 { + sim.pump(); + } + assert_eq!(sim.entries, quiet, "no interrupt arrives while the reader is stopped"); + sim.settle(); + sim.check(); + assert_eq!(sim.got.len(), 5000); + assert!(sim.got.iter().all(|e| !e.1), "nothing was lost, so nothing is marked"); + assert_eq!(sim.uart.imsc, INT_RX | INT_RT | INT_OE, "the gate is open again"); + } +} + +#[test] +fn the_reader_alone_reopens_the_gate_without_waiting_for_a_tick() { + for (depth, trigger, backpressure) in [(1, 1, true), (16, 1, true), (32, 16, false)] { + let mut sim = Sim::new(Fake::new(depth, trigger, backpressure)); + sim.send(&[b'a'; RING + 40]); + assert_eq!(sim.uart.imsc, 0); + // 틱도 잠들기 전 확인도 없이 꺼내기만 함 + let mut popped = 0; + while sim.pop() { + popped += 1; + assert!(popped < 10_000); + } + if backpressure { + assert_eq!(popped, RING + 40); + } else { + assert!(popped >= RING + depth); + } + assert_eq!(sim.uart.imsc, INT_RX | INT_RT | INT_OE); + assert!(!sim.uart.line()); + // 그 뒤의 바이트는 다시 인터럽트로 들어옴 + let before = sim.entries; + sim.send(&[b'b'; 32]); + assert!(sim.entries > before && sim.rx.has_data()); + } +} + +#[test] +fn the_work_of_one_interrupt_is_bounded_by_the_room_in_the_ring() { + let mut sim = Sim::new(Fake::new(32, 16, false)); + for round in 0..40 { + let before = sim.uart.dr_reads; + let room = RING - sim.rx.len; + sim.send(&[round as u8; 16]); + assert!(sim.uart.dr_reads - before <= room.max(1) + 16); + } +} + +#[test] +fn random_schedules_on_the_emulator_model_deliver_every_byte_exactly_once() { + let mut rng = Rng(0x243F_6A88_85A3_08D3); + for round in 0..300 { + let depth = [1usize, 16, 32][rng.below(3) as usize]; + let mut sim = Sim::new(Fake::new(depth, 1, true)); + for _ in 0..rng.below(60) { + match rng.below(10) { + 0..=3 => { + let n = [1, 3, 40, 300, 700][rng.below(5) as usize]; + let bytes: Vec = (0..n).map(|_| rng.next() as u8).collect(); + sim.send(&bytes); + } + 4..=7 => { + for _ in 0..rng.below(200) { + sim.pop(); + } + } + _ => sim.tick(), + } + } + sim.settle(); + sim.check(); + assert_eq!(sim.got.len(), sim.sent, "round {round}"); + assert!(sim.got.iter().all(|e| !e.1), "round {round}: a mark without a loss"); + assert!(sim.enabled, "round {round}: a healthy uart was cut off"); + } +} + +#[test] +fn random_schedules_on_the_hardware_model_mark_every_hole() { + let mut rng = Rng(0x1319_8A2E_0370_7344); + let mut holes = 0; + for round in 0..400 { + let (depth, trigger) = [(16usize, 8usize), (32, 16), (32, 4), (1, 1)][rng.below(4) as usize]; + let mut sim = Sim::new(Fake::new(depth, trigger, false)); + for _ in 0..rng.below(60) { + match rng.below(12) { + 0..=3 => { + let n = [1, 2, 7, 20, 90, 400][rng.below(6) as usize]; + let bytes: Vec = (0..n).map(|_| rng.next() as u8).collect(); + sim.send(&bytes); + } + 4 => { + // 선로의 break는 오류 표시가 붙은 문자로 들어옴 + sim.waiting.push_back(BREAK); + sim.pump(); + } + 5..=8 => { + for _ in 0..rng.below(300) { + sim.pop(); + } + } + 9 => { + sim.uart.idle(); + sim.pump(); + } + _ => sim.tick(), + } + } + sim.settle(); + sim.check(); + holes += usize::from(sim.accepted.len() != sim.sent); + if sim.accepted.len() == sim.sent { + assert!(sim.got.iter().all(|e| !e.1), "round {round}: a mark without a loss"); + } + assert!(sim.enabled, "round {round}: a healthy uart was cut off"); + } + assert!(holes > 100, "the schedules must actually overrun the fifo ({holes} rounds did)"); +} + +#[test] +fn a_break_marks_the_byte_after_it() { + let mut sim = Sim::new(Fake::new(16, 1, true)); + sim.send(b"vault zeroize con"); + sim.waiting.push_back(BREAK); + sim.pump(); + sim.send(b"firm\r"); + sim.settle(); + let marks: Vec = sim.got.iter().enumerate().filter(|(_, e)| e.1).map(|(i, _)| i).collect(); + assert_eq!(marks, [17]); + sim.check(); +} + +#[test] +fn an_overrun_marks_what_was_in_the_fifo_and_the_first_byte_after() { + // 읽는 쪽이 멈춘 동안 링과 FIFO가 모두 차서 바이트가 사라짐 + let mut sim = Sim::new(Fake::new(16, 8, false)); + let first: Vec = (0..RING as u32 + 16).map(|i| i as u8).collect(); + sim.send(&first); + sim.send(b"these bytes are lost"); + assert_eq!(sim.accepted.len(), RING + 16); + // 자리가 난 뒤에 온 바이트는 받음 + for _ in 0..200 { + sim.pop(); + } + sim.send(b"after"); + sim.settle(); + sim.check(); + // 구멍은 FIFO에 있던 16바이트의 뒤이지만 경계를 알 수 없으므로 그 16바이트와 + // 뒤의 첫 바이트가 모두 표시됨. 링에 먼저 들어가 있던 바이트는 표시되지 않음 + let marks: Vec = sim.got.iter().enumerate().filter(|(_, e)| e.1).map(|(i, _)| i).collect(); + assert_eq!(marks.first(), Some(&RING)); + assert_eq!(marks.last(), Some(&(RING + 16))); + assert!(sim.got[..RING].iter().all(|e| !e.1)); + assert!(!sim.got[RING + 17].1); +} + +#[test] +fn flush_drops_the_ring_the_fifo_and_the_marks() { + let mut sim = Sim::new(Fake::new(16, 8, false)); + sim.send(&[b'x'; 400]); + sim.send(b"lost"); + assert!(sim.rx.has_data()); + sim.rx.flush(&mut sim.uart); + assert!(!sim.rx.has_data() && sim.uart.fifo.is_empty()); + assert_eq!(sim.uart.imsc, INT_RX | INT_RT | INT_OE); + assert_eq!(sim.uart.ris & INT_OE, 0); + sim.got.clear(); + sim.send(b"help\r"); + sim.settle(); + assert_eq!(sim.got, [(b'h', false), (b'e', false), (b'l', false), (b'p', false), (b'\r', false)]); + + // 닫혀 있는 경로에서는 아무 일도 하지 않음 + let mut uart = Fake::new(16, 8, false); + let mut rx = Rx::new(true); + rx.flush(&mut uart); + assert_eq!(uart.accesses, 0); +} + +#[test] +fn input_still_arrives_when_the_interrupt_never_comes() { + // 디바이스 트리가 조용한 다른 선을 가리킨 경우, 또는 수신 타임아웃이 없는 + // UART에서 FIFO가 트리거에 못 미친 경우: 틱마다 들여다보는 것으로 도착함 + let mut sim = Sim::new(Fake::new(32, 16, false)); + sim.enabled = false; + sim.send(b"help\r"); + assert!(!sim.rx.has_data()); + sim.tick(); + assert!(sim.rx.has_data()); + sim.settle(); + sim.check(); + assert_eq!(sim.got.len(), 5); +} + +/// 원인을 밝히지 않으면서 선을 붙들고 있는 장치입니다(다른 장치의 선). +struct Stuck { + accesses: usize, + mis: u32, +} + +impl Regs for Stuck { + fn read(&mut self, reg: Reg) -> u32 { + self.accesses += 1; + match reg { + Reg::Mis => self.mis, + Reg::Fr => FR_RXFE, + _ => 0, + } + } + + fn write(&mut self, _reg: Reg, _value: u32) { + self.accesses += 1; + } +} + +#[test] +fn a_line_that_stays_up_without_a_cause_is_cut_off_after_a_few_entries() { + // 원인이 없다고 하는 경우와, 수신이라고 하면서 FIFO가 비어 있는 경우 + for mis in [0, INT_RX, INT_RT] { + let mut regs = Stuck { accesses: 0, mis }; + let mut rx = Rx::new(true); + rx.open(&mut regs); + for _ in 0..SPURIOUS_MAX - 1 { + assert_eq!(rx.interrupt(&mut regs), Irq::Spurious); + assert!(!rx.is_off()); + } + assert_eq!(rx.interrupt(&mut regs), Irq::CutOff); + assert!(rx.is_off() && !rx.is_open() && !rx.has_data()); + // 끈 뒤에 들어오는 인터럽트는 레지스터를 건드리지 않음 + let after = regs.accesses; + assert_eq!(rx.interrupt(&mut regs), Irq::Spurious); + rx.poll(&mut regs); + rx.flush(&mut regs); + rx.open(&mut regs); + assert_eq!(rx.pop(&mut regs), None); + assert_eq!(regs.accesses, after); + assert!(rx.is_off()); + } +} + +#[test] +fn a_real_cause_resets_the_spurious_count() { + let mut sim = Sim::new(Fake::new(16, 1, true)); + for round in 0..50 { + // 원인 없는 진입을 끊기 직전까지 넣고, 바이트 하나로 되돌림 + for _ in 0..SPURIOUS_MAX - 1 { + assert_eq!(sim.rx.interrupt(&mut sim.uart), Irq::Spurious); + } + sim.send(&[round]); + assert!(!sim.rx.is_off()); + } + sim.settle(); + assert_eq!(sim.got.len(), 50); +} + +#[test] +fn turning_the_path_off_masks_the_uart_and_empties_the_ring() { + let mut sim = Sim::new(Fake::new(16, 1, true)); + sim.send(b"abc"); + sim.rx.turn_off(&mut sim.uart); + assert_eq!(sim.uart.imsc, 0); + assert!(sim.rx.is_off() && !sim.rx.has_data()); + assert_eq!(sim.rx.pop(&mut sim.uart), None); +} diff --git a/crates/k0-efi/src/acpi.rs b/crates/k0-efi/src/acpi.rs index f37ad30..ae4710f 100644 --- a/crates/k0-efi/src/acpi.rs +++ b/crates/k0-efi/src/acpi.rs @@ -34,6 +34,8 @@ pub enum Uart { pub struct Serial { pub kind: Uart, pub reg: MemRegion, + /// 콘솔의 인터럽트 번호(GSIV). SPCR이 GIC의 SPI 하나로 밝힌 경우에만 있음 + pub irq: Option, } /// 인터럽트 컨트롤러입니다. @@ -309,7 +311,18 @@ fn serial_of(t: &[u8]) -> Option { if kind != Uart::Ns16550 && base % 4 != 0 { return None; } - Some(Serial { kind, reg: MemRegion { base, size } }) + // 인터럽트: 종류가 GIC 하나뿐이고(비트 3만) 번호가 SPI일 때만 받음. 종류는 + // 오프셋 52, 번호는 54부터 4바이트라서 테이블이 58바이트보다 짧으면 + // 인터럽트 없이 콘솔만 받음 + let irq = match (t.get(52), le32(t, 54)) { + (Some(&0x08), Some(gsiv)) if (32..=1019).contains(&gsiv) => Some(gsiv), + _ => None, + }; + Some(Serial { + kind, + reg: MemRegion { base, size }, + irq, + }) } /// ACPI 정적 테이블에서 콘솔, 인터럽트 컨트롤러, 타이머 인터럽트를 읽는 diff --git a/crates/k0-efi/src/synth.rs b/crates/k0-efi/src/synth.rs index cc7bab1..d841227 100644 --- a/crates/k0-efi/src/synth.rs +++ b/crates/k0-efi/src/synth.rs @@ -98,6 +98,14 @@ pub fn synthesize(found: &Found, placeholder: MemRegion, out: &mut [u8]) -> Resu w.prop(b"reg-shift", &0u32.to_be_bytes())?; w.prop(b"reg-io-width", &1u32.to_be_bytes())?; } + if let Some(irq) = serial.irq { + // 종류 0(SPI), SPI 번호, 레벨 트리거에 액티브 하이. 커널의 파서가 + // 받는 모양은 이것 하나뿐임 + let mut spec = [0u8; 12]; + spec[4..8].copy_from_slice(&(irq - 32).to_be_bytes()); + spec[8..].copy_from_slice(&4u32.to_be_bytes()); + w.prop(b"interrupts", &spec)?; + } w.end()?; } diff --git a/crates/k0-efi/src/tests.rs b/crates/k0-efi/src/tests.rs index a3edac0..0bc6b6f 100644 --- a/crates/k0-efi/src/tests.rs +++ b/crates/k0-efi/src/tests.rs @@ -895,10 +895,25 @@ mod acpi_tables { sdt(b"GTDT", &body) } + /// QEMU가 만드는 SPCR과 같은 모양: 인터럽트는 GIC의 SPI 1번(GSIV 33) fn spcr(interface: u8, space: u8, width: u8, access: u8, addr: u64) -> Vec { - let mut body = vec![0u8; 44]; + spcr_irq(interface, space, width, access, addr, 44, 0x08, 33) + } + + /// 인터럽트 칸을 따로 정한 SPCR입니다. + /// + /// # Arguments + /// `body_len` - 헤더 뒤의 길이(인터럽트 칸까지 담으려면 22 이상) + /// `kind` - 인터럽트 종류(비트 3이 GIC) + /// `gsiv` - 인터럽트 번호 + #[allow(clippy::too_many_arguments)] + fn spcr_irq(interface: u8, space: u8, width: u8, access: u8, addr: u64, body_len: usize, kind: u8, gsiv: u32) -> Vec { + let mut body = vec![0u8; body_len.max(22)]; (body[0], body[4], body[5], body[7]) = (interface, space, width, access); body[8..16].copy_from_slice(&addr.to_le_bytes()); + body[16] = kind; + body[18..22].copy_from_slice(&gsiv.to_le_bytes()); + body.truncate(body_len); sdt(b"SPCR", &body) } @@ -1126,6 +1141,37 @@ mod acpi_tables { } } + #[test] + fn the_console_interrupt_is_taken_only_as_one_gic_spi() { + let irq = |t: Vec| read(&with(qemu_v3(), 2, t), RSDP, 0).unwrap().serial.unwrap().irq; + let pl011 = |len: usize, kind: u8, gsiv: u32| spcr_irq(0x03, 0, 32, 3, 0x900_0000, len, kind, gsiv); + assert_eq!(irq(pl011(44, 0x08, 33)), Some(33)); + assert_eq!(irq(pl011(44, 0x08, 32)), Some(32)); + assert_eq!(irq(pl011(44, 0x08, 1019)), Some(1019)); + // 번호까지 담는 가장 짧은 테이블(58바이트) + assert_eq!(irq(pl011(22, 0x08, 33)), Some(33)); + // 번호가 잘린 테이블, SPI가 아닌 번호, GIC가 아니거나 다른 종류가 섞인 표시: + // 콘솔은 받되 인터럽트는 없음 + for t in [ + pl011(21, 0x08, 33), + pl011(16, 0x08, 33), + pl011(44, 0x08, 31), + pl011(44, 0x08, 1020), + pl011(44, 0x08, u32::MAX), + pl011(44, 0x00, 33), + pl011(44, 0x01, 33), + pl011(44, 0x09, 33), + pl011(44, 0x18, 33), + ] { + assert_eq!(irq(t), None); + } + // 만든 트리에서 커널의 파서가 같은 번호를 읽음 + let found = read(&with(qemu_v3(), 2, pl011(44, 0x08, 300)), RSDP, 0).unwrap(); + assert_eq!(discover_blob(&tree(&found)).unwrap().platform.console.unwrap().irq, Some(300)); + let found = read(&with(qemu_v3(), 2, pl011(44, 0x00, 300)), RSDP, 0).unwrap(); + assert_eq!(discover_blob(&tree(&found)).unwrap().platform.console.unwrap().irq, None); + } + #[test] fn devices_named_by_the_tables_must_not_lie_in_memory() { let found = read(&machine(&qemu_v3()), RSDP, 0).unwrap(); diff --git a/crates/k0-ipc/Cargo.toml b/crates/k0-ipc/Cargo.toml index 372f240..90df8a4 100644 --- a/crates/k0-ipc/Cargo.toml +++ b/crates/k0-ipc/Cargo.toml @@ -11,6 +11,9 @@ publish.workspace = true default = ["granule-4k"] granule-4k = ["k0-mm/granule-4k", "k0-task/granule-4k", "k0-sched/granule-4k"] granule-16k = ["k0-mm/granule-16k", "k0-task/granule-16k", "k0-sched/granule-16k"] +# 콘솔 입력을 읽는 시스템 콜과 그 대기 상태. 고르지 않으면 이 크레이트에 +# 그 코드가 없음 +console-input = ["k0-arch/console-input", "k0-task/console-input"] [dependencies] k0-abi = { path = "../k0-abi" } diff --git a/crates/k0-ipc/src/console.rs b/crates/k0-ipc/src/console.rs new file mode 100644 index 0000000..df1e2a0 --- /dev/null +++ b/crates/k0-ipc/src/console.rs @@ -0,0 +1,232 @@ +//! 콘솔 입력을 읽는 시스템 콜(CONSOLE_READ)과 그 대기자를 다루는 모듈입니다. +//! +//! # Features +//! 커널을 `console-input`으로 빌드한 이미지에만 있습니다. 바이트를 받는 일은 +//! `k0_arch::conin`(수신 로직과 UART)이 하고, 이 모듈은 누가 읽을 수 있는지와 +//! 기다리는 태스크를 다룹니다. +//! +//! 읽으려면 읽기 권한(R)이 있는 Console 케이퍼빌리티를 제시해야 합니다. 받아 +//! 둔 바이트가 없으면 태스크는 `BlockedConsole` 상태로 잠들고, 대기자 자리는 +//! 하나뿐이라 그동안 다른 태스크의 읽기는 BUSY로 끝납니다. 기한은 IPC와 같은 +//! 기한 목록을 씁니다. +//! +//! 수신 인터럽트의 핸들러는 링에 바이트를 옮기기만 하고 스케줄러를 건드리지 +//! 않습니다. 대기자를 깨우는 일은 [wake]가 하고, 커널이 스케줄러에 배타적으로 +//! 접근할 수 있는 문맥(EL0에서 들어온 인터럽트의 끝, 대기 루프, 틱)에서 +//! 부릅니다. 깨울 때는 대기자가 그 케이퍼빌리티를 아직 쥐고 있는지 다시 +//! 확인하므로, 기다리는 동안 권한을 잃은 태스크는 바이트를 받지 못합니다. +//! 깨어난 태스크는 준비 큐의 끝에 섭니다(선점하지 않음). + +use core::cell::UnsafeCell; +use core::fmt::Write; + +use k0_abi::{console as flag, err}; +use k0_arch::conin; +use k0_arch::earlycon::EarlyCon; +use k0_arch::usermode::Context; +use k0_cap::{rights, Cap}; +use k0_task::{TaskState, Tcb}; + +/// 콘솔 입력을 기다리는 태스크(커널 VA, 0 = 없음)를 담는 자리입니다. +struct Waiter(UnsafeCell); + +// SAFETY: 단일 코어이고 이 모듈의 함수는 전부 인터럽트가 마스크된 커널 +// 문맥에서만 불리므로 동시에 접근하지 않음 +unsafe impl Sync for Waiter {} + +static WAITER: Waiter = Waiter(UnsafeCell::new(0)); + +fn waiter() -> *mut Tcb { + // SAFETY: 위의 Sync 근거대로 이 접근은 배타적임 + unsafe { *WAITER.0.get() as *mut Tcb } +} + +fn set_waiter(t: *mut Tcb) { + // SAFETY: 위의 Sync 근거대로 이 접근은 배타적임 + unsafe { *WAITER.0.get() = t as u64 }; +} + +/// 태스크의 CNode에서 슬롯을 찾아 읽기 권한이 있는 Console인지 확인하는 +/// 함수입니다. +/// +/// # Errors +/// 범위 밖이거나 빈 슬롯은 BAD_SLOT, Console이 아니면 BAD_CAP, 읽기 권한이 +/// 없으면 NO_RIGHTS +/// +/// # Safety +/// `t`는 유효한 TCB여야 하고 접근이 배타적이어야 합니다. +unsafe fn readable(t: *mut Tcb, slot: u64) -> Result<(), i64> { + // SAFETY: 함수 계약대로 접근이 배타적이고 t는 유효한 TCB임 + let cnode = match unsafe { Tcb::cspace(t) } { + Ok(Some(c)) => c, + Ok(None) => return Err(err::BAD_SLOT), + Err(_) => k0_arch::fatal("cap slot corrupt (cspace)"), + }; + let Some(s) = cnode.slot(slot) else { + return Err(err::BAD_SLOT); + }; + // SAFETY: s는 살아 있는 CNode의 범위 안 슬롯임 + match unsafe { k0_cap::read(s) } { + Ok(Some(k0_cap::Entry { + cap: Cap::Console { rights }, + .. + })) => { + if rights & rights::R == 0 { + return Err(err::NO_RIGHTS); + } + Ok(()) + } + Ok(Some(_)) => Err(err::BAD_CAP), + Ok(None) => Err(err::BAD_SLOT), + Err(_) => k0_arch::fatal("cap slot corrupt (console)"), + } +} + +fn deliver(ctx: &mut Context, byte: u8, lost: bool) { + ctx.x[0] = 0; + ctx.x[1] = u64::from(byte); + ctx.x[2] = if lost { flag::LOST } else { 0 }; +} + +/// CONSOLE_READ 시스템 콜 처리 함수입니다. +/// +/// 반환 레지스터는 이 함수가 직접 씁니다(블록되는 경우에는 깨우는 쪽이 씀). +/// 호출한 태스크가 블록됐는데 준비된 태스크가 없으면 false를 돌려줍니다. +/// +/// 권한 확인을 통과하고 입력 경로가 있는 첫 호출에서 주기적인 틱 줄을 멈추고 +/// 수신 인터럽트를 켭니다. 그 전에 장치에 쌓인 바이트는 버려집니다. +/// +/// # Arguments +/// `ctx` - 호출한 태스크의 컨텍스트(x0 = Console 슬롯, x1 = 플래그) +#[must_use] +pub fn sys_console_read(ctx: &mut Context) -> bool { + let (slot, flags) = (ctx.x[0], ctx.x[1]); + let fail = |ctx: &mut Context, e: i64| { + ctx.x[0] = e as u64; + true + }; + // SAFETY: 이양 후의 시스템 콜 컨텍스트(단일 코어, DAIF 마스크)라 접근이 + // 배타적이고 current는 유효한 TCB임 + let cur = unsafe { k0_sched::current() }; + // SAFETY: 위와 같음 + if let Err(e) = unsafe { readable(cur, slot) } { + return fail(ctx, e); + } + if flags & flag::RESERVED != 0 { + return fail(ctx, err::BAD_FLAGS); + } + if !conin::available() { + return fail(ctx, err::NO_DEVICE); + } + if k0_arch::irq::quiet_ticks() { + let _ = writeln!(EarlyCon, "k0: tick lines off (console input in use)"); + } + conin::open(); + if !waiter().is_null() { + return fail(ctx, err::BUSY); + } + if flags & flag::FLUSH != 0 { + conin::flush(); + } + if let Some((b, lost)) = conin::pop() { + deliver(ctx, b, lost); + return true; + } + if flags & flag::NONBLOCK != 0 { + return fail(ctx, err::WOULD_BLOCK); + } + // 잠들기 전에 장치를 한 번 들여다봄. 인터럽트가 알려 주지 않은 바이트가 + // FIFO에 남아 있으면 여기서 가져옴 + conin::poll(); + if let Some((b, lost)) = conin::pop() { + deliver(ctx, b, lost); + return true; + } + // SAFETY: 접근이 배타적이고 cur는 실행 중인 유효한 TCB라 어떤 큐에도 없음 + unsafe { + (*cur).state = TaskState::BlockedConsole; + // 깨울 때 권한을 다시 확인할 슬롯 번호 + (*cur).blocked_on = slot; + set_waiter(cur); + k0_sched::arm_timeout(cur, crate::deadline_of(flags)); + k0_sched::block_and_switch() + } +} + +/// 콘솔 입력을 기다리는 태스크가 있는지 알려 주는 함수입니다. +pub fn waiting() -> bool { + !waiter().is_null() +} + +/// 기다리는 태스크를 깨울 수 있으면 깨우는 함수입니다. +/// +/// 바이트가 도착했으면 그것을 전달하고, 입력 경로가 꺼졌으면 NO_DEVICE로, +/// 대기자가 그사이 케이퍼빌리티를 잃었으면 바이트를 쓰지 않고 REVOKED로 +/// 깨웁니다. 깨울 까닭이 없으면 아무 일도 하지 않습니다. +/// +/// # Arguments +/// `current_ctx` - 현재 태스크의 컨텍스트가 살아 있는 참조. 대기 루프에서는 +/// 블록된 현재 태스크가 대기자일 수 있고, 그때는 반환값을 이 +/// 참조로 써야 함. 실행 중이던 태스크를 끊고 들어온 문맥에서는 +/// `None` +/// +/// # Safety +/// 스케줄러에 배타적으로 접근할 수 있는 커널 문맥(시스템 콜, EL0에서 들어온 +/// 인터럽트의 끝, 대기 루프)에서만 불러야 합니다. +pub unsafe fn wake(mut current_ctx: Option<&mut Context>) { + let t = waiter(); + if t.is_null() { + return; + } + // SAFETY: 함수 계약대로 접근이 배타적이고, 대기자 자리에 있는 TCB는 + // teardown이 빼기 전까지 살아 있는 BlockedConsole 태스크임 + unsafe { + if (*t).state != TaskState::BlockedConsole { + k0_arch::fatal("console waiter is not waiting"); + } + let held = readable(t, (*t).blocked_on).is_ok(); + let off = !conin::available(); + let result = if !held { + Some((err::REVOKED as u64, 0, 0)) + } else if off { + Some((err::NO_DEVICE as u64, 0, 0)) + } else { + conin::pop().map(|(b, lost)| (0, u64::from(b), if lost { flag::LOST } else { 0 })) + }; + let Some((x0, x1, x2)) = result else { + return; + }; + let write = |c: &mut Context| { + c.x[0] = x0; + if x0 == 0 { + c.x[1] = x1; + c.x[2] = x2; + } + }; + if t == k0_sched::current() { + match current_ctx.as_deref_mut() { + Some(c) => write(c), + None => k0_arch::fatal("running task is the console waiter"), + } + } else { + write(&mut (*t).ctx); + } + (*t).blocked_on = 0; + set_waiter(core::ptr::null_mut()); + k0_sched::enqueue(t); + } +} + +/// 기한이 지난 대기자를 대기자 자리에서 빼는 함수입니다. 반환값을 쓰고 준비 +/// 큐에 넣는 일은 부른 쪽([crate::expire_timeouts])이 합니다. +/// +/// # Safety +/// [wake]와 같고, `t`는 `BlockedConsole` 상태여야 합니다. +pub(crate) unsafe fn drop_waiter(t: *mut Tcb) { + if waiter() != t { + k0_arch::fatal("console waiter slot corrupt"); + } + // SAFETY: 함수 계약대로 t는 유효한 TCB임 + unsafe { (*t).blocked_on = 0 }; + set_waiter(core::ptr::null_mut()); +} diff --git a/crates/k0-ipc/src/lib.rs b/crates/k0-ipc/src/lib.rs index 922b32d..063a41a 100644 --- a/crates/k0-ipc/src/lib.rs +++ b/crates/k0-ipc/src/lib.rs @@ -28,6 +28,9 @@ #![no_std] +#[cfg(feature = "console-input")] +pub mod console; + use k0_arch::usermode::Context; use k0_cap::{rights, Cap}; use k0_task::{Endpoint, TaskState, Tcb}; @@ -443,7 +446,16 @@ pub unsafe fn expire_timeouts(now: u64, mut current_ctx: Option<&mut Context>) { (*t).reply_from = 0; k0_abi::err::REPLY_TIMEOUT as u64 } - _ => k0_arch::fatal("timeout on a task that is not blocked"), + #[cfg(feature = "console-input")] + TaskState::BlockedConsole => { + console::drop_waiter(t); + k0_abi::err::TIMEOUT as u64 + } + TaskState::Inactive + | TaskState::Stopped + | TaskState::Ready + | TaskState::Running + | TaskState::Dead => k0_arch::fatal("timeout on a task that is not blocked"), }; if t == cur { match current_ctx.as_deref_mut() { @@ -503,6 +515,10 @@ pub unsafe fn teardown(t: *mut Tcb) { } (*holder).reply_to = 0; } + // 콘솔 입력을 기다리던 태스크는 대기자 자리를 비워, 그 TCB의 + // 메모리가 재분류된 뒤에 커널이 옛 포인터로 깨우는 일이 없게 함 + #[cfg(feature = "console-input")] + TaskState::BlockedConsole => console::drop_waiter(t), } abort_reply(t); (*t).state = TaskState::Dead; diff --git a/crates/k0-task/Cargo.toml b/crates/k0-task/Cargo.toml index a8e2d91..81a049f 100644 --- a/crates/k0-task/Cargo.toml +++ b/crates/k0-task/Cargo.toml @@ -11,6 +11,8 @@ publish.workspace = true default = ["granule-4k"] granule-4k = ["k0-mm/granule-4k"] granule-16k = ["k0-mm/granule-16k"] +# 콘솔 입력을 기다리는 태스크 상태(BlockedConsole)를 더함 +console-input = [] [dependencies] k0-abi = { path = "../k0-abi" } diff --git a/crates/k0-task/src/lib.rs b/crates/k0-task/src/lib.rs index a0a54a0..012e5bb 100644 --- a/crates/k0-task/src/lib.rs +++ b/crates/k0-task/src/lib.rs @@ -78,6 +78,10 @@ pub enum TaskState { BlockedReply = 7, /// 엔드포인트 대기 큐에서 수신자를 기다리는 중(CALL, 전달 시 응답 대기로 전환) BlockedCall = 8, + /// 콘솔 입력을 기다리는 중(CONSOLE_READ). 어떤 큐에도 없고 커널의 대기자 + /// 자리 하나가 가리킴. `blocked_on`에는 제시한 슬롯 번호가 들어 있음 + #[cfg(feature = "console-input")] + BlockedConsole = 9, } /// TCB 내장 슬롯 배열에서 케이퍼빌리티 공간(CNode)이 드는 자리 diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml index ecd4bae..903a98e 100644 --- a/kernel/Cargo.toml +++ b/kernel/Cargo.toml @@ -32,6 +32,13 @@ granule-16k = [ console-pl011 = ["k0-arch/console-pl011"] console-16550 = ["k0-arch/console-16550"] console = ["console-pl011", "console-16550"] +# console-input 콘솔 입력의 수신 경로(PL011과 SBSA UART). 읽기 권한이 있는 +# Console 케이퍼빌리티로 CONSOLE_READ를 부르는 태스크만 받음. +# 콘솔 드라이버는 따로 골라야 함(16550에는 수신이 없음) +# terminal 루트 태스크 이미지에 운영자 터미널을 넣음(자가 검증 뒤에 +# 서비스로 시작). console-input을 함께 켬 +console-input = ["k0-arch/console-input", "k0-ipc/console-input", "k0-task/console-input", "k0-boot/console-input"] +terminal = ["console-input", "k0-boot/terminal", "k0-cap/root-cnode-1024"] # 루트 태스크 이미지에 키 볼트(서명 오라클)를 넣음. 알고리즘은 따로 더함 # vault 볼트 서비스와 그 자가 검증(서명 알고리즘 없음) # vault-ed25519 위에 Ed25519를 더함 diff --git a/kernel/src/main.rs b/kernel/src/main.rs index 272136d..c378640 100644 --- a/kernel/src/main.rs +++ b/kernel/src/main.rs @@ -214,6 +214,8 @@ extern "C" fn kernel_main(dtb_phys: usize) -> ! { match setup_irq(&traps, &platform, counter_hz) { Ok(_irq) => { let _ = writeln!(con, "k0: irq on (timer 1s)"); + #[cfg(feature = "console-input")] + setup_console_input(&mut con, &_irq, &platform); } Err(e) => { let _ = writeln!(con, "k0: irq init failed: {e:?}"); @@ -374,6 +376,8 @@ extern "C" fn kernel_main(dtb_phys: usize) -> ! { addr_space_root: user_root, addr_space_asid: root_asid, cnode: cnode_frame, + // 입력을 읽을 권한은 커널에 입력 경로가 있는 이미지에서만 줌 + console_rights: k0_cap::rights::W | if cfg!(feature = "console-input") { k0_cap::rights::R } else { 0 }, }; // 예약 구간은 위에서 이미 뺐으므로 남은 구간이 그대로 untyped가 됨 // SAFETY: cnode의 슬롯은 전부 비어 있고 접근이 배타적임 @@ -753,7 +757,10 @@ fn write_bootinfo(frame_pa: u64, cnode: &k0_cap::CNodeRef, count: u64, image: &I None => plain(cap_kind::EMPTY), Some(Cap::Tcb { .. }) => plain(cap_kind::TCB), Some(Cap::AddrSpace { .. }) => plain(cap_kind::ADDR_SPACE), - Some(Cap::Console) => plain(cap_kind::CONSOLE), + Some(Cap::Console { rights }) => CapDesc { + rights: u64::from(rights), + ..plain(cap_kind::CONSOLE) + }, Some(Cap::CNode { .. }) => plain(cap_kind::CNODE), Some(Cap::PageTable { .. }) => plain(cap_kind::PAGE_TABLE), Some(Cap::Endpoint { .. }) => plain(cap_kind::ENDPOINT), @@ -938,6 +945,72 @@ fn attach_console(con: &mut EarlyCon, c: &k0_boot::Console, counter_hz: u64) { unsafe { k0_arch::earlycon::attach(uart, va as usize, counter_hz) }; } +/// 붙어 있는 콘솔에 입력 경로를 준비하는 함수입니다. +/// +/// UART의 인터럽트를 전부 막아 둔 다음 인터럽트 컨트롤러에서 콘솔의 선을 +/// 켭니다. UART 쪽의 수신 인터럽트는 태스크가 입력을 처음 읽을 때 켜지므로, +/// 그때까지는 직렬 선에 무엇이 들어와도 커널에 인터럽트가 오지 않습니다. +/// +/// 어느 단계에서든 실패하면 입력만 없는 채로 부팅을 계속하고 까닭을 한 줄로 +/// 남깁니다. 인터럽트 번호는 디바이스 트리가 준 것이라 틀릴 수 있는데, 틀린 +/// 번호가 선을 붙드는 경우는 수신 로직이 실행 중에 그 선을 끕니다. +#[cfg(feature = "console-input")] +fn setup_console_input(con: &mut EarlyCon, irq: &k0_arch::irq::Irq, platform: &k0_boot::Platform) { + use k0_arch::irq::IrqError; + // 수신 로직이 건드리는 레지스터의 끝(인터럽트 지우기 레지스터 0x44의 뒤) + const RX_SPAN: u64 = 0x48; + let outcome = (|| { + let c = platform.console.as_ref().ok_or("no console")?; + let (name, has_cr) = match c.kind { + k0_boot::ConsoleKind::Pl011 => ("pl011", true), + k0_boot::ConsoleKind::SbsaUart => ("sbsa", false), + k0_boot::ConsoleKind::Ns16550 { .. } => return Err("no receive driver for this uart"), + }; + let intid = c.irq.ok_or("no usable interrupt in the device tree")?; + // 송신 드라이버보다 넓은 범위를 건드리므로, 그 범위가 선언된 구간과 + // 매핑해 둔 그래뉼 안에 있는지 따로 확인함 + let g = k0_mm::GRANULE as u64; + if c.base - c.reg.base + RX_SPAN > c.reg.size || c.base % g + RX_SPAN > g { + return Err("register frame too small"); + } + // SAFETY: 콘솔이 붙어 있을 때만 준비가 이루어지고(붙지 않았으면 false), + // 수신 로직이 쓰는 범위가 매핑된 그래뉼 안임을 위에서 확인함 + if !unsafe { k0_arch::conin::prepare(has_cr) } { + return Err("console not attached"); + } + // GICv3는 SPI마다 라우팅 레지스터가 있고, 그 자리는 초기화에 쓰는 첫 + // 페이지의 밖임. 선언된 디스트리뷰터 구간 안에 있을 때만 매핑함 + let router = match &platform.intc { + k0_boot::Intc::GicV3 { dist, .. } => { + let at = k0_arch::irq::gicv3::router_offset(intid); + if at + 8 > dist.size { + return Err("interrupt not available"); + } + Some(k0_mm::map_device(dist.base + at).map_err(|_| "interrupt not available")? as usize) + } + k0_boot::Intc::GicV2 { .. } => None, + }; + // SAFETY: setup_irq가 매핑한 디스트리뷰터는 커널이 사는 동안 그대로이고, + // 라우팅 레지스터는 방금 Device로 매핑함 + if let Err(e) = unsafe { k0_arch::irq::enable_console_irq(irq, intid, router) } { + k0_arch::conin::shut(); + return Err(match e { + IrqError::SpiOutOfRange => "interrupt number out of range", + _ => "interrupt not available", + }); + } + Ok((name, intid)) + })(); + match outcome { + Ok((name, intid)) => { + let _ = writeln!(con, "k0: console input on ({name} irq {intid})"); + } + Err(why) => { + let _ = writeln!(con, "k0: console input off ({why})"); + } + } +} + /// 콘솔 드라이버가 없는 빌드의 연결 함수입니다. /// /// 콘솔을 찾았더라도 장치 페이지를 매핑하지 않고 UART에 접근하지 않습니다. diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index 00fbf6e..40d6344 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -21,6 +21,11 @@ //! 기다리고, 틱마다 기한이 지난 IPC 대기자를 깨웁니다. 그래서 한 태스크가 //! 마지막으로 블록되는 것만으로는 나머지 태스크의 타임아웃이 멈추지 않습니다. //! +//! 커널을 `console-input`으로 빌드하면 콘솔 입력을 읽는 시스템 콜이 하나 +//! 더 있습니다(CONSOLE_READ). 입력을 기다리며 잠든 태스크는 바이트가 도착했을 +//! 때 깨어나고, 그 태스크만 남아 있는 동안 커널은 조용히 기다립니다(운영자의 +//! 입력을 기다리는 것은 정상 상태라서 줄을 찍지 않음). +//! //! # Errors //! 미지의 시스템 콜 번호와 EL0 폴트는 호출한 태스크만 종료시킵니다. //! 케이퍼빌리티 슬롯이나 사용자 페이지 테이블의 손상은 `k0_arch::fatal`로 @@ -103,6 +108,12 @@ extern "C" fn k0_syscall(ctx: &mut Context) { let switched = k0_ipc::sys_reply_recv(ctx); ipc_or_idle(ctx, switched) } + // 블록되면 반환 레지스터는 깨우는 쪽이 쓰므로 IPC와 같은 길을 탐 + #[cfg(feature = "console-input")] + nr::CONSOLE_READ => { + let switched = k0_ipc::console::sys_console_read(ctx); + ipc_or_idle(ctx, switched) + } other => { let _ = writeln!(con, "k0: unknown syscall {other}, killing task"); kill_current(); @@ -144,11 +155,27 @@ extern "C" fn k0_fault(ctx: &mut Context, esr: u64, far: u64) { extern "C" fn k0_preempt() { // SAFETY: 벡터가 사용자 컨텍스트 저장을 마친 EL0 IRQ/FIQ 컨텍스트임 unsafe { + // 틱이 장치를 들여다보다 가져온 입력이 있으면 기다리는 태스크를 깨움 + #[cfg(feature = "console-input")] + k0_ipc::console::wake(None); k0_ipc::expire_timeouts(k0_arch::irq::ticks(), None); k0_sched::rotate(); } } +/// 콘솔 입력이 도착했을 때의 정책 함수입니다. (k0-arch가 EL0 IRQ 경로에서 +/// 링크 계약으로 호출) +/// +/// 입력을 기다리는 태스크가 있으면 바이트를 전달하고 준비 큐의 끝에 넣습니다. +/// 실행 중이던 태스크는 그대로 이어서 실행됩니다(입력이 선점을 일으키지 않음). +#[cfg(feature = "console-input")] +#[unsafe(no_mangle)] +extern "C" fn k0_console_event() { + // SAFETY: 벡터가 사용자 컨텍스트 저장을 마친 EL0 IRQ 컨텍스트라 스케줄러 + // 접근이 배타적이고, 실행 중이던 태스크는 대기자가 아님 + unsafe { k0_ipc::console::wake(None) }; +} + /// 핸들러가 끝난 뒤의 공통 종료 경로 함수입니다. /// /// 이 시점에는 케이퍼빌리티 삭제에 따른 정리가 전부 끝나 있습니다(k0-cap이 @@ -209,8 +236,9 @@ fn ipc_or_idle(ctx: &mut Context, switched: bool) -> Option { /// 세우지 않고 다음 인터럽트까지 재웠다가, 틱이 지나면 기한이 지난 IPC /// 대기자를 깨우고 준비된 태스크로 전환합니다. 깨어나는 태스크는 블록된 채 /// 기다리던 현재 태스크 자신일 수도 있습니다. 지금 태스크를 깨울 수 있는 -/// 것은 타임아웃뿐이라서, 기한을 건 대기자가 하나도 없으면 이 함수는 -/// 돌아오지 않습니다(틱은 계속 처리함). +/// 것은 타임아웃과 (입력 경로가 있는 이미지에서는) 콘솔 입력뿐이라서, 기한을 +/// 건 대기자도 입력을 기다리는 태스크도 없으면 이 함수는 돌아오지 +/// 않습니다(틱은 계속 처리함). /// /// # Arguments /// `ctx` - 이번 진입을 일으킨 태스크(스케줄러의 현재 태스크)의 컨텍스트 @@ -227,6 +255,9 @@ fn idle_until_ready(ctx: &mut Context) { if !WAITING.swap(true, Ordering::Relaxed) { let _ = writeln!(con, "k0: idle (waiting for a timeout)"); } + } else if console_waiting() { + // 운영자의 입력을 기다리는 것은 정상 상태임. 줄을 찍으면 프롬프트 + // 뒤에 끼어들므로 아무것도 찍지 않음 } else if !STOPPED.swap(true, Ordering::Relaxed) { let _ = writeln!(con, "k0: all tasks stopped (none ready, no timeout pending)"); } @@ -236,6 +267,10 @@ fn idle_until_ready(ctx: &mut Context) { // 반환값은 이 참조로만 기록됨 unsafe { k0_arch::irq::wait_for_interrupt(); + // 방금의 인터럽트가 입력을 가져왔으면 기다리는 태스크를 깨움. + // 대기자가 블록된 현재 태스크 자신일 수 있어 ctx를 넘김 + #[cfg(feature = "console-input")] + k0_ipc::console::wake(Some(&mut *ctx)); k0_ipc::expire_timeouts(k0_arch::irq::ticks(), Some(&mut *ctx)); if k0_sched::block_and_switch() { return; @@ -244,6 +279,15 @@ fn idle_until_ready(ctx: &mut Context) { } } +/// 콘솔 입력을 기다리는 태스크가 있는지 알려 주는 함수입니다. 입력 경로가 없는 +/// 이미지에서는 언제나 false입니다. +fn console_waiting() -> bool { + #[cfg(feature = "console-input")] + return k0_ipc::console::waiting(); + #[cfg(not(feature = "console-input"))] + false +} + /// 오브젝트의 PA를 커널 별칭 주소로 바꾸는 함수입니다. fn kva(pa: u64) -> u64 { pa + k0_mm::KERNEL_VA_OFFSET @@ -311,9 +355,15 @@ fn done(r: Result<(), i64>) -> i64 { /// DEBUG_PUTC 시스템 콜 처리 함수입니다. /// -/// Console 케이퍼빌리티 제시가 필요합니다(암묵 권한 없음). 출력 가능한 -/// ASCII와 개행만 그대로 내보내고 나머지 바이트는 `?`로 바꿔 터미널 제어 -/// 문자 주입을 막습니다. +/// 쓰기 권한(W)이 있는 Console 케이퍼빌리티 제시가 필요합니다(암묵 권한 +/// 없음). 출력 가능한 ASCII와 개행만 그대로 내보내고 나머지 바이트는 `?`로 +/// 바꿔 터미널 제어 문자 주입을 막습니다. +/// +/// 입력 경로가 있는 이미지에서, 읽기 권한(R)도 있는 케이퍼빌리티로 부르면 +/// 백스페이스(0x08) 하나만 더 통과시킵니다. 운영자가 입력한 글자를 화면에서 +/// 지우는 데 필요하고, 그 권한은 터미널 태스크만 받습니다. 백스페이스는 같은 +/// 줄 안에서만 커서를 되돌리므로 이미 끝난 줄(커널의 줄 포함)은 건드리지 +/// 못합니다. /// /// # Arguments /// `slot` - Console 슬롯(x0) @@ -322,11 +372,15 @@ fn sys_putc(slot: u64, byte: u64) -> i64 { done((|| { let cn = cspace()?; let (_, e) = lookup(&cn, slot)?; - if e.cap != Cap::Console { + let Cap::Console { rights } = e.cap else { return Err(err::BAD_CAP); + }; + if rights & k0_cap::rights::W == 0 { + return Err(err::NO_RIGHTS); } let b = byte as u8; - let safe = if b == b'\n' || (0x20..=0x7E).contains(&b) { b } else { b'?' }; + let erase = cfg!(feature = "console-input") && b == 0x08 && rights & k0_cap::rights::R != 0; + let safe = if b == b'\n' || (0x20..=0x7E).contains(&b) || erase { b } else { b'?' }; EarlyCon.put_user_byte(safe); Ok(()) })()) @@ -586,7 +640,10 @@ fn sys_cap_move(src: u64, cnode: u64, index: u64) -> i64 { let (s, _) = lookup(&cn, src)?; let d = dest_slot(&cn, cnode, index)?; // SAFETY: 두 슬롯은 살아 있는 CNode의 범위 안 슬롯이고 접근이 배타적임 - unsafe { k0_cap::move_cap(s, d) }.map_err(cap_err) + let r = unsafe { k0_cap::move_cap(s, d) }.map_err(cap_err); + // 대기자가 쥔 Console이 다른 슬롯으로 옮겨졌으면 그 대기자를 바로 깨움 + console_recheck(); + r })()) } @@ -605,10 +662,28 @@ fn sys_cap_delete(slot: u64) -> i64 { let (s, _) = lookup(&cn, slot)?; // SAFETY: s는 살아 있는 슬롯이고, 파생 리스트로 이어진 슬롯은 전부 // 살아 있는 CNode / TCB 안에 있으며 접근이 배타적임 - unsafe { k0_cap::delete(s, &mut Reaper) }.map_err(cap_err) + let r = unsafe { k0_cap::delete(s, &mut Reaper) }.map_err(cap_err); + console_recheck(); + r })()) } +/// 케이퍼빌리티가 지워진 뒤, 콘솔 입력을 기다리던 태스크가 그 권한을 잃었으면 +/// 바로 깨우는 함수입니다. 입력 경로가 없는 이미지에서는 아무 일도 하지 +/// 않습니다. +/// +/// 삭제와 회수가 끝난 뒤에 부릅니다(슬롯이 바뀌는 도중의 콜백 안에서는 부르지 +/// 않음). 권한이 그대로면 대기자는 계속 기다립니다. 바이트가 이미 와 있었다면 +/// 여기서 전달될 수도 있습니다. +fn console_recheck() { + // SAFETY: 시스템 콜 컨텍스트라 스케줄러 접근이 배타적이고, 시스템 콜을 + // 부른 실행 중인 태스크는 대기자가 아님 + #[cfg(feature = "console-input")] + unsafe { + k0_ipc::console::wake(None) + }; +} + /// CAP_REVOKE 시스템 콜 처리 함수입니다. /// /// 슬롯에서 파생된 케이퍼빌리티를 전부 지우고 슬롯 자신은 남깁니다. @@ -622,7 +697,9 @@ fn sys_cap_revoke(slot: u64) -> i64 { let cn = cspace()?; let (s, _) = lookup(&cn, slot)?; // SAFETY: sys_cap_delete와 동일 - unsafe { k0_cap::revoke(s, &mut Reaper) }.map_err(cap_err) + let r = unsafe { k0_cap::revoke(s, &mut Reaper) }.map_err(cap_err); + console_recheck(); + r })()) } diff --git a/tools/boot-matrix.sh b/tools/boot-matrix.sh index d23e4ef..2dab174 100755 --- a/tools/boot-matrix.sh +++ b/tools/boot-matrix.sh @@ -42,8 +42,23 @@ cargo build -p k0-kernel --offline --features console,vault --target-dir target/ imgvault="$root/target/vault/aarch64-unknown-none-softfloat/debug/k0-kernel" imgvault16="$root/target/vault16/aarch64-unknown-none-softfloat/debug/k0-kernel" imgvaultna="$root/target/vaultna/aarch64-unknown-none-softfloat/debug/k0-kernel" +# 콘솔 입력과 운영자 터미널을 넣은 이미지들: 터미널과 볼트(4K, 16K), 터미널만, +# 터미널과 알고리즘 없는 볼트, 입력 경로만, 수신 드라이버가 없는 16550과 입력 +cargo build -p k0-kernel --offline --features console,terminal,vault-ed25519 --target-dir target/term || exit 2 +cargo build -p k0-kernel --offline --no-default-features --features granule-16k,console,terminal,vault-ed25519 --target-dir target/term16 || exit 2 +cargo build -p k0-kernel --offline --features console,terminal --target-dir target/termnv || exit 2 +cargo build -p k0-kernel --offline --features console,terminal,vault --target-dir target/termna || exit 2 +cargo build -p k0-kernel --offline --features console,console-input --target-dir target/input || exit 2 +cargo build -p k0-kernel --offline --features console-16550,console-input --target-dir target/input16550 || exit 2 +imgterm="$root/target/term/aarch64-unknown-none-softfloat/debug/k0-kernel" +imgterm16="$root/target/term16/aarch64-unknown-none-softfloat/debug/k0-kernel" +imgtermnv="$root/target/termnv/aarch64-unknown-none-softfloat/debug/k0-kernel" +imgtermna="$root/target/termna/aarch64-unknown-none-softfloat/debug/k0-kernel" +imginput="$root/target/input/aarch64-unknown-none-softfloat/debug/k0-kernel" +imginput16550="$root/target/input16550/aarch64-unknown-none-softfloat/debug/k0-kernel" # UEFI 로더: 위에서 빌드한 바로 그 커널을 내장함 efi4="$(tools/build-loader.sh "$img4")" || exit 2 +efiterm="$(tools/build-loader.sh "$imgterm")" || exit 2 efi16="$(tools/build-loader.sh "$img16")" || exit 2 failed="" @@ -80,6 +95,22 @@ pass() { fi } +# 터미널 행: 이름, 이미지, 그 뒤는 환경 변수 대입들. 이미지를 부팅해 직렬 +# 포트로 명령을 넣고 답을 대조함(tools/term-test.py). 부팅 구간의 줄들은 그 +# 스크립트가 부팅 시험의 판정 전용 모드로 넘겨 같은 규칙으로 봄 +term() { + name="$1"; elf="$2"; shift 2 + want "$name" $only || return 0 + ran=$((ran + 1)) + if env "$@" K0_TERM_LOG="$root/target/matrix-$name.log" tools/term-test.py "$elf" > "target/matrix-$name.out" 2>&1; then + echo "matrix: $name pass" + else + echo "matrix: $name FAIL" + show "target/matrix-$name.out" + failed="$failed $name" + fi +} + # 거부 행: 이름, ELF, 적재 물리 주소, 로그에 있어야 할 사유, 그 뒤는 환경 변수 대입들 # 사유가 로그에 나타날 때까지 1초 간격으로 읽습니다(느린 호스트에서도 기다림). refuse() { @@ -168,6 +199,29 @@ fi # 볼트의 코드가 feature대로만 들어가는지, 그리고 쓰기 가능한 static을 쓰지 # 않는지 루트 태스크의 ELF에서 확인합니다. 격리 태스크의 주소 공간에는 이미지의 # .data와 .bss가 없어서, 볼트나 암호 구현이 static에 쓰면 그 태스크가 죽습니다. +# 콘솔 입력과 터미널은 고른 이미지에만 들어 있어야 함. 커널의 수신 코드는 +# 심볼로, 줄과 터미널(커널 ELF에 바이트로 든 루트 태스크 이미지)은 글자열로 봄 +if want input-symbols $only; then + ran=$((ran + 1)) + host="$(rustc -vV | sed -n 's/^host: //p')" + nm="$(rustc --print sysroot)/lib/rustlib/${host}/bin/llvm-nm" + bad="" + for spec in "$img4:0:0" "$imgquiet:0:0" "$imgvault:0:0" "$imginput:1:0" "$imginput16550:1:0" "$imgterm:1:1" "$imgtermnv:1:1"; do + elf="${spec%%:*}"; rest="${spec#*:}"; want_in="${rest%%:*}"; want_term="${rest#*:}" + s="$("$nm" -C "$elf" 2>&1)" || { bad="$bad llvm-nm-failed"; continue; } + code=0; printf '%s\n' "$s" | grep -Eq 'k0_conin::|k0_arch::conin::|k0_ipc::console::|k0_console_event' && code=1 + line=0; grep -aq 'k0: tick lines off' "$elf" && line=1 + shell=0; grep -aq 'K0 operator console' "$elf" && shell=1 + [ "$code$line$shell" = "$want_in$want_in$want_term" ] || bad="$bad ${elf#"$root"/target/}=$code$line$shell" + done + if [ -z "$bad" ]; then + echo "matrix: input-symbols pass" + else + echo "matrix: input-symbols FAIL (${bad# })" + failed="$failed input-symbols" + fi +fi + if want vault-symbols $only; then ran=$((ran + 1)) host="$(rustc -vV | sed -n 's/^host: //p')" @@ -243,6 +297,49 @@ pass vault-max "$imgvault" K0_QEMU_CPU=max K0_BOOT_FAULTS=8 K0_BOOT_REQUIR pass vault-el2 "$imgvault" K0_QEMU_MACHINE=virt,gic-version=3,virtualization=on K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE="root: oracle tests pass" pass vault-16k "$imgvault16" K0_QEMU_CPU=max K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE="root: oracle tests pass" pass vault-no-alg "$imgvaultna" K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE="root: oracle tests pass" + +# 콘솔 입력: 입력 경로만 든 이미지는 루트 태스크의 입력 자가 검증까지 보고, +# 수신 드라이버가 없는 16550만 든 이미지는 입력이 꺼졌다는 줄을 봄(QEMU의 +# 콘솔은 PL011이라 이 이미지는 직렬 포트에 아무것도 쓰지 않음) +pass input-only "$imginput" K0_BOOT_INPUT=on K0_BOOT_REQUIRE="k0: console input on (pl011 irq 33)|,irq33 " +pass input-gicv2 "$imginput" K0_BOOT_INPUT=on K0_QEMU_MACHINE=virt,gic-version=2 K0_BOOT_REQUIRE="k0: console input on (pl011 irq 33)" +pass input-16550 "$imginput16550" K0_BOOT_INPUT=off K0_BOOT_MEMLOG=0x40080000 K0_BOOT_SERIAL=empty K0_BOOT_CONSOLE_PAGE=unmapped K0_BOOT_REQUIRE="k0: console input off (console not attached)|root: console input tests pass (no input path)" +# 디바이스 트리가 콘솔의 인터럽트로 이 컨트롤러에 없는 번호를 대는 경우: 그 +# 번호는 플랫폼 줄에 그대로 찍히고, 커널은 입력만 포기한 채 끝까지 부팅함 +if want input-bad-irq $only; then + bdt="$root/target/matrix-input-bad-irq.dtb" + if qemu-system-aarch64 -machine "virt,gic-version=3,dumpdtb=$bdt.orig" -cpu cortex-a72 -m 512M -smp 1 -nographic > target/matrix-input-bad-irq.dump 2>&1 < /dev/null \ + && python3 - "$bdt.orig" "$bdt" >> target/matrix-input-bad-irq.dump 2>&1 <<'SWAP' +import struct, sys +data = bytearray(open(sys.argv[1], "rb").read()) +old = struct.pack(">III", 0, 1, 4) # pl011의 interrupts: SPI 1번, 레벨 +new = struct.pack(">III", 0, 900, 4) # INTID 932, QEMU의 GIC가 구현하지 않은 번호 +if data.count(old) != 1: + sys.exit(f"expected exactly one <0 1 4> in the device tree, found {data.count(old)}") +at = data.index(old) +data[at:at + 12] = new +_, _, off_struct, off_strings, _, _, _, _, size_strings, size_struct = struct.unpack(">10I", data[:40]) +used = (max(off_struct + size_struct, off_strings + size_strings) + 7) & ~7 +data[4:8] = struct.pack(">I", used) +open(sys.argv[2], "wb").write(data[:used]) +SWAP + then + pass input-bad-irq "$imginput" K0_QEMU_EXTRA="-dtb $bdt" K0_BOOT_INPUT=off K0_BOOT_REQUIRE=",irq932 |k0: console input off (interrupt number out of range)|root: console input tests pass (no input path)" + else + ran=$((ran + 1)) + echo "matrix: input-bad-irq FAIL (could not prepare the device tree)" + show target/matrix-input-bad-irq.dump + failed="$failed input-bad-irq" + fi +fi +# 운영자 터미널: 자가 검증 뒤에 서비스가 뜨고, 직렬 포트로 넣은 명령에 답함 +term term "$imgterm" +term term-max "$imgterm" K0_QEMU_CPU=max K0_TERM_SEED=rng-seed+rndr +term term-el2 "$imgterm" K0_QEMU_MACHINE=virt,gic-version=3,virtualization=on +term term-gicv2 "$imgterm" K0_QEMU_MACHINE=virt,gic-version=2 +term term-16k "$imgterm16" K0_QEMU_CPU=max K0_TERM_SEED=rng-seed+rndr +term term-no-vault "$imgtermnv" K0_TERM_VAULT=absent +term term-no-alg "$imgtermna" K0_TERM_VAULT=none pass gic3-el1-max "$img4" K0_QEMU_CPU=max K0_BOOT_REQUIRE="rndr=on|k0: pac=on bti=present pan=on" pass gic3-el2 "$img4" K0_QEMU_MACHINE=virt,gic-version=3,virtualization=on pass gic3-el2-max "$img4" K0_QEMU_MACHINE=virt,gic-version=3,virtualization=on K0_QEMU_CPU=max @@ -380,6 +477,10 @@ pass uefi-acpi-smp4 "$efi4" K0_BOOT_REUSE=skip K0_QEMU_MACHINE=virt,gic-vers pass uefi-acpi-16k "$efi16" K0_BOOT_REUSE=skip K0_QEMU_MACHINE=virt,gic-version=3 K0_QEMU_CPU=max K0_BOOT_REQUIRE="$acpi" # ACPI에는 펌웨어의 씨앗이 없으므로 엔트로피는 펌웨어 난수 프로토콜의 32바이트뿐 pass uefi-acpi-rng "$efi4" K0_BOOT_REUSE=skip K0_QEMU_MACHINE=virt,gic-version=3 K0_QEMU_EXTRA="-device virtio-rng-pci" K0_BOOT_REQUIRE="$acpi|k0: entropy dtb=32B" +# 운영자 터미널을 UEFI로: 펌웨어가 쓰던 UART를 넘겨받아 입력을 받음. 디바이스 +# 트리 경로와, 콘솔 인터럽트를 SPCR에서 읽는 ACPI 경로(씨앗은 펌웨어 난수에서) +term term-uefi "$efiterm" K0_BOOT_REUSE=skip +term term-uefi-acpi "$efiterm" K0_BOOT_REUSE=skip K0_QEMU_MACHINE=virt,gic-version=3 K0_QEMU_EXTRA="-device virtio-rng-pci" K0_BOOT_REQUIRE="$acpi|,irq33 |k0: console input on (pl011 irq 33)" # 그래뉼이 없는 CPU는 로더가 거부 refuse_serial uefi-16k-on-a72 "$efi16" "this cpu has no 16K translation granule" # 내장한 커널 이미지의 한 바이트가 바뀐 로더는 해시 불일치로 거부 @@ -403,6 +504,7 @@ if [ "${K0_MATRIX_HVF:-0}" = 1 ]; then pass uefi-hvf-acpi "$efi4" K0_BOOT_REUSE=skip K0_QEMU_ACCEL=hvf K0_QEMU_CPU=host K0_QEMU_MACHINE=virt,gic-version=3 K0_BOOT_REQUIRE="$acpi" pass hvf-el1 "$img4" K0_QEMU_ACCEL=hvf K0_QEMU_CPU=host pass hvf-vault "$imgvault" K0_QEMU_ACCEL=hvf K0_QEMU_CPU=host K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE="root: oracle tests pass" + term hvf-term "$imgterm" K0_QEMU_ACCEL=hvf K0_QEMU_CPU=host pass hvf-el2 "$img4" K0_QEMU_ACCEL=hvf K0_QEMU_CPU=host K0_QEMU_MACHINE=virt,gic-version=3,virtualization=on pass hvf-16k "$img16" K0_QEMU_ACCEL=hvf K0_QEMU_CPU=host pass hvf-quiet "$imgquiet" K0_QEMU_ACCEL=hvf K0_QEMU_CPU=host K0_BOOT_MEMLOG=0x40080000 K0_BOOT_SERIAL=empty K0_BOOT_CONSOLE_PAGE=unmapped K0_BOOT_REQUIRE="$quietreq" diff --git a/tools/host-test.sh b/tools/host-test.sh index 12590b0..a629490 100755 --- a/tools/host-test.sh +++ b/tools/host-test.sh @@ -6,10 +6,13 @@ cd "$root" host="$(rustc -vV | sed -n 's/^host: //p')" -cargo test --offline --target "$host" -p k0-abi -p k0-cap -p k0-boot -p k0-efi "$@" +cargo test --offline --target "$host" -p k0-abi -p k0-cap -p k0-boot -p k0-efi -p k0-conin "$@" # 키 볼트: 알고리즘을 넣은 것과 뺀 것을 따로 돌림(feature가 다르면 다른 코드) cargo test --offline --target "$host" -p k0-vault --features ed25519 "$@" cargo test --offline --target "$host" -p k0-vault "$@" +# 운영자 터미널: 볼트 프로토콜을 아는 것과 모르는 것 +cargo test --offline --target "$host" -p k0-term --features vault "$@" +cargo test --offline --target "$host" -p k0-term "$@" case "$(uname -m)" in arm64|aarch64) diff --git a/tools/qemu-boot-test.sh b/tools/qemu-boot-test.sh index 7e6a526..c3fb6f5 100755 --- a/tools/qemu-boot-test.sh +++ b/tools/qemu-boot-test.sh @@ -27,10 +27,20 @@ log="${K0_BOOT_LOG:-$root/target/qemu-boot-test.log}" memlog="${K0_BOOT_MEMLOG:-}" serial_rule="${K0_BOOT_SERIAL:-}" page_rule="${K0_BOOT_CONSOLE_PAGE:-}" +# 콘솔 입력이 든 이미지의 판정. on이면 입력 경로가 켜진 줄과 입력 자가 검증의 +# 줄을 요구하고, off면 입력 경로가 없다는 줄을 요구함(수신 드라이버가 없는 +# UART나 인터럽트를 못 쓰는 기계). 비어 있으면 입력이 없는 이미지로 봄 +input_rule="${K0_BOOT_INPUT:-}" +# 터미널이 든 이미지의 판정. vault면 볼트와 터미널, plain이면 터미널만 서비스로 +# 시작한 줄들을 요구함 +service_rule="${K0_BOOT_SERVICE:-}" +# 판정 전용: 값이 있으면 QEMU를 띄우지 않고 그 파일을 직렬 로그로 보고 줄들만 +# 대조함. tools/term-test.py가 자기가 띄운 QEMU의 부팅 구간을 넘길 때 씀 +judge="${K0_BOOT_JUDGE:-}" # 커널이 로그에 남기는 틱 줄의 수(crates/k0-arch/src/irq.rs의 LOGGED_TICKS) logged_ticks=4 -if [ ! -f "$elf" ]; then +if [ -z "$judge" ] && [ ! -f "$elf" ]; then echo "boot-test: kernel ELF not found: $elf" >&2 echo "boot-test: build it first with: cargo build -p k0-kernel --features console --offline" >&2 exit 2 @@ -55,7 +65,11 @@ case "$memlog:$elf" in esac mkdir -p "$(dirname "$log")" -: > "$log" +if [ -z "$judge" ]; then + : > "$log" +elif [ "$judge" != "$log" ]; then + cp "$judge" "$log" +fi # 메모리에서 읽을 때는 직렬 포트의 출력을 따로 받아 둡니다. QEMU 자신의 경고는 # 표준 오류로 나오므로 직렬 포트의 바이트와 섞이지 않게 나눕니다. @@ -65,7 +79,10 @@ cleanup() { [ -z "$sock" ] || rm -f "$sock" "$log.new" [ -z "$sockdir" ] || rmdir "$sockdir" 2>/dev/null || true } -if [ -n "$memlog" ]; then +if [ -n "$judge" ]; then + serial="$log" + pid="" +elif [ -n "$memlog" ]; then serial="$log.serial" : > "$log.reader" # 모니터 소켓은 이 실행만 쓰는 디렉토리에 둠. 유닉스 소켓 경로는 길이 제한이 @@ -77,8 +94,8 @@ else serial="$log" "$root/tools/qemu-virt-runner.sh" "$elf" "$@" > "$log" 2>&1 < /dev/null & fi -pid=$! -trap 'kill "$pid" 2>/dev/null || true; cleanup' EXIT INT TERM +[ -n "$judge" ] || pid=$! +trap '[ -z "$pid" ] || kill "$pid" 2>/dev/null || true; cleanup' EXIT INT TERM fail_re='root: FAIL|k0: EXCEPTION|k0: PANIC|k0: FATAL|k0: UNEXPECTED|rejected|failed|check fail|k0: all tasks|corrupt|overflow|no frame window|too many root task segments|k0-loader: refused' @@ -95,6 +112,10 @@ elapsed=0 state=timeout pass_ticks="" while [ "$elapsed" -lt "$timeout_s" ]; do + if [ -n "$judge" ]; then + if judged | grep -Eq "$fail_re"; then state=failure; else state=done; fi + break + fi if [ -n "$memlog" ]; then # 읽기에 성공한 마지막 기록만 남김(모니터가 아직 안 떴거나 로그가 비어 있으면 실패함) if "$root/tools/boot-log.py" "$elf" "$memlog" "$sock" > "$log.new" 2> "$log.reader"; then @@ -123,6 +144,11 @@ while [ "$elapsed" -lt "$timeout_s" ]; do elif sed -n '/^root: sched tests pass/,$p' "$log" | grep -q '^k0: tick '; then state=done break + elif grep -q '^root: sched tests pass' "$log" && grep -q '^k0: tick lines off ' "$log"; then + # 태스크가 콘솔 입력을 쓰기 시작한 이미지는 틱 줄을 더 내지 않음. 그 + # 줄이 나온 뒤에 자가 검증의 마지막 줄까지 왔다는 것이 살아 있다는 증거임 + state=done + break fi if ! kill -0 "$pid" 2>/dev/null; then state=exited @@ -132,7 +158,7 @@ while [ "$elapsed" -lt "$timeout_s" ]; do elapsed=$(($(date +%s) - started)) done -kill "$pid" 2>/dev/null || true +[ -z "$pid" ] || kill "$pid" 2>/dev/null || true wait "$pid" 2>/dev/null || true trap - EXIT INT TERM cleanup @@ -154,6 +180,36 @@ markers="k0: entry phase 1 (pre-MMU)|k0: dtb = |k0: mmu on (identity + fixed ima if [ -n "$memlog" ]; then markers="${markers%|k0: tick }" fi +# 콘솔 입력이 든 이미지: 입력 경로의 줄과 입력 자가 검증의 줄을 순서에 끼워 +# 넣음. 입력을 처음 읽는 순간 커널이 틱 줄을 멈추므로 끝의 틱은 요구하지 않음 +case "$input_rule" in +on) + markers="$(printf '%s' "$markers" | sed -e 's/|k0: irq on (timer 1s)|/|k0: irq on (timer 1s)|k0: console input on (|/' \ + -e 's/|root: sched tests pass/|root: backspace without the input right [?]|k0: tick lines off (console input in use)|root: console input tests pass|root: sched tests pass/')" + markers="${markers%|k0: tick }" + ;; +off) + markers="$(printf '%s' "$markers" | sed -e 's/|k0: irq on (timer 1s)|/|k0: irq on (timer 1s)|k0: console input off (|/' \ + -e 's/|root: sched tests pass/|root: backspace without the input right [?]|root: console input tests pass (no input path)|root: sched tests pass/')" + ;; +"") ;; +*) + echo "boot-test: K0_BOOT_INPUT must be on or off" >&2 + exit 2 + ;; +esac +# 터미널이 든 이미지: 자가 검증 뒤에 서비스가 시작되는 줄들. 터미널과 똑같이 +# 배선한 적대적 태스크 둘이 폴트로 끝나야 함 +case "$service_rule" in +vault) markers="$markers|root: vault |root: terminal console filter [?|root: terminal wiring holds|k0: task fault dabort-lower|k0: task fault dabort-lower|root: service started" ;; +plain) markers="$markers|root: terminal console filter [?|root: terminal wiring holds|k0: task fault dabort-lower|k0: task fault dabort-lower|root: service started" ;; +none) markers="$markers|root: no console input, terminal not started" ;; +"") ;; +*) + echo "boot-test: K0_BOOT_SERVICE must be vault, plain or none" >&2 + exit 2 + ;; +esac missing="$(tr -d '\r' < "$log" | sed "$reuse_sed" | awk -v markers="$markers" ' BEGIN { diff --git a/tools/term-test.py b/tools/term-test.py new file mode 100755 index 0000000..ac1a87f --- /dev/null +++ b/tools/term-test.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python3 +"""운영자 터미널 시험: 이미지를 QEMU로 부팅해 직렬 포트로 명령을 넣고 답을 대조합니다. + +사용법: tools/term-test.py <이미지> [--vault ed25519|none|absent] [--seed rng-seed|rng-seed+rndr] + + --vault ed25519 볼트와 Ed25519가 든 이미지(기본) + --vault none 볼트는 있고 알고리즘이 없는 이미지 + --vault absent 볼트가 없는 이미지 + --seed `vault status`의 seed 줄에 기대하는 값(기본 rng-seed) + +환경 변수 + K0_TERM_VAULT --vault의 기본값 + K0_TERM_SEED --seed의 기본값 + K0_TERM_LOG 직렬 출력 기록 파일(기본 target/term-test.log) + K0_TERM_TIMEOUT 프롬프트가 뜰 때까지 기다리는 초(기본 120) + K0_QEMU_* tools/qemu-virt-runner.sh가 읽는 머신 구성 + K0_BOOT_* 부팅 구간의 판정에 그대로 전달(tools/qemu-boot-test.sh). + K0_BOOT_INPUT, K0_BOOT_SERVICE, K0_BOOT_FAULTS는 이 스크립트가 + 이미지의 종류에 맞게 정함 + +직렬 포트는 QEMU의 표준 입출력에 파이프로 붙입니다. 모니터를 유닉스 소켓으로 +따로 빼야 표준 입출력이 직렬 전용이 되어 입력 바이트가 그대로 전달됩니다. +부팅 구간(프롬프트 전)의 판정은 tools/qemu-boot-test.sh의 판정 전용 모드에 +맡기고, 이 스크립트는 그 뒤의 대화만 봅니다. 표준 라이브러리만 씁니다. +""" +import os +import re +import shutil +import socket +import subprocess +import sys +import tempfile +import threading +import time + +PROMPT = b"k0> " +BANNER = b"K0 operator console, type 'help'\n" +# 누구나 아는 시드의 공개키. 서비스의 키가 이 값이면 진짜 부트 시드가 볼트에 +# 닿지 않은 것임(RFC 8032 첫 시험 벡터, 그리고 전부 0인 시드) +KNOWN_KEYS = ( + b"d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", + b"3b6a27bcceb6a42d62a3a8d02a6f0d73653215771de243a63ac048a18b59da29", +) +FAIL_RE = re.compile(rb"root: FAIL|k0: EXCEPTION|k0: PANIC|k0: FATAL|k0: UNEXPECTED|k0: task fault|k0: all tasks|k0: tick ") + + +class Failure(Exception): + pass + + +class Session: + """QEMU 하나와 그 직렬 포트를 쥐는 객체입니다.""" + + def __init__(self, root, image, log_path, boot_timeout): + self.root = root + self.log_path = log_path + self.boot_timeout = boot_timeout + self.buf = bytearray() + self.pos = 0 + self.lock = threading.Condition() + self.tmp = tempfile.mkdtemp(prefix="k0-term.", dir="/tmp") + self.sock = os.path.join(self.tmp, "monitor") + env = dict(os.environ, K0_QEMU_MONITOR=self.sock) + self.err = open(log_path + ".qemu", "wb") + self.proc = subprocess.Popen( + [os.path.join(root, "tools/qemu-virt-runner.sh"), image], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=self.err, + env=env, + cwd=root, + ) + self.reader = threading.Thread(target=self._read, daemon=True) + self.reader.start() + + def _read(self): + with open(self.log_path, "wb") as log: + while True: + data = os.read(self.proc.stdout.fileno(), 65536) + if not data: + break + log.write(data) + log.flush() + # 커널은 콘솔에서 줄바꿈을 CR LF로 내보냄 + data = data.replace(b"\r", b"") + with self.lock: + self.buf += data + self.lock.notify_all() + + def close(self): + try: + s = socket.socket(socket.AF_UNIX) + s.settimeout(2) + s.connect(self.sock) + s.sendall(b"quit\n") + s.close() + except OSError: + pass + try: + self.proc.wait(timeout=5) + except subprocess.TimeoutExpired: + self.proc.kill() + self.err.close() + shutil.rmtree(self.tmp, ignore_errors=True) + + def monitor(self, command): + s = socket.socket(socket.AF_UNIX) + s.settimeout(2) + s.connect(self.sock) + s.sendall(command.encode() + b"\n") + time.sleep(0.3) + s.close() + + def send(self, data): + self.proc.stdin.write(data) + self.proc.stdin.flush() + + def tail(self): + with self.lock: + return bytes(self.buf[max(self.pos - 200, 0):][-600:]).decode(errors="replace") + + def expect(self, want, timeout=20, what=None): + """아직 읽지 않은 출력이 정확히 `want`로 시작할 때까지 기다립니다.""" + deadline = time.time() + timeout + with self.lock: + while True: + have = bytes(self.buf[self.pos:self.pos + len(want)]) + if have == want: + self.pos += len(want) + return + if not want.startswith(have): + raise Failure("%s: expected %r, got %r" % (what or "output", want, bytes(self.buf[self.pos:self.pos + len(want) + 80]))) + left = deadline - time.time() + if left <= 0 or self.proc.poll() is not None: + raise Failure("%s: timed out waiting for %r, got %r" % (what or "output", want, have)) + self.lock.wait(min(left, 1)) + + def wait_for(self, marker, timeout): + """`marker`가 나올 때까지 기다리고 그 앞까지의 출력을 돌려줍니다.""" + deadline = time.time() + timeout + with self.lock: + while True: + at = self.buf.find(marker, self.pos) + if at >= 0: + before = bytes(self.buf[self.pos:at]) + self.pos = at + len(marker) + return before + left = deadline - time.time() + if left <= 0 or self.proc.poll() is not None: + raise Failure("timed out waiting for %r, last output %r" % (marker, bytes(self.buf[-300:]))) + self.lock.wait(min(left, 1)) + + def run(self, line, reply, typed=None, echo=None, timeout=20): + """한 줄을 입력하고, 되돌아온 글자와 답과 다음 프롬프트를 대조합니다.""" + keys = line.encode() + b"\r" if typed is None else typed + self.send(keys) + shown = (line.encode() if echo is None else echo) + b"\n" + self.expect(shown + reply.encode() + PROMPT, timeout, what=repr(line)) + + +def boot_judge(root, image, log_path, boot, vault): + """프롬프트 전의 출력을 부팅 시험의 판정 전용 모드로 넘깁니다.""" + path = log_path + ".boot" + with open(path, "wb") as f: + f.write(boot) + # 터미널과 똑같이 배선한 적대적 태스크 둘이 폴트로 끝나므로 폴트가 둘 더 있음 + faults = 8 if vault == "absent" else 10 + env = dict( + os.environ, + K0_BOOT_JUDGE=path, + K0_BOOT_LOG=path, + K0_BOOT_INPUT="on", + K0_BOOT_SERVICE="plain" if vault == "absent" else "vault", + K0_BOOT_FAULTS=str(faults), + ) + r = subprocess.run([os.path.join(root, "tools/qemu-boot-test.sh"), image], env=env, cwd=root, capture_output=True) + if r.returncode != 0: + raise Failure("boot part: " + (r.stdout + r.stderr).decode(errors="replace").strip()) + + +def wiring(boot, vault): + """터미널과 똑같이 배선한 적대적 태스크가 남긴 줄을 바이트까지 대조합니다.""" + # 여섯 바이트(ESC, BS, CR, NUL, DEL, 0x9B) 가운데 백스페이스만 그대로 나감 + if b"root: terminal console filter [?\x08????]\n" not in boot: + raise Failure("the output filter let something other than backspace through") + tail = boot[boot.index(b"root: terminal wiring holds\n"):] + fars = re.findall(rb"k0: task fault dabort-lower \(esr 0x[0-9a-f]+ elr 0x[0-9a-f]+ far 0x([0-9a-f]+)\)", tail) + secret = re.search(rb"root: secret at 0x([0-9a-f]+)", boot) + if len(fars) != 2 or secret is None: + raise Failure("expected two faults after the wiring line, found %r" % fars) + # 첫 폴트는 읽기 전용 응답 프레임에 쓴 것, 둘째는 루트의 데이터를 읽은 것 + if vault != "absent" and int(fars[0], 16) != 0x5C0000: + raise Failure("the first hostile fault is not the write to the response frame: %r" % fars[0]) + if int(fars[1], 16) != int(secret.group(1), 16): + raise Failure("the second hostile fault is not the read of root data: %r" % fars[1]) + + +def session(s, vault, seed): + full_help = ( + "help\nvault status\nvault pubkey\nvault keygen alg: %s\nvault zeroize confirm\nok\n" + % ("ed25519" if vault == "ed25519" else "none") + ) + if vault == "absent": + s.run("help", "help\nok\n") + s.run("vault status", "err no-vault\n") + s.run("vault zeroize confirm", "err no-vault\n") + s.run("status", "err unknown-command\n") + return + if vault == "none": + # 알고리즘이 없는 이미지의 볼트는 시드를 받지 않음 + fresh = "state=fresh\nalg=none\nselftest=passed\nseed=none\nvalidated=no\nok\n" + else: + fresh = "state=seeded\nalg=none\nselftest=passed\nseed=%s\nvalidated=no\nok\n" % seed + s.run("help", full_help) + s.run("vault status", fresh) + s.run("vault pubkey", "err no-key\n") + # 오타를 지우고 고쳐 쓰기. 지울 때마다 BS, 공백, BS가 돌아옴 + s.run("vault status", fresh, typed=b"vault stauts\x08\x08\x7ftus\r", echo=b"vault stauts\x08 \x08\x08 \x08\x08 \x08tus") + # 줄 취소는 실행하지 않고 새 프롬프트를 줌 + s.send(b"vault zeroize confirm\x03") + s.expect(b"vault zeroize confirm^C\n" + PROMPT, what="cancel") + s.send(b"vault zeroize confirm\x15") + s.expect(b"vault zeroize confirm^U\n" + PROMPT, what="cancel") + # 화살표 키는 화면에도 명령에도 들어가지 않음 + s.run("help", full_help, typed=b"he\x1b[A\x1b[1;5Clp\x1bOP\r") + # CR LF는 줄 하나이고, 빈 줄은 프롬프트만 냄 + s.run("help", full_help, typed=b"help\r\n") + s.run("", "", typed=b"\n") + s.run("sign", "err unknown-command\n") + s.run("vault sign", "err unknown-command\n") + s.run("vault keygen", "err bad-argument\n") + s.run("vault keygen rsa", "err unsupported-algorithm\n") + s.run("x" * 64, "err unknown-command\n") + s.send(b"y" * 65 + b"zzz\r") + s.expect(b"y" * 64 + b"\nerr line-too-long\n" + PROMPT, what="long line") + if vault == "none": + s.run("vault keygen ed25519", "err unsupported-algorithm\n") + s.run("vault status", fresh) + else: + s.run("vault keygen ed25519", "state=ready\nalg=ed25519\nok\n", timeout=60) + s.run("vault keygen ed25519", "err key-exists\n") + s.send(b"vault pubkey\r") + s.expect(b"vault pubkey\npubkey=", what="pubkey") + body = s.wait_for(b"\nok\n" + PROMPT, 20) + if not re.fullmatch(rb"[0-9a-f]{32}\n {7}[0-9a-f]{32}", body): + raise Failure("public key format: %r" % body) + if body.replace(b"\n ", b"") in KNOWN_KEYS: + raise Failure("the service key comes from a publicly known seed: %r" % body) + ready = "state=ready\nalg=ed25519\nselftest=passed\nseed=%s\nvalidated=no\nok\n" % seed + s.run("vault status", ready) + s.run("vault zeroize", "hint=type 'vault zeroize confirm' to erase the key\nerr confirm-required\n") + s.run("vault status", ready) + # 줄 끝 없는 홍수: 터미널은 아무것도 돌려보내지 않고, 커널은 계속 답함 + s.send(b"A" * 64) + s.expect(b"A" * 64, what="flood head") + for _ in range(50): + s.send(b"B" * 4000) + s.send(b"\r") + s.expect(b"\nerr line-too-long\n" + PROMPT, timeout=120, what="flood") + # 줄 끝이 섞인 홍수: 줄마다 답이 나오고 끝난 뒤에도 정상임 + burst = b"q\r" * 2000 + s.send(burst) + for _ in range(2000): + s.expect(b"q\nerr unknown-command\n" + PROMPT, timeout=120, what="burst") + # 직렬 선의 break는 커널이 유실로 알리고, 터미널은 그 줄을 버림 + s.send(b"vault zeroize con") + s.expect(b"vault zeroize con", what="partial line") + s.monitor("chardev-send-break serial0") + s.send(b"firm\r") + s.expect(b"\nerr input-lost\n" + PROMPT, what="break") + if vault == "ed25519": + s.run("vault status", ready) + s.run("vault zeroize confirm", "state=zeroized\nok\n") + s.run("vault pubkey", "err zeroized\n") + s.run("vault keygen ed25519", "err zeroized\n") + s.run("vault status", "state=zeroized\nalg=none\nselftest=passed\nseed=none\nvalidated=no\nok\n") + else: + s.run("vault zeroize confirm", "state=zeroized\nok\n") + # 알고리즘이 없는 이미지는 상태를 보기 전에 알고리즘부터 거절함 + s.run("vault keygen ed25519", "err unsupported-algorithm\n") + + +def main(): + args = sys.argv[1:] + vault, seed = os.environ.get("K0_TERM_VAULT", "ed25519"), os.environ.get("K0_TERM_SEED", "rng-seed") + image = None + while args: + a = args.pop(0) + if a == "--vault": + vault = args.pop(0) + elif a == "--seed": + seed = args.pop(0) + else: + image = a + if image is None or vault not in ("ed25519", "none", "absent"): + print(__doc__.strip().splitlines()[2], file=sys.stderr) + return 2 + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + log_path = os.environ.get("K0_TERM_LOG", os.path.join(root, "target/term-test.log")) + boot_timeout = int(os.environ.get("K0_TERM_TIMEOUT", "120")) + s = Session(root, os.path.abspath(image), log_path, boot_timeout) + try: + boot = s.wait_for(BANNER, boot_timeout) + s.expect(PROMPT, what="first prompt") + if not boot.endswith(b"root: service started\n"): + raise Failure("the banner must follow the service line, got %r" % boot[-120:]) + boot_judge(root, os.path.abspath(image), log_path, boot, vault) + wiring(boot, vault) + start = s.pos + session(s, vault, seed) + with s.lock: + talk = bytes(s.buf[start:]) + bad = FAIL_RE.search(talk) + if bad: + raise Failure("kernel line during the session: %r" % talk[bad.start(): bad.start() + 80]) + except Failure as e: + print("term-test: FAIL %s" % e, file=sys.stderr) + print("term-test: last output: %r" % s.tail(), file=sys.stderr) + print("term-test: log in %s" % log_path, file=sys.stderr) + return 1 + finally: + s.close() + print("term-test: pass (vault %s)" % vault) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/userspace/k0-term/Cargo.toml b/userspace/k0-term/Cargo.toml new file mode 100644 index 0000000..535d9e4 --- /dev/null +++ b/userspace/k0-term/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "k0-term" +version.workspace = true +edition.workspace = true +license.workspace = true +publish.workspace = true + +# `vault`를 주면 볼트 프로토콜의 값을 터미널의 타입으로 옮기는 모듈이 들어감. +# 주지 않으면 이 크레이트는 볼트를 전혀 모름 +[features] +vault = ["dep:k0-vault"] + +[dependencies] +k0-vault = { path = "../k0-vault", optional = true } diff --git a/userspace/k0-term/src/lib.rs b/userspace/k0-term/src/lib.rs new file mode 100644 index 0000000..5827d7d --- /dev/null +++ b/userspace/k0-term/src/lib.rs @@ -0,0 +1,550 @@ +//! K0 운영자 터미널의 줄 편집과 명령 해석을 맡는 크레이트입니다. +//! +//! # Features +//! 직렬 선에서 온 바이트를 하나씩 받아 줄을 만들고, 줄이 끝나면 명령으로 풀어 +//! 실행한 뒤 결과를 글자로 내보냅니다. 시스템 콜은 쓰지 않고 바깥과는 두 +//! 트레이트([Out], [Vault])로만 이어지므로, 모든 경로를 호스트에서 바이트를 +//! 넣고 출력을 비교하는 방식으로 테스트합니다. +//! +//! 터미널의 코드는 루트 태스크 이미지에 들어가고 격리된 태스크에서 돌기 +//! 때문에 할당도 가변 static도 쓰지 않습니다. `unsafe`도 없습니다. +//! +//! 화면 규칙은 다음과 같습니다. 프롬프트는 [PROMPT]이고, 값은 `이름=값` 줄로 +//! 내며, 모든 명령은 `ok` 또는 `err <이유>` 한 줄로 끝납니다. 터미널이 되돌려 +//! 보내는 글자는 언제나 프롬프트 뒤에 놓이므로 입력이 줄의 첫머리가 되는 일은 +//! 없습니다. 화면에 보인 줄과 실행되는 줄은 항상 같습니다(버퍼에 넣은 글자만 +//! 되돌려 보냄). +//! +//! 운영자가 할 수 있는 일은 상태 조회, 공개키 조회, 알고리즘을 골라 키 생성, +//! 키 소거뿐입니다. 서명을 받는 명령은 없습니다. +//! +//! 커널이 입력 유실을 알리면 그 줄을 버리고 다음 줄 끝까지 아무것도 받지 +//! 않습니다. 빠진 줄의 꼬리가 다른 명령으로 읽히지 않게 하려는 것입니다. 한 +//! 가지 한계가 있습니다. 운영자가 입력하는 도중에 커널의 줄이 끼어들면 화면의 +//! 줄은 둘로 나뉘지만 버퍼는 이어져 있어서, 그때 줄 끝을 누르면 화면에 보이는 +//! 조각이 아니라 버퍼의 전체 줄이 실행됩니다. + +#![cfg_attr(not(test), no_std)] +#![forbid(unsafe_code)] + +#[cfg(feature = "vault")] +pub mod wire; + +#[cfg(test)] +mod tests; + +/// 한 줄의 최대 길이(줄 끝 문자 제외) +pub const LINE_MAX: usize = 64; +/// 프롬프트 +pub const PROMPT: &str = "k0> "; +/// 시작할 때 한 번 내는 줄 +pub const BANNER: &str = "K0 operator console, type 'help'\n"; +/// 공개키를 받는 버퍼의 길이 +pub const KEY_MAX: usize = 64; +/// 공개키 한 줄에 찍는 바이트 수 +const KEY_ROW: usize = 16; +/// ESC 열에서 매개변수 바이트를 이만큼 넘게 보면 열을 버림 +const ESC_MAX: u8 = 16; + +/// 터미널이 바이트를 내보내는 통로입니다. +pub trait Out { + /// 바이트 하나를 내보내는 함수입니다. + /// + /// # Arguments + /// `b` - 내보낼 바이트(인쇄 가능한 ASCII, 줄바꿈, 백스페이스 중 하나) + fn put(&mut self, b: u8); +} + +/// 서명 알고리즘을 나타내는 열거형입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Alg { + Ed25519, +} + +impl Alg { + /// 이 크레이트가 이름을 아는 알고리즘 전부 + pub const ALL: [Alg; 1] = [Alg::Ed25519]; + + /// 명령과 출력에 쓰는 이름을 주는 함수입니다. + pub const fn name(self) -> &'static str { + match self { + Alg::Ed25519 => "ed25519", + } + } + + /// 낱말을 알고리즘으로 푸는 함수입니다. 모르는 이름이면 `None`입니다. + /// + /// # Arguments + /// `word` - 명령 줄의 낱말 + pub fn parse(word: &[u8]) -> Option { + Self::ALL.into_iter().find(|a| a.name().as_bytes() == word) + } +} + +/// 볼트의 키 상태를 나타내는 열거형입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum KeyState { + /// 시드도 키도 없음 + Fresh, + /// 시드를 받았고 키는 아직 없음 + Seeded, + /// 키가 있음 + Ready, + /// 키와 시드가 지워졌음 + Zeroized, + /// 자가 시험이 실패해 볼트가 오류 상태임 + Failed, +} + +impl KeyState { + const fn name(self) -> &'static str { + match self { + KeyState::Fresh => "fresh", + KeyState::Seeded => "seeded", + KeyState::Ready => "ready", + KeyState::Zeroized => "zeroized", + KeyState::Failed => "failed", + } + } +} + +/// 볼트의 상태 조회 결과를 담는 구조체입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Status { + pub state: KeyState, + /// 지금 있는 키의 알고리즘 + pub alg: Option, + /// 시작 시 자가 시험을 통과했는지 + pub self_test: bool, + /// 시드에 `rng-seed` 32바이트 이상이 들어갔는지 + pub seed_rng: bool, + /// 시드에 RNDR 난수 256비트가 들어갔는지 + pub seed_rndr: bool, + /// 이미지에 들어 있는 알고리즘인지([Alg::ALL]과 같은 순서) + pub built: [bool; Alg::ALL.len()], +} + +/// 볼트 명령이 실패한 이유를 나타내는 열거형입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Fail { + /// 볼트가 이 역할에 그 연산을 허용하지 않음 + Denied, + /// 이 이미지에 볼트가 없거나 볼트 태스크가 사라졌음 + NoVault, + /// 키가 아직 없음 + NoKey, + /// 키가 이미 있음(부팅당 키 하나) + KeyExists, + /// 시드의 재료가 모자라 볼트가 시드를 받지 않았음 + NoEntropy, + /// 그 알고리즘이 이 이미지에 없음 + Unsupported, + /// 키가 지워졌음(재부팅해야 새 키를 만듦) + Zeroized, + /// 볼트가 오류 상태임 + VaultFailed, + /// 요청이 기한 안에 볼트에 전달되지 않음(볼트는 요청을 보지 못했음) + VaultTimeout, + /// 요청은 전달됐지만 기한 안에 답이 오지 않음. 볼트가 그 요청을 처리했는지 + /// 알 수 없음 + VaultUnanswered, +} + +impl Fail { + /// `err` 뒤에 찍는 이름을 주는 함수입니다. + pub const fn name(self) -> &'static str { + match self { + Fail::Denied => "denied", + Fail::NoVault => "no-vault", + Fail::NoKey => "no-key", + Fail::KeyExists => "key-exists", + Fail::NoEntropy => "no-entropy", + Fail::Unsupported => "unsupported-algorithm", + Fail::Zeroized => "zeroized", + Fail::VaultFailed => "vault-failed", + Fail::VaultTimeout | Fail::VaultUnanswered => "vault-timeout", + } + } +} + +/// 터미널이 볼트에 말을 거는 통로입니다. 운영자 역할의 네 연산만 있습니다. +pub trait Vault { + /// 볼트의 상태를 묻는 함수입니다. + fn status(&mut self) -> Result; + /// 공개키를 받아 그 길이를 돌려주는 함수입니다. + /// + /// # Arguments + /// `key` - 공개키를 받을 버퍼 + fn pubkey(&mut self, key: &mut [u8; KEY_MAX]) -> Result; + /// 고른 알고리즘으로 키를 만들게 하는 함수입니다. + /// + /// # Arguments + /// `alg` - 키의 알고리즘 + fn keygen(&mut self, alg: Alg) -> Result<(), Fail>; + /// 키를 지우게 하는 함수입니다. + fn zeroize(&mut self) -> Result<(), Fail>; +} + +/// 볼트가 없는 이미지에서 [Vault] 자리를 채우는 타입입니다. 값이 존재하지 +/// 않으므로 그 이미지에는 볼트를 부르는 경로가 없습니다. +pub enum NoVault {} + +impl Vault for NoVault { + fn status(&mut self) -> Result { + match *self {} + } + + fn pubkey(&mut self, _key: &mut [u8; KEY_MAX]) -> Result { + match *self {} + } + + fn keygen(&mut self, _alg: Alg) -> Result<(), Fail> { + match *self {} + } + + fn zeroize(&mut self) -> Result<(), Fail> { + match *self {} + } +} + +/// ESC로 시작하는 열(화살표 키 등)을 건너뛰는 상태입니다. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Esc { + Idle, + /// ESC를 방금 봄 + Start, + /// `ESC [` 뒤, 지금까지 본 매개변수 바이트 수 + Csi(u8), + /// `ESC O` 뒤, 한 바이트를 더 버림 + One, +} + +/// 줄 끝까지 입력을 버리는 이유입니다. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Skip { + No, + /// 줄이 [LINE_MAX]를 넘음 + TooLong, + /// 커널이 입력을 잃었다고 알림 + Lost, +} + +/// 터미널의 상태를 담는 구조체입니다. +/// +/// 줄 버퍼와 그 길이, 건너뛰기 상태뿐이라 태스크의 스택에 둡니다. +pub struct Term { + line: [u8; LINE_MAX], + len: usize, + skip: Skip, + esc: Esc, + /// 바로 앞 바이트가 CR이었는지(CRLF의 LF를 삼키는 데 씀) + cr: bool, +} + +impl Default for Term { + fn default() -> Self { + Self::new() + } +} + +fn text(out: &mut impl Out, s: &str) { + for b in s.bytes() { + out.put(b); + } +} + +fn hex(out: &mut impl Out, bytes: &[u8]) { + for b in bytes { + for nib in [b >> 4, b & 0xF] { + out.put(if nib < 10 { b'0' + nib } else { b'a' + nib - 10 }); + } + } +} + +fn ok(out: &mut impl Out) { + text(out, "ok\n"); +} + +fn err(out: &mut impl Out, reason: &str) { + text(out, "err "); + text(out, reason); + out.put(b'\n'); +} + +impl Term { + /// 빈 터미널 상태를 만드는 함수입니다. + pub const fn new() -> Self { + Self { + line: [0; LINE_MAX], + len: 0, + skip: Skip::No, + esc: Esc::Idle, + cr: false, + } + } + + /// 시작 줄과 첫 프롬프트를 내는 함수입니다. + /// + /// # Arguments + /// `out` - 출력 통로 + pub fn start(&mut self, out: &mut impl Out) { + text(out, BANNER); + text(out, PROMPT); + } + + /// 입력 바이트 하나를 처리하는 함수입니다. + /// + /// # Arguments + /// `b` - 받은 바이트 + /// `lost` - 이 바이트 앞에서 입력이 유실됐다고 커널이 알렸는지 + /// `out` - 출력 통로 + /// `vault` - 볼트로 가는 통로(볼트가 없는 이미지에서는 `None`) + pub fn feed(&mut self, b: u8, lost: bool, out: &mut O, mut vault: Option<&mut V>) { + if lost && self.skip != Skip::Lost { + // 어디가 빠졌는지 알 수 없으므로 지금 줄을 버리고 다음 줄 끝까지 + // 아무것도 받지 않음. 빠진 줄의 꼬리가 다른 명령으로 읽히지 않게 함 + out.put(b'\n'); + err(out, "input-lost"); + self.len = 0; + self.skip = Skip::Lost; + self.esc = Esc::Idle; + } + let after_cr = self.cr; + self.cr = b == b'\r'; + if b == b'\n' && after_cr { + return; + } + if self.skip != Skip::No { + self.skipping(b, out); + return; + } + if !self.escape(b) { + return; + } + match b { + b'\r' | b'\n' => { + out.put(b'\n'); + let len = core::mem::take(&mut self.len); + run(&self.line[..len], out, vault.as_deref_mut()); + text(out, PROMPT); + } + 0x08 | 0x7F => { + if self.len > 0 { + self.len -= 1; + for e in [0x08, b' ', 0x08] { + out.put(e); + } + } + } + 0x03 | 0x15 => self.cancel(b, out), + 0x1B => self.esc = Esc::Start, + 0x20..=0x7E => { + if self.len < LINE_MAX { + self.line[self.len] = b; + self.len += 1; + out.put(b); + } else { + self.skip = Skip::TooLong; + } + } + // 그 밖의 제어 바이트와 0x80 이상은 버림 + _ => {} + } + } + + /// 줄을 버리고 새 프롬프트를 내는 함수입니다. 누른 키를 `^C`나 `^U`로 보여 + /// 줍니다. + fn cancel(&mut self, key: u8, out: &mut impl Out) { + self.len = 0; + self.skip = Skip::No; + text(out, if key == 0x03 { "^C\n" } else { "^U\n" }); + text(out, PROMPT); + } + + /// 줄 끝까지 버리는 동안의 바이트 하나를 처리하는 함수입니다. + fn skipping(&mut self, b: u8, out: &mut impl Out) { + match b { + b'\r' | b'\n' => { + if self.skip == Skip::TooLong { + out.put(b'\n'); + err(out, "line-too-long"); + } + self.len = 0; + self.skip = Skip::No; + text(out, PROMPT); + } + 0x03 | 0x15 => self.cancel(b, out), + _ => {} + } + } + + /// ESC 열을 건너뛰는 함수입니다. 이 바이트를 평소대로 처리해야 하면 + /// true를 돌려줍니다. + fn escape(&mut self, b: u8) -> bool { + match self.esc { + Esc::Idle => true, + // 제어 바이트(줄 끝, 취소 등)는 열을 끊고 평소대로 처리함 + _ if b < 0x20 || b == 0x7F => { + self.esc = Esc::Idle; + true + } + Esc::Start => { + self.esc = match b { + b'[' => Esc::Csi(0), + b'O' => Esc::One, + _ => Esc::Idle, + }; + false + } + Esc::One => { + self.esc = Esc::Idle; + false + } + // 매개변수 바이트가 이어지는 동안은 열 안이고, 그 밖의 바이트(끝 + // 바이트나 0x80 이상)에서 열이 끝남. 어느 쪽이든 이 바이트는 버림 + Esc::Csi(n) => { + self.esc = match b { + 0x20..=0x3F if n < ESC_MAX => Esc::Csi(n + 1), + _ => Esc::Idle, + }; + false + } + } + } +} + +/// 줄을 낱말로 나눠 `words`에 담고 낱말 수를 돌려주는 함수입니다. `words`보다 +/// 낱말이 많으면 `words.len() + 1`을 돌려줍니다. +fn split<'a>(line: &'a [u8], words: &mut [&'a [u8]]) -> usize { + let mut n = 0; + for w in line.split(|b| *b == b' ').filter(|w| !w.is_empty()) { + if n == words.len() { + return n + 1; + } + words[n] = w; + n += 1; + } + n +} + +/// 완성된 줄 하나를 실행하는 함수입니다. +fn run(line: &[u8], out: &mut O, vault: Option<&mut V>) { + let mut words: [&[u8]; 3] = [&[]; 3]; + let n = split(line, &mut words); + if n == 0 { + return; + } + let args = &words[1..n.min(3)]; + match words[0] { + b"help" if n == 1 => help(out, vault), + b"help" => err(out, "bad-argument"), + b"vault" => match vault { + None => err(out, "no-vault"), + // 낱말이 셋을 넘는 줄은 어느 명령에도 맞지 않음 + Some(_) if n > 3 => err(out, "bad-argument"), + Some(v) => vault_command(args, out, v), + }, + _ => err(out, "unknown-command"), + } +} + +fn help(out: &mut O, vault: Option<&mut V>) { + text(out, "help\n"); + if let Some(v) = vault { + text(out, "vault status\nvault pubkey\nvault keygen alg:"); + match v.status() { + Ok(st) if st.built.iter().any(|b| *b) => { + for (a, _) in Alg::ALL.iter().zip(st.built).filter(|(_, built)| *built) { + out.put(b' '); + text(out, a.name()); + } + } + Ok(_) => text(out, " none"), + Err(_) => text(out, " unknown"), + } + text(out, "\nvault zeroize confirm\n"); + } + ok(out); +} + +fn vault_command(args: &[&[u8]], out: &mut O, v: &mut V) { + match args { + [b"status"] => match v.status() { + Ok(st) => { + status(out, &st); + ok(out); + } + Err(f) => err(out, f.name()), + }, + [b"pubkey"] => { + let mut key = [0u8; KEY_MAX]; + match v.pubkey(&mut key) { + Ok(len) => { + for (i, row) in key[..len.min(KEY_MAX)].chunks(KEY_ROW).enumerate() { + text(out, if i == 0 { "pubkey=" } else { " " }); + hex(out, row); + out.put(b'\n'); + } + ok(out); + } + Err(f) => err(out, f.name()), + } + } + [b"keygen", name] => match Alg::parse(name) { + None => err(out, Fail::Unsupported.name()), + Some(alg) => match v.keygen(alg) { + Ok(()) => { + text(out, "state=ready\nalg="); + text(out, alg.name()); + out.put(b'\n'); + ok(out); + } + Err(f) => changed(out, f), + }, + }, + [b"zeroize", b"confirm"] => match v.zeroize() { + Ok(()) => { + text(out, "state=zeroized\n"); + ok(out); + } + Err(f) => changed(out, f), + }, + [b"zeroize"] => { + text(out, "hint=type 'vault zeroize confirm' to erase the key\n"); + err(out, "confirm-required"); + } + [] | [b"status" | b"pubkey" | b"keygen" | b"zeroize", ..] => err(out, "bad-argument"), + _ => err(out, "unknown-command"), + } +} + +/// 상태를 바꾸는 명령이 실패했을 때의 끝줄을 내는 함수입니다. 요청이 전달된 뒤 +/// 답이 오지 않았으면 볼트가 그 일을 했는지 알 수 없으므로, 확인하는 방법을 한 +/// 줄 덧붙입니다. +fn changed(out: &mut impl Out, f: Fail) { + if f == Fail::VaultUnanswered { + text(out, "hint=run 'vault status' to see whether it took effect\n"); + } + err(out, f.name()); +} + +fn status(out: &mut impl Out, st: &Status) { + text(out, "state="); + text(out, st.state.name()); + text(out, "\nalg="); + text(out, st.alg.map_or("none", Alg::name)); + text(out, "\nselftest="); + text(out, if st.self_test { "passed" } else { "failed" }); + text(out, "\nseed="); + text( + out, + match (st.seed_rng, st.seed_rndr) { + (false, false) => "none", + (true, false) => "rng-seed", + (false, true) => "rndr", + (true, true) => "rng-seed+rndr", + }, + ); + // 구현이 어떤 인증도 받지 않았음을 운영자에게 항상 보여 줌 + text(out, "\nvalidated=no\n"); +} diff --git a/userspace/k0-term/src/tests.rs b/userspace/k0-term/src/tests.rs new file mode 100644 index 0000000..4e49807 --- /dev/null +++ b/userspace/k0-term/src/tests.rs @@ -0,0 +1,563 @@ +//! 터미널의 줄 편집과 명령 해석을 검증하는 테스트 모듈입니다. + +use super::*; + +impl Out for Vec { + fn put(&mut self, b: u8) { + self.push(b); + } +} + +/// 부른 연산을 적어 두는 가짜 볼트입니다. +struct Fake { + state: KeyState, + alg: Option, + built: bool, + fail: Option, + calls: Vec<&'static str>, +} + +impl Fake { + fn new() -> Self { + Self { + state: KeyState::Seeded, + alg: None, + built: true, + fail: None, + calls: Vec::new(), + } + } + + fn gate(&mut self, name: &'static str) -> Result<(), Fail> { + self.calls.push(name); + self.fail.map_or(Ok(()), Err) + } +} + +impl Vault for Fake { + fn status(&mut self) -> Result { + self.gate("status")?; + Ok(Status { + state: self.state, + alg: self.alg, + self_test: true, + seed_rng: true, + seed_rndr: false, + built: [self.built], + }) + } + + fn pubkey(&mut self, key: &mut [u8; KEY_MAX]) -> Result { + self.gate("pubkey")?; + if self.state != KeyState::Ready { + return Err(Fail::NoKey); + } + for (i, b) in key.iter_mut().enumerate().take(32) { + *b = i as u8 * 8 + 1; + } + Ok(32) + } + + fn keygen(&mut self, alg: Alg) -> Result<(), Fail> { + self.gate("keygen")?; + if self.state == KeyState::Ready { + return Err(Fail::KeyExists); + } + self.state = KeyState::Ready; + self.alg = Some(alg); + Ok(()) + } + + fn zeroize(&mut self) -> Result<(), Fail> { + self.gate("zeroize")?; + self.state = KeyState::Zeroized; + self.alg = None; + Ok(()) + } +} + +/// 바이트 열을 넣고 출력을 글자열로 돌려주는 도우미입니다. +fn type_in(term: &mut Term, vault: &mut Fake, input: &[u8]) -> String { + let mut out = Vec::new(); + for b in input { + term.feed(*b, false, &mut out, Some(&mut *vault)); + } + String::from_utf8(out).unwrap() +} + +fn session(input: &[u8]) -> (String, Fake) { + let mut vault = Fake::new(); + let out = type_in(&mut Term::new(), &mut vault, input); + (out, vault) +} + +fn bare(input: &[u8]) -> String { + let mut term = Term::new(); + let mut out = Vec::new(); + for b in input { + term.feed(*b, false, &mut out, None::<&mut NoVault>); + } + String::from_utf8(out).unwrap() +} + +#[test] +fn the_banner_comes_once_and_ends_with_the_prompt() { + let mut out = Vec::new(); + Term::new().start(&mut out); + assert_eq!(out, b"K0 operator console, type 'help'\nk0> "); +} + +#[test] +fn help_lists_the_commands_and_the_algorithms_in_the_image() { + let (out, vault) = session(b"help\r"); + assert_eq!( + out, + "help\nhelp\nvault status\nvault pubkey\nvault keygen alg: ed25519\nvault zeroize confirm\nok\nk0> " + ); + assert_eq!(vault.calls, ["status"]); + + let mut none = Fake::new(); + none.built = false; + assert!(type_in(&mut Term::new(), &mut none, b"help\r").contains("alg: none\n")); + let mut dead = Fake::new(); + dead.fail = Some(Fail::VaultTimeout); + let out = type_in(&mut Term::new(), &mut dead, b"help\r"); + assert!(out.contains("alg: unknown\n") && out.ends_with("ok\nk0> ")); +} + +#[test] +fn without_a_vault_help_is_the_only_command() { + assert_eq!(bare(b"help\r"), "help\nhelp\nok\nk0> "); + assert_eq!(bare(b"vault status\r"), "vault status\nerr no-vault\nk0> "); + assert_eq!(bare(b"vault zeroize confirm\r"), "vault zeroize confirm\nerr no-vault\nk0> "); + assert_eq!(bare(b"status\r"), "status\nerr unknown-command\nk0> "); +} + +#[test] +fn every_command_ends_with_exactly_one_ok_or_err_line() { + let lines: [&[u8]; 16] = [ + b"help", + b"help me", + b"vault", + b"vault status", + b"vault status now", + b"vault pubkey", + b"vault keygen", + b"vault keygen ed25519", + b"vault keygen rsa", + b"vault keygen ed25519 again", + b"vault zeroize", + b"vault zeroize confirm", + b"vault zeroize confirm now", + b"vault sign", + b"sign", + b"a b c d e", + ]; + for line in lines { + let mut input = line.to_vec(); + input.push(b'\r'); + let (out, _) = session(&input); + let body = out.strip_prefix(core::str::from_utf8(line).unwrap()).unwrap(); + let body = body.strip_suffix("k0> ").unwrap(); + let ends = body.lines().filter(|l| *l == "ok" || l.starts_with("err ")).count(); + assert_eq!(ends, 1, "{out:?}"); + let last = body.lines().last().unwrap(); + assert!(last == "ok" || last.starts_with("err "), "{out:?}"); + } +} + +#[test] +fn wrong_words_get_the_right_error() { + let cases: [(&[u8], &str); 12] = [ + (b"sign", "unknown-command"), + (b"HELP", "unknown-command"), + (b"help me", "bad-argument"), + (b"vault", "bad-argument"), + (b"vault sign", "unknown-command"), + (b"vault status now", "bad-argument"), + (b"vault pubkey x", "bad-argument"), + (b"vault keygen", "bad-argument"), + (b"vault keygen rsa", "unsupported-algorithm"), + (b"vault keygen ED25519", "unsupported-algorithm"), + (b"vault zeroize CONFIRM", "bad-argument"), + (b"vault zeroize confirm now", "bad-argument"), + ]; + for (line, want) in cases { + let mut input = line.to_vec(); + input.push(b'\n'); + let (out, vault) = session(&input); + assert!(out.ends_with(&format!("\nerr {want}\nk0> ")), "{out:?}"); + assert!(!vault.calls.contains(&"zeroize") && !vault.calls.contains(&"keygen"), "{out:?}"); + } +} + +#[test] +fn status_prints_every_field() { + let (out, _) = session(b"vault status\r"); + assert_eq!( + out, + "vault status\nstate=seeded\nalg=none\nselftest=passed\nseed=rng-seed\nvalidated=no\nok\nk0> " + ); + let mut out = Vec::new(); + for (state, name) in [ + (KeyState::Fresh, "fresh"), + (KeyState::Seeded, "seeded"), + (KeyState::Ready, "ready"), + (KeyState::Zeroized, "zeroized"), + (KeyState::Failed, "failed"), + ] { + for (rng, rndr, seed) in [ + (false, false, "none"), + (true, false, "rng-seed"), + (false, true, "rndr"), + (true, true, "rng-seed+rndr"), + ] { + out.clear(); + let st = Status { + state, + alg: (state == KeyState::Ready).then_some(Alg::Ed25519), + self_test: state != KeyState::Failed, + seed_rng: rng, + seed_rndr: rndr, + built: [true], + }; + status(&mut out, &st); + let alg = if state == KeyState::Ready { "ed25519" } else { "none" }; + let test = if state == KeyState::Failed { "failed" } else { "passed" }; + assert_eq!( + String::from_utf8(out.clone()).unwrap(), + format!("state={name}\nalg={alg}\nselftest={test}\nseed={seed}\nvalidated=no\n") + ); + } + } +} + +#[test] +fn key_generation_then_public_key_then_zeroize() { + let (out, vault) = session(b"vault pubkey\rvault keygen ed25519\rvault keygen ed25519\rvault pubkey\rvault zeroize\rvault zeroize confirm\r"); + let want = "vault pubkey\nerr no-key\nk0> \ +vault keygen ed25519\nstate=ready\nalg=ed25519\nok\nk0> \ +vault keygen ed25519\nerr key-exists\nk0> \ +vault pubkey\npubkey=0109111921293139414951596169717981899199a1a9b1b9c1c9d1d9e1e9f1f9\nok\nk0> "; + // 공개키는 16바이트씩 두 줄이고 둘째 줄은 7칸 들여 씀 + let want = want.replace( + "pubkey=0109111921293139414951596169717981899199a1a9b1b9c1c9d1d9e1e9f1f9", + "pubkey=01091119212931394149515961697179\n 81899199a1a9b1b9c1c9d1d9e1e9f1f9", + ); + let rest = "vault zeroize\nhint=type 'vault zeroize confirm' to erase the key\nerr confirm-required\nk0> \ +vault zeroize confirm\nstate=zeroized\nok\nk0> "; + assert_eq!(out, format!("{want}{rest}")); + assert_eq!(vault.calls, ["pubkey", "keygen", "keygen", "pubkey", "zeroize"]); +} + +#[test] +fn every_failure_has_its_own_name_from_the_agreed_list() { + let all = [ + (Fail::Denied, "denied"), + (Fail::NoVault, "no-vault"), + (Fail::NoKey, "no-key"), + (Fail::KeyExists, "key-exists"), + (Fail::NoEntropy, "no-entropy"), + (Fail::Unsupported, "unsupported-algorithm"), + (Fail::Zeroized, "zeroized"), + (Fail::VaultFailed, "vault-failed"), + (Fail::VaultTimeout, "vault-timeout"), + (Fail::VaultUnanswered, "vault-timeout"), + ]; + for (fail, name) in all { + assert_eq!(fail.name(), name); + let mut vault = Fake::new(); + vault.fail = Some(fail); + for line in [&b"vault status\r"[..], b"vault pubkey\r", b"vault keygen ed25519\r", b"vault zeroize confirm\r"] { + let out = type_in(&mut Term::new(), &mut vault, line); + assert!(out.ends_with(&format!("\nerr {name}\nk0> ")), "{out:?}"); + } + } +} + +#[test] +fn a_change_whose_outcome_is_unknown_says_how_to_find_out() { + let hint = "hint=run 'vault status' to see whether it took effect\nerr vault-timeout\nk0> "; + for fail in [Fail::VaultUnanswered, Fail::VaultTimeout, Fail::NoVault, Fail::Denied] { + let mut vault = Fake::new(); + vault.fail = Some(fail); + for (line, changes) in [ + (&b"vault keygen ed25519\r"[..], true), + (b"vault zeroize confirm\r", true), + (b"vault status\r", false), + (b"vault pubkey\r", false), + ] { + let out = type_in(&mut Term::new(), &mut vault, line); + // 전달됐지만 답이 없었던, 상태를 바꾸는 명령에만 붙음 + assert_eq!(out.ends_with(hint), changes && fail == Fail::VaultUnanswered, "{fail:?} {out:?}"); + } + } +} + +#[test] +fn the_terminal_never_claims_validation() { + // 터미널이 낼 수 있는 글자열을 전부 모아, 인증이나 승인을 뜻하는 말이 + // 없는지 확인함. 구현은 어떤 인증도 받지 않았고 화면은 그것을 그대로 말함 + let mut all = String::new(); + for state in [KeyState::Fresh, KeyState::Seeded, KeyState::Ready, KeyState::Zeroized, KeyState::Failed] { + for fail in [None, Some(Fail::VaultUnanswered), Some(Fail::VaultFailed)] { + let mut vault = Fake::new(); + vault.state = state; + vault.alg = (state == KeyState::Ready).then_some(Alg::Ed25519); + vault.fail = fail; + let lines = b"help\rvault status\rvault pubkey\rvault keygen ed25519\rvault zeroize\rvault zeroize confirm\rx\r"; + all += &type_in(&mut Term::new(), &mut vault, lines); + } + } + let mut out = Vec::new(); + Term::new().start(&mut out); + all += core::str::from_utf8(&out).unwrap(); + let lower = all.to_lowercase(); + for word in ["fips", "approved", "compliant", "certified", "validated=yes"] { + assert!(!lower.contains(word), "the terminal must not say {word:?}"); + } + assert!(all.contains("validated=no\n")); +} + +#[test] +fn backspace_and_delete_erase_what_was_echoed() { + let (out, vault) = session(b"vault stauts\x08\x08\x7ftus\r"); + assert!(out.starts_with("vault stauts\x08 \x08\x08 \x08\x08 \x08tus\nstate=seeded\n"), "{out:?}"); + assert_eq!(vault.calls, ["status"]); + // 빈 줄에서는 아무것도 내보내지 않아 프롬프트를 지우지 못함 + assert_eq!(bare(b"\x08\x7f\x08"), ""); + assert_eq!(bare(b"a\x08\x08\x08"), "a\x08 \x08"); +} + +#[test] +fn cancel_keys_drop_the_line() { + for (key, shown) in [(0x03u8, "^C"), (0x15, "^U")] { + let mut input = b"vault zeroize confirm".to_vec(); + input.push(key); + input.extend_from_slice(b"\rhelp\r"); + let (out, vault) = session(&input); + assert!(out.starts_with(&format!("vault zeroize confirm{shown}\nk0> \nk0> help\n")), "{out:?}"); + assert_eq!(vault.calls, ["status"]); + } +} + +#[test] +fn line_ends_are_cr_lf_or_both() { + assert_eq!(bare(b"help\r\n"), "help\nhelp\nok\nk0> "); + assert_eq!(bare(b"help\n"), "help\nhelp\nok\nk0> "); + assert_eq!(bare(b"help\r\rhelp\n\n"), "help\nhelp\nok\nk0> \nk0> help\nhelp\nok\nk0> \nk0> "); + // CR 다음이 아닌 LF는 그 자체로 줄 끝임 + assert_eq!(bare(b"\rx\n"), "\nk0> x\nerr unknown-command\nk0> "); + assert_eq!(bare(b"\r\n\r\n"), "\nk0> \nk0> "); +} + +#[test] +fn an_empty_line_gives_only_a_prompt() { + assert_eq!(bare(b"\r"), "\nk0> "); + assert_eq!(bare(b" \r"), " \nk0> "); +} + +#[test] +fn spaces_around_words_do_not_matter() { + let (out, vault) = session(b" vault zeroize confirm \r"); + assert!(out.ends_with("\nstate=zeroized\nok\nk0> "), "{out:?}"); + assert_eq!(vault.calls, ["zeroize"]); +} + +#[test] +fn escape_sequences_are_swallowed() { + // 화살표, 수정 키가 붙은 화살표, 기능 키, Alt 글자 + for seq in [&b"\x1b[A"[..], b"\x1b[1;5C", b"\x1bOP", b"\x1bx", b"\x1b[200~", b"\x1b\x1b[B"] { + let mut input = b"he".to_vec(); + input.extend_from_slice(seq); + input.extend_from_slice(b"lp\r"); + assert_eq!(bare(&input), "help\nhelp\nok\nk0> ", "{seq:?}"); + } + // 끝나지 않은 열은 줄 끝에서 끊기고, 줄 끝은 평소대로 처리됨 + assert_eq!(bare(b"help\x1b[12\r"), "help\nhelp\nok\nk0> "); + assert_eq!(bare(b"help\x1b\r"), "help\nhelp\nok\nk0> "); + assert_eq!(bare(b"xy\x1b[\x03help\r"), "xy^C\nk0> help\nhelp\nok\nk0> "); + // 열 안의 글자는 화면에도 버퍼에도 들어가지 않음 + assert_eq!(bare(b"\x1b[vault\r"), "ault\nerr unknown-command\nk0> "); +} + +#[test] +fn an_escape_sequence_that_never_ends_stops_swallowing() { + let mut input = b"\x1b[".to_vec(); + input.extend_from_slice(&[b'1'; 16]); + // 열일곱 번째 매개변수 바이트에서 열을 버리고, 그 뒤는 평소 글자임 + input.extend_from_slice(b"1help\r"); + assert_eq!(bare(&input), "help\nhelp\nok\nk0> "); +} + +#[test] +fn other_control_bytes_and_high_bytes_are_ignored() { + let mut input = Vec::new(); + for b in (0u8..=0xFF).filter(|b| !matches!(b, 0x03 | 0x08 | 0x0A | 0x0D | 0x15 | 0x1B | 0x20..=0x7F)) { + input.push(b); + } + input.extend_from_slice(b"h\x00e\x80l\xffp\x07\r"); + assert_eq!(bare(&input), "help\nhelp\nok\nk0> "); +} + +#[test] +fn a_line_that_is_too_long_is_refused_whole() { + let mut input = vec![b'a'; LINE_MAX]; + input.push(b'\r'); + let out = bare(&input); + assert_eq!(out, format!("{}\nerr unknown-command\nk0> ", "a".repeat(LINE_MAX))); + + // 한 글자가 넘치면 그 뒤로는 되돌려 보내지 않고, 지우기도 듣지 않으며, + // 줄 끝에서 줄 전체를 거부함 + let mut vault = Fake::new(); + let mut input = b"vault zeroize confirm".to_vec(); + input.resize(LINE_MAX, b' '); + input.extend_from_slice(b"x\x08\x08\r"); + let out = type_in(&mut Term::new(), &mut vault, &input); + assert_eq!(out, format!("{:<64}\nerr line-too-long\nk0> ", "vault zeroize confirm")); + assert!(vault.calls.is_empty()); + + // 넘친 줄도 취소 키로 버릴 수 있음 + let mut input = vec![b'a'; LINE_MAX + 5]; + input.extend_from_slice(b"\x03help\r"); + assert!(bare(&input).ends_with("^C\nk0> help\nhelp\nok\nk0> ")); +} + +#[test] +fn lost_input_drops_everything_up_to_the_next_line_end() { + let mut term = Term::new(); + let mut vault = Fake::new(); + let mut out = Vec::new(); + for b in b"vault zero" { + term.feed(*b, false, &mut out, Some(&mut vault)); + } + // 유실 알림과 함께 온 바이트부터 줄 끝까지는 완전한 명령이라도 실행하지 않음 + let mut lost = true; + for b in b"vault zeroize confirm\r" { + term.feed(*b, lost, &mut out, Some(&mut vault)); + lost = false; + } + assert_eq!(String::from_utf8(out.clone()).unwrap(), "vault zero\nerr input-lost\nk0> "); + assert!(vault.calls.is_empty()); + + // 버리는 동안 유실이 또 알려져도 오류 줄은 한 번만 나감 + out.clear(); + term.feed(b'x', true, &mut out, Some(&mut vault)); + term.feed(b'y', true, &mut out, Some(&mut vault)); + term.feed(b'\n', true, &mut out, Some(&mut vault)); + assert_eq!(String::from_utf8(out.clone()).unwrap(), "\nerr input-lost\nk0> "); + + // 그 뒤의 줄은 평소대로 실행됨 + out.clear(); + for b in b"vault status\r" { + term.feed(*b, false, &mut out, Some(&mut vault)); + } + assert!(String::from_utf8(out).unwrap().ends_with("validated=no\nok\nk0> ")); + assert_eq!(vault.calls, ["status"]); +} + +/// 터미널이 낸 바이트를 화면처럼 해석해 줄들을 돌려주는 도우미입니다. 커서가 +/// 줄의 첫머리보다 왼쪽으로 가려 하면 패닉합니다. +fn screen(out: &[u8]) -> Vec { + let mut rows = vec![Vec::new()]; + let mut col = 0usize; + for b in out { + let row = rows.last_mut().unwrap(); + match b { + b'\n' => { + rows.push(Vec::new()); + col = 0; + } + 0x08 => { + assert!(col > 0, "backspace at the start of a line"); + col -= 1; + } + 0x20..=0x7E => { + if col == row.len() { + row.push(*b); + } else { + row[col] = *b; + } + col += 1; + } + other => panic!("byte {other:#x} must never be sent"), + } + } + rows.into_iter().map(|r| String::from_utf8(r).unwrap().trim_end().to_string()).collect() +} + +/// 고정된 씨앗의 의사 난수입니다(xorshift64). +struct Rng(u64); + +impl Rng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } +} + +#[test] +fn random_input_never_forges_a_line_and_runs_only_what_the_screen_shows() { + let pool: &[&[u8]] = &[ + b"vault zeroize confirm", + b"vault zeroize", + b"vault keygen ed25519", + b"vault status", + b"vault pubkey", + b"help", + b"k0: FATAL", + b"root: FAIL", + b"\r", + b"\n", + b"\r\n", + b"\x08", + b"\x7f", + b"\x03", + b"\x15", + b"\x1b", + b"\x1b[", + b"\x1bO", + b" ", + b"confirm", + b"zeroize", + ]; + let mut rng = Rng(0x9E37_79B9_7F4A_7C15); + for round in 0..2000 { + let mut term = Term::new(); + let mut vault = Fake::new(); + let mut out = Vec::new(); + term.start(&mut out); + let mut zeroized_at = None; + for _ in 0..(rng.next() % 40) { + let lost = rng.next() % 50 == 0; + let r = rng.next(); + let piece: Vec = if r % 4 == 0 { + vec![(r >> 8) as u8] + } else { + pool[(r >> 8) as usize % pool.len()].to_vec() + }; + for (i, b) in piece.iter().enumerate() { + term.feed(*b, lost && i == 0, &mut out, Some(&mut vault)); + if zeroized_at.is_none() && vault.calls.contains(&"zeroize") { + zeroized_at = Some(out.len()); + } + } + } + let rows = screen(&out); + for row in &rows[1..] { + // 입력이 닿는 줄은 언제나 프롬프트로 시작하므로 커널이나 루트 + // 태스크의 줄처럼 보이는 줄은 나올 수 없음 + assert!(!row.starts_with("k0:") && !row.starts_with("root:"), "round {round}: {row:?}"); + } + if let Some(at) = zeroized_at { + // 소거가 실행됐다면 화면에서 그 직전의 프롬프트 줄이 정확히 그 + // 명령이어야 함 + let before = screen(&out[..at]); + let shown = before.iter().rev().find(|r| r.starts_with("k0> ")).unwrap(); + let words: Vec<&str> = shown["k0> ".len()..].split(' ').filter(|w| !w.is_empty()).collect(); + assert_eq!(words, ["vault", "zeroize", "confirm"], "round {round}: {shown:?}"); + } + } +} diff --git a/userspace/k0-term/src/wire.rs b/userspace/k0-term/src/wire.rs new file mode 100644 index 0000000..8a76a74 --- /dev/null +++ b/userspace/k0-term/src/wire.rs @@ -0,0 +1,148 @@ +//! 볼트 프로토콜의 값을 터미널의 타입으로 옮기는 모듈입니다. +//! +//! # Features +//! 터미널은 볼트의 운영자 역할로 네 연산만 부릅니다. 이 모듈은 그 응답의 +//! 숫자(상태 워드, 표시 비트, 상태 값)를 터미널이 화면에 내는 타입으로 바꾸는 +//! 표를 한곳에 모읍니다. 시스템 콜을 부르는 일은 루트 태스크의 배선이 하고, +//! 여기의 함수들은 순수해서 호스트에서 시험됩니다. + +use k0_vault::proto::{alg, indicator, state, status, status_word}; + +use crate::{Alg, Fail, KeyState, Status}; + +/// 알고리즘의 프로토콜 번호를 주는 함수입니다. +pub const fn alg_number(a: Alg) -> u64 { + match a { + Alg::Ed25519 => alg::ED25519, + } +} + +/// 프로토콜 번호를 알고리즘으로 푸는 함수입니다. 터미널이 이름을 모르는 +/// 번호와 "없음"은 `None`입니다. +pub fn alg_of(number: u64) -> Option { + Alg::ALL.into_iter().find(|a| alg_number(*a) == number) +} + +/// 상태 조회 응답을 푸는 함수입니다. 모르는 상태 값이면 `None`입니다. +/// +/// # Arguments +/// `word` - 응답의 MR1(상태 워드) +/// `ind` - 응답의 MR2(표시 비트) +pub fn status_of(word: u64, ind: u64) -> Option { + let state = match status_word::state(word) { + state::FRESH => KeyState::Fresh, + state::SEEDED => KeyState::Seeded, + state::READY => KeyState::Ready, + state::ZEROIZED => KeyState::Zeroized, + state::FAILED => KeyState::Failed, + _ => return None, + }; + let built = status_word::built(word); + Some(Status { + state, + alg: alg_of(status_word::key_alg(word)), + self_test: ind & indicator::SELF_TEST_PASSED != 0, + seed_rng: ind & indicator::SEED_RNG_SEED != 0, + seed_rndr: ind & indicator::SEED_RNDR != 0, + built: Alg::ALL.map(|a| built >> alg_number(a) & 1 != 0), + }) +} + +/// 볼트 응답의 상태 값(MR0)을 실패로 옮기는 함수입니다. 성공이면 `None`입니다. +/// +/// 터미널이 보낼 리 없는 요청에 대한 거절(잘못된 요청)과 모르는 값은 "거절"로 +/// 묶습니다. +pub fn fail_of(st: u64) -> Option { + Some(match st { + status::OK => return None, + status::UNSUPPORTED => Fail::Unsupported, + status::NOT_READY => Fail::NoKey, + status::FAILED => Fail::VaultFailed, + status::ZEROIZED => Fail::Zeroized, + status::NO_ENTROPY => Fail::NoEntropy, + status::KEY_EXISTS => Fail::KeyExists, + _ => Fail::Denied, + }) +} + +/// 키가 없는 볼트에 공개키를 물었을 때의 실패를 상태에서 정하는 함수입니다. +pub fn no_key(state: KeyState) -> Fail { + match state { + KeyState::Zeroized => Fail::Zeroized, + KeyState::Failed => Fail::VaultFailed, + _ => Fail::NoKey, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_status_word_becomes_the_terminal_status() { + let ind = indicator::SELF_TEST_PASSED | indicator::SEED_RNG_SEED; + let st = status_of(status_word::pack(state::READY, alg::ED25519, 1 << alg::ED25519), ind).unwrap(); + assert_eq!( + st, + Status { + state: KeyState::Ready, + alg: Some(Alg::Ed25519), + self_test: true, + seed_rng: true, + seed_rndr: false, + built: [true], + } + ); + let st = status_of(status_word::pack(state::FRESH, alg::NONE, 0), indicator::SEED_RNDR).unwrap(); + assert_eq!((st.state, st.alg, st.self_test, st.seed_rndr, st.built), (KeyState::Fresh, None, false, true, [false])); + for (n, want) in [ + (state::FRESH, KeyState::Fresh), + (state::SEEDED, KeyState::Seeded), + (state::READY, KeyState::Ready), + (state::ZEROIZED, KeyState::Zeroized), + (state::FAILED, KeyState::Failed), + ] { + assert_eq!(status_of(n, 0).unwrap().state, want); + } + // 모르는 상태 값은 꾸며 내지 않음 + assert_eq!(status_of(5, 0), None); + assert_eq!(status_of(0xFF, 0), None); + // 터미널이 이름을 모르는 알고리즘의 키는 "없음"으로 보이고, 비트맵의 + // 다른 비트는 무시함 + let st = status_of(status_word::pack(state::READY, 9, 0xFFFD), 0).unwrap(); + assert_eq!((st.alg, st.built), (None, [false])); + } + + #[test] + fn every_vault_status_has_a_name() { + assert_eq!(fail_of(status::OK), None); + let table = [ + (status::DENIED, Fail::Denied), + (status::BAD_REQUEST, Fail::Denied), + (status::UNSUPPORTED, Fail::Unsupported), + (status::NOT_READY, Fail::NoKey), + (status::FAILED, Fail::VaultFailed), + (status::ZEROIZED, Fail::Zeroized), + (status::NO_ENTROPY, Fail::NoEntropy), + (status::KEY_EXISTS, Fail::KeyExists), + (9, Fail::Denied), + (u64::MAX, Fail::Denied), + ]; + for (st, want) in table { + assert_eq!(fail_of(st), Some(want), "status {st}"); + } + assert_eq!(no_key(KeyState::Fresh), Fail::NoKey); + assert_eq!(no_key(KeyState::Seeded), Fail::NoKey); + assert_eq!(no_key(KeyState::Zeroized), Fail::Zeroized); + assert_eq!(no_key(KeyState::Failed), Fail::VaultFailed); + } + + #[test] + fn algorithm_numbers_round_trip() { + for a in Alg::ALL { + assert_eq!(alg_of(alg_number(a)), Some(a)); + } + assert_eq!(alg_of(alg::NONE), None); + assert_eq!(alg_of(200), None); + } +} diff --git a/userspace/k0-vault/src/proto.rs b/userspace/k0-vault/src/proto.rs index b1fe75a..7a5373a 100644 --- a/userspace/k0-vault/src/proto.rs +++ b/userspace/k0-vault/src/proto.rs @@ -4,8 +4,9 @@ //! 클라이언트는 볼트의 엔드포인트에 `CALL`합니다. 요청의 메시지 레지스터는 //! MR0 = 연산과 알고리즘([request]), MR1 = 요청 프레임에 둔 바이트 수, MR2 = //! 클라이언트가 고른 일회용 번호입니다. 응답은 MR0 = [status], MR1 = 응답 -//! 프레임에 쓴 바이트 수(상태 조회에서는 볼트의 [state]), MR2 = [indicator], -//! MR3 = 요청의 일회용 번호입니다. 볼트는 네 레지스터를 항상 전부 채웁니다. +//! 프레임에 쓴 바이트 수(상태 조회에서는 볼트의 상태를 담은 워드, +//! [status_word]), MR2 = [indicator], MR3 = 요청의 일회용 번호입니다. 볼트는 네 +//! 레지스터를 항상 전부 채웁니다. //! //! 본문은 프레임으로 오갑니다. 요청 프레임은 클라이언트만 쓰고 볼트는 읽기만 //! 하며, 응답 프레임은 그 반대입니다. 응답 프레임의 앞 [RESPONSE_HEADER] @@ -13,9 +14,20 @@ //! 성공이고 프레임의 번호가 자기 번호와 같을 때만 본문을 믿어야 합니다 //! (타임아웃으로 버린 예전 요청의 답이 뒤늦게 쓰일 수 있음). //! +//! 본문이 있는 연산은 서명([request::SIGN])과 시드 전달([request::INIT])뿐이고, +//! 응답 본문이 있는 연산은 공개키와 서명뿐입니다. 볼트는 그 밖의 연산에서는 +//! 어떤 프레임에도 닿지 않습니다([fetch_plan], [publish_plan]). +//! //! 누가 무엇을 할 수 있는지는 엔드포인트 배지로 정하고 빌드 때 고정됩니다 -//! ([role_of]). 배지는 커널이 케이퍼빌리티에서 읽어 전달하므로 클라이언트가 -//! 꾸밀 수 없습니다. 정책을 바꾸는 연산은 없습니다. +//! ([caller_of], [allowed]). 배지는 커널이 케이퍼빌리티에서 읽어 전달하므로 +//! 클라이언트가 꾸밀 수 없습니다. 정책을 바꾸는 연산은 없습니다. 역할은 넷입니다. +//! 관리자(루트 태스크)는 시드를 넘기고, 운영자(직렬 터미널)는 알고리즘을 골라 +//! 키를 만들게 하고 지우게 하며 공개키를 봅니다. 서명 클라이언트만 서명을 +//! 받고, 읽기 클라이언트는 공개키만 받습니다. 운영자는 서명을 받지 못합니다. +//! +//! 키는 부팅당 하나입니다. 볼트는 시드를 받은 뒤([state::SEEDED]) 키 생성 +//! 요청을 기다리고, 키를 만들면 시드를 지웁니다. 지운 키는 되살릴 수 없고 새 +//! 키는 재부팅해야 만듭니다. /// 요청 본문(서명할 메시지)의 최대 길이 pub const MAX_MESSAGE: usize = 1024; @@ -39,10 +51,26 @@ pub mod request { pub const PUBLIC_KEY: u64 = 2; /// 요청 프레임의 메시지에 서명해 응답 프레임으로 받는 연산 pub const SIGN: u64 = 3; - /// 시드를 주어 키를 만들게 하는 연산(관리자 전용, 한 번만) + /// 시드와 그 재료 정보를 넘기는 연산(관리자 전용, 한 번만). 키는 만들지 + /// 않고 볼트가 시드를 쥔 채 [KEYGEN]을 기다림 pub const INIT: u64 = 4; - /// 키를 지우게 하는 연산(관리자 전용) + /// 키와 쥐고 있는 시드를 지우게 하는 연산(관리자와 운영자). 오류 상태의 + /// 볼트는 이미 아무것도 쥐고 있지 않으므로 지울 것이 없고, 다른 연산과 + /// 마찬가지로 [super::status::FAILED]로 답함 pub const ZEROIZE: u64 = 5; + /// 쥐고 있는 시드로 키를 만들게 하는 연산(관리자와 운영자, 한 번만). + /// 알고리즘은 MR0에 실어 고름 + pub const KEYGEN: u64 = 6; + + /// 요청 본문이 있는 연산인지 알려 주는 함수입니다. + pub const fn takes_body(op: u64) -> bool { + matches!(op, SIGN | INIT) + } + + /// 응답 본문이 있는 연산인지 알려 주는 함수입니다. + pub const fn gives_body(op: u64) -> bool { + matches!(op, PUBLIC_KEY | SIGN) + } /// 연산과 알고리즘을 MR0 값으로 묶는 함수입니다. pub const fn word(op: u64, alg: u64) -> u64 { @@ -50,7 +78,8 @@ pub mod request { } } -/// 알고리즘 번호 모듈입니다. +/// 알고리즘 번호 모듈입니다. 번호는 16보다 작아야 합니다(상태 워드의 비트맵이 +/// 16비트). pub mod alg { /// 알고리즘을 가리지 않는 연산에 쓰는 값 pub const NONE: u64 = 0; @@ -58,6 +87,33 @@ pub mod alg { pub const ED25519: u64 = 1; } +/// 상태 조회 응답의 MR1을 만들고 푸는 모듈입니다. +/// +/// 하위 8비트가 볼트의 [state], 그 위 8비트가 지금 있는 키의 알고리즘(없으면 +/// [alg::NONE]), 그 위 16비트가 이 이미지에 들어 있는 알고리즘의 비트맵(비트 +/// n = 알고리즘 n)입니다. +pub mod status_word { + /// 세 값을 워드로 묶는 함수입니다. + pub const fn pack(state: u64, key_alg: u64, built: u64) -> u64 { + (state & 0xFF) | (key_alg & 0xFF) << 8 | (built & 0xFFFF) << 16 + } + + /// 볼트의 상태를 꺼내는 함수입니다. + pub const fn state(word: u64) -> u64 { + word & 0xFF + } + + /// 지금 있는 키의 알고리즘을 꺼내는 함수입니다. + pub const fn key_alg(word: u64) -> u64 { + (word >> 8) & 0xFF + } + + /// 이미지에 들어 있는 알고리즘의 비트맵을 꺼내는 함수입니다. + pub const fn built(word: u64) -> u64 { + (word >> 16) & 0xFFFF + } +} + /// 응답의 MR0 값 모듈입니다. pub mod status { pub const OK: u64 = 0; @@ -73,16 +129,24 @@ pub mod status { pub const FAILED: u64 = 5; /// 키가 지워졌음 pub const ZEROIZED: u64 = 6; - /// 시드의 재료가 키를 만들기에 모자람 + /// 시드의 재료가 키를 만들기에 모자라거나, 볼트가 시드를 받지 못했음 pub const NO_ENTROPY: u64 = 7; + /// 키가 이미 있음(부팅당 키 하나) + pub const KEY_EXISTS: u64 = 8; } /// 볼트의 상태(상태 조회 응답의 MR1) 모듈입니다. pub mod state { + /// 시드도 키도 없음 pub const FRESH: u64 = 0; + /// 키가 있음 pub const READY: u64 = 1; + /// 키와 시드가 지워졌음 pub const ZEROIZED: u64 = 2; + /// 자가 시험이나 쌍 일치 시험이 실패했음(시드도 키도 쥐고 있지 않음) pub const FAILED: u64 = 3; + /// 시드를 받았고 키는 아직 없음 + pub const SEEDED: u64 = 4; } /// 응답의 MR2에 실리는 표시 비트 모듈입니다. @@ -94,30 +158,42 @@ pub mod indicator { pub const FIPS_186_5_ALGORITHM: u64 = 1; /// 시작 시 자가 시험을 통과했음 pub const SELF_TEST_PASSED: u64 = 2; - /// 키의 시드에 `rng-seed` 32바이트 이상이 들어갔음 + /// 키의 시드에 `rng-seed` 32바이트 이상이 들어갔음. 상태 조회에서는 + /// 볼트가 쥐고 있는 시드에 대해서도 알림. 바이트가 있었다는 뜻이지 그 + /// 바이트를 예측할 수 없었다는 뜻은 아님 pub const SEED_RNG_SEED: u64 = 4; - /// 키의 시드에 RNDR 난수 256비트가 들어갔음 + /// 키의 시드에 RNDR 난수 256비트가 들어갔음. 상태 조회에서는 볼트가 쥐고 + /// 있는 시드에 대해서도 알림 pub const SEED_RNDR: u64 = 8; } /// 배지가 가리키는 역할을 나타내는 열거형입니다. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Role { - /// 루트 태스크. 키를 만들게 하고 지우게 할 수 있지만 서명은 받지 못함 + /// 루트 태스크. 시드를 넘기고 키를 만들게 하고 지우게 할 수 있지만 서명도 + /// 공개키도 받지 못함 Admin, /// 공개키를 받고 서명을 받을 수 있는 클라이언트 Signer, /// 공개키만 받을 수 있는 클라이언트 Reader, + /// 직렬 터미널. 알고리즘을 골라 키를 만들게 하고 지우게 하며 공개키를 + /// 받음. 서명은 받지 못하고 시드를 넘기지도 못함 + Operator, } /// 역할을 담는 배지의 윗부분 const ROLE_ADMIN: u64 = 0xAD_0000_0000_0000; const ROLE_SIGNER: u64 = 0x51_0000_0000_0000; const ROLE_READER: u64 = 0x4E_0000_0000_0000; +const ROLE_OPERATOR: u64 = 0x0E_0000_0000_0000; /// 관리자(루트 태스크)의 배지 pub const ADMIN_BADGE: u64 = ROLE_ADMIN; +/// 운영자(직렬 터미널)의 배지 +pub const OPERATOR_BADGE: u64 = ROLE_OPERATOR; +/// 운영자의 응답 프레임 번호. 클라이언트의 프레임 번호들 바로 뒤 +pub const OPERATOR_FRAME: u64 = MAX_CLIENTS + 1; /// 서명 클라이언트의 배지를 만드는 함수입니다. /// @@ -135,26 +211,100 @@ pub const fn reader_badge(client: u64) -> u64 { ROLE_READER | client } -/// 배지를 (역할, 프레임 번호)로 푸는 함수입니다. 이 표에 없는 배지와 배지 -/// 없는 호출(0)은 `None`입니다. +/// 호출자 하나의 역할과 프레임을 담는 구조체입니다. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Caller { + pub role: Role, + /// 요청 프레임의 번호. 본문을 보낼 일이 없는 호출자(운영자)에게는 요청 + /// 프레임이 없음 + pub request: Option, + /// 응답 프레임의 번호 + pub response: u64, +} + +/// 배지를 호출자로 푸는 함수입니다. 이 표에 없는 배지와 배지 없는 호출(0)은 +/// `None`입니다. /// /// 프레임 번호는 볼트가 그 호출자의 요청 프레임과 응답 프레임을 고르는 데 -/// 씁니다. 관리자가 0번이고 클라이언트는 자기 번호입니다. -pub const fn role_of(badge: u64) -> Option<(Role, u64)> { +/// 씁니다. 관리자가 0번, 클라이언트는 자기 번호, 운영자의 응답 프레임은 +/// [OPERATOR_FRAME]입니다. +pub const fn caller_of(badge: u64) -> Option { let client = badge & 0xFFFF_FFFF_FFFF; - match badge & !0xFFFF_FFFF_FFFF { - ROLE_ADMIN if client == 0 => Some((Role::Admin, 0)), - ROLE_SIGNER if client >= 1 && client <= MAX_CLIENTS => Some((Role::Signer, client)), - ROLE_READER if client >= 1 && client <= MAX_CLIENTS => Some((Role::Reader, client)), - _ => None, + let numbered = client >= 1 && client <= MAX_CLIENTS; + let (role, request, response) = match badge & !0xFFFF_FFFF_FFFF { + ROLE_ADMIN if client == 0 => (Role::Admin, Some(0), 0), + ROLE_SIGNER if numbered => (Role::Signer, Some(client), client), + ROLE_READER if numbered => (Role::Reader, Some(client), client), + ROLE_OPERATOR if client == 0 => (Role::Operator, None, OPERATOR_FRAME), + _ => return None, + }; + Some(Caller { + role, + request, + response, + }) +} + +/// 배지가 가리키는 역할을 주는 함수입니다. +pub const fn role_of(badge: u64) -> Option { + match caller_of(badge) { + Some(c) => Some(c.role), + None => None, } } /// 역할이 그 연산을 해도 되는지 알려 주는 함수입니다. pub const fn allowed(role: Role, op: u64) -> bool { match role { - Role::Admin => matches!(op, request::STATUS | request::INIT | request::ZEROIZE), + Role::Admin => matches!(op, request::STATUS | request::INIT | request::KEYGEN | request::ZEROIZE), Role::Signer => matches!(op, request::STATUS | request::PUBLIC_KEY | request::SIGN), Role::Reader => matches!(op, request::STATUS | request::PUBLIC_KEY), + Role::Operator => { + matches!(op, request::STATUS | request::PUBLIC_KEY | request::KEYGEN | request::ZEROIZE) + } + } +} + +/// 이 요청의 본문을 어느 요청 프레임에서 몇 바이트 옮겨 올지 정하는 +/// 함수입니다. `None`이면 볼트는 어떤 프레임도 읽지 않습니다. +/// +/// 본문이 있는 연산이고, 그 호출자에게 요청 프레임이 있고, 말한 길이가 0이 +/// 아닐 때만 옮깁니다. 그 밖의 요청이 길이를 말했다면 볼트는 빈 본문으로 +/// 처리하므로, 말한 길이와 본문의 길이가 달라 요청 전체가 거부됩니다. 요청 +/// 프레임이 없는 호출자가 길이를 꾸며 볼트에게 매핑되지 않은 주소를 읽히는 +/// 길은 없습니다. +/// +/// # Arguments +/// `badge` - 커널이 전달한 호출자의 배지 +/// `mr` - 요청의 메시지 레지스터 +pub const fn fetch_plan(badge: u64, mr: &[u64; 4]) -> Option<(u64, u64)> { + let Some(caller) = caller_of(badge) else { + return None; + }; + let Some(frame) = caller.request else { + return None; + }; + if !request::takes_body(mr[0] & 0xFF) || mr[1] == 0 { + return None; + } + Some((frame, mr[1])) +} + +/// 이 요청의 응답 본문을 어느 응답 프레임에 쓸지 정하는 함수입니다. `None`이면 +/// 볼트는 어떤 프레임에도 쓰지 않습니다. +/// +/// # Arguments +/// `badge` - 커널이 전달한 호출자의 배지 +/// `mr` - 요청의 메시지 레지스터 +/// `status` - 볼트가 이 요청에 낸 응답의 MR0 +pub const fn publish_plan(badge: u64, mr: &[u64; 4], status: u64) -> Option { + let Some(caller) = caller_of(badge) else { + return None; + }; + if status != status::OK || !request::gives_body(mr[0] & 0xFF) { + return None; } + Some(caller.response) } + +const _: () = assert!(alg::ED25519 < 16); diff --git a/userspace/k0-vault/src/server.rs b/userspace/k0-vault/src/server.rs index 8c2a9b6..52f5705 100644 --- a/userspace/k0-vault/src/server.rs +++ b/userspace/k0-vault/src/server.rs @@ -11,11 +11,17 @@ //! 옮기며, 그 뒤로 볼트는 사본만 봅니다. 읽는 도중에 프레임이 바뀌면 사본이 //! 뒤섞일 뿐이고, 그것은 클라이언트가 처음부터 보낼 수 있었던 내용입니다. //! +//! 키는 두 걸음으로 생깁니다. 관리자가 시드를 넘기면([request::INIT]) 볼트는 +//! 재료를 확인한 뒤 시드를 쥐고, 관리자나 운영자가 알고리즘을 골라 키를 만들게 +//! 하면([request::KEYGEN]) 그 시드로 키를 만들고 시드를 지웁니다. 알고리즘이 +//! 하나도 없는 이미지의 볼트는 시드를 받지 않습니다. +//! //! # Errors //! 자가 시험이나 쌍 일치 시험이 실패하면 [state::FAILED]가 되어 상태 조회 -//! 말고는 전부 [status::FAILED]로 거부합니다. +//! 말고는 전부 [status::FAILED]로 거부합니다. 그 상태로 가는 모든 길에서 +//! 시드와 키를 지우므로, 오류 상태의 볼트는 비밀을 쥐고 있지 않습니다. -use crate::proto::{alg, allowed, indicator, request, role_of, state, status, Role}; +use crate::proto::{alg, allowed, indicator, request, role_of, state, status, status_word}; use crate::proto::{INIT_LEN, MAX_MESSAGE, MAX_RESPONSE, RESPONSE_HEADER}; use crate::provider::{self, Key}; @@ -24,13 +30,27 @@ const MIN_RNG_SEED: u64 = 32; /// 커널이 준 시드 정보의 비트(k0-abi의 bootinfo 상수와 같음) const SEED_RNG_SEED_BYTES: u64 = k0_abi::bootinfo::SEED_RNG_SEED_BYTES; const SEED_RNDR: u64 = k0_abi::bootinfo::SEED_RNDR; +/// 표시 비트 가운데 시드의 재료에 관한 것 +const SEED_BITS: u64 = indicator::SEED_RNG_SEED | indicator::SEED_RNDR; +/// 이 이미지에 들어 있는 알고리즘의 비트맵(비트 n = 알고리즘 n) +const BUILT: u64 = if provider::HAS_ED25519 { 1 << alg::ED25519 } else { 0 }; /// 볼트의 상태를 담는 구조체입니다. +/// +/// 비밀은 두 가지입니다. 키와, 키를 만들기 전까지 쥐고 있는 시드입니다. 시드는 +/// [state::SEEDED]인 동안에만 값이 있고, 키를 만들거나 지우거나 오류 상태로 +/// 가는 모든 길에서 0으로 덮습니다. pub struct Vault { state: u64, key: Key, - /// 표시 비트 가운데 자가 시험과 시드 재료에 관한 것 + /// 지금 있는 키의 알고리즘(없으면 [alg::NONE]) + key_alg: u64, + /// 관리자가 넘긴 시드. 키를 만들 때까지만 쥠 + seed: [u8; 32], + /// 표시 비트 가운데 자가 시험과, 지금 있는 키의 시드 재료에 관한 것 flags: u64, + /// 쥐고 있는 시드의 재료에 관한 표시 비트. 키가 만들어지면 `flags`로 옮김 + pending: u64, } impl Vault { @@ -42,7 +62,10 @@ impl Vault { Vault { state: if ok { state::FRESH } else { state::FAILED }, key: Key::empty(), + key_alg: alg::NONE, + seed: [0; 32], flags: if ok { indicator::SELF_TEST_PASSED } else { 0 }, + pending: 0, } } @@ -50,7 +73,7 @@ impl Vault { /// /// 응답 레지스터 네 개를 전부 채워 돌려주고(쓰지 않는 값이 새지 않게), /// 응답 본문은 `out`의 앞에 씁니다. 본문 길이는 응답의 두 번째 값입니다 - /// (상태 조회에서는 그 자리가 볼트의 상태이고 본문은 없음). + /// (상태 조회에서는 그 자리가 상태 워드이고 본문은 없음). /// /// # Arguments /// `badge` - 커널이 전달한 호출자의 배지 @@ -60,34 +83,47 @@ impl Vault { pub fn handle(&mut self, badge: u64, mr: [u64; 4], body: &[u8], out: &mut [u8; MAX_RESPONSE]) -> [u64; 4] { let nonce = mr[2]; let reply = |status: u64, len: u64, ind: u64| [status, len, ind, nonce]; - let Some((role, _)) = role_of(badge) else { + let Some(role) = role_of(badge) else { return reply(status::DENIED, 0, 0); }; let (op, algo) = (mr[0] & 0xFF, (mr[0] >> 8) & 0xFF); // 예약 비트가 서 있거나, 말한 길이와 옮겨 온 본문의 길이가 다르면 - // (버퍼보다 긴 본문은 잘려서 옴) 요청 전체를 거부함 + // (버퍼보다 긴 본문은 잘려서 오고, 본문이 없는 연산과 요청 프레임이 + // 없는 호출자의 본문은 아예 옮겨 오지 않음) 요청 전체를 거부함 if mr[0] >> 16 != 0 || mr[3] != 0 || mr[1] != body.len() as u64 { return reply(status::BAD_REQUEST, 0, 0); } if !matches!( op, - request::STATUS | request::PUBLIC_KEY | request::SIGN | request::INIT | request::ZEROIZE + request::STATUS + | request::PUBLIC_KEY + | request::SIGN + | request::INIT + | request::ZEROIZE + | request::KEYGEN ) { return reply(status::BAD_REQUEST, 0, 0); } if !allowed(role, op) { return reply(status::DENIED, 0, 0); } + if !request::takes_body(op) && !body.is_empty() { + return reply(status::BAD_REQUEST, 0, 0); + } if op == request::STATUS { - return reply(status::OK, self.state, self.flags); + // 시드의 재료는 키가 있으면 그 키의 것, 시드를 쥐고 있으면 그 + // 시드의 것을 알림 + let word = status_word::pack(self.state, self.key_alg, BUILT); + return reply(status::OK, word, self.flags | self.pending); } if self.state == state::FAILED { return reply(status::FAILED, 0, self.flags); } match op { - request::INIT => self.init(role, body, reply), + request::INIT => self.init(body, reply), + request::KEYGEN => self.keygen(algo, reply), request::ZEROIZE => { - self.key.wipe(); + self.forget(); self.state = state::ZEROIZED; scrub_stack(); reply(status::OK, 0, self.flags) @@ -96,7 +132,17 @@ impl Vault { } } - fn init(&mut self, _role: Role, body: &[u8], reply: impl Fn(u64, u64, u64) -> [u64; 4]) -> [u64; 4] { + /// 키와 시드, 그리고 그것들에 관한 표시를 지우는 함수입니다. + fn forget(&mut self) { + self.key.wipe(); + self.key_alg = alg::NONE; + wipe(&mut self.seed); + self.pending = 0; + self.flags &= !SEED_BITS; + } + + /// 시드를 받는 함수입니다. 키는 만들지 않습니다. + fn init(&mut self, body: &[u8], reply: impl Fn(u64, u64, u64) -> [u64; 4]) -> [u64; 4] { if self.state != state::FRESH { return reply(status::DENIED, 0, self.flags); } @@ -115,22 +161,51 @@ impl Vault { if info & SEED_RNDR != 0 { seed_flags |= indicator::SEED_RNDR; } - if seed_flags == 0 { - // 재료가 카운터뿐인 시드로는 키를 만들지 않음 + // 재료가 카운터뿐인 시드로는 키를 만들지 않음. 전부 0인 시드는 재료 + // 정보가 무엇이라 하든 받지 않음(이미 소거된 시드가 다시 넘어온 경우) + let blank = seed.iter().fold(0u8, |acc, b| acc | b) == 0; + if seed_flags == 0 || blank { wipe(&mut seed); return reply(status::NO_ENTROPY, 0, self.flags); } - let made = provider::keygen(&mut seed); + if BUILT == 0 { + // 알고리즘이 하나도 없는 이미지에서는 쓸 일이 없는 비밀을 쥐지 않음 + wipe(&mut seed); + return reply(status::UNSUPPORTED, 0, self.flags); + } + self.seed = seed; wipe(&mut seed); + self.pending = seed_flags; + self.state = state::SEEDED; + reply(status::OK, 0, self.flags) + } + + /// 쥐고 있는 시드로 키를 만드는 함수입니다. + fn keygen(&mut self, algo: u64, reply: impl Fn(u64, u64, u64) -> [u64; 4]) -> [u64; 4] { + if algo != alg::ED25519 || !provider::HAS_ED25519 { + return reply(status::UNSUPPORTED, 0, self.flags); + } + match self.state { + state::SEEDED => {} + state::READY => return reply(status::KEY_EXISTS, 0, self.flags), + state::ZEROIZED => return reply(status::ZEROIZED, 0, self.flags), + _ => return reply(status::NO_ENTROPY, 0, self.flags), + } + let made = provider::keygen(&mut self.seed); + // 시드는 키가 됐든 안 됐든 여기서 끝남 + wipe(&mut self.seed); scrub_stack(); match made { Some(key) => { self.key = key; + self.key_alg = algo; self.state = state::READY; - self.flags |= seed_flags; + self.flags |= self.pending; + self.pending = 0; reply(status::OK, 0, self.flags) } None => { + self.forget(); self.state = state::FAILED; self.flags &= !indicator::SELF_TEST_PASSED; reply(status::FAILED, 0, self.flags) @@ -150,15 +225,12 @@ impl Vault { return reply(status::UNSUPPORTED, 0, self.flags); } match self.state { - state::FRESH => return reply(status::NOT_READY, 0, self.flags), + state::READY => {} state::ZEROIZED => return reply(status::ZEROIZED, 0, self.flags), - _ => {} + _ => return reply(status::NOT_READY, 0, self.flags), } let ind = self.flags | indicator::FIPS_186_5_ALGORITHM; if op == request::PUBLIC_KEY { - if !body.is_empty() { - return reply(status::BAD_REQUEST, 0, self.flags); - } let Some(public) = self.key.public() else { return reply(status::NOT_READY, 0, self.flags); }; @@ -185,9 +257,25 @@ impl Vault { Vault { state: state::FAILED, key: Key::empty(), + key_alg: alg::NONE, + seed: [0; 32], flags: 0, + pending: 0, } } + + /// 볼트가 시드나 키를 쥐고 있는지 알려 주는 함수입니다(테스트 전용). + pub fn holds_a_secret(&self) -> bool { + self.seed.iter().any(|b| *b != 0) || self.key.public().is_some() + } + + /// 키 생성 뒤의 쌍 일치 시험이 실패했을 때와 같은 길로 볼트를 오류 상태에 + /// 넣는 함수입니다(테스트 전용). + pub fn fail_for_test(&mut self) { + self.forget(); + self.state = state::FAILED; + self.flags &= !indicator::SELF_TEST_PASSED; + } } impl Default for Vault { diff --git a/userspace/k0-vault/src/tests.rs b/userspace/k0-vault/src/tests.rs index 9649f8d..2cc8085 100644 --- a/userspace/k0-vault/src/tests.rs +++ b/userspace/k0-vault/src/tests.rs @@ -1,11 +1,29 @@ -use crate::proto::{alg, indicator, request, state, status}; -use crate::proto::{reader_badge, role_of, signer_badge, Role, ADMIN_BADGE, INIT_LEN, MAX_MESSAGE, MAX_RESPONSE}; +use crate::proto::{alg, indicator, request, state, status, status_word}; +use crate::proto::{caller_of, fetch_plan, publish_plan, reader_badge, role_of, signer_badge, Caller, Role}; +use crate::proto::{ADMIN_BADGE, INIT_LEN, MAX_CLIENTS, MAX_MESSAGE, MAX_RESPONSE, OPERATOR_BADGE, OPERATOR_FRAME}; use crate::server::{fetch, publish, Vault}; const SIGNER: u64 = signer_badge(1); const READER: u64 = reader_badge(1); +const OPERATOR: u64 = OPERATOR_BADGE; /// 시드 정보: rng-seed 32바이트 const GOOD_INFO: u64 = 32; +/// 연산 전부 +const OPS: [u64; 6] = [ + request::STATUS, + request::PUBLIC_KEY, + request::SIGN, + request::INIT, + request::ZEROIZE, + request::KEYGEN, +]; + +/// 볼트의 상태를 관리자의 상태 조회로 읽는 도우미입니다. +fn state_of(v: &mut Vault) -> u64 { + let (r, _) = call(v, ADMIN_BADGE, request::STATUS, alg::NONE, &[]); + assert_eq!(r[0], status::OK); + status_word::state(r[1]) +} fn call(v: &mut Vault, badge: u64, op: u64, algo: u64, body: &[u8]) -> ([u64; 4], Vec) { let mut out = [0xEEu8; MAX_RESPONSE]; @@ -25,52 +43,196 @@ fn init_body(seed: [u8; 32], info: u64) -> Vec { b } -fn ready() -> Vault { +/// 시드를 받은 볼트를 만드는 도우미입니다. 알고리즘이 없는 이미지에서는 시드를 +/// 받지 않으므로 처음 상태 그대로입니다. +fn seeded() -> Vault { let mut v = Vault::new(); let (r, _) = call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &init_body([7; 32], GOOD_INFO)); + if cfg!(feature = "ed25519") { + assert_eq!(r[0], status::OK); + assert_eq!(state_of(&mut v), state::SEEDED); + } else { + assert_eq!(r[0], status::UNSUPPORTED); + assert_eq!(state_of(&mut v), state::FRESH); + } + v +} + +/// 키가 있는 볼트를 만드는 도우미입니다(알고리즘이 있는 이미지에서만). +#[cfg(feature = "ed25519")] +fn ready() -> Vault { + let mut v = seeded(); + let (r, _) = call(&mut v, OPERATOR, request::KEYGEN, alg::ED25519, &[]); assert_eq!(r[0], status::OK); + assert_eq!(state_of(&mut v), state::READY); v } #[test] -fn badges_map_to_fixed_roles() { - assert_eq!(role_of(0), None, "a call without a badge has no role"); - assert_eq!(role_of(ADMIN_BADGE), Some((Role::Admin, 0))); - assert_eq!(role_of(ADMIN_BADGE | 1), None); - assert_eq!(role_of(signer_badge(1)), Some((Role::Signer, 1))); - assert_eq!(role_of(signer_badge(0)), None); - assert_eq!(role_of(signer_badge(2)), None, "no frame pair is mapped for a second caller"); - assert_eq!(role_of(reader_badge(1)), Some((Role::Reader, 1))); - assert_eq!(role_of(1), None); - assert_eq!(role_of(u64::MAX), None); +fn badges_map_to_fixed_roles_and_frames() { + let caller = |role, request, response| Some(Caller { role, request, response }); + assert_eq!(caller_of(0), None, "a call without a badge has no role"); + assert_eq!(caller_of(ADMIN_BADGE), caller(Role::Admin, Some(0), 0)); + assert_eq!(caller_of(ADMIN_BADGE | 1), None); + assert_eq!(caller_of(signer_badge(1)), caller(Role::Signer, Some(1), 1)); + assert_eq!(caller_of(signer_badge(0)), None); + assert_eq!(caller_of(signer_badge(2)), None, "no frame pair is mapped for a second caller"); + assert_eq!(caller_of(reader_badge(1)), caller(Role::Reader, Some(1), 1)); + // 운영자에게는 요청 프레임이 없고, 응답 프레임은 누구의 것과도 겹치지 않음 + assert_eq!(caller_of(OPERATOR_BADGE), caller(Role::Operator, None, OPERATOR_FRAME)); + assert_eq!(caller_of(OPERATOR_BADGE | 1), None); + assert!(OPERATOR_FRAME > MAX_CLIENTS); + assert_eq!(caller_of(1), None); + assert_eq!(caller_of(u64::MAX), None); + assert_eq!(role_of(OPERATOR_BADGE), Some(Role::Operator)); + assert_eq!(role_of(0), None); + // 네 배지는 서로 다름 + let all = [ADMIN_BADGE, OPERATOR_BADGE, SIGNER, READER]; + for (i, a) in all.iter().enumerate() { + assert!(all[i + 1..].iter().all(|b| a != b)); + } } #[test] -fn policy_is_enforced_before_anything_else() { - let mut v = ready(); - let msg = b"m"; - for (badge, op) in [ - (0, request::STATUS), - (0, request::SIGN), - (0x99, request::SIGN), - (READER, request::SIGN), - (ADMIN_BADGE, request::SIGN), - (ADMIN_BADGE, request::PUBLIC_KEY), - (SIGNER, request::INIT), - (SIGNER, request::ZEROIZE), - (READER, request::ZEROIZE), - ] { - let (r, out) = call(&mut v, badge, op, alg::ED25519, msg); - assert_eq!(r[0], status::DENIED, "badge {badge:#x} op {op}"); - assert!(out.is_empty()); +fn each_role_may_do_exactly_its_operations() { + use request::{INIT, KEYGEN, PUBLIC_KEY, SIGN, STATUS, ZEROIZE}; + let table: [(u64, &[u64]); 4] = [ + (ADMIN_BADGE, &[STATUS, INIT, KEYGEN, ZEROIZE]), + (OPERATOR, &[STATUS, PUBLIC_KEY, KEYGEN, ZEROIZE]), + (SIGNER, &[STATUS, PUBLIC_KEY, SIGN]), + (READER, &[STATUS, PUBLIC_KEY]), + ]; + for (badge, may) in table { + for op in OPS { + // 거부는 볼트의 상태와 무관해야 하므로 상태마다 확인함. 요청은 그 + // 연산에 맞는 모양으로 보냄(잘못된 모양은 다른 까닭으로 거부되므로) + for stage in 0..3 { + let mut v = Vault::new(); + let seed = init_body([7; 32], GOOD_INFO); + if stage >= 1 { + call(&mut v, ADMIN_BADGE, INIT, alg::NONE, &seed); + } + if stage >= 2 { + call(&mut v, ADMIN_BADGE, KEYGEN, alg::ED25519, &[]); + } + let body: &[u8] = match op { + INIT => &seed, + SIGN => b"m", + _ => &[], + }; + let (r, out) = call(&mut v, badge, op, alg::ED25519, body); + if may.contains(&op) { + // 시드는 한 번만 받으므로, 이미 받은 볼트는 관리자의 두 번째 + // 시드도 같은 상태 값으로 거절함. 그 밖에는 거절이 아니어야 함 + if !(op == INIT && stage >= 1) { + assert_ne!(r[0], status::DENIED, "badge {badge:#x} op {op} stage {stage}"); + } + } else { + assert_eq!(r[0], status::DENIED, "badge {badge:#x} op {op} stage {stage}"); + assert!(out.is_empty()); + } + } + } + } +} + +#[test] +fn no_frame_is_touched_for_a_request_that_cannot_have_a_body() { + let word = |op| request::word(op, alg::ED25519); + // 본문이 있는 연산에서, 요청 프레임이 있는 호출자가 길이를 말했을 때만 읽음 + assert_eq!(fetch_plan(SIGNER, &[word(request::SIGN), 5, 0, 0]), Some((1, 5))); + assert_eq!(fetch_plan(ADMIN_BADGE, &[word(request::INIT), 40, 0, 0]), Some((0, 40))); + assert_eq!(fetch_plan(SIGNER, &[word(request::SIGN), 0, 0, 0]), None); + // 운영자는 어떤 연산과 길이로도 프레임을 읽히지 못함 + for op in 0..=255u64 { + for len in [0, 1, 40, 1024, u64::MAX] { + assert_eq!(fetch_plan(OPERATOR, &[word(op), len, 0, 0]), None, "op {op} len {len}"); + } } - // 거부된 요청들은 볼트의 상태를 바꾸지 않았음 - assert_eq!(call(&mut v, SIGNER, request::STATUS, alg::NONE, &[]).0[1], state::READY); + // 본문이 없는 연산은 누가 길이를 말해도 읽지 않음 + for badge in [ADMIN_BADGE, SIGNER, READER] { + for op in [request::STATUS, request::PUBLIC_KEY, request::ZEROIZE, request::KEYGEN, 0, 9] { + assert_eq!(fetch_plan(badge, &[word(op), 7, 0, 0]), None, "badge {badge:#x} op {op}"); + } + } + // 모르는 배지와 배지 없는 호출 + for badge in [0, 1, 0x99, u64::MAX] { + assert_eq!(fetch_plan(badge, &[word(request::SIGN), 5, 0, 0]), None); + assert_eq!(publish_plan(badge, &[word(request::SIGN), 5, 0, 0], status::OK), None); + } + // 응답 프레임에는 응답 본문이 있는 연산이 성공했을 때만 씀 + assert_eq!(publish_plan(SIGNER, &[word(request::SIGN), 5, 0, 0], status::OK), Some(1)); + assert_eq!(publish_plan(READER, &[word(request::PUBLIC_KEY), 0, 0, 0], status::OK), Some(1)); + assert_eq!(publish_plan(OPERATOR, &[word(request::PUBLIC_KEY), 0, 0, 0], status::OK), Some(OPERATOR_FRAME)); + assert_eq!(publish_plan(SIGNER, &[word(request::SIGN), 5, 0, 0], status::DENIED), None); + for op in [request::STATUS, request::INIT, request::ZEROIZE, request::KEYGEN] { + for badge in [ADMIN_BADGE, OPERATOR, SIGNER, READER] { + assert_eq!(publish_plan(badge, &[word(op), 0, 0, 0], status::OK), None); + } + } +} + +#[test] +fn a_request_that_claims_a_body_it_cannot_have_is_refused() { + // 요청 프레임이 없는 운영자가 길이를 말하면 볼트는 아무것도 읽지 않고 + // 빈 본문으로 처리하므로, 말한 길이와 맞지 않아 거부됨 + let mut out = [0u8; MAX_RESPONSE]; + for op in OPS { + for len in [1, 40, 1024, u64::MAX] { + let mut v = seeded(); + let r = v.handle(OPERATOR, [request::word(op, alg::ED25519), len, 7, 0], &[], &mut out); + assert_eq!((r[0], r[3]), (status::BAD_REQUEST, 7), "op {op} len {len}"); + assert_eq!(state_of(&mut v), seeded_state()); + } + } + // 본문이 없는 연산에 본문이 오면 거부함 + for op in [request::STATUS, request::PUBLIC_KEY, request::ZEROIZE, request::KEYGEN] { + let mut v = seeded(); + let (r, _) = call(&mut v, ADMIN_BADGE, op, alg::ED25519, b"x"); + assert!(matches!(r[0], status::BAD_REQUEST | status::DENIED), "op {op}: {}", r[0]); + assert_eq!(state_of(&mut v), seeded_state()); + } +} + +/// [seeded]가 만드는 볼트의 상태(알고리즘이 없는 이미지에서는 시드를 받지 않음) +fn seeded_state() -> u64 { + if cfg!(feature = "ed25519") { state::SEEDED } else { state::FRESH } +} + +#[test] +fn the_status_word_packs_state_algorithm_and_what_is_built() { + assert_eq!(status_word::pack(state::SEEDED, alg::NONE, 0), state::SEEDED); + let w = status_word::pack(state::READY, alg::ED25519, 1 << alg::ED25519); + assert_eq!(w, 0x0002_0101); + assert_eq!( + (status_word::state(w), status_word::key_alg(w), status_word::built(w)), + (state::READY, alg::ED25519, 2) + ); + // 볼트는 어느 상태에서든 이미지에 든 알고리즘을 알림 + let built = if cfg!(feature = "ed25519") { 1 << alg::ED25519 } else { 0 }; + for mut v in [Vault::new(), seeded(), Vault::failed_for_test()] { + let (r, _) = call(&mut v, READER, request::STATUS, alg::NONE, &[]); + assert_eq!(status_word::built(r[1]), built); + assert_eq!(status_word::key_alg(r[1]), alg::NONE); + } +} + +#[test] +fn a_call_without_a_known_badge_is_denied() { + let mut v = seeded(); + for badge in [0, 0x99, ADMIN_BADGE | 1, OPERATOR_BADGE | 1, signer_badge(2), u64::MAX] { + for op in OPS { + let (r, out) = call(&mut v, badge, op, alg::ED25519, &[]); + assert_eq!(r[0], status::DENIED, "badge {badge:#x} op {op}"); + assert!(out.is_empty()); + } + } + assert_eq!(state_of(&mut v), seeded_state()); } #[test] fn malformed_requests_are_refused_whole() { - let mut v = ready(); + let mut v = seeded(); let mut out = [0u8; MAX_RESPONSE]; let ok = request::word(request::SIGN, alg::ED25519); // 예약 비트, 쓰지 않는 레지스터, 모르는 연산, 말한 길이와 다른 본문 @@ -90,12 +252,21 @@ fn a_seed_without_real_entropy_makes_no_key() { let mut v = Vault::new(); let (r, _) = call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &init_body([1; 32], info)); assert_eq!(r[0], status::NO_ENTROPY, "info {info}"); - assert_eq!(call(&mut v, SIGNER, request::STATUS, alg::NONE, &[]).0[1], state::FRESH); + assert_eq!(state_of(&mut v), state::FRESH); + assert!(!v.holds_a_secret()); + // 시드를 받지 못한 볼트에 키를 만들라고 하면 같은 까닭으로 거절함 + let (r, _) = call(&mut v, OPERATOR, request::KEYGEN, alg::ED25519, &[]); + let want = if cfg!(feature = "ed25519") { status::NO_ENTROPY } else { status::UNSUPPORTED }; + assert_eq!(r[0], want); + } + // 전부 0인 시드는 재료 정보가 무엇이라 하든 받지 않음(이미 지워진 시드가 + // 다시 넘어온 경우). 받아들이면 누구나 아는 키가 만들어짐 + for info in [GOOD_INFO, SEED_RNDR, GOOD_INFO | SEED_RNDR] { + let mut v = Vault::new(); + let (r, _) = call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &init_body([0; 32], info)); + assert_eq!(r[0], status::NO_ENTROPY); + assert_eq!(state_of(&mut v), state::FRESH); } - let mut v = Vault::new(); - let (r, _) = call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &init_body([1; 32], SEED_RNDR)); - assert_eq!(r[0], status::OK); - assert_eq!(r[2] & (indicator::SEED_RNDR | indicator::SEED_RNG_SEED), indicator::SEED_RNDR); // 길이가 다른 INIT 본문 let mut v = Vault::new(); let (r, _) = call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &[1; 39]); @@ -103,15 +274,28 @@ fn a_seed_without_real_entropy_makes_no_key() { } #[test] -fn init_happens_once_and_zeroize_is_final() { - let mut v = ready(); +fn the_seed_is_taken_once_and_zeroize_is_final() { + let mut v = seeded(); let (r, _) = call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &init_body([9; 32], GOOD_INFO)); - assert_eq!(r[0], status::DENIED, "a second key cannot replace the first"); - let (r, _) = call(&mut v, ADMIN_BADGE, request::ZEROIZE, alg::NONE, &[]); + if cfg!(feature = "ed25519") { + assert_eq!(r[0], status::DENIED, "a second seed cannot replace the first"); + assert!(v.holds_a_secret()); + } + // 운영자도 지울 수 있고, 시드만 쥔 상태에서도 지워짐 + let (r, _) = call(&mut v, OPERATOR, request::ZEROIZE, alg::NONE, &[]); assert_eq!(r[0], status::OK); - assert_eq!(call(&mut v, SIGNER, request::STATUS, alg::NONE, &[]).0[1], state::ZEROIZED); + assert_eq!(state_of(&mut v), state::ZEROIZED); + assert!(!v.holds_a_secret()); + // 지운 뒤에는 시드도 키 생성도 받지 않고, 다시 지우는 것은 그대로 성공함 let (r, _) = call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &init_body([9; 32], GOOD_INFO)); assert_eq!(r[0], status::DENIED); + let (r, _) = call(&mut v, OPERATOR, request::KEYGEN, alg::ED25519, &[]); + let want = if cfg!(feature = "ed25519") { status::ZEROIZED } else { status::UNSUPPORTED }; + assert_eq!(r[0], want); + assert_eq!(call(&mut v, ADMIN_BADGE, request::ZEROIZE, alg::NONE, &[]).0[0], status::OK); + // 지워진 볼트는 시드의 재료도 더는 알리지 않음 + let (r, _) = call(&mut v, READER, request::STATUS, alg::NONE, &[]); + assert_eq!(r[2] & (indicator::SEED_RNG_SEED | indicator::SEED_RNDR), 0); } #[test] @@ -145,15 +329,98 @@ mod ed25519 { assert!(provider::self_test()); let mut v = Vault::new(); let (r, _) = call(&mut v, READER, request::STATUS, alg::NONE, &[]); - assert_eq!((r[0], r[1]), (status::OK, state::FRESH)); + assert_eq!((r[0], status_word::state(r[1])), (status::OK, state::FRESH)); assert_eq!(r[2], indicator::SELF_TEST_PASSED); } + #[test] + fn key_generation_follows_the_states() { + use k0_abi::bootinfo::SEED_RNDR; + // 시드를 쥔 볼트는 그 재료를 상태 조회로 알림. 키는 아직 없음 + let mut v = Vault::new(); + let info = GOOD_INFO | SEED_RNDR; + assert_eq!(call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &init_body([7; 32], info)).0[0], status::OK); + let (r, _) = call(&mut v, OPERATOR, request::STATUS, alg::NONE, &[]); + assert_eq!((status_word::state(r[1]), status_word::key_alg(r[1])), (state::SEEDED, alg::NONE)); + let both = indicator::SEED_RNG_SEED | indicator::SEED_RNDR; + assert_eq!(r[2], indicator::SELF_TEST_PASSED | both); + assert!(v.holds_a_secret()); + for badge in [SIGNER, READER, OPERATOR] { + assert_eq!(call(&mut v, badge, request::PUBLIC_KEY, alg::ED25519, &[]).0[0], status::NOT_READY); + } + assert_eq!(call(&mut v, SIGNER, request::SIGN, alg::ED25519, b"m").0[0], status::NOT_READY); + + // 이미지에 없는 알고리즘을 고르면 거절하고 시드는 그대로 쥠 + for algo in [alg::NONE, 2, 15, 0xFF] { + let (r, _) = call(&mut v, OPERATOR, request::KEYGEN, algo, &[]); + assert_eq!(r[0], status::UNSUPPORTED, "alg {algo}"); + } + assert_eq!(state_of(&mut v), state::SEEDED); + + // 운영자가 키를 만들게 함. 시드는 지워지고 그 재료의 표시는 키의 것이 됨 + let (r, _) = call(&mut v, OPERATOR, request::KEYGEN, alg::ED25519, &[]); + assert_eq!((r[0], r[1]), (status::OK, 0)); + let (r, _) = call(&mut v, OPERATOR, request::STATUS, alg::NONE, &[]); + assert_eq!((status_word::state(r[1]), status_word::key_alg(r[1])), (state::READY, alg::ED25519)); + assert_eq!(r[2], indicator::SELF_TEST_PASSED | both); + // 키는 그 시드에서 나옴 + let (_, public) = call(&mut v, OPERATOR, request::PUBLIC_KEY, alg::ED25519, &[]); + let direct = ed25519_dalek::SigningKey::from_bytes(&[7; 32]).verifying_key().to_bytes(); + assert_eq!(public, direct); + + // 부팅당 키 하나: 누구도 두 번째 키를 만들지 못함 + for badge in [OPERATOR, ADMIN_BADGE] { + assert_eq!(call(&mut v, badge, request::KEYGEN, alg::ED25519, &[]).0[0], status::KEY_EXISTS); + } + let (_, again) = call(&mut v, READER, request::PUBLIC_KEY, alg::ED25519, &[]); + assert_eq!(again, direct); + + // 관리자도 키를 만들게 할 수 있음(터미널이 없는 이미지의 자가 검증) + let mut v = seeded(); + assert_eq!(call(&mut v, ADMIN_BADGE, request::KEYGEN, alg::ED25519, &[]).0[0], status::OK); + assert_eq!(state_of(&mut v), state::READY); + } + + #[test] + fn the_operator_gets_the_public_key_and_never_a_signature() { + let mut v = ready(); + let (r, public) = call(&mut v, OPERATOR, request::PUBLIC_KEY, alg::ED25519, &[]); + assert_eq!((r[0], public.len()), (status::OK, 32)); + for body in [&b"m"[..], &[], &[0u8; MAX_MESSAGE]] { + let (r, out) = call(&mut v, OPERATOR, request::SIGN, alg::ED25519, body); + assert_eq!(r[0], status::DENIED); + assert!(out.is_empty()); + } + // 운영자는 시드를 넘기지도 못함 + let mut fresh = Vault::new(); + let (r, _) = call(&mut fresh, OPERATOR, request::INIT, alg::NONE, &init_body([7; 32], GOOD_INFO)); + assert_eq!(r[0], status::DENIED); + assert!(!fresh.holds_a_secret()); + } + + #[test] + fn a_vault_that_fails_holds_no_secret() { + // 시드를 쥔 채로, 그리고 키를 쥔 채로 오류 상태에 들어가는 경우 + for mut v in [seeded(), ready()] { + assert!(v.holds_a_secret()); + v.fail_for_test(); + assert!(!v.holds_a_secret()); + let (r, _) = call(&mut v, OPERATOR, request::STATUS, alg::NONE, &[]); + assert_eq!((status_word::state(r[1]), status_word::key_alg(r[1]), r[2]), (state::FAILED, alg::NONE, 0)); + for op in [request::KEYGEN, request::ZEROIZE, request::PUBLIC_KEY] { + assert_eq!(call(&mut v, OPERATOR, op, alg::ED25519, &[]).0[0], status::FAILED); + } + } + } + #[test] fn signatures_verify_and_the_key_follows_the_seed() { let mut v = Vault::new(); let (r, _) = call(&mut v, SIGNER, request::SIGN, alg::ED25519, b"too early"); assert_eq!(r[0], status::NOT_READY); + let mut v = seeded(); + let (r, _) = call(&mut v, SIGNER, request::SIGN, alg::ED25519, b"still too early"); + assert_eq!(r[0], status::NOT_READY); let mut v = ready(); let (r, public) = call(&mut v, READER, request::PUBLIC_KEY, alg::ED25519, &[]); assert_eq!((r[0], r[1]), (status::OK, 32)); @@ -226,7 +493,7 @@ mod ed25519 { fn a_failed_vault_refuses_everything_but_status() { let mut v = Vault::failed_for_test(); let (r, _) = call(&mut v, SIGNER, request::STATUS, alg::NONE, &[]); - assert_eq!((r[0], r[1], r[2]), (status::OK, state::FAILED, 0)); + assert_eq!((r[0], status_word::state(r[1]), r[2]), (status::OK, state::FAILED, 0)); assert_eq!(call(&mut v, SIGNER, request::SIGN, alg::ED25519, b"m").0[0], status::FAILED); assert_eq!(call(&mut v, READER, request::PUBLIC_KEY, alg::ED25519, &[]).0[0], status::FAILED); let init = init_body([7; 32], GOOD_INFO); @@ -237,9 +504,19 @@ mod ed25519 { #[cfg(not(feature = "ed25519"))] #[test] -fn without_an_algorithm_every_signing_request_is_unsupported() { - let mut v = ready(); +fn without_an_algorithm_the_vault_takes_no_seed_and_serves_nothing() { + // 쓸 일이 없는 비밀은 쥐지 않음: 시드를 받지 않고 처음 상태로 남음 + let mut v = seeded(); + assert!(!v.holds_a_secret()); + assert_eq!(state_of(&mut v), state::FRESH); + for badge in [OPERATOR, ADMIN_BADGE] { + assert_eq!(call(&mut v, badge, request::KEYGEN, alg::ED25519, &[]).0[0], status::UNSUPPORTED); + } assert_eq!(call(&mut v, SIGNER, request::SIGN, alg::ED25519, b"m").0[0], status::UNSUPPORTED); assert_eq!(call(&mut v, READER, request::PUBLIC_KEY, alg::ED25519, &[]).0[0], status::UNSUPPORTED); - assert_eq!(call(&mut v, READER, request::STATUS, alg::NONE, &[]).0[0], status::OK); + let (r, _) = call(&mut v, READER, request::STATUS, alg::NONE, &[]); + assert_eq!((r[0], status_word::built(r[1]), status_word::key_alg(r[1])), (status::OK, 0, alg::NONE)); + // 지우는 것은 여기서도 됨 + assert_eq!(call(&mut v, OPERATOR, request::ZEROIZE, alg::NONE, &[]).0[0], status::OK); + assert_eq!(state_of(&mut v), state::ZEROIZED); } diff --git a/userspace/root-task/Cargo.toml b/userspace/root-task/Cargo.toml index fff6685..a9edf5e 100644 --- a/userspace/root-task/Cargo.toml +++ b/userspace/root-task/Cargo.toml @@ -8,9 +8,17 @@ publish.workspace = true [dependencies] k0-abi = { path = "../../crates/k0-abi" } k0-vault = { path = "../k0-vault", optional = true } +k0-term = { path = "../k0-term", optional = true } # 키 볼트(서명 오라클)는 선택 기능입니다. `vault`는 서비스와 그 자가 검증을 # 넣고, 알고리즘은 따로 더합니다. 아무것도 기본으로 켜지지 않습니다. +# +# `console-input`은 커널에 콘솔 입력 경로가 있다는 뜻이고(커널의 같은 이름 +# feature가 넘김) 입력 시스템 콜의 자가 검증을 넣습니다. `terminal`은 운영자 +# 터미널을 넣어 자가 검증 뒤에 서비스로 시작합니다. 볼트가 함께 있으면 +# 터미널이 볼트의 운영자 역할을 맡습니다. [features] -vault = ["dep:k0-vault"] +vault = ["dep:k0-vault", "k0-term?/vault"] vault-ed25519 = ["vault", "k0-vault/ed25519"] +console-input = [] +terminal = ["console-input", "dep:k0-term"] diff --git a/userspace/root-task/src/main.rs b/userspace/root-task/src/main.rs index 03661fa..c98a29c 100644 --- a/userspace/root-task/src/main.rs +++ b/userspace/root-task/src/main.rs @@ -38,6 +38,8 @@ use core::sync::atomic::{AtomicU64, Ordering}; #[cfg(feature = "vault")] mod oracle; +#[cfg(feature = "terminal")] +mod service; use k0_abi::bootinfo::slot; use k0_abi::{bootinfo, err, ipc, obj, perm, rights, syscall}; @@ -160,6 +162,32 @@ fn putc(slot: u64, b: u8) -> i64 { sys(syscall::DEBUG_PUTC, [slot, u64::from(b), 0, 0, 0, 0]) as i64 } +/// 콘솔 입력에서 바이트 하나를 읽는 함수입니다. (상태, 바이트, 유실 표시)를 +/// 돌려줍니다. 커널에 콘솔 입력 경로가 있는 이미지에서만 부를 수 있습니다. +/// +/// static을 쓰지 않으므로 격리된 태스크에서도 부를 수 있습니다. +/// +/// # Arguments +/// `slot` - 읽기 권한이 있는 Console 슬롯 +/// `flags` - [k0_abi::console]의 플래그와 타임아웃 +#[cfg(feature = "console-input")] +#[inline(always)] +fn console_read(slot: u64, flags: u64) -> (i64, u8, bool) { + let (status, byte, lost): (u64, u64, u64); + // SAFETY: svc는 커널로의 동기 트랩이고 커널이 컨텍스트 전체를 복원함 + unsafe { + asm!( + "svc #0", + in("x8") syscall::CONSOLE_READ, + inlateout("x0") slot => status, + inlateout("x1") flags => byte, + lateout("x2") lost, + options(nostack), + ); + } + (status as i64, byte as u8, lost & k0_abi::console::LOST != 0) +} + fn put_str(s: &str) { for b in s.bytes() { putc(slot::CONSOLE, b); @@ -708,15 +736,17 @@ static BOOT_SEED: [AtomicU64; 4] = [ ]; static SEED_INFO: AtomicU64 = AtomicU64::new(0); -/// 부트 시드를 꺼내고 보관하던 자리를 지우는 함수입니다. 두 번째부터는 0만 -/// 나옵니다. +/// 부트 시드와 그 재료 정보를 꺼내고 보관하던 자리를 지우는 함수입니다. 두 +/// 번째부터는 시드도 정보도 0만 나옵니다. 정보까지 지우는 까닭은, 이미 꺼낸 +/// 시드(전부 0)가 "재료가 충분함"이라는 정보와 함께 다시 넘어가 누구나 아는 +/// 키가 만들어지는 일을 막기 위해서입니다. #[allow(dead_code)] fn take_boot_seed() -> ([u8; 32], u64) { let mut seed = [0u8; 32]; for (chunk, word) in seed.chunks_exact_mut(8).zip(&BOOT_SEED) { chunk.copy_from_slice(&word.swap(0, Ordering::Relaxed).to_le_bytes()); } - (seed, SEED_INFO.load(Ordering::Relaxed)) + (seed, SEED_INFO.swap(0, Ordering::Relaxed)) } #[unsafe(no_mangle)] @@ -747,8 +777,9 @@ extern "C" fn _start(s0: u64, s1: u64, s2: u64, s3: u64, seed_info: u64) -> ! { put_str("root: boot seed from rng-seed bytes "); put_hex(seed_info & bootinfo::SEED_RNG_SEED_BYTES); put_str(if seed_info & bootinfo::SEED_RNDR != 0 { " and rndr\n" } else { " without rndr\n" }); - // 시드를 쓸 서비스가 없는 이미지에서는 보관하지 않고 바로 지움 - #[cfg(not(feature = "vault"))] + // 시드를 쓰는 것은 서비스의 볼트뿐임(자가 검증의 볼트는 공개 시험 시드를 + // 씀). 그 서비스가 없는 이미지에서는 보관하지 않고 바로 지움 + #[cfg(not(all(feature = "vault", feature = "terminal")))] let _ = take_boot_seed(); check( "bootinfo frame size", @@ -822,15 +853,199 @@ extern "C" fn _start(s0: u64, s1: u64, s2: u64, s3: u64, seed_info: u64) -> ! { test_sched_ipc_fault(&b); test_isolation(&b); #[cfg(feature = "vault")] - oracle::test_oracle(&b); + oracle::test_oracle(&b, seed_info); test_reserve(&b); + // 입력을 처음 읽으면 커널이 주기적인 틱 줄을 멈추므로, 틱 줄을 세는 검증이 + // 모두 끝난 뒤인 맨 마지막에 돌림 + #[cfg(feature = "console-input")] + test_console_input(&b); put_str("root: sched tests pass\n"); + // 자가 검증을 모두 통과한 뒤에만 서비스를 시작함. 시작했으면 돌아오지 않음 + #[cfg(feature = "terminal")] + service::start(&b); loop { yield_now(); } } +/// 앞의 검증들이 쓰지 않는 untyped 가운데 가장 큰 것을 고르는 함수입니다. 그런 +/// 것이 없으면 0입니다. 볼트 검증, 입력 검증, 서비스가 차례로 씁니다(앞의 +/// 검증들은 주 untyped를 거의 다 쓰기도 함). +#[allow(dead_code)] +fn spare_untyped(b: &Boot) -> u64 { + // SAFETY: 커널이 이 VA에 bootinfo 페이지를 RO로 매핑하고 내용을 채웠음 + let cap_count = unsafe { (*(bootinfo::VA as *const bootinfo::Header)).cap_count }; + let (mut best, mut best_frames) = (0, 0); + for i in 0..cap_count { + let d = desc(i); + if d.kind != bootinfo::cap_kind::UNTYPED || i == b.ut_main || i == b.ut_small || i == b.ut_reuse { + continue; + } + let n = frames_in(d, b.frame_size); + if n >= 512 && n > best_frames { + best = i; + best_frames = n; + } + } + best +} + +/// 자가 검증의 끝과 그 뒤의 서비스가 오브젝트를 만들 untyped를 고르는 +/// 함수입니다. 앞의 검증들이 쓰지 않는 큰 untyped가 있으면 그것을, 없으면 주 +/// untyped를 씁니다. 주 untyped에는 커널 예약 검증이 이 단계의 몫을 남겨 +/// 둡니다([test_reserve]). +#[allow(dead_code)] +fn late_untyped(b: &Boot) -> u64 { + match spare_untyped(b) { + 0 => b.ut_main, + spare => spare, + } +} + +/// 콘솔 입력을 기다리다 그 결과를 [INPUT_SEEN]에 적는 자식 스레드의 +/// 진입점입니다. +/// +/// # Arguments +/// `slot` - 읽을 Console 슬롯 +#[cfg(feature = "console-input")] +extern "C" fn input_waiter_entry(slot: u64) -> ! { + INPUT_SEEN.store(INPUT_WAITING, Ordering::Relaxed); + let (status, _, _) = console_read(slot, 0); + INPUT_SEEN.store(status as u64, Ordering::Relaxed); + sys1(syscall::EXIT, 0); + loop { + core::hint::spin_loop(); + } +} + +/// [input_waiter_entry]가 본 상태. 기다리는 동안은 [INPUT_WAITING] +#[cfg(feature = "console-input")] +static INPUT_SEEN: AtomicU64 = AtomicU64::new(0); +#[cfg(feature = "console-input")] +const INPUT_WAITING: u64 = 0x1D1E; + +/// 콘솔 입력 시스템 콜의 권한과 대기를 검증하는 함수입니다. +/// +/// 누가 읽을 수 있는지(읽기 권한이 있는 Console 케이퍼빌리티만), 대기자 자리가 +/// 하나뿐인 것, 기한, 대기자의 삭제와 권한 회수를 봅니다. 직렬 선은 커널 +/// 밖의 것이라 이 검증 도중에 바이트가 들어올 수 있습니다. 그런 경우는 +/// 실패로 치지 않고 그 뒤의 검증을 건너뛴 뒤 한 줄로 알립니다(바이트 하나로 +/// 자가 검증이 실패해 서비스가 뜨지 않으면 안 됨). +#[cfg(feature = "console-input")] +fn test_console_input(b: &Boot) { + use k0_abi::console::{FLUSH, NONBLOCK}; + let (ut, fs) = (late_untyped(b), b.frame_size); + let con = slot::CONSOLE as i64; + + // 출력만 남긴 복사본: 읽지 못하고 백스페이스도 `?`로 바뀜 + let wo = copy_here(con, rights::W, 0); + check("console copy w", wo > 0); + check("read needs the input right", console_read(wo as u64, NONBLOCK).0 == err::NO_RIGHTS); + put_str("root: backspace without the input right ["); + check("putc bs w-only", putc(wo as u64, 0x08) == 0); + put_str("]\n"); + // 입력만 남긴 복사본: 출력하지 못함. 권한은 복사로 되살릴 수 없음 + let ro = copy_here(con, rights::R, 0); + check("console copy r", ro > 0); + check("write needs the output right", putc(ro as u64, b'x') == err::NO_RIGHTS); + check("rights do not come back", copy_here(wo, rights::R, 0) == err::NO_RIGHTS as i64); + check("rights do not come back", copy_here(ro, rights::W, 0) == err::NO_RIGHTS as i64); + // 거부 경로는 받아 둔 입력을 건드리지 않음 + check("read bad cap", console_read(slot::ADDR_SPACE, NONBLOCK).0 == err::BAD_CAP); + check("read bad slot", console_read(9999, NONBLOCK).0 == err::BAD_SLOT); + check("read null slot", console_read(0, NONBLOCK).0 == err::BAD_SLOT); + check("read reserved flags", console_read(slot::CONSOLE, 4 | NONBLOCK).0 == err::BAD_FLAGS); + + let first = console_read(slot::CONSOLE, NONBLOCK | FLUSH).0; + if first == err::NO_DEVICE { + // 수신 드라이버가 없는 UART이거나 인터럽트를 쓸 수 없는 기계 + check("no input path", console_read(ro as u64, 0).0 == err::NO_DEVICE); + put_str("root: console input tests pass (no input path)\n"); + return; + } + let busy_line = || put_str("root: console input tests cut short (the line is busy)\n"); + if first != err::WOULD_BLOCK { + check("first read", first == 0); + return busy_line(); + } + // 기한이 있는 읽기는 입력이 없으면 기한에 끝남 + match console_read(ro as u64, FLUSH | ipc::timeout(1)).0 { + 0 => return busy_line(), + e => check("read times out", e == err::TIMEOUT), + } + + // 대기자 자리는 하나: 자식이 기다리는 동안 다른 읽기는 BUSY + let stack = retype(ut, obj::FRAME); + check("input waiter stack", stack > 0); + check("input waiter stack map", map(stack, TEST_VA + 0x70 * 0x4000, perm::RW) == 0); + let sp = TEST_VA + 0x70 * 0x4000 + fs; + let waiter = |slot: i64| { + INPUT_SEEN.store(0, Ordering::Relaxed); + let tcb = retype(ut, obj::TCB); + check( + "input waiter", + tcb > 0 + && tcb_configure(tcb, input_waiter_entry as usize as u64, sp, slot::ADDR_SPACE as i64, slot::CNODE as i64, slot as u64) + == 0 + && tcb_resume(tcb) == 0, + ); + for _ in 0..8 { + yield_now(); + } + tcb + }; + // 여기서부터는 직렬 선에서 바이트 하나가 들어오면 결과가 달라짐(기다리던 + // 자식이 그 바이트를 받아 자리가 비거나, 링에 바이트가 남음). 그런 경우는 + // 실패가 아니므로 만든 것을 치우고 건너뜀 + let still_waiting = || INPUT_SEEN.load(Ordering::Relaxed) == INPUT_WAITING; + let empty = || console_read(slot::CONSOLE, NONBLOCK | FLUSH).0 == err::WOULD_BLOCK; + let child = waiter(ro); + let busy = still_waiting() + && console_read(slot::CONSOLE, NONBLOCK).0 == err::BUSY + && console_read(slot::CONSOLE, ipc::timeout(1)).0 == err::BUSY; + // 기다리던 태스크를 삭제하면 자리가 빔 + check("delete the waiter", cap_delete(child) == 0); + if !busy || !empty() { + check("input stack unmap", unmap(stack) == 0); + return busy_line(); + } + + // 기다리는 동안 그 케이퍼빌리티를 잃은 태스크는 곧바로 REVOKED로 깨어남. + // 삭제와 이동 둘 다 그러함 + for by_move in [false, true] { + let lease = copy_here(con, rights::R, 0); + check("console lease", lease > 0); + let child = waiter(lease); + let waiting = still_waiting(); + let taken = if by_move { + let away = alloc_slot(); + let moved = cap_move(lease, slot::CNODE as i64, away) == 0; + check("console lease moved", moved); + away as i64 + } else { + check("take the lease back", cap_delete(lease) == 0); + 0 + }; + for _ in 0..8 { + yield_now(); + } + let seen = INPUT_SEEN.load(Ordering::Relaxed); + check("input waiter delete", cap_delete(child) == 0); + if taken != 0 { + check("moved lease delete", cap_delete(taken) == 0); + } + if !waiting || seen != err::REVOKED as u64 || !empty() { + // 자식이 바이트를 받고 끝났으면 0이 보임. 그 밖의 값은 진짜 실패임 + check("waiter saw the revocation or a byte", !waiting || seen == 0 || seen == err::REVOKED as u64); + check("input stack unmap", unmap(stack) == 0); + return busy_line(); + } + } + check("input stack unmap", unmap(stack) == 0); + put_str("root: console input tests pass\n"); +} + /// 콘솔 거부 경로와 제어 문자 필터를 검증하는 함수입니다. fn test_console() { let con = slot::CONSOLE; @@ -1994,8 +2209,16 @@ fn test_reserve(b: &Boot) { // 남짓이었으므로 40구획을 넘기면 반드시 바닥났음. untyped가 그보다 작은 // 배치에서는 끝까지 감 let per_table = fs / 8; + // 이 검증 뒤에 오브젝트를 더 만드는 이미지(입력 검증, 서비스)에서는 주 + // untyped의 절반까지만 걸어 그 몫을 남김. 그래뉼이 큰 배치에서는 40구획이 + // untyped보다 커서, 끝까지 걸으면 뒤에 쓸 메모리가 없음 + let limit = if cfg!(feature = "console-input") { + (40 * per_table).min(frames_in(desc(ut), fs) / 2) + } else { + 40 * per_table + }; let mut walked = 0u64; - while walked < 40 * per_table { + while walked < limit { let r = retype_at(ut, obj::FRAME, tmp); if r == err::EXHAUSTED { break; diff --git a/userspace/root-task/src/oracle.rs b/userspace/root-task/src/oracle.rs index 6f454e1..4c98413 100644 --- a/userspace/root-task/src/oracle.rs +++ b/userspace/root-task/src/oracle.rs @@ -16,25 +16,39 @@ //! 격리 태스크에는 이미지의 `.data`와 `.bss`가 매핑되지 않으므로, 볼트와 //! 클라이언트의 진입점에서는 static을 쓰지 않습니다(출력과 `check`도 못 씀). //! 결과는 보고용 엔드포인트로 루트에 알립니다. +//! +//! 이 자가 검증의 볼트는 RFC 8032에 실린 공개 시험 벡터의 시드로 키를 +//! 만듭니다. 커널이 준 진짜 부트 시드는 여기서 쓰지 않습니다(서비스의 볼트가 +//! 한 번만 씀). 그래서 이 검증의 볼트와 클라이언트가 쓰던 메모리에는 비밀이 +//! 남지 않습니다. 재료가 충분한지의 판정에는 진짜 시드의 재료 정보를 그대로 +//! 씁니다. -use k0_vault::proto::{self, alg, request, state, status, MAX_MESSAGE, MAX_RESPONSE, RESPONSE_HEADER}; +use k0_vault::proto::{self, alg, request, state, status, status_word}; +use k0_vault::proto::{MAX_MESSAGE, MAX_RESPONSE, RESPONSE_HEADER}; use k0_vault::provider; use k0_vault::server::{fetch, publish, wipe, Vault}; use super::{ - call, cap_copy, cap_delete, cap_revoke, check, copy_here, desc, err, frames_in, ipc, make_aspace, map, - map_into, obj, perm, put_str, recv, reply_recv, retype, rights, send, take_boot_seed, tcb_configure, + call, cap_copy, cap_delete, cap_revoke, check, copy_here, err, ipc, make_aspace, map, + map_into, obj, perm, put_str, recv, reply_recv, retype, rights, send, spare_untyped, tcb_configure, tcb_resume, yield_now, Boot, TEST_VA, }; +/// RFC 8032 7.1절 첫 시험 벡터의 비밀키(시드). 누구나 아는 값이라 자가 검증의 +/// 볼트는 비밀을 쥐지 않습니다 +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, +]; + /// 볼트와 클라이언트의 스택(각자의 주소 공간에서 같은 VA). 곡선 연산이 깊어 /// 격리 검증의 한 장짜리 스택으로는 모자람 -const STACK_BASE: u64 = 0x52_0000; -const STACK_SIZE: u64 = 0x8000; +pub(super) const STACK_BASE: u64 = 0x52_0000; +pub(super) const STACK_SIZE: u64 = 0x8000; /// 볼트가 n번 호출자의 요청 프레임과 응답 프레임을 보는 VA(n = 0은 관리자) -const VAULT_REQ: u64 = 0x54_0000; -const VAULT_RESP: u64 = 0x58_0000; -const FRAME_STEP: u64 = 0x8000; +pub(super) const VAULT_REQ: u64 = 0x54_0000; +pub(super) const VAULT_RESP: u64 = 0x58_0000; +pub(super) const FRAME_STEP: u64 = 0x8000; /// 클라이언트가 자기 요청 프레임과 응답 프레임을 보는 VA const CLIENT_REQ: u64 = VAULT_REQ; const CLIENT_RESP: u64 = VAULT_RESP; @@ -61,7 +75,11 @@ const MODE_AFTER_ZEROIZE: u64 = 4; /// 자가 시험을 돌린 뒤 요청을 하나씩 처리합니다. 요청 본문은 호출자의 요청 /// 프레임에서 한 번만 옮겨 오고, 응답 본문은 성공했을 때만 그 호출자의 응답 /// 프레임에 씁니다. 응답 레지스터 네 개는 항상 전부 채웁니다. -extern "C" fn vault_entry(_arg: u64) -> ! { +/// +/// 어느 프레임을 읽고 쓸지는 프로토콜의 계획 함수가 배지와 연산만 보고 +/// 정합니다. 본문이 없는 연산이나 요청 프레임이 없는 호출자(운영자)의 요청은 +/// 길이를 무엇이라 말하든 어떤 프레임도 읽지 않습니다. +pub(super) extern "C" fn vault_entry(_arg: u64) -> ! { let mut vault = Vault::new(); let mut body = [0u8; MAX_MESSAGE]; let mut out = [0u8; MAX_RESPONSE]; @@ -73,25 +91,24 @@ extern "C" fn vault_entry(_arg: u64) -> ! { yield_now(); } } - let reply = match proto::role_of(r.badge) { - Some((_, index)) => { + let n = match proto::fetch_plan(r.badge, &r.mr) { + Some((index, len)) => { let req = (VAULT_REQ + index * FRAME_STEP) as *const u8; - // SAFETY: 루트가 이 호출자의 요청 프레임을 이 VA에 읽기 전용으로 - // 매핑해 두었고 버퍼는 프레임보다 작음 - let n = unsafe { fetch(req, r.mr[1], &mut body) }; - let reply = vault.handle(r.badge, r.mr, &body[..n], &mut out); - wipe(&mut body[..n]); - if reply[0] == status::OK && r.mr[0] & 0xFF != request::STATUS { - let resp = (VAULT_RESP + index * FRAME_STEP) as *mut u8; - let len = (reply[1] as usize).min(MAX_RESPONSE); - // SAFETY: 루트가 이 호출자의 응답 프레임을 이 VA에 쓰기 - // 가능으로 매핑해 두었고 프레임은 정렬돼 있음 - unsafe { publish(resp, r.mr[2], &out[..len]) }; - } - reply + // SAFETY: 요청 프레임이 있는 호출자마다 루트가 그 프레임을 이 + // VA에 읽기 전용으로 매핑해 두었고 버퍼는 프레임보다 작음 + unsafe { fetch(req, len, &mut body) } } - None => vault.handle(r.badge, r.mr, &[], &mut out), + None => 0, }; + let reply = vault.handle(r.badge, r.mr, &body[..n], &mut out); + wipe(&mut body[..n]); + if let Some(index) = proto::publish_plan(r.badge, &r.mr, reply[0]) { + let resp = (VAULT_RESP + index * FRAME_STEP) as *mut u8; + let len = (reply[1] as usize).min(MAX_RESPONSE); + // SAFETY: 응답을 받는 호출자마다 루트가 그 응답 프레임을 이 VA에 + // 쓰기 가능으로 매핑해 두었고 프레임은 정렬돼 있음 + unsafe { publish(resp, r.mr[2], &out[..len]) }; + } r = reply_recv(1, 0, reply); } } @@ -135,8 +152,10 @@ fn ask(op: u64, algo: u64, len: u64, nonce: u64) -> (u64, u64, u64) { /// 서명 클라이언트의 정상 경로 함수입니다. 실패한 단계의 번호를 주고 전부 /// 통과하면 0 fn signer_path() -> u64 { - let (st, vault_state, _) = ask(request::STATUS, alg::NONE, 0, 1); - if st != status::OK || vault_state != state::READY { + let (st, word, _) = ask(request::STATUS, alg::NONE, 0, 1); + // 알고리즘 없이 빌드한 이미지의 볼트는 시드를 받지 않아 처음 상태 그대로임 + let want = if provider::HAS_ED25519 { state::READY } else { state::FRESH }; + if st != status::OK || status_word::state(word) != want { return 1; } let msg = b"k0 signing oracle self test message"; @@ -171,9 +190,16 @@ fn signer_path() -> u64 { || ask(request::SIGN, 9, 1, 5).0 != status::UNSUPPORTED || ask(request::INIT, alg::NONE, 0, 6).0 != status::DENIED || ask(request::ZEROIZE, alg::NONE, 0, 7).0 != status::DENIED + || ask(request::KEYGEN, alg::ED25519, 0, 8).0 != status::DENIED { return 7; } + // 본문이 없는 연산에 길이를 말하면 볼트는 프레임을 읽지 않고 거부함 + if ask(request::PUBLIC_KEY, alg::ED25519, 5, 9).0 != status::BAD_REQUEST + || ask(request::STATUS, alg::NONE, 5, 10).0 != status::BAD_REQUEST + { + return 8; + } 0 } @@ -223,28 +249,8 @@ extern "C" fn client_entry(mode: u64) -> ! { } } -/// 이 검증이 쓸 untyped를 고르는 함수입니다. 다른 검증이 쓰지 않는 것 중 가장 -/// 큰 것이고, 그런 것이 없으면 0 -fn spare_untyped(b: &Boot) -> u64 { - // SAFETY: 커널이 이 VA에 bootinfo 페이지를 RO로 매핑하고 내용을 채웠음 - let cap_count = unsafe { (*(super::bootinfo::VA as *const super::bootinfo::Header)).cap_count }; - let (mut best, mut best_frames) = (0, 0); - for i in 0..cap_count { - let d = desc(i); - if d.kind != super::bootinfo::cap_kind::UNTYPED || i == b.ut_main || i == b.ut_small || i == b.ut_reuse { - continue; - } - let n = frames_in(d, b.frame_size); - if n >= 512 && n > best_frames { - best = i; - best_frames = n; - } - } - best -} - /// 주소 공간 하나와 그 안의 스택을 만드는 함수입니다. 주소 공간 슬롯을 줍니다. -fn make_space(ut: u64, b: &Boot) -> i64 { +pub(super) fn make_space(ut: u64, b: &Boot) -> i64 { let (aspace, _) = make_aspace(ut, b); let mut va = STACK_BASE; while va < STACK_BASE + STACK_SIZE { @@ -262,7 +268,7 @@ fn make_space(ut: u64, b: &Boot) -> i64 { /// # Arguments /// `rw` - (주소 공간 슬롯, VA). 주소 공간이 0이면 루트 자신 /// `ro` - 읽기 전용으로 볼 쪽 -fn link(ut: u64, rw: (i64, u64), ro: (i64, u64)) { +pub(super) fn link(ut: u64, rw: (i64, u64), ro: (i64, u64)) { let frame = retype(ut, obj::FRAME); let view = copy_here(frame, rights::R, 0); check("oracle frame", frame > 0 && view > 0); @@ -274,7 +280,7 @@ fn link(ut: u64, rw: (i64, u64), ro: (i64, u64)) { } /// 태스크 하나를 만들어 실행 대기 상태로 만드는 함수입니다. TCB 슬롯을 줍니다. -fn spawn(ut: u64, aspace: i64, entry: u64, arg: u64, caps: &[(i64, u64, u64)]) -> i64 { +pub(super) fn spawn(ut: u64, aspace: i64, entry: u64, arg: u64, caps: &[(i64, u64, u64)]) -> i64 { let cnode = retype(ut, obj::CNODE); check("oracle cnode", cnode > 0); for (i, &(src, mask, badge)) in caps.iter().enumerate() { @@ -303,7 +309,10 @@ fn client(ut: u64, space: i64, ep: i64, report: i64, badge: u64, mode: u64) -> i } /// 서명 오라클을 띄우고 검증하는 함수입니다. -pub fn test_oracle(b: &Boot) { +/// +/// # Arguments +/// `info` - 커널이 준 부트 시드의 재료 정보. 시드 자체는 쓰지 않음 +pub fn test_oracle(b: &Boot, info: u64) { let spare = spare_untyped(b); let ut = if spare != 0 { spare } else { b.ut_main }; let (ep, report) = (retype(ut, obj::ENDPOINT), retype(ut, obj::ENDPOINT)); @@ -322,33 +331,65 @@ pub fn test_oracle(b: &Boot) { }; // 자가 시험을 통과한 볼트는 아직 키가 없는 상태임. 배지 없는 호출은 거부됨 - let (st, vault_state, ind) = ask(admin, request::STATUS, 0, 1); - check("vault self test", st == status::OK && vault_state == state::FRESH); + let (st, word, ind) = ask(admin, request::STATUS, 0, 1); + check("vault self test", st == status::OK && status_word::state(word) == state::FRESH); check("vault self test indicator", ind == proto::indicator::SELF_TEST_PASSED); check("call without a badge refused", ask(ep, request::STATUS, 0, 2).0 == status::DENIED); + let built = status_word::built(word); + check("vault algorithms", (built != 0) == provider::HAS_ED25519); - // 커널이 준 부트 시드를 관리자 프레임으로 넘겨 키를 만들게 하고, 루트 쪽 - // 사본은 지움. 재료가 모자란 시드로는 볼트가 키를 만들지 않음 - let (mut seed, info) = take_boot_seed(); - for (i, byte) in seed.iter().chain(&info.to_le_bytes()).enumerate() { + // 공개 시험 시드를 관리자 프레임으로 넘김. 재료 정보는 이 부팅의 진짜 + // 값이라서, 재료가 모자란 부팅에서는 볼트가 시드를 받지 않음 + for (i, byte) in TEST_SEED.iter().chain(&info.to_le_bytes()).enumerate() { // SAFETY: 방금 이 VA에 관리자 요청 프레임을 쓰기 가능으로 매핑했음 unsafe { (ROOT_REQ as *mut u8).add(i).write_volatile(*byte) }; } - wipe(&mut seed); let init = ask(admin, request::INIT, proto::INIT_LEN as u64, 3).0; - for i in 0..proto::INIT_LEN { - // SAFETY: 위와 같음 - unsafe { (ROOT_REQ as *mut u8).add(i).write_volatile(0) }; - } + let vault_state = |nonce: u64| status_word::state(ask(admin, request::STATUS, 0, nonce).1); if init == status::NO_ENTROPY { - check("no key without entropy", ask(admin, request::STATUS, 0, 4).1 == state::FRESH); + check("no key without entropy", vault_state(4) == state::FRESH); check("cleanup", cap_delete(vault_tcb) == 0); put_str("root: oracle made no key (boot seed has no entropy)\n"); return; } - check("vault key made", init == status::OK); - check("second init refused", ask(admin, request::INIT, proto::INIT_LEN as u64, 5).0 == status::DENIED); - check("admin cannot sign", ask(admin, request::SIGN, 1, 6).0 == status::DENIED); + // 운영자 배지의 호출: 요청 프레임이 없는 호출자가 길이를 말해도 볼트는 + // 어떤 프레임도 읽지 않고 거부하며, 서명과 시드 전달은 허용되지 않음 + let operator = copy_here(ep, rights::W, proto::OPERATOR_BADGE); + check("oracle operator cap", operator > 0); + for (nonce, op) in [request::STATUS, request::SIGN, request::INIT, request::KEYGEN, request::ZEROIZE] + .into_iter() + .enumerate() + { + let r = ask(operator, op, 1, 20 + nonce as u64).0; + check("operator length refused", r == status::BAD_REQUEST); + } + check("operator cannot sign", ask(operator, request::SIGN, 0, 30).0 == status::DENIED); + check("operator cannot seed", ask(operator, request::INIT, 0, 31).0 == status::DENIED); + if provider::HAS_ED25519 { + check("vault seeded", init == status::OK && vault_state(5) == state::SEEDED); + check("second seed refused", ask(admin, request::INIT, proto::INIT_LEN as u64, 6).0 == status::DENIED); + // 이미지에 없는 알고리즘으로는 키를 만들지 않고 시드를 그대로 쥠 + let r = call(admin, WAIT, [request::word(request::KEYGEN, 9), 0, 7, 0]); + check("unknown algorithm refused", r.status == 0 && r.mr[0] == status::UNSUPPORTED); + let r = call(admin, WAIT, [request::word(request::KEYGEN, alg::ED25519), 0, 8, 0]); + check("vault key made", r.status == 0 && r.mr[0] == status::OK && r.mr[3] == 8); + let (_, word, _) = ask(admin, request::STATUS, 0, 9); + check( + "vault ready", + status_word::state(word) == state::READY && status_word::key_alg(word) == alg::ED25519, + ); + let r = call(operator, WAIT, [request::word(request::KEYGEN, alg::ED25519), 0, 10, 0]); + check("one key per boot", r.status == 0 && r.mr[0] == status::KEY_EXISTS); + } else { + // 알고리즘이 없는 이미지의 볼트는 쓸 일이 없는 시드를 받지 않음 + check("no algorithm, no seed", init == status::UNSUPPORTED && vault_state(5) == state::FRESH); + } + for i in 0..proto::INIT_LEN { + // SAFETY: 위와 같음 + unsafe { (ROOT_REQ as *mut u8).add(i).write_volatile(0) }; + } + check("admin cannot sign", ask(admin, request::SIGN, 0, 11).0 == status::DENIED); + check("vault still answers", ask(admin, request::STATUS, 0, 12).0 == status::OK); // 클라이언트들의 주소 공간과 1번 호출자의 프레임 한 쌍 let space = make_space(ut, b); @@ -378,7 +419,7 @@ pub fn test_oracle(b: &Boot) { // 관리자가 키를 지우게 하면 볼트는 더는 서명하지 않음 check("zeroize", ask(admin, request::ZEROIZE, 0, 7).0 == status::OK); - check("vault zeroized", ask(admin, request::STATUS, 0, 8).1 == state::ZEROIZED); + check("vault zeroized", vault_state(13) == state::ZEROIZED); reports(MODE_AFTER_ZEROIZE, proto::signer_badge(1)); // 볼트가 사라진 뒤의 호출은 영원히 기다리지 않고 기한에 끝남 diff --git a/userspace/root-task/src/service.rs b/userspace/root-task/src/service.rs new file mode 100644 index 0000000..b6c5775 --- /dev/null +++ b/userspace/root-task/src/service.rs @@ -0,0 +1,398 @@ +//! 자가 검증 뒤에 시작하는 서비스(키 볼트와 운영자 터미널) 모듈입니다. +//! +//! # Features +//! 자가 검증을 모두 통과한 루트 태스크가 서비스를 새로 띄웁니다. 볼트가 든 +//! 이미지에서는 볼트 태스크를 자기 주소 공간에 만들어 커널이 준 부트 시드를 +//! 넘기고, 터미널 태스크를 또 다른 주소 공간에 만듭니다. 줄 편집과 명령 +//! 해석은 `k0-term` 크레이트가 하고 이 모듈은 그것을 시스템 콜에 잇습니다. +//! +//! 배선이 곧 정책입니다. 터미널의 CNode에는 케이퍼빌리티가 둘뿐입니다. 입력과 +//! 출력 권한이 있는 Console 복사본, 그리고 볼트 엔드포인트의 송신 전용 +//! 복사본(운영자 배지)입니다. 운영자 배지로 볼트가 해 주는 일은 상태 조회, +//! 공개키, 키 생성, 소거뿐이고 서명은 없습니다. 볼트가 공개키를 쓰는 응답 +//! 프레임은 터미널에 읽기 전용으로 매핑됩니다. 직렬 선에는 인증이 없으므로, +//! 선에 닿는 사람은 누구나 이 운영자 권한을 갖습니다(그 이상은 갖지 못함). +//! +//! 진짜 터미널을 띄우기 전에, 터미널과 똑같이 배선한 적대적 태스크를 먼저 +//! 돌립니다. 그 태스크는 볼트에 온갖 요청을 보내고, 출력 필터를 두드리고, +//! 읽기 전용 프레임에 쓰고, 루트의 데이터를 읽으려 합니다. 터미널이 장악돼도 +//! 운영자 권한 밖으로 나가지 못한다는 것을 배선 그대로 확인하는 검증입니다. +//! +//! 서비스가 시작되면 루트 태스크는 아무도 쥐지 않은 엔드포인트에서 영원히 +//! 기다립니다. 터미널이나 볼트가 죽어도 다시 띄우지 않습니다. + +use k0_abi::console::{FLUSH, NONBLOCK}; +use k0_term::Term; + +use super::{ + cap_copy, cap_delete, check, console_read, err, make_aspace, map_into, obj, perm, put_str, putc, recv, + retype, rights, slot, sys1, syscall, tcb_configure, tcb_resume, yield_now, Boot, +}; + +/// 서비스 태스크의 스택(각자의 주소 공간에서 같은 VA) +const STACK_BASE: u64 = 0x52_0000; +const STACK_SIZE: u64 = 0x8000; +/// 터미널 CNode에서 Console이 드는 슬롯 +const CON: u64 = 1; + +fn say(text: &str) { + for b in text.bytes() { + putc(CON, b); + } +} + +fn exit(code: u64) -> ! { + sys1(syscall::EXIT, code); + loop { + core::hint::spin_loop(); + } +} + +use k0_term::Out; + +/// 터미널이 글자를 내보내는 통로입니다. 자기 CNode의 Console로 한 바이트씩 +/// 냅니다. 이 케이퍼빌리티에는 입력 권한이 있어 백스페이스가 그대로 나갑니다. +struct Con; + +impl Out for Con { + fn put(&mut self, b: u8) { + putc(CON, b); + } +} + +/// 볼트로 가는 터미널 쪽 통로입니다(볼트가 든 이미지에서만). +#[cfg(feature = "vault")] +mod port { + use k0_term::{wire, Alg, Fail, Status, Vault, KEY_MAX}; + use k0_vault::proto::{alg, request, RESPONSE_HEADER}; + + use super::super::{call, err, ipc}; + + /// 터미널 CNode에서 볼트 엔드포인트가 드는 슬롯 + pub const VAULT: i64 = 2; + /// 터미널이 운영자 응답 프레임을 보는 VA + pub const RESP: u64 = 0x5C_0000; + /// 볼트의 답을 기다리는 한도(틱) + const WAIT: u64 = ipc::timeout(5); + + /// 볼트를 부르는 상태입니다. 요청마다 새 번호를 써서, 기한이 지나 버린 + /// 예전 요청의 답을 지금 요청의 답으로 읽지 않게 합니다. + pub struct Port { + pub nonce: u64, + } + + impl Port { + fn ask(&mut self, op: u64, algo: u64) -> Result<[u64; 4], Fail> { + self.nonce += 1; + let r = call(VAULT, WAIT, [request::word(op, algo), 0, self.nonce, 0]); + match r.status { + 0 => {} + e if e == err::TIMEOUT => return Err(Fail::VaultTimeout), + e if e == err::REPLY_TIMEOUT => return Err(Fail::VaultUnanswered), + _ => return Err(Fail::NoVault), + } + // 자기 번호를 돌려주지 않는 답은 믿지 않음 + if r.mr[3] != self.nonce { + return Err(Fail::NoVault); + } + match wire::fail_of(r.mr[0]) { + Some(f) => Err(f), + None => Ok(r.mr), + } + } + } + + impl Vault for Port { + fn status(&mut self) -> Result { + let mr = self.ask(request::STATUS, alg::NONE)?; + wire::status_of(mr[1], mr[2]).ok_or(Fail::VaultFailed) + } + + fn pubkey(&mut self, key: &mut [u8; KEY_MAX]) -> Result { + // 공개키 요청은 알고리즘을 대야 하므로 지금 있는 키의 것을 먼저 물음 + let st = self.status()?; + let Some(a) = st.alg else { + return Err(wire::no_key(st.state)); + }; + let mr = self.ask(request::PUBLIC_KEY, wire::alg_number(a))?; + let len = usize::try_from(mr[1]).unwrap_or(usize::MAX); + if len > KEY_MAX { + return Err(Fail::Denied); + } + let frame = RESP as *const u8; + // SAFETY: 루트가 이 VA에 운영자 응답 프레임을 읽기 전용으로 매핑해 + // 두었고, 앞머리와 본문은 프레임 하나보다 작음 + unsafe { + // 프레임의 번호와 길이가 이 요청의 것일 때만 본문을 믿음 + if frame.cast::().read_volatile() != self.nonce + || frame.add(8).cast::().read_volatile() != len as u64 + { + return Err(Fail::NoVault); + } + for (i, b) in key[..len].iter_mut().enumerate() { + *b = frame.add(RESPONSE_HEADER + i).read_volatile(); + } + } + Ok(len) + } + + fn keygen(&mut self, a: Alg) -> Result<(), Fail> { + self.ask(request::KEYGEN, wire::alg_number(a)).map(|_| ()) + } + + fn zeroize(&mut self) -> Result<(), Fail> { + self.ask(request::ZEROIZE, alg::NONE).map(|_| ()) + } + } +} + +/// 터미널 태스크의 진입점입니다. +/// +/// 입력 경로를 열고 그동안 들어온 것을 버린 뒤 시작 줄을 내고, 한 번 더 버린 +/// 다음 프롬프트를 내고 바이트를 하나씩 읽어 터미널에 넘깁니다. 그래서 +/// 프롬프트가 뜨기 전에 UART에 도착한 것은 명령으로 읽히지 않습니다(장치 +/// 밖에서 붙들려 있다가 나중에 도착하는 바이트는 커널이 구별할 수 없음). 입력 +/// 경로가 꺼지면 한 줄을 남기고 끝납니다. +extern "C" fn term_entry(_arg: u64) -> ! { + let mut out = Con; + let mut term = Term::new(); + let _ = console_read(CON, NONBLOCK | FLUSH); + for b in k0_term::BANNER.bytes() { + putc(CON, b); + } + // 시작 줄을 내는 동안 들어온 것까지 버린 다음에 프롬프트를 냄 + let _ = console_read(CON, NONBLOCK | FLUSH); + for b in k0_term::PROMPT.bytes() { + putc(CON, b); + } + #[cfg(feature = "vault")] + let mut vault = port::Port { nonce: 0 }; + loop { + let (status, byte, lost) = console_read(CON, 0); + if status != 0 { + break; + } + #[cfg(feature = "vault")] + term.feed(byte, lost, &mut out, Some(&mut vault)); + #[cfg(not(feature = "vault"))] + term.feed(byte, lost, &mut out, None::<&mut k0_term::NoVault>); + } + say("\nK0 operator console closed (no console input)\n"); + exit(0) +} + +/// 터미널과 똑같이 배선한 적대적 태스크의 진입점입니다. +/// +/// 기대대로면 두 방식 모두 폴트로 끝납니다. 폴트가 나지 않거나 볼트가 허용 +/// 밖의 요청에 답하면 `root: FAIL` 줄을 남깁니다. +/// +/// # Arguments +/// `mode` - 0이면 볼트와 출력 필터를 두드린 뒤 읽기 전용 페이지에 쓰고, +/// 1이면 루트의 데이터를 읽음 +extern "C" fn hostile_entry(mode: u64) -> ! { + if mode != 0 { + // 루트의 .data는 이 주소 공간에 매핑돼 있지 않음 + // SAFETY: 의도된 위반 + let leaked = unsafe { (&raw const super::ROOT_SECRET).cast::().read_volatile() }; + say(if leaked == 0 { "root: FAIL terminal wiring (read)\n" } else { "root: FAIL terminal wiring (leak)\n" }); + exit(1) + } + #[cfg(feature = "vault")] + { + use k0_vault::proto::{alg, request, status}; + let mut wrong = 0u64; + for op in 0..=8u64 { + for algo in [alg::NONE, alg::ED25519, 2] { + for len in [0, 1, 40, u64::MAX] { + // 운영자에게 허용된, 상태를 바꾸는 두 요청만 빼고 전부 보냄 + // (이 볼트는 곧 서비스가 쓸 것이므로 상태를 건드리지 않음) + let changes = len == 0 + && (op == request::ZEROIZE || (op == request::KEYGEN && algo == alg::ED25519)); + if changes { + continue; + } + let r = super::call(port::VAULT, super::ipc::timeout(5), [request::word(op, algo), len, 7, 0]); + // 운영자의 연산이 아닌 것은 거절이나 잘못된 요청으로만 끝나야 함. + // 키가 없는 볼트가 "아직 없음"으로 답하는 것은 운영자에게 + // 허용된 연산(공개키, 키 생성)에서만 받아들임 + let own = matches!(op, request::PUBLIC_KEY | request::KEYGEN); + let fine = r.status == 0 + && r.mr[3] == 7 + && match r.mr[0] { + status::OK => op == request::STATUS && len == 0, + status::DENIED | status::BAD_REQUEST => true, + status::UNSUPPORTED | status::NOT_READY | status::NO_ENTROPY => own, + _ => false, + }; + wrong += u64::from(!fine); + } + } + } + // 예약 비트와 쓰지 않는 레지스터를 채운 요청 + let r = super::call(port::VAULT, super::ipc::timeout(5), [request::word(request::STATUS, 0) | 1 << 16, 0, 7, 0]); + wrong += u64::from(r.status != 0 || r.mr[0] != status::BAD_REQUEST); + let r = super::call(port::VAULT, super::ipc::timeout(5), [request::word(request::STATUS, 0), 0, 7, 9]); + wrong += u64::from(r.status != 0 || r.mr[0] != status::BAD_REQUEST); + if wrong != 0 { + say("root: FAIL terminal wiring (vault)\n"); + exit(1) + } + } + // 출력 필터: 입력 권한이 있는 Console이라 백스페이스 하나만 더 통과하고 + // 나머지 제어 바이트는 `?`가 됨 + say("root: terminal console filter ["); + for b in [0x1Bu8, 0x08, 0x0D, 0x00, 0x7F, 0x9B] { + putc(CON, b); + } + say("]\n"); + say("root: terminal wiring holds\n"); + // 응답 프레임은 터미널에 읽기 전용이고, 볼트가 없는 이미지에서는 자기 + // 코드에 씀(실행 전용 페이지). 어느 쪽이든 쓰면 이 태스크가 종료됨 + #[cfg(feature = "vault")] + let target = port::RESP; + #[cfg(not(feature = "vault"))] + let target = hostile_entry as usize as u64; + // SAFETY: 의도된 위반 + unsafe { (target as *mut u64).write_volatile(0xBAD) }; + say("root: FAIL terminal wiring (write)\n"); + exit(1) +} + +/// 주소 공간 하나와 그 안의 스택을 만드는 함수입니다. 주소 공간 슬롯을 줍니다. +fn make_space(ut: u64, b: &Boot) -> i64 { + let (aspace, _) = make_aspace(ut, b); + let mut va = STACK_BASE; + while va < STACK_BASE + STACK_SIZE { + let f = retype(ut, obj::FRAME); + check("service stack", f > 0 && map_into(f, va, perm::RW, aspace) == 0); + va += b.frame_size; + } + aspace +} + +/// 태스크 하나를 만들어 실행 대기 상태로 만드는 함수입니다. TCB 슬롯을 줍니다. +/// +/// # Arguments +/// `caps` - 태스크의 CNode 1번 슬롯부터 차례로 넣을 (원본, 남길 권한, 배지) +fn spawn(ut: u64, aspace: i64, entry: u64, arg: u64, caps: &[(i64, u64, u64)]) -> i64 { + let cnode = retype(ut, obj::CNODE); + check("service cnode", cnode > 0); + for (i, &(src, mask, badge)) in caps.iter().enumerate() { + check("service grant", cap_copy(src, cnode, 1 + i as u64, mask, badge) == 0); + } + let tcb = retype(ut, obj::TCB); + check( + "service task", + tcb > 0 + && tcb_configure(tcb, entry, STACK_BASE + STACK_SIZE, aspace, cnode, arg) == 0 + && tcb_resume(tcb) == 0, + ); + tcb +} + +/// 서비스의 볼트를 띄우고 부트 시드를 넘기는 함수입니다. (엔드포인트, 관리자 +/// 케이퍼빌리티, 시드를 넘긴 뒤의 볼트 상태 워드)를 줍니다. +/// +/// 진짜 부트 시드가 쓰이는 곳은 여기 한 번뿐입니다. 넘긴 뒤에는 루트 쪽의 +/// 사본과 관리자 요청 프레임을 지웁니다. +#[cfg(feature = "vault")] +fn start_vault(ut: u64, b: &Boot, term_space: i64) -> (i64, i64, u64) { + use k0_vault::proto::{self, alg, request, status}; + use k0_vault::server::wipe; + + use super::{call, copy_here, ipc, oracle, take_boot_seed, TEST_VA}; + + /// 루트가 서비스 볼트의 관리자 요청 프레임을 보는 VA. 루트의 시험용 VA + /// 구역(페이지 테이블이 이미 깔린 2MiB) 안에서 다른 검증이 쓰지 않는 자리 + const ROOT_REQ: u64 = TEST_VA + 0x78 * 0x4000; + + let ep = retype(ut, obj::ENDPOINT); + check("service endpoint", ep > 0); + let vault_space = make_space(ut, b); + oracle::link(ut, (0, ROOT_REQ), (vault_space, oracle::VAULT_REQ)); + oracle::link( + ut, + (vault_space, oracle::VAULT_RESP + proto::OPERATOR_FRAME * oracle::FRAME_STEP), + (term_space, port::RESP), + ); + spawn(ut, vault_space, oracle::vault_entry as usize as u64, 0, &[(ep, rights::R, 0)]); + let admin = copy_here(ep, rights::W, proto::ADMIN_BADGE); + check("service admin cap", admin > 0); + + let (mut seed, info) = take_boot_seed(); + for (i, byte) in seed.iter().chain(&info.to_le_bytes()).enumerate() { + // SAFETY: 방금 이 VA에 관리자 요청 프레임을 쓰기 가능으로 매핑했음 + unsafe { (ROOT_REQ as *mut u8).add(i).write_volatile(*byte) }; + } + wipe(&mut seed); + let r = call(admin, ipc::timeout(5), [request::word(request::INIT, alg::NONE), proto::INIT_LEN as u64, 1, 0]); + for i in 0..proto::INIT_LEN { + // SAFETY: 위와 같음 + unsafe { (ROOT_REQ as *mut u8).add(i).write_volatile(0) }; + } + check("service seed delivered", r.status == 0 && r.mr[3] == 1); + put_str(match r.mr[0] { + status::OK => "root: vault seeded\n", + status::NO_ENTROPY => "root: vault has no seed (boot seed has no entropy)\n", + status::UNSUPPORTED => "root: vault has no seed (no algorithm in this image)\n", + _ => super::fail("service seed"), + }); + let r = call(admin, ipc::timeout(5), [request::word(request::STATUS, alg::NONE), 0, 2, 0]); + check("service vault status", r.status == 0 && r.mr[0] == status::OK && r.mr[3] == 2); + (ep, admin, r.mr[1]) +} + +/// 서비스를 시작하는 함수입니다. 시작했으면 돌아오지 않습니다. +/// +/// 콘솔 입력 경로가 없는 기계에서는 터미널을 띄울 까닭이 없으므로 한 줄을 +/// 남기고 돌아갑니다(쓰지 않게 된 부트 시드는 지움). +pub fn start(b: &Boot) { + if console_read(slot::CONSOLE, NONBLOCK).0 == err::NO_DEVICE { + #[cfg(feature = "vault")] + { + let (mut seed, _) = super::take_boot_seed(); + k0_vault::server::wipe(&mut seed); + } + put_str("root: no console input, terminal not started\n"); + return; + } + let ut = super::late_untyped(b); + let con = slot::CONSOLE as i64; + let term_space = make_space(ut, b); + + #[cfg(feature = "vault")] + let (ep, admin, before) = start_vault(ut, b, term_space); + #[cfg(feature = "vault")] + let caps = [(con, rights::R | rights::W, 0), (ep, rights::W, k0_vault::proto::OPERATOR_BADGE)]; + #[cfg(not(feature = "vault"))] + let caps = [(con, rights::R | rights::W, 0)]; + + // 터미널과 같은 주소 공간, 같은 케이퍼빌리티 목록으로 적대적 태스크를 돌림. + // 둘 다 폴트로 죽어야 하고, 그동안 낸 줄과 폴트 수는 시험 하니스가 확인함 + for mode in [0, 1] { + let tcb = spawn(ut, term_space, hostile_entry as usize as u64, mode, &caps); + for _ in 0..6000 { + yield_now(); + } + check("hostile task delete", cap_delete(tcb) == 0); + } + #[cfg(feature = "vault")] + { + use k0_vault::proto::{alg, request, status}; + // 볼트는 살아 있고 상태가 그대로임. 관리자 권한은 여기서 내려놓음 + let r = super::call(admin, super::ipc::timeout(5), [request::word(request::STATUS, alg::NONE), 0, 3, 0]); + check("vault survived the hostile task", r.status == 0 && r.mr[0] == status::OK && r.mr[1] == before); + check("drop admin cap", cap_delete(admin) == 0); + } + + // 터미널의 시작 줄이 이 줄의 한가운데에 끼어들지 않게 먼저 찍음 + put_str("root: service started\n"); + spawn(ut, term_space, term_entry as usize as u64, 0, &caps); + // 루트의 일은 끝났음. 아무도 쥐지 않은 엔드포인트에서 기다려, 입력이 없는 + // 동안 커널이 다음 인터럽트까지 쉬게 함 + let quiet = retype(ut, obj::ENDPOINT); + check("service idle endpoint", quiet > 0); + loop { + let _ = recv(quiet, 0); + } +} From 24713f792ace2be61b3532050e8f69566fd1f46b Mon Sep 17 00:00:00 2001 From: Quant-TheodoreFelix <53819958+Quant-TheodoreFelix@users.noreply.github.com> Date: Fri, 13 Nov 2026 05:32:24 +0900 Subject: [PATCH 2/2] Document serial input and the operator terminal - New design note `terminal.md` in English and Korean with its figure - Updated the guides and design notes for console input, the four vault roles and the new tests --- CONTRIBUTING.md | 8 +- CONTRIBUTING_KR.md | 8 +- INTRODUCTION.md | 79 +++++++++++------ INTRODUCTION_KR.md | 79 +++++++++++------ README.md | 10 +++ README_KR.md | 10 +++ SECURITY.md | 89 +++++++++++++++---- SECURITY_KR.md | 89 +++++++++++++++---- USAGE.md | 135 ++++++++++++++++++++++++++-- USAGE_KR.md | 135 ++++++++++++++++++++++++++-- assets/terminal-flow.svg | 60 +++++++++++++ assets/terminal-flow_KR.svg | 60 +++++++++++++ ci/threat_model.md | 21 +++-- design/en/README.md | 1 + design/en/boot.md | 35 ++++++-- design/en/capabilities.md | 17 ++-- design/en/dtb.md | 7 +- design/en/exceptions.md | 21 +++-- design/en/hardening.md | 9 +- design/en/ipc.md | 47 ++++++++-- design/en/scheduling.md | 12 ++- design/en/terminal.md | 165 +++++++++++++++++++++++++++++++++++ design/en/uefi.md | 3 +- design/en/vault.md | 95 +++++++++++++++----- design/kr/README.md | 1 + design/kr/boot_KR.md | 35 ++++++-- design/kr/capabilities_KR.md | 17 ++-- design/kr/dtb_KR.md | 7 +- design/kr/exceptions_KR.md | 21 +++-- design/kr/hardening_KR.md | 9 +- design/kr/ipc_KR.md | 47 ++++++++-- design/kr/scheduling_KR.md | 12 ++- design/kr/terminal_KR.md | 165 +++++++++++++++++++++++++++++++++++ design/kr/uefi_KR.md | 3 +- design/kr/vault_KR.md | 95 +++++++++++++++----- 35 files changed, 1365 insertions(+), 242 deletions(-) create mode 100644 assets/terminal-flow.svg create mode 100644 assets/terminal-flow_KR.svg create mode 100644 design/en/terminal.md create mode 100644 design/kr/terminal_KR.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 387df6a..118fd2c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -68,9 +68,9 @@ $ tools/build-loader.sh # put the built kernel into the UEFI loader, prints th Input and output are optional in K0. You can select them with Cargo features of the kernel crate. > [!NOTE] -> A feature for input or for a terminal does not exist yet. Console output is the only thing you can select today. +> Console input and the operator terminal are features too (`console-input`, `terminal`), and they are off by default. -Console output exists only in an image built with a console feature (`console-pl011`, `console-16550`, `console`). No image has input. `cargo virt` is an alias for `cargo run -p k0-kernel --features console`. [USAGE.md](USAGE.md#console-features) explains the features. +Console output exists only in an image built with a console feature (`console-pl011`, `console-16550`, `console`). An image has input only if it was built with `console-input` or `terminal`. `cargo virt` is an alias for `cargo run -p k0-kernel --features console`. [USAGE.md](USAGE.md#console-features) explains the features. The kernel never exits. Once the root task finishes its self-tests, it yields forever and a kernel with console prints `k0: tick N` once a second. Stop QEMU with `Ctrl-A X`. @@ -92,11 +92,11 @@ $ cargo build -p k0-kernel --features console --offline $ tools/qemu-boot-test.sh # boot under QEMU and check the self-tests ``` -`tools/host-test.sh` runs the tests of `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi` and `k0-vault` on any host (276 tests on an AArch64 host, 190 elsewhere). It runs `k0-vault` twice, with and without the algorithm feature `vault-ed25519`, which gives 13 and 7 tests. The tests of `k0-mm` contain AArch64 inline assembly, so they only run on an AArch64 host (Apple Silicon or Linux arm64). The script runs them for both the 4 KiB and the 16 KiB granule. +`tools/host-test.sh` runs the tests of `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-conin`, `k0-vault` and `k0-term` on any host (354 tests on an AArch64 host, 268 elsewhere). It runs `k0-vault` twice, with and without the algorithm feature `vault-ed25519`, which gives 20 and 11 tests. It runs `k0-term` with and without the vault feature, which gives 24 and 21 tests. The tests of `k0-mm` contain AArch64 inline assembly, so they only run on an AArch64 host (Apple Silicon or Linux arm64). The script runs them for both the 4 KiB and the 16 KiB granule. `tools/qemu-boot-test.sh` boots the debug kernel, checks the boot log line by line in a fixed order, fails on any error marker, and stops QEMU as soon as the root task reports `root: sched tests pass`. Besides the pass lines, it expects `k0: kernel reserve ` before the `k0: untyped ` lines, `k0: idle (waiting for a timeout)` and `root: timeout tests pass` after `root: teardown tests pass`, and `root: kernel reserve tests pass` after `root: revocation tests pass`. Any line that starts with `k0: all tasks` is a failure. It also counts the timer tick lines between `root: teardown tests pass` and `root: timeout tests pass` and wants at least 4, because EL0 has no clock and this is how the lower bound of a timeout is checked. The timeout tests wait for real ticks, so a boot takes about 4 seconds longer than it did before. Set `K0_BOOT_TIMEOUT` (seconds) on slow machines. It reads the serial port, so it needs an image with a console driver. To test an image without console, use `K0_BOOT_MEMLOG`, `K0_BOOT_SERIAL=empty` and `K0_BOOT_CONSOLE_PAGE`, which are described in "Testing an image without console" in [USAGE.md](USAGE.md#testing-an-image-without-console). -An image with the signing oracle (`vault` or `vault-ed25519`) has two more intended faults, so it prints 8 `k0: task fault` lines instead of 6. Run the test with `K0_BOOT_FAULTS=8` and require `root: oracle tests pass` with `K0_BOOT_REQUIRE`. The boot matrix has the rows `vault`, `vault-max`, `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault` and the static check `vault-symbols` for it, and 61 rows in total on a Mac with HVF and 51 in CI. [USAGE.md](USAGE.md) describes the rows. +An image with the signing oracle (`vault` or `vault-ed25519`) has two more intended faults, so it prints 8 `k0: task fault` lines instead of 6. Run the test with `K0_BOOT_FAULTS=8` and require `root: oracle tests pass` with `K0_BOOT_REQUIRE`. The boot matrix has the rows `vault`, `vault-max`, `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault` and the static check `vault-symbols` for it, and 76 rows in total on a Mac with HVF and 65 in CI. The rows `input-*` and `term-*` cover console input and the terminal. A terminal image prints two more `k0: task fault` lines (8 without the vault, 10 with it), and `tools/term-test.py ` runs its scripted serial session. [USAGE.md](USAGE.md) describes the rows. The default QEMU CPU model (`cortex-a72`) has no PAC, PAN or RNDR. To exercise those paths as well, boot on QEMU's `max` model and require the matching log lines. Any arguments after the kernel path are passed to QEMU. You can enter it as follows: diff --git a/CONTRIBUTING_KR.md b/CONTRIBUTING_KR.md index 0f8268e..f6dbb2f 100644 --- a/CONTRIBUTING_KR.md +++ b/CONTRIBUTING_KR.md @@ -70,9 +70,9 @@ $ tools/build-loader.sh # 빌드한 커널을 UEFI 로더에 포함하고 .efi K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Cargo features로 선택할 수 있습니다. > [!NOTE] -> 입력 또는 터미널용 feature는 아직 없습니다. 지금 선택할 수 있는 것은 콘솔 출력뿐입니다. +> 콘솔 입력과 운영자 터미널도 feature(`console-input`, `terminal`)이며 기본으로는 꺼져 있습니다. -콘솔 출력은 콘솔 feature(`console-pl011`, `console-16550`, `console`)를 포함해 빌드한 이미지에만 있습니다. 입력은 어떤 이미지에도 없습니다. `cargo virt`는 `cargo run -p k0-kernel --features console`의 별칭입니다. feature의 설명은 [USAGE_KR.md](USAGE_KR.md#콘솔-feature)에 있습니다. +콘솔 출력은 콘솔 feature(`console-pl011`, `console-16550`, `console`)를 포함해 빌드한 이미지에만 있습니다. 입력은 `console-input` 또는 `terminal`을 포함해 빌드한 이미지에만 있습니다. `cargo virt`는 `cargo run -p k0-kernel --features console`의 별칭입니다. feature의 설명은 [USAGE_KR.md](USAGE_KR.md#콘솔-feature)에 있습니다. 커널은 종료하지 않습니다. 루트 태스크가 자가 테스트를 마치면 계속 양보하고, 콘솔이 있는 커널은 1초마다 `k0: tick N`을 출력합니다. QEMU는 `Ctrl-A X`로 끕니다. @@ -94,11 +94,11 @@ $ cargo build -p k0-kernel --features console --offline $ tools/qemu-boot-test.sh # QEMU 부팅과 자가 테스트 확인 ``` -`tools/host-test.sh`는 `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-vault`의 테스트를 어느 호스트에서나 실행합니다(AArch64 호스트에서 276개, 그 밖에서 190개). `k0-vault`는 알고리즘 feature `vault-ed25519`를 포함한 경우와 포함하지 않은 경우로 두 번 실행하며, 각각 13개와 7개입니다. `k0-mm` 테스트는 AArch64 인라인 어셈블리를 포함하기 때문에 AArch64 호스트(Apple Silicon 또는 Linux arm64)에서만 실행되며, 스크립트가 4 KiB와 16 KiB 그래뉼 두 구성으로 모두 돌립니다. +`tools/host-test.sh`는 `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-conin`, `k0-vault`, `k0-term`의 테스트를 어느 호스트에서나 실행합니다(AArch64 호스트에서 354개, 그 밖에서 268개). `k0-vault`는 알고리즘 feature `vault-ed25519`를 포함한 경우와 포함하지 않은 경우로 두 번 실행하며, 각각 20개와 11개입니다. `k0-term`도 `vault` feature를 포함한 경우와 포함하지 않은 경우로 실행하며, 각각 24개와 21개입니다. `k0-mm` 테스트는 AArch64 인라인 어셈블리를 포함하기 때문에 AArch64 호스트(Apple Silicon 또는 Linux arm64)에서만 실행되며, 스크립트가 4 KiB와 16 KiB 그래뉼 두 구성으로 모두 돌립니다. `tools/qemu-boot-test.sh`는 디버그 커널을 부팅하고 부팅 로그를 정해진 순서대로 한 줄씩 확인합니다. 에러 표식이 하나라도 나오면 실패하고, 루트 태스크가 `root: sched tests pass`를 출력하면 곧바로 QEMU를 종료합니다. 통과 줄 외에도 `k0: untyped ` 줄보다 앞의 `k0: kernel reserve `, `root: teardown tests pass` 뒤의 `k0: idle (waiting for a timeout)`와 `root: timeout tests pass`, `root: revocation tests pass` 뒤의 `root: kernel reserve tests pass`를 기대합니다. `k0: all tasks`로 시작하는 줄은 모두 실패입니다. `root: teardown tests pass`와 `root: timeout tests pass` 사이의 타이머 틱 줄도 세어 4개 이상을 요구하는데, EL0에는 시계가 없어서 이것이 타임아웃의 하한을 확인하는 방법이기 때문입니다. 타임아웃 테스트는 실제 틱을 기다리므로 부팅 한 번이 이전보다 약 4초 더 걸립니다. 느린 환경에서는 `K0_BOOT_TIMEOUT`(초)을 늘려 주세요. 직렬 포트를 읽기 때문에 콘솔 드라이버가 있는 이미지가 필요합니다. 콘솔 없는 이미지를 시험하려면 [USAGE_KR.md](USAGE_KR.md#콘솔-없는-이미지-시험)의 "콘솔 없는 이미지 시험"에 설명된 `K0_BOOT_MEMLOG`, `K0_BOOT_SERIAL=empty`, `K0_BOOT_CONSOLE_PAGE`를 사용하세요. -서명 오라클이 있는 이미지(`vault` 또는 `vault-ed25519`)는 일부러 일으키는 폴트가 두 번 더 있어 `k0: task fault` 줄이 6개가 아니라 8개이므로 `K0_BOOT_FAULTS=8`이 필요하고, `root: oracle tests pass`를 `K0_BOOT_REQUIRE`로 요구하세요. 부팅 매트릭스에는 이를 위한 행 `vault`, `vault-max`, `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`와 정적 검사 `vault-symbols`가 있으며, 행렬은 HVF가 있는 Mac에서 61행, CI에서 51행입니다. 행의 내용은 [USAGE_KR.md](USAGE_KR.md)에 있습니다. +서명 오라클이 있는 이미지(`vault` 또는 `vault-ed25519`)는 일부러 일으키는 폴트가 두 번 더 있어 `k0: task fault` 줄이 6개가 아니라 8개이므로 `K0_BOOT_FAULTS=8`이 필요하고, `root: oracle tests pass`를 `K0_BOOT_REQUIRE`로 요구하세요. 부팅 매트릭스에는 이를 위한 행 `vault`, `vault-max`, `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`와 정적 검사 `vault-symbols`가 있으며, 행렬은 HVF가 있는 Mac에서 76행, CI에서 65행입니다. 행 `input-*`와 `term-*`는 콘솔 입력과 터미널을 다룹니다. 터미널 이미지는 `k0: task fault` 줄이 두 개 더 나오며(볼트 없이 8개, 볼트와 함께 10개), `tools/term-test.py <이미지>`가 정해진 직렬 세션을 실행합니다. 행의 내용은 [USAGE_KR.md](USAGE_KR.md)에 있습니다. 기본 QEMU CPU 모델(`cortex-a72`)에는 PAC, PAN, RNDR이 없습니다. 이 경로까지 검증하려면 QEMU의 `max` 모델로 부팅하고 해당 로그 줄을 필수로 지정하세요. 커널 경로 뒤의 인자는 그대로 QEMU에 전달됩니다. 다음과 같이 입력할 수 있습니다. diff --git a/INTRODUCTION.md b/INTRODUCTION.md index 97fdd82..c8499ce 100644 --- a/INTRODUCTION.md +++ b/INTRODUCTION.md @@ -35,6 +35,7 @@ In the following table, you can find the words used in this document. | **Endpoint** | A mailbox through which tasks exchange messages (IPC) | | **System call** | A request that a program makes to the kernel | | **Interrupt** | A signal from the hardware, such as a timer, that makes the processor stop and run the kernel | +| **Terminal** | A screen on the serial line where a person types commands and reads the answers. In K0 one ordinary task provides it | ## Goals @@ -46,7 +47,7 @@ K0 is meant to become the isolation core of high-security systems. The targets a - **Research base**: formal verification and certification research > [!NOTE] -> Only a first small step exists: the optional signing oracle described under "What works today". The rest does not work yet. Today K0 is a research platform: it boots and checks its own security properties, but by default it does no useful work of its own yet. +> Only a first small step exists: the optional signing oracle and the operator terminal that drives it over the serial line, both described under "What works today". The rest does not work yet. Today K0 is a research platform: it boots and checks its own security properties, but by default it does no useful work of its own yet. ## What works today @@ -76,39 +77,40 @@ K0 is meant to become the isolation core of high-security systems. The targets a - **Finding devices**: from the device tree the kernel takes only three things. - - **Console**: the node named by `stdout-path` in `/chosen` (PL011, SBSA UART or 16550 family). + - **Console**: the node named by `stdout-path` in `/chosen` (PL011, SBSA UART or 16550 family). If the node has `interrupts`, its interrupt number is read as well, and it is used for input only. Through the UEFI loader it comes from the ACPI SPCR table. - **Interrupt controller**: the interrupt parent of the timer node (GICv2 or GICv3). - **Timer interrupt**: the interrupt number of the EL1 virtual timer. - They go into one platform descriptor that never changes, printed as a `k0: platform ...` line. It is checked against the memory map before any device page is mapped. The hardware must agree with the device tree (the identification registers of the GIC and the PL011), otherwise the kernel refuses to boot. With any other UART, or without `stdout-path`, there is no console. Every image finds and checks the console node this way, even an image that never drives the console (see the next item). A device tree whose console fails the checks is therefore refused by every image. + They go into one platform descriptor that never changes, printed as a `k0: platform ...` line. It is checked against the memory map before any device page is mapped. The hardware must agree with the device tree (the identification registers of the GIC and the PL011), otherwise the kernel refuses to boot. With any other UART, or without `stdout-path`, there is no console. Every image finds and checks the console node this way, even an image that never drives the console (see the next item). A device tree whose console fails the checks is therefore refused by every image. A console node without a usable interrupt is not a reason to refuse: only input is switched off. -- **Console output is optional**: input and output are optional in K0. You can select them with Cargo features of the kernel crate. +- **Console input and output are optional**: input and output are optional in K0. You can select them with Cargo features of the kernel crate. Console output exists only in an image built with a console feature, and console input exists only in an image built with `console-input` or `terminal`. In the following table, you can find the Cargo features. -> [!NOTE] -> A feature for input or for a terminal does not exist yet. Console output is the only thing you can select today. - -Console output exists only in an image built with a console feature. No image has input. In the following table, you can find the Cargo features that add a transmit driver. - -| Feature | Transmit driver it adds | +| Feature | What it adds | | --- | --- | -| `console-pl011` | PL011 and SBSA UART | -| `console-16550` | The 16550 family | -| `console` | Both of the above | +| `console-pl011` | The transmit driver for PL011 and SBSA UART | +| `console-16550` | The transmit driver for the 16550 family | +| `console` | Both transmit drivers above | +| `console-input` | The receive path for the console UART and the system call `CONSOLE_READ`. It needs a console driver feature to do anything | +| `terminal` | The operator terminal task in the root task image. It turns `console-input` on | + +> [!NOTE] +> Input exists only for the PL011 and the SBSA UART. A 16550 console has output and no input. These features only add and are not in `default`, so **every build command must name the features**, for example `cargo build -p k0-kernel --features console --offline`. An image built without them has the following properties: - It contains no UART driver code. - It never maps the console device page. - It writes nothing to a UART. +- It has no receive code and no `CONSOLE_READ`. - It prints `k0: no console (driver not built in)`. - All its output goes only to the boot log. -`DEBUG_PUTC`, the `Console` capability and the boot log stay in every image, and so does the check of the console node. `grep -a 'k0: console drivers' ` tells which drivers an image has (a label, not proof), and `k0: device pages [...]` lists every device page the kernel keeps mapped. The UEFI loader still prints through the firmware console. See [design/en/boot.md](design/en/boot.md) and the section "Optional console output" in [SECURITY.md](SECURITY.md). +`DEBUG_PUTC`, the `Console` capability and the boot log stay in every image, and so does the check of the console node. The `Console` capability carries the rights R (read input) and W (write output). A copy can only lose them, and the root task's capability has W, and R only in images with `console-input`. `grep -a 'k0: console drivers' ` tells which drivers an image has (a label, not proof), and `k0: device pages [...]` lists every device page the kernel keeps mapped. The UEFI loader still prints through the firmware console. See [design/en/boot.md](design/en/boot.md) and the section "Optional console output" in [SECURITY.md](SECURITY.md). - **Boot log**: every line the kernel prints also goes into a 16 KiB buffer in kernel memory. Lines printed before the console is attached are replayed once it is. With no console, this buffer is the only record. `tools/boot-log.py` reads it from the memory of a QEMU guest. Output of user tasks is recorded only up to a quota (6 KiB of the 16 KiB), and only the first 4 timer tick lines are logged. - **Timer**: only the EL1 virtual timer is used, so it works inside hypervisor guests. The image never touches the physical timer, and the boot matrix checks that. - **Granule**: the page size is 4 KiB by default. A 16 KiB build is a build option (see [USAGE.md](USAGE.md)). It is not selected at run time, and on a processor without 16 KiB support the 16 KiB image refuses to boot. -- **Pinned build**: an image built with `K0_PIN` set to the platform line of a boot log refuses to boot when the discovered platform, the entry level or the RAM range differs. This catches a wrong board or a swapped device tree. It is not a defence against a hostile boot chain, because the comparison uses values that come from the device tree. +- **Pinned build**: an image built with `K0_PIN` set to the platform line of a boot log refuses to boot when the discovered platform, the entry level or the RAM range differs. The platform line now also carries the console interrupt number (`con=pl011@0x9000000,irq33`), so pin strings made earlier must be made again. This catches a wrong board or a swapped device tree. It is not a defence against a hostile boot chain, because the comparison uses values that come from the device tree. - **Protecting its own memory**: the kernel keeps the following. - No page of kernel memory is both writable and executable (W^X). - An empty guard page sits below the kernel's boot stack, so running off the end of the stack stops the kernel instead of damaging other memory. @@ -132,7 +134,7 @@ These features only add and are not in `default`, so **every build command must - **Running tasks**: a task is tied to one key ring and one address space when it is set up (TCB_CONFIGURE) and then started (TCB_RESUME). Tasks take turns, and a timer interrupts a task that runs too long (round-robin scheduling with timer preemption). A task can give up its turn (YIELD) or finish (EXIT). - **Messages**: tasks exchange short messages that travel in processor registers. The sender waits until the receiver takes the message (synchronous IPC: SEND, RECV, CALL, REPLY_RECV). Sending needs the write right on the mailbox key and receiving needs the read right. The receiver learns the tag of the sender's key, and the right to reply can be used only once. - **Timeouts**: every one of these calls can carry a time limit, counted in timer ticks (one tick is one second). If no partner arrives in time, the call returns an error (`TIMEOUT`, or `REPLY_TIMEOUT` when a `CALL` was delivered but no reply came). Without a limit a task waits as long as it takes. The wait lasts at least the given number of ticks and may be a little longer. The limit says when the task becomes ready again, not when it runs. -- **Idle**: when no task can run, the kernel no longer stops. It waits for the next interrupt, wakes tasks whose time limit has passed and carries on. If nothing can ever wake a task, the machine stays idle and the boot log says `k0: all tasks stopped (none ready, no timeout pending)`. +- **Idle**: when no task can run, the kernel no longer stops. It waits for the next interrupt, wakes tasks whose time limit has passed and carries on. If nothing can ever wake a task, the machine stays idle and the boot log says `k0: all tasks stopped (none ready, no timeout pending)`. That line appears only when there is neither a timed waiter nor a task waiting for console input. A terminal image prints nothing there, because waiting for input is its normal state. - **Kernel tables sized at boot**: the kernel sets aside the memory for its own page tables and address space entries at boot, in proportion to the memory it hands out (about 0.4 % of RAM). So a task cannot use these tables up, and the number of address spaces is limited only by memory. - **Crash containment**: when a task crashes, makes a system call the kernel does not know, or exits, only that task is stopped (fault isolation). - **Task isolation and taking keys back**: tasks tied to different key rings and address spaces cannot reach each other's memory or keys. Every key remembers which key it was copied from (derivation list). Taking a key back (CAP_REVOKE) or deleting it (CAP_DELETE) has the following effects. @@ -147,11 +149,28 @@ These features only add and are not in `default`, so **every build command must - **Signing oracle (optional)**: this is the first service that does a job for other programs. A digital signature is a short value that proves a message was approved by whoever holds a secret key, and anyone with the matching public key can check it. A signing oracle is a program that signs messages for others and never shows its secret key. In K0 a vault task holds one key. Client tasks send it messages through a mailbox (IPC) and get back a signature or the public key, but never the key. The vault runs in its own address space, so no task other than the root task can map its memory. - **Off by default**: two Cargo features of the kernel crate add it. `vault` adds the service, with no signing algorithm: every signing request answers "unsupported". `vault-ed25519` adds the algorithm. For example: `cargo build -p k0-kernel --features console,vault-ed25519`. The vault's code is part of the root task image, which is checked at boot like before, and nothing is loaded after boot. The default image has no vault code and no crypto code. - **Algorithm**: Ed25519 (PureEdDSA with SHA-512, as in FIPS 186-5 and RFC 8032). The implementation is the vendored crate `ed25519-dalek` 2.2.0 and has no validation of any kind. The key does not come from an approved random bit generator. - - **Who may do what**: the rules are fixed at build time and depend on the tag (badge) that the kernel puts on each message, so a client cannot forge it. The root task is the admin: it can ask for the status, create the key once (INIT) and wipe it (ZEROIZE), but it cannot sign. A signer can ask for the status and the public key and can sign. A reader can ask for the status and the public key only. A call without a known tag is refused. All signers share the one key, so a signature does not tell which client asked. - - **The key**: the vault makes the key only if the boot seed holds enough randomness (at least 32 bytes from the device tree `rng-seed` or 256 bits from the processor's random number instruction RNDR). Otherwise it refuses. Before the kernel starts the root task, it zeroes the seed bytes in the device tree it received, and the boot log says `k0: dtb seeds wiped B`. The seed is as good as its inputs and no better. Copies that the firmware or the UEFI loader keep are not wiped. - - **Self-test**: every image built with `vault` runs a test in the root task, which plays the admin and several clients. It shows that an unbadged call is refused, that the key is made once, that the admin cannot sign, that a signer gets a signature that checks and fails for a changed message, that a reader cannot sign, that a client that writes its read-only reply memory or reads another client's request is stopped by a fault, and that signing is refused after ZEROIZE. It ends with `root: oracle tests pass`. The test clients run one after another in one address space, so it shows the isolation between the vault and a client, not between clients. + - **Who may do what**: the rules are fixed at build time and depend on the tag (badge) that the kernel puts on each message, so a client cannot forge it. There are four roles. The root task is the admin: it can ask for the status, deliver the seed once (INIT), create the key (KEYGEN) and wipe it (ZEROIZE), but it cannot sign. The operator (the terminal) can ask for the status and the public key, create the key and wipe it, but it can neither sign nor deliver a seed. A signer can ask for the status and the public key and can sign. A reader can ask for the status and the public key only. A call without a known tag is refused. All signers share the one key, so a signature does not tell which client asked. + - **The key**: INIT only delivers the boot seed. The vault takes and holds the seed (`seeded`) only if it has enough randomness (at least 32 bytes from the device tree `rng-seed` or 256 bits from the processor's random number instruction RNDR), and otherwise refuses. KEYGEN then makes the key of the chosen algorithm from the held seed and wipes the seed (`ready`). There is one key per boot: a second KEYGEN is refused, and after ZEROIZE a reboot is needed. Before the kernel starts the root task, it zeroes the seed bytes in the device tree it received, and the boot log says `k0: dtb seeds wiped B`. The seed is as good as its inputs and no better. Copies that the firmware or the UEFI loader keep are not wiped. + - **Self-test**: every image built with `vault` runs a test in the root task, which plays the admin and several clients. Its vault makes its key from the public RFC 8032 test seed, and the entropy rule still runs. The test shows that an unbadged call is refused, that the key is made once, that the admin cannot sign, that a signer gets a signature that checks and fails for a changed message, that a reader cannot sign, that a client that writes its read-only reply memory or reads another client's request is stopped by a fault, and that signing is refused after ZEROIZE. It ends with `root: oracle tests pass`. The test clients run one after another in one address space, so it shows the isolation between the vault and a client, not between clients. + +- **Operator terminal (optional)**: a task that lets a person type commands on the serial line to work with the signing oracle's vault. It can make the key, read the public key and erase the key, but it cannot sign. + - **How to turn it on**: it is off by default and is added by the Cargo feature `terminal` of the kernel crate. The vault also needs `vault-ed25519` to make a key. You can build it and run it in QEMU as follows: + + ```sh + $ cargo build -p k0-kernel --features console,terminal,vault-ed25519 + $ cargo run -p k0-kernel --features console,terminal,vault-ed25519 + ``` + + Under `cargo run`, QEMU's own escape key is Ctrl-A (Ctrl-A, then X quits QEMU), so Ctrl-A never reaches K0. + - **Start-up order**: a terminal image runs all self-tests first. Then the root task starts a new vault and hands it the boot seed (`root: vault seeded`), checks that two hostile tasks wired exactly like the terminal are refused and end in a fault (`root: terminal wiring holds`), drops its own admin capability and starts the terminal (`root: service started`). After that the banner `K0 operator console, type 'help'` and the prompt `k0> ` appear. On a machine without an input path, `root: no console input, terminal not started` appears and the terminal does not start. + - **Commands**: they are `help`, `vault status` (the vault's state), `vault pubkey` (the public key), `vault keygen ed25519` (make the key) and `vault zeroize confirm` (erase the key). `vault zeroize` alone erases nothing and answers `err confirm-required`. Every command ends with one line, `ok` or `err `. `vault status` always prints `validated=no`, because the implementation has no validation of any kind. [USAGE.md](USAGE.md) has the details and an example screen. + - **Input rules**: a line ends with Enter (CR or LF), has at most 64 characters and takes printable ASCII only. Backspace and DEL erase one character, Ctrl-C and Ctrl-U cancel the line, and escape sequences such as the arrow keys are ignored. Bytes that reached the UART before the prompt are dropped. If input was lost, everything up to the next line end is dropped and `err input-lost` is printed. + - **What the kernel does**: the kernel only collects the bytes received by the UART in a ring of 256 bytes and never interprets them. A task takes them one byte at a time with the system call `CONSOLE_READ`, and only one task can wait at a time. The receive interrupt stays off until a task first reads console input. At that moment one line `k0: tick lines off (console input in use)` is printed and the periodic `k0: tick N` lines stop, while the timer, preemption and timeouts keep working. When the ring is full, the kernel masks the receive interrupt itself and reopens it after the task has taken half of the ring, so a flood of input costs the kernel no more work than the reader allows. At boot the log says `k0: console input on (pl011 irq 33)` or `k0: console input off ()`. A wrong interrupt number switches off input only and does not stop the boot. + - **There is no authentication**: whoever holds the serial line is the operator and can do all four of the operator's jobs (status, public key, make the key, erase the key). That includes erasing the key and so stopping the service, which is by design. The operator cannot get a signature and cannot change policy. + - **Do not trust the screen**: if a kernel line appears while someone is typing, the line on the screen is split but the input buffer is whole, and Enter runs the whole buffer. Any task with console output can print lines that look like kernel or root task lines, so a line prefix proves nothing. The terminal can also erase within its own line (it prints backspace). + - **Known limits**: the terminal and the vault are not restarted if they die (the root task is trusted). In service mode no client asks for signatures yet, so the key is made and shown but not used by another task (the self-test shows client signing). Terminal output counts against the user share of the boot log, and once that share is full, later task output is not recorded there. -The root task tests every item above with self-tests on every boot. The signing oracle is tested in the images built with it. +The root task tests every item above with self-tests on every boot. The signing oracle and the terminal are tested in the images built with them. ## Where it has run @@ -164,7 +183,7 @@ The following picture summarizes what each evidence tier means. > [!NOTE] > Only the first two tiers may be called supported. -- **Tier 1**: checked by `tools/boot-matrix.sh` (CI runs it on QEMU 7.2). +- **Tier 1**: checked by `tools/boot-matrix.sh` (CI runs it on QEMU 7.2). It has 76 rows locally with HVF and 65 in CI. - **Direct boot rows** - QEMU virt with GICv3 and with GICv2, each entered at EL1 and at EL2 - The CPU models cortex-a72, cortex-a53 and max @@ -186,6 +205,8 @@ The following picture summarizes what each evidence tier means. - A static check of the loader's PE file form and of the order of its cache and MMU instructions (`tools/pe-check.py`) - **ACPI rows**: the rows `uefi-acpi-gic3-el1`, `uefi-acpi-gic3-el2`, `uefi-acpi-gic2-el1`, `uefi-acpi-smp4`, `uefi-acpi-16k` and `uefi-acpi-rng` boot the default QEMU machine with ACPI on, without a device tree, through the tables. - **Signing oracle rows**: `vault`, `vault-max` (with RNDR), `vault-el2`, `vault-16k`, `vault-no-alg` (no signing algorithm) and `hvf-vault` (only on a Mac with HVF) boot images with the oracle and judge its self-test. The static row `vault-symbols` checks that the default image has no vault or crypto code. + - **Input rows**: `input-only`, `input-gicv2`, `input-16550` and `input-bad-irq` boot images with the input path on and judge whether input came on (or went off where it must) and the self-test. The static row `input-symbols` checks that an image built without an input feature has no receive code, no `CONSOLE_READ` and none of the new log lines. + - **Terminal rows**: `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi` and `hvf-term` (only on a Mac with HVF) boot terminal images. `tools/term-test.py ` connects QEMU's serial port to pipes and runs a scripted session: every command and error, erase and cancel, a line that is too long, key generation and the public key format, zeroize, 200 kB without a line end, 2000 lines in a row and a serial break. - **Refusal checks**: two refusals are read from the serial log. - The 16 KiB image on a CPU without 16 KiB pages - A loader whose embedded kernel has one flipped byte @@ -216,6 +237,7 @@ The rows also ran locally on QEMU 11.1.3. - Any real board, KVM, Firecracker, Cloud Hypervisor, crosvm - The 16550 console driver: no machine in the matrix has one, so no test has ever executed it. It was checked by review only. - The SBSA UART: it uses the PL011 driver without an identity check. + - Parts of input: a 16550 console has no input. The receive path of the SBSA UART, FIFO overruns and the receive timeout interrupt are not exercised by QEMU and are covered only by host tests with a fake UART. So is the cut-off of an interrupt line that fires without a UART cause. No test has measured kernel time under a flood of input on a machine. The bound is argued from the design and shown in host tests. - Release (LTO) images of the feature sets without console: the matrix builds and boots only debug images, and the symbol check runs on them. - Any image without console booted through UEFI - GICs with real security extensions on hardware @@ -253,6 +275,9 @@ What it does not stop: - A fatal error inside the kernel, or an error from the hardware that the kernel cannot attribute to one task, still stops the whole machine. - The kernel part of the boot log can be filled up by crash and exit lines. - The signing oracle is no exception: clients share one mailbox to the vault and must give a timeout on every call, or a stuck vault holds them up. + - In an image with input, an outside party can cause interrupts while tasks run. Their number is bounded by the reader, but the reader learns arrival times finer than a timer tick, and other tasks can notice the stolen time. This timing channel has not been analysed. + - Input waits behind the running tasks. There are no priorities, so the delay is up to one tick for each ready task. + - The receive code runs in the kernel (EL1). It is small and never interprets a byte, but it is kernel code driven by an outside party. Moving it to a user-space driver needs delegation of devices and interrupts, which K0 does not have yet. - **Tasks that share a key ring and an address space**: such tasks are not isolated from each other. They behave like threads, parts of one program that share everything. - **Control of a task**: whoever holds the key to a task, to its key ring or to its address space controls that task. - **The root task**: it builds every task, key ring and address space, so it is trusted and is outside the isolation. It could read the memory of the signing oracle and with it the key. "No task other than the root task can map the vault's memory" is all that holds. @@ -264,7 +289,7 @@ What it does not stop: Missing features: -- **Input**: input of any kind does not exist yet. No code reads from a UART or from any other device, and no feature for input or for a terminal exists. +- **The rest of input**: only input from the console UART exists (PL011 and SBSA UART, optional). Input from a 16550 console or from any other device does not exist yet, and neither does handling input in a user-space driver. - **Capability transfer**: a key cannot be handed to another task inside a message (capability transfer over IPC). - **Hardware interrupt notification**: a program cannot be told about hardware interrupts (Notification objects). - **Crash reports**: a crashed task is only stopped. It is not reported to a handler task. @@ -276,9 +301,9 @@ Missing features: - No persistence: the key lives only in memory and is gone after a reboot or ZEROIZE. - One key only, and no way to import or export a key. - No post-quantum (PQC) algorithm yet. - - No operator input: nobody can type a command to it, because no input of any kind exists. + - No authentication of the operator: the terminal reads the serial line, and whoever holds the line is the operator. In service mode no signing client uses the key yet. - No validation of the implementation, no analysis of timing or cache side channels of the crypto crate on this kernel, and no random bit generator beyond the boot seed. - - It has been run only in QEMU (TCG and HVF). + - It has been run only in QEMU (TCG and HVF), never on real hardware. - **Signature checking**: checking a digital signature (Ed25519) once the root task ships separately from the kernel. The signing oracle makes signatures but does not use them to check the root task. - **Real boards and other virtualization**: K0 has not been booted on real boards, or on KVM, Firecracker, Cloud Hypervisor or crosvm (tier 3 above). - **Entry from EL3 and ACPI beyond the static tables**: these two are missing. @@ -316,6 +341,7 @@ In the following table, you can find the contents of each path in the repository | `kernel/` | The kernel program: startup assembly, the order of initialization, system call handling (`syscall.rs`), cleanup when a key is removed (`object.rs`), files that describe the memory layout of the kernel image (linker scripts) | | `crates/k0-abi` | System call numbers, error codes and the boot information layout that programs share with the kernel | | `crates/k0-arch` | Handling of errors, system calls and interrupts (exceptions), entering and leaving user mode, interrupt controller and timer, PAC and PAN, the boot log and the optional console drivers | +| `crates/k0-conin` | The receive logic of console input (the ring and the loss mark), tested on the host with a fake UART | | `crates/k0-boot` | Device tree parser, the built-in root task image and its integrity check, PAC key derivation, the search for the boot memory window (shared with the loader) | | `crates/k0-efi` | The loader's logic without `unsafe` code: planning RAM from the UEFI memory map, rewriting the firmware device tree, an independent re-check of the result, and the check of the kernel image header. It runs the kernel's own device tree code on the result before the jump | | `crates/k0-cap` | Keys and their rights, key rings, the derivation list, untyped memory, retype, revoke and delete | @@ -324,8 +350,9 @@ In the following table, you can find the contents of each path in the repository | `crates/k0-sched` | Round-robin scheduler | | `crates/k0-ipc` | Synchronous messages | | `loader/` | The UEFI application (`k0-loader`, target `aarch64-unknown-uefi`) that embeds a built kernel image and starts it: UEFI calls, the flow, and the final cache flush, MMU off and jump | -| `userspace/root-task` | The first program and its self-tests, and the wiring and self-test of the signing oracle (`oracle.rs`) | +| `userspace/root-task` | The first program and its self-tests, and the wiring and self-test of the signing oracle (`oracle.rs`), and the start of the terminal service (`service.rs`) | +| `userspace/k0-term` | The operator terminal: line editing, command parsing and the requests to the vault | | `userspace/k0-vault` | The signing oracle service: protocol and fixed policy, the request handling, and the boundary around the crypto crate | -| `tools/` | QEMU runner (also for `.efi` files), boot test, boot matrix, boot log reader, host test, loader build (`build-loader.sh`), PE and instruction order check (`pe-check.py`) | +| `tools/` | QEMU runner (also for `.efi` files), boot test, boot matrix, terminal session test (`term-test.py`), boot log reader, host test, loader build (`build-loader.sh`), PE and instruction order check (`pe-check.py`) | | `ci/` | The CI build and test image (`Dockerfile`) and the threat model (`threat_model.md`) | | `vendor/` | Third-party crates kept in the repository (`sha2`, `ed25519-dalek` and their dependencies) | diff --git a/INTRODUCTION_KR.md b/INTRODUCTION_KR.md index dc8420d..f675685 100644 --- a/INTRODUCTION_KR.md +++ b/INTRODUCTION_KR.md @@ -35,6 +35,7 @@ | **엔드포인트** | 태스크끼리 메시지를 주고받는 우편함(IPC)입니다 | | **시스템 콜** | 프로그램이 커널에 하는 요청입니다 | | **인터럽트** | 타이머 같은 하드웨어가 보내는 신호입니다. 프로세서가 하던 일을 멈추고 커널을 실행하게 합니다 | +| **터미널** | 시리얼 줄로 사람이 명령을 입력하고 답을 읽는 화면입니다. K0에서는 일반 태스크 하나가 맡습니다 | ## 목표 @@ -46,7 +47,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - **연구용 기반**: 정형 검증과 인증 연구 > [!NOTE] -> 첫 작은 걸음만 있습니다. "지금 동작하는 것"에 적은 선택 사항인 서명 오라클입니다. 나머지는 아직 동작하지 않습니다. 지금의 K0는 연구용 플랫폼으로, 부팅해서 자신의 보안 성질을 스스로 확인하지만 기본값으로는 아직 그 자체로 쓸모 있는 일을 하지는 않습니다. +> 첫 작은 걸음만 있습니다. "지금 동작하는 것"에 적은 선택 사항인 서명 오라클과, 그것을 시리얼 줄로 다루는 운영자 터미널입니다. 나머지는 아직 동작하지 않습니다. 지금의 K0는 연구용 플랫폼으로, 부팅해서 자신의 보안 성질을 스스로 확인하지만 기본값으로는 아직 그 자체로 쓸모 있는 일을 하지는 않습니다. ## 지금 동작하는 것 @@ -76,39 +77,40 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - **장치 찾기**: 커널은 디바이스 트리에서 세 가지만 가져옵니다. - - **콘솔**: `/chosen`의 `stdout-path`가 가리키는 노드입니다(PL011·SBSA UART·16550 계열). + - **콘솔**: `/chosen`의 `stdout-path`가 가리키는 노드입니다(PL011·SBSA UART·16550 계열). 노드에 `interrupts`가 있으면 인터럽트 번호도 가져오며, 이 번호는 입력에만 사용합니다. UEFI 로더를 거치면 ACPI SPCR 표에서 가져옵니다. - **인터럽트 컨트롤러**: 타이머 노드의 인터럽트 부모입니다(GICv2 또는 GICv3). - **타이머 인터럽트**: EL1 가상 타이머의 인터럽트 번호입니다. - 이 값들은 바뀌지 않는 플랫폼 기술자 하나에 담겨 `k0: platform ...` 줄로 출력됩니다. 장치 페이지를 하나라도 매핑하기 전에 메모리 맵과 대조합니다. 하드웨어가 디바이스 트리와 일치해야 하며(GIC와 PL011의 식별 레지스터), 맞지 않으면 커널은 부팅을 거부합니다. 다른 UART이거나 `stdout-path`가 없으면 콘솔이 없습니다. 모든 이미지가 콘솔 노드를 이렇게 찾고 검사합니다. 콘솔을 전혀 구동하지 않는 이미지도 마찬가지입니다(다음 항목 참고). 그래서 콘솔이 검사를 통과하지 못하는 디바이스 트리는 모든 이미지가 거부합니다. + 이 값들은 바뀌지 않는 플랫폼 기술자 하나에 담겨 `k0: platform ...` 줄로 출력됩니다. 장치 페이지를 하나라도 매핑하기 전에 메모리 맵과 대조합니다. 하드웨어가 디바이스 트리와 일치해야 하며(GIC와 PL011의 식별 레지스터), 맞지 않으면 커널은 부팅을 거부합니다. 다른 UART이거나 `stdout-path`가 없으면 콘솔이 없습니다. 모든 이미지가 콘솔 노드를 이렇게 찾고 검사합니다. 콘솔을 전혀 구동하지 않는 이미지도 마찬가지입니다(다음 항목 참고). 그래서 콘솔이 검사를 통과하지 못하는 디바이스 트리는 모든 이미지가 거부합니다. 콘솔 노드에 쓸 수 있는 인터럽트가 없는 것은 거부 사유가 아닙니다. 그 경우에는 입력만 꺼집니다. -- **콘솔 출력은 선택 사항**: K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Cargo features로 선택할 수 있습니다. +- **콘솔 입출력은 선택 사항**: K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Cargo features로 선택할 수 있습니다. 콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있고, 콘솔 입력은 `console-input` 또는 `terminal`을 포함해 빌드한 이미지에만 있습니다. 다음 표는 Cargo feature를 정리한 것입니다. -> [!NOTE] -> 입력 또는 터미널용 feature는 아직 없습니다. 지금 선택할 수 있는 것은 콘솔 출력뿐입니다. - -콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다. 입력은 어떤 이미지에도 없습니다. 다음 표는 송신 드라이버를 더하는 Cargo feature를 정리한 것입니다. - -| feature | 더하는 송신 드라이버 | +| feature | 더하는 것 | | --- | --- | -| `console-pl011` | PL011과 SBSA UART | -| `console-16550` | 16550 계열 | -| `console` | 위의 둘 모두 | +| `console-pl011` | PL011과 SBSA UART의 송신 드라이버 | +| `console-16550` | 16550 계열의 송신 드라이버 | +| `console` | 위의 두 송신 드라이버 모두 | +| `console-input` | 콘솔 UART의 수신 경로와 시스템 콜 `CONSOLE_READ`. 콘솔 드라이버 feature와 함께 써야 동작합니다 | +| `terminal` | 루트 태스크 이미지 안의 운영자 터미널 태스크. `console-input`을 함께 켭니다 | + +> [!NOTE] +> 입력 받기는 PL011과 SBSA UART에만 있습니다. 16550 콘솔은 출력만 있고 입력이 없습니다. 이 feature는 더하기만 하며 `default`에 없습니다. 따라서 **모든 빌드 명령이 feature 이름을 직접 적어야 합니다**. 예를 들어 `cargo build -p k0-kernel --features console --offline`입니다. feature 없이 빌드한 이미지는 다음과 같습니다. - UART 드라이버 코드가 아예 없습니다. - 콘솔 장치 페이지를 매핑하지 않습니다. - UART에 아무것도 쓰지 않습니다. +- 수신 코드와 `CONSOLE_READ`도 없습니다. - `k0: no console (driver not built in)`을 출력합니다. - 출력은 모두 부트 로그로만 갑니다. -`DEBUG_PUTC`, `Console` 케이퍼빌리티, 부트 로그는 모든 이미지에 남고, 콘솔 노드의 검사도 그대로입니다. `grep -a 'k0: console drivers' <이미지 파일>`로 이미지에 어떤 드라이버가 있는지 알 수 있습니다(증거가 아니라 표지입니다). `k0: device pages [...]`는 커널이 매핑한 채로 두는 모든 장치 페이지를 나열합니다. UEFI 로더는 여전히 펌웨어 콘솔로 출력합니다. [design/kr/boot_KR.md](design/kr/boot_KR.md)와 [SECURITY_KR.md](SECURITY_KR.md)의 "선택적 콘솔 출력" 절을 참고하세요. +`DEBUG_PUTC`, `Console` 케이퍼빌리티, 부트 로그는 모든 이미지에 남고, 콘솔 노드의 검사도 그대로입니다. `Console` 케이퍼빌리티에는 읽기(R, 입력)와 쓰기(W, 출력) 권한이 있습니다. 복사할 때 줄일 수만 있고, 루트 태스크의 케이퍼빌리티는 W를 가지며 `console-input` 이미지에서만 R도 가집니다. `grep -a 'k0: console drivers' <이미지 파일>`로 이미지에 어떤 드라이버가 있는지 알 수 있습니다(증거가 아니라 표지입니다). `k0: device pages [...]`는 커널이 매핑한 채로 두는 모든 장치 페이지를 나열합니다. UEFI 로더는 여전히 펌웨어 콘솔로 출력합니다. [design/kr/boot_KR.md](design/kr/boot_KR.md)와 [SECURITY_KR.md](SECURITY_KR.md)의 "선택적 콘솔 출력" 절을 참고하세요. - **부트 로그**: 커널이 출력하는 모든 줄은 커널 메모리의 16 KiB 버퍼에도 들어갑니다. 콘솔이 붙기 전에 출력한 줄은 콘솔이 붙을 때 다시 출력합니다. 콘솔이 없으면 이 버퍼가 유일한 기록입니다. `tools/boot-log.py`가 QEMU 게스트의 메모리에서 이를 읽습니다. 사용자 태스크의 출력은 할당량(16 KiB 중 6 KiB)까지만 기록하고, 타이머 tick 줄은 처음 4개만 기록합니다. - **타이머**: EL1 가상 타이머만 사용하므로 하이퍼바이저 게스트 안에서도 동작합니다. 이미지는 물리 타이머를 건드리지 않으며, 부팅 매트릭스가 이를 확인합니다. - **그래뉼**: 페이지 크기는 기본 4 KiB입니다. 16 KiB 빌드는 빌드 옵션입니다([USAGE_KR.md](USAGE_KR.md) 참고). 실행 중에 선택하는 것이 아니며, 16 KiB 지원이 없는 프로세서에서는 16 KiB 이미지가 부팅을 거부합니다. -- **고정 빌드**: 부트 로그의 플랫폼 줄을 `K0_PIN`에 설정해 빌드한 이미지는 찾아낸 플랫폼, 진입 단계, RAM 범위가 다르면 부팅을 거부합니다. 보드를 잘못 선택했거나 디바이스 트리를 바꿔치기한 경우를 잡아냅니다. 비교에 사용하는 값이 디바이스 트리에서 나오므로, 악의적인 부트 체인을 막는 방어는 아닙니다. +- **고정 빌드**: 부트 로그의 플랫폼 줄을 `K0_PIN`에 설정해 빌드한 이미지는 찾아낸 플랫폼, 진입 단계, RAM 범위가 다르면 부팅을 거부합니다. 플랫폼 줄에는 이제 콘솔 인터럽트 번호도 들어가므로(`con=pl011@0x9000000,irq33`) 이전에 만든 고정 문자열은 다시 만들어야 합니다. 보드를 잘못 선택했거나 디바이스 트리를 바꿔치기한 경우를 잡아냅니다. 비교에 사용하는 값이 디바이스 트리에서 나오므로, 악의적인 부트 체인을 막는 방어는 아닙니다. - **커널 자신의 메모리 보호**: 다음을 지킵니다. - 커널 메모리의 어떤 페이지도 쓰기와 실행이 동시에 되지 않습니다(W^X). - 커널의 부트 스택 아래에는 빈 경계 페이지를 두어서, 스택 끝을 넘어가면 다른 메모리를 망가뜨리지 않고 커널이 멈춥니다. @@ -132,7 +134,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - **태스크 실행**: 태스크는 준비할 때 열쇠고리 하나와 주소 공간 하나에 묶이고(TCB_CONFIGURE) 그다음 시작됩니다(TCB_RESUME). 태스크는 차례를 돌아가며 실행되고, 너무 오래 도는 태스크는 타이머가 끊습니다(타이머 선점이 있는 라운드 로빈 스케줄링). 태스크는 자기 차례를 양보하거나(YIELD) 끝낼 수 있습니다(EXIT). - **메시지**: 태스크는 프로세서 레지스터에 담긴 짧은 메시지를 주고받습니다. 보내는 쪽은 받는 쪽이 메시지를 가져갈 때까지 기다립니다(동기 IPC: SEND, RECV, CALL, REPLY_RECV). 보내려면 우편함 열쇠에 쓰기 권한이, 받으려면 읽기 권한이 있어야 합니다. 받는 쪽은 보낸 쪽 열쇠의 표식을 알게 되고, 답장할 권리는 한 번만 사용할 수 있습니다. - **타임아웃**: 이 호출들은 모두 제한 시간을 줄 수 있습니다. 단위는 타이머 틱입니다(1틱은 1초). 제한 시간 안에 상대가 오지 않으면 호출이 오류(`TIMEOUT`, 또는 `CALL`이 전달됐지만 답이 오지 않은 경우 `REPLY_TIMEOUT`)로 돌아옵니다. 제한 시간을 주지 않으면 태스크는 필요한 만큼 계속 기다립니다. 기다리는 시간은 준 틱 수 이상이며 조금 더 길 수 있습니다. 제한 시간은 태스크가 다시 준비 상태가 되는 때를 정할 뿐, 실행되는 때를 정하지는 않습니다. -- **대기 상태**: 실행할 수 있는 태스크가 없어도 커널은 더 이상 멈추지 않습니다. 다음 인터럽트를 기다리다가, 제한 시간이 지난 태스크를 깨우고 계속 진행합니다. 태스크를 깨울 수 있는 것이 아무것도 없으면 기계는 대기 상태로 남고, 부트 로그에 `k0: all tasks stopped (none ready, no timeout pending)`이 찍힙니다. +- **대기 상태**: 실행할 수 있는 태스크가 없어도 커널은 더 이상 멈추지 않습니다. 다음 인터럽트를 기다리다가, 제한 시간이 지난 태스크를 깨우고 계속 진행합니다. 태스크를 깨울 수 있는 것이 아무것도 없으면 기계는 대기 상태로 남고, 부트 로그에 `k0: all tasks stopped (none ready, no timeout pending)`이 찍힙니다. 시간 제한이 걸린 대기도, 콘솔 입력을 기다리는 태스크도 없을 때만 이 줄이 찍힙니다. 터미널 이미지는 입력을 기다리는 것이 정상이라 아무것도 출력하지 않습니다. - **부팅 때 크기를 정하는 커널 표**: 커널은 자신이 쓸 페이지 테이블과 주소 공간 항목의 메모리를 부팅할 때 따로 떼어 둡니다. 크기는 커널이 내어 주는 메모리에 비례합니다(RAM의 약 0.4 %). 그래서 태스크가 이 표들을 다 사용해 버릴 수 없고, 주소 공간의 수는 메모리로만 제한됩니다. - **충돌 격리**: 태스크가 죽거나, 커널이 모르는 시스템 콜을 부르거나, 끝나면 그 태스크만 멈춥니다(폴트 격리). - **태스크 격리와 열쇠 회수**: 서로 다른 열쇠고리와 주소 공간에 묶인 태스크는 서로의 메모리와 열쇠에 닿을 수 없습니다. 모든 열쇠는 어느 열쇠에서 복사됐는지 기억합니다(파생 목록). 열쇠를 회수하거나(CAP_REVOKE) 지우면(CAP_DELETE) 다음 일이 일어납니다. @@ -148,11 +150,28 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - **서명 오라클(선택 사항)**: 다른 프로그램을 위해 일하는 첫 번째 서비스입니다. 디지털 서명은 어떤 메시지를 비밀 키를 가진 쪽이 승인했음을 보여 주는 짧은 값이고, 짝이 되는 공개 키가 있으면 누구나 검증할 수 있습니다. 서명 오라클은 다른 프로그램의 메시지에 서명해 주면서 비밀 키는 절대 보여 주지 않는 프로그램입니다. K0에서는 볼트 태스크가 키 하나를 가집니다. 클라이언트 태스크는 우편함(IPC)으로 메시지를 보내 서명 또는 공개 키를 받지만 키는 받지 못합니다. 볼트는 자기만의 주소 공간에서 실행되므로 루트 태스크 이외의 어떤 태스크도 볼트의 메모리를 매핑할 수 없습니다. - **기본값은 꺼짐**: 커널 크레이트의 Cargo features 두 개로 추가합니다. `vault`는 서명 알고리즘 없이 서비스만 추가하며, 모든 서명 요청에 "unsupported"로 답합니다. `vault-ed25519`는 알고리즘을 추가합니다. 예를 들어 `cargo build -p k0-kernel --features console,vault-ed25519`입니다. 볼트의 코드는 루트 태스크 이미지의 일부이고 이전과 같이 부팅 때 검사하며, 부팅 뒤에는 아무것도 적재하지 않습니다. 기본 이미지에는 볼트 코드도 암호 코드도 없습니다. - **알고리즘**: Ed25519(FIPS 186-5와 RFC 8032의 SHA-512를 쓰는 PureEdDSA)입니다. 구현은 vendor에 둔 크레이트 `ed25519-dalek` 2.2.0이며 어떤 종류의 검증도 받지 않았습니다. 키는 승인된 난수 비트 생성기에서 나오지 않습니다. - - **누가 무엇을 할 수 있나**: 규칙은 빌드 때 고정되며, 커널이 각 메시지에 붙이는 표식(배지)에 따라 정해집니다. 클라이언트는 이 표식을 위조할 수 없습니다. 루트 태스크는 관리자로서 상태 조회, 키 생성(INIT, 한 번만), 키 소거(ZEROIZE)를 할 수 있지만 서명은 할 수 없습니다. 서명자는 상태와 공개 키를 조회하고 서명할 수 있습니다. 읽기 전용 역할은 상태와 공개 키만 조회할 수 있습니다. 알려진 표식이 없는 호출은 거부합니다. 서명자는 모두 키 하나를 공유하므로 서명만으로는 어느 클라이언트가 요청했는지 알 수 없습니다. - - **키**: 볼트는 부팅 시드에 충분한 무작위성(디바이스 트리 `rng-seed` 32바이트 이상 또는 프로세서의 난수 명령 RNDR에서 256비트)이 있을 때만 키를 만들고, 그렇지 않으면 거부합니다. 커널은 루트 태스크를 시작하기 직전에 받은 디바이스 트리 안의 시드 바이트를 0으로 지우며, 부트 로그에 `k0: dtb seeds wiped B`가 찍힙니다. 시드는 입력만큼만 좋습니다. 펌웨어나 UEFI 로더가 따로 가진 사본은 지우지 못합니다. - - **자가 테스트**: `vault`를 포함해 빌드한 이미지는 모두 루트 태스크에서 테스트를 실행합니다. 루트 태스크가 관리자와 여러 클라이언트를 연기합니다. 이 테스트는 배지 없는 호출의 거부, 키가 한 번만 만들어짐, 관리자가 서명하지 못함, 서명자가 받은 서명이 검증되고 바뀐 메시지에서는 실패함, 읽기 전용 역할이 서명하지 못함, 읽기 전용 응답 메모리에 쓰거나 다른 클라이언트의 요청을 읽는 클라이언트가 폴트로 멈춤, ZEROIZE 뒤 서명 거부를 확인하고 `root: oracle tests pass`로 끝납니다. 테스트 클라이언트는 한 주소 공간에서 차례로 실행되므로, 이 테스트가 보여 주는 것은 볼트와 클라이언트 사이의 격리이며 클라이언트끼리의 격리가 아닙니다. + - **누가 무엇을 할 수 있나**: 규칙은 빌드 때 고정되며, 커널이 각 메시지에 붙이는 표식(배지)에 따라 정해집니다. 클라이언트는 이 표식을 위조할 수 없습니다. 역할은 네 가지입니다. 루트 태스크는 관리자로서 상태 조회, 시드 전달(INIT, 한 번만), 키 생성(KEYGEN), 키 소거(ZEROIZE)를 할 수 있지만 서명은 할 수 없습니다. 운영자(터미널)는 상태 조회, 공개 키 조회, 키 생성, 키 소거만 할 수 있고 서명도 시드 전달도 할 수 없습니다. 서명자는 상태와 공개 키를 조회하고 서명할 수 있습니다. 읽기 전용 역할은 상태와 공개 키만 조회할 수 있습니다. 알려진 표식이 없는 호출은 거부합니다. 서명자는 모두 키 하나를 공유하므로 서명만으로는 어느 클라이언트가 요청했는지 알 수 없습니다. + - **키**: INIT은 부팅 시드를 전달할 뿐입니다. 볼트는 시드에 충분한 무작위성(디바이스 트리 `rng-seed` 32바이트 이상 또는 프로세서의 난수 명령 RNDR에서 256비트)이 있을 때만 시드를 받아 두고(`seeded`), 그렇지 않으면 거부합니다. KEYGEN이 받아 둔 시드로 고른 알고리즘의 키를 만들고 시드를 지웁니다(`ready`). 키는 부팅마다 하나뿐이어서 두 번째 KEYGEN은 거부되고, ZEROIZE 뒤에는 재부팅이 필요합니다. 커널은 루트 태스크를 시작하기 직전에 받은 디바이스 트리 안의 시드 바이트를 0으로 지우며, 부트 로그에 `k0: dtb seeds wiped B`가 찍힙니다. 시드는 입력만큼만 좋습니다. 펌웨어나 UEFI 로더가 따로 가진 사본은 지우지 못합니다. + - **자가 테스트**: `vault`를 포함해 빌드한 이미지는 모두 루트 태스크에서 테스트를 실행합니다. 루트 태스크가 관리자와 여러 클라이언트를 연기합니다. 이 테스트의 볼트는 공개된 RFC 8032 시험 시드로 키를 만들며, 엔트로피 규칙은 그대로 실행합니다. 테스트는 배지 없는 호출의 거부, 키가 한 번만 만들어짐, 관리자가 서명하지 못함, 서명자가 받은 서명이 검증되고 바뀐 메시지에서는 실패함, 읽기 전용 역할이 서명하지 못함, 읽기 전용 응답 메모리에 쓰거나 다른 클라이언트의 요청을 읽는 클라이언트가 폴트로 멈춤, ZEROIZE 뒤 서명 거부를 확인하고 `root: oracle tests pass`로 끝납니다. 테스트 클라이언트는 한 주소 공간에서 차례로 실행되므로, 이 테스트가 보여 주는 것은 볼트와 클라이언트 사이의 격리이며 클라이언트끼리의 격리가 아닙니다. + +- **운영자 터미널(선택 사항)**: 사람이 시리얼 줄로 명령을 입력해 서명 오라클의 볼트를 다루게 해 주는 태스크입니다. 서명 오라클에 키를 만들게 하고 공개 키를 읽고 키를 지울 수 있지만, 서명은 할 수 없습니다. + - **켜는 법**: 기본값은 꺼짐이고, 커널 크레이트의 Cargo feature `terminal`로 추가합니다. 볼트가 키를 만들려면 `vault-ed25519`도 필요합니다. 다음과 같이 빌드하고 QEMU에서 실행할 수 있습니다. + + ```sh + $ cargo build -p k0-kernel --features console,terminal,vault-ed25519 + $ cargo run -p k0-kernel --features console,terminal,vault-ed25519 + ``` + + `cargo run` 아래에서는 QEMU 자신의 탈출 키가 Ctrl-A라서(Ctrl-A 다음 X로 QEMU 종료) Ctrl-A는 K0에 닿지 않습니다. + - **시작 순서**: 터미널 이미지는 자가 테스트를 모두 실행한 다음, 루트 태스크가 새 볼트를 시작해 부팅 시드를 건네고(`root: vault seeded`), 터미널과 똑같이 연결한 적대 태스크 둘이 거부되고 폴트로 끝나는지 확인한 뒤(`root: terminal wiring holds`), 자기 관리자 열쇠를 버리고 터미널을 시작합니다(`root: service started`). 그 뒤 배너 `K0 operator console, type 'help'`와 프롬프트 `k0> `가 나옵니다. 입력 경로가 없는 기계에서는 `root: no console input, terminal not started`가 나오고 터미널은 시작하지 않습니다. + - **명령**: `help`, `vault status`(볼트 상태), `vault pubkey`(공개 키), `vault keygen ed25519`(키 만들기), `vault zeroize confirm`(키 지우기)이 있습니다. `vault zeroize`만 입력하면 지우지 않고 `err confirm-required`가 나옵니다. 모든 명령은 `ok` 또는 `err <이유>` 한 줄로 끝납니다. `vault status`는 항상 `validated=no`를 출력합니다. 구현이 어떤 검증도 받지 않았기 때문입니다. 자세한 사용법과 예시 화면은 [USAGE_KR.md](USAGE_KR.md)에 있습니다. + - **입력 규칙**: 줄은 Enter(CR 또는 LF)로 끝나고 64자까지이며 출력할 수 있는 ASCII만 받습니다. Backspace와 DEL은 한 글자를 지우고, Ctrl-C와 Ctrl-U는 줄을 취소하며, 방향키 같은 ESC 열은 무시합니다. 프롬프트가 나오기 전에 UART에 도착한 바이트는 버립니다. 입력이 유실되면 다음 줄 끝까지 모두 버리고 `err input-lost`를 출력합니다. + - **커널이 하는 일**: 커널은 UART에서 받은 바이트를 256바이트 링에 쌓기만 하고 해석하지 않습니다. 태스크는 시스템 콜 `CONSOLE_READ`로 한 번에 한 바이트씩 가져가며, 한 번에 한 태스크만 기다릴 수 있습니다. 수신 인터럽트는 어떤 태스크가 처음 입력을 읽을 때까지 꺼져 있습니다. 그때 `k0: tick lines off (console input in use)` 한 줄을 남기고 주기적인 `k0: tick N` 줄이 멈추지만 타이머, 선점, 제한 시간은 계속 동작합니다. 링이 차면 커널이 수신 인터럽트를 스스로 막았다가 태스크가 절반을 가져간 뒤 다시 열어서, 입력이 몰려도 커널의 일은 읽는 쪽 속도로 제한됩니다. 부팅 때 `k0: console input on (pl011 irq 33)` 또는 `k0: console input off (<이유>)`가 출력됩니다. 틀린 인터럽트 번호는 입력만 끄고 부팅은 막지 않습니다. + - **인증이 없습니다**: 시리얼 줄을 쥔 사람이 곧 운영자이고, 운영자의 네 가지 일(상태, 공개 키, 키 만들기, 키 지우기)을 모두 할 수 있습니다. 키를 지워 서비스를 멈추게 하는 것까지 포함하며, 이것은 설계에 따른 것입니다. 서명을 받거나 정책을 바꾸지는 못합니다. + - **화면을 믿으면 안 됩니다**: 커널 줄이 입력 도중에 끼어들면 화면의 줄은 갈라져 보이지만 입력 버퍼는 온전하고, Enter를 치면 버퍼 전체가 실행됩니다. 콘솔 출력을 가진 태스크는 커널이나 루트 태스크 줄처럼 보이는 줄을 아무거나 출력할 수 있어서 줄 머리말은 아무것도 증명하지 않습니다. 터미널은 거기에 더해 자기 줄 안에서 글자를 지울 수 있습니다(백스페이스 출력). + - **알려진 한계**: 터미널과 볼트는 죽어도 다시 시작하지 않습니다(루트 태스크는 신뢰합니다). 서비스 모드에는 서명을 요청하는 클라이언트가 아직 없어서 키는 만들고 보여 줄 뿐 다른 태스크가 쓰지 못합니다(클라이언트의 서명은 자가 테스트가 보여 줍니다). 터미널 출력은 부트 로그의 사용자 몫을 차지하므로, 그 몫이 차면 이후 태스크 출력은 기록되지 않습니다. -위 항목은 전부 루트 태스크가 부팅할 때마다 자가 테스트로 확인합니다. 서명 오라클은 그것을 포함해 빌드한 이미지에서 테스트합니다. +위 항목은 전부 루트 태스크가 부팅할 때마다 자가 테스트로 확인합니다. 서명 오라클과 터미널은 그것을 포함해 빌드한 이미지에서 테스트합니다. ## 어디서 돌려 봤나 @@ -165,7 +184,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. > [!NOTE] > 앞의 두 단계만 지원한다고 말할 수 있습니다. -- **1단계**: `tools/boot-matrix.sh`가 확인합니다(CI가 QEMU 7.2로 실행). +- **1단계**: `tools/boot-matrix.sh`가 확인합니다(CI가 QEMU 7.2로 실행). 행은 HVF가 있는 로컬에서 76개, CI에서 65개입니다. - **직접 부팅 행** - GICv3와 GICv2의 QEMU virt를 각각 EL1과 EL2로 진입 - CPU 모델 cortex-a72, cortex-a53, max @@ -187,6 +206,8 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - 로더 PE 파일의 형식과 캐시·MMU 명령의 순서에 대한 정적 검사(`tools/pe-check.py`) - **ACPI 행**: `uefi-acpi-gic3-el1`, `uefi-acpi-gic3-el2`, `uefi-acpi-gic2-el1`, `uefi-acpi-smp4`, `uefi-acpi-16k`, `uefi-acpi-rng` 행은 ACPI를 켠 기본 QEMU 머신을 디바이스 트리 없이 테이블만으로 부팅합니다. - **서명 오라클 행**: `vault`, `vault-max`(RNDR 포함), `vault-el2`, `vault-16k`, `vault-no-alg`(서명 알고리즘 없음), `hvf-vault`(HVF가 있는 Mac에서만)는 오라클을 포함한 이미지를 부팅해 그 자가 테스트를 판정합니다. 정적 행 `vault-symbols`는 기본 이미지에 볼트 코드와 암호 코드가 없는지 확인합니다. + - **입력 행**: `input-only`, `input-gicv2`, `input-16550`, `input-bad-irq`는 입력 경로를 켠 이미지를 부팅해 입력이 켜졌는지(또는 꺼져야 하는 곳에서 꺼졌는지)와 그 자가 테스트를 판정합니다. 정적 행 `input-symbols`는 입력 feature 없이 빌드한 이미지에 수신 코드, `CONSOLE_READ`, 새 로그 줄이 없는지 확인합니다. + - **터미널 행**: `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi`, `hvf-term`(HVF가 있는 Mac에서만)은 터미널 이미지를 부팅합니다. `tools/term-test.py <이미지>`는 QEMU의 시리얼 포트를 파이프로 이어 모든 명령과 오류, 지우기와 취소, 너무 긴 줄, 키 생성과 공개 키 형식, 키 소거, 줄 끝 없는 200 kB, 연속 2000줄, 시리얼 break까지 정해 둔 대화를 그대로 실행합니다. - **거부 확인**: 시리얼 로그로 확인하는 거부는 두 가지입니다. - 16 KiB 페이지가 없는 CPU에서의 16 KiB 이미지 - 내장 커널의 한 바이트를 뒤집은 로더 @@ -217,6 +238,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - 모든 실제 보드, KVM, Firecracker, Cloud Hypervisor, crosvm - **16550 콘솔 드라이버**: 매트릭스의 어떤 머신에도 없어서 어떤 테스트도 실행한 적이 없고, 리뷰로만 확인했습니다. - **SBSA UART**: 식별 검사 없이 PL011 드라이버를 사용합니다. + - **입력의 일부**: 16550 콘솔에는 입력이 없습니다. SBSA UART의 수신 경로, FIFO 넘침, 수신 시간 초과 인터럽트는 QEMU가 실행하지 않아서 가짜 UART를 쓰는 호스트 테스트로만 확인했습니다. 설명 없이 계속 울리는 인터럽트 선을 끊는 장치도 호스트 테스트로만 확인했습니다. 입력이 몰릴 때 커널이 쓰는 시간을 실제 기계에서 잰 테스트는 없고, 상한은 설계에서 따져 보고 호스트 테스트로 보인 것입니다. - **콘솔 없는 feature 조합의 릴리즈(LTO) 이미지**: 매트릭스는 디버그 이미지만 빌드하고 부팅하며 심볼 검사도 거기서 합니다. - UEFI로 부팅한 콘솔 없는 이미지 - 실제 하드웨어의 보안 확장이 있는 GIC @@ -254,6 +276,9 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - 커널 안의 치명적 오류, 또는 커널이 한 태스크의 탓으로 돌릴 수 없는 하드웨어 오류는 여전히 기계 전체를 멈춥니다. - 부트 로그의 커널 부분은 충돌과 종료 줄로 가득 찰 수 있습니다. - 서명 오라클도 예외가 아닙니다. 클라이언트는 볼트로 가는 우편함 하나를 함께 사용하므로 모든 호출에 타임아웃을 줘야 하며, 그렇지 않으면 멈춘 볼트가 클라이언트를 붙잡습니다. + - 입력을 켠 이미지에서는 바깥 쪽이 태스크가 실행되는 동안에도 인터럽트를 일으킬 수 있습니다. 그 횟수는 읽는 쪽 속도로 제한되지만, 읽는 태스크는 타이머 틱보다 더 잘게 도착 시각을 알 수 있고 다른 태스크도 빼앗긴 시간을 눈치챌 수 있습니다. 이 시간 채널은 분석하지 않았습니다. + - 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없어서 지연은 준비된 태스크마다 최대 한 틱입니다. + - 입력 수신 코드는 커널(EL1)에서 실행됩니다. 작고 바이트를 해석하지 않지만, 바깥 쪽이 움직이는 커널 코드입니다. 이것을 사용자 공간 드라이버로 옮기려면 장치와 인터럽트를 넘겨 주는 기능이 필요한데, K0에는 아직 없습니다. - **열쇠고리와 주소 공간을 함께 사용하는 태스크**: 이런 태스크끼리는 격리되지 않습니다. 모든 것을 함께 사용하는 한 프로그램의 일부, 즉 스레드처럼 동작합니다. - **태스크 통제**: 어떤 태스크나 그 태스크의 열쇠고리, 주소 공간의 열쇠를 가진 쪽이 그 태스크를 통제합니다. - **루트 태스크**: 모든 태스크, 열쇠고리, 주소 공간을 만들기 때문에 신뢰해야 하며 격리 바깥에 있습니다. 서명 오라클의 메모리와 그 안의 키를 읽을 수 있습니다. "루트 태스크 이외의 어떤 태스크도 볼트의 메모리를 매핑할 수 없다"만 성립합니다. @@ -265,7 +290,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. 없는 기능: -- **입력**: 어떤 종류의 입력도 아직 없습니다. UART든 다른 장치든 읽는 코드가 없고, 입력 또는 터미널용 feature도 없습니다. +- **입력의 나머지**: 콘솔 UART의 입력만 있습니다(PL011과 SBSA UART, 선택 사항). 16550 콘솔과 다른 장치의 입력은 아직 없습니다. 입력을 사용자 공간 드라이버로 처리하는 것도 아직 없습니다. - **케이퍼빌리티 전송**: 메시지에 열쇠를 담아 다른 태스크에 넘기는 기능입니다(IPC를 통한 케이퍼빌리티 전송). - **하드웨어 인터럽트 알림**: 하드웨어 인터럽트를 프로그램에 알려 주는 기능입니다(Notification 오브젝트). - **죽은 태스크 통지**: 죽은 태스크를 멈추기만 하지 않고 처리 담당 태스크에 알려 주는 기능입니다. @@ -277,9 +302,9 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - 영속성이 없습니다. 키는 메모리에만 있고 재부팅이나 ZEROIZE 뒤에는 사라집니다. - 키는 하나뿐이며, 키를 가져오거나 내보내는 방법이 없습니다. - 양자내성(PQC) 알고리즘은 아직 없습니다. - - 운영자 입력이 없습니다. 어떤 종류의 입력도 없으므로 아무도 명령을 입력할 수 없습니다. + - 운영자의 인증이 없습니다. 시리얼 줄에서 입력하는 터미널은 있지만 줄을 쥔 사람이 곧 운영자입니다. 서비스 모드에서 키를 쓰는 서명 클라이언트도 아직 없습니다. - 구현은 검증받지 않았고, 이 커널에서 암호 크레이트의 타이밍·캐시 사이드 채널을 분석하지 않았으며, 부팅 시드 이외의 난수 비트 생성기도 없습니다. - - QEMU(TCG와 HVF)에서만 실행했습니다. + - QEMU(TCG와 HVF)에서만 실행했고, 실제 하드웨어에서는 실행한 적이 없습니다. - **서명 검증**: 루트 태스크를 커널과 따로 배포할 때의 디지털 서명(Ed25519) 검증입니다. 서명 오라클은 서명을 만들지만, 그 서명으로 루트 태스크를 검증하지는 않습니다. - **실제 보드와 가상화 환경 부팅**: 실제 보드, 그리고 KVM·Firecracker·Cloud Hypervisor·crosvm에서의 부팅입니다(위 3단계). - **EL3 진입과 정적 테이블 너머의 ACPI**: 이 둘은 없습니다. @@ -317,6 +342,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. | `kernel/` | 커널 프로그램. 시작 어셈블리, 초기화 순서, 시스템 콜 처리(`syscall.rs`), 열쇠가 지워질 때의 정리(`object.rs`), 커널 이미지의 메모리 배치를 정하는 파일(링커 스크립트) | | `crates/k0-abi` | 프로그램과 커널이 함께 사용하는 시스템 콜 번호, 에러 코드, 부팅 정보 레이아웃 | | `crates/k0-arch` | 에러, 시스템 콜, 인터럽트 처리(예외), 사용자 모드 진입과 복귀, 인터럽트 컨트롤러와 타이머, PAC과 PAN, 부트 로그와 선택적 콘솔 드라이버 | +| `crates/k0-conin` | 콘솔 입력의 수신 논리(링과 유실 표시). 가짜 UART로 호스트에서 테스트합니다 | | `crates/k0-boot` | 디바이스 트리 파서, 내장된 루트 태스크 이미지와 무결성 검사, PAC 키 파생, 부트 메모리 창 탐색(로더와 공유) | | `crates/k0-efi` | `unsafe` 없는 로더의 논리. UEFI 메모리 맵에서 RAM 계획, 펌웨어 디바이스 트리 고쳐 쓰기, 결과의 독립적인 재검사, 커널 이미지 헤더 검사. 점프 전에 결과에 커널 자신의 디바이스 트리 코드를 돌려 봅니다 | | `crates/k0-cap` | 열쇠와 권한, 열쇠고리, 파생 목록, untyped 메모리, retype, revoke와 delete | @@ -325,8 +351,9 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. | `crates/k0-sched` | 라운드 로빈 스케줄러 | | `crates/k0-ipc` | 동기 메시지 | | `loader/` | 빌드된 커널 이미지를 품고 시작시키는 UEFI 응용 프로그램(`k0-loader`, 타겟 `aarch64-unknown-uefi`). UEFI 호출, 흐름, 마지막의 캐시 비우기·MMU 끄기·점프 | -| `userspace/root-task` | 첫 프로그램과 자가 테스트, 서명 오라클의 연결과 자가 테스트(`oracle.rs`) | +| `userspace/root-task` | 첫 프로그램과 자가 테스트, 서명 오라클의 연결과 자가 테스트(`oracle.rs`), 터미널 서비스의 시작(`service.rs`) | +| `userspace/k0-term` | 운영자 터미널. 줄 편집, 명령 해석, 볼트로 보내는 요청 | | `userspace/k0-vault` | 서명 오라클 서비스. 프로토콜과 고정 정책, 요청 처리, 암호 크레이트를 감싸는 경계 | -| `tools/` | QEMU 러너(`.efi`도 지원), 부팅 테스트, 부팅 매트릭스, 부트 로그 읽기, 호스트 테스트, 로더 빌드(`build-loader.sh`), PE와 명령 순서 검사(`pe-check.py`) | +| `tools/` | QEMU 러너(`.efi`도 지원), 부팅 테스트, 부팅 매트릭스, 터미널 대화 테스트(`term-test.py`), 부트 로그 읽기, 호스트 테스트, 로더 빌드(`build-loader.sh`), PE와 명령 순서 검사(`pe-check.py`) | | `ci/` | CI 빌드·테스트 이미지(`Dockerfile`)와 위협 모델(`threat_model.md`) | | `vendor/` | 저장소 안에 함께 넣어 둔 서드파티 크레이트(`sha2`, `ed25519-dalek`과 그 의존성) | diff --git a/README.md b/README.md index ceae4f0..48112e4 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,10 @@ K0 is a small operating system kernel for 64-bit ARM (AArch64) computers. It is - **Write or run, never both**: no memory is writable and executable at the same time. The flip side is that no new code can become executable after boot, so programs cannot load new code. - **Distrust of boot input**: the hardware description handed over at boot is checked as if an attacker wrote it. - **Optional signing oracle**: a build option adds a task that signs messages for other tasks and never gives out its key. It is off by default, the Ed25519 implementation is unvalidated, and it keeps one key in memory only. See [INTRODUCTION.md](INTRODUCTION.md). +- **Optional operator terminal**: a build option adds a screen on the serial line where a person types commands. It can make the signing oracle's key, read the public key and erase the key, but it cannot sign. It is off by default. + +> [!NOTE] +> The terminal has no authentication, so whoever holds the serial line is the operator. Input exists only for the PL011 and the SBSA UART, and it has never been run on real hardware. The first program checks these properties with self-tests on every boot. @@ -48,6 +52,12 @@ $ cd k0 $ cargo virt ``` +To build an image with the terminal and run it in QEMU, you can enter the following. Under `cargo run`, Ctrl-A is QEMU's own escape key, so it never reaches K0. + +```sh +$ cargo run -p k0-kernel --features console,terminal,vault-ed25519 +``` + [USAGE.md](USAGE.md) explains what you need, how to read the output and how to run the automatic tests. ## Documents diff --git a/README_KR.md b/README_KR.md index 555bbfd..ac1bd08 100644 --- a/README_KR.md +++ b/README_KR.md @@ -34,6 +34,10 @@ K0는 64비트 ARM(AArch64) 컴퓨터용 작은 운영체제 커널입니다. Ru - **쓰기와 실행은 동시에 불가**: 어떤 메모리도 쓰기와 실행이 동시에 되지 않습니다. 그 대가로 부팅 뒤에는 새 코드를 실행 가능하게 만들 수 없어서, 프로그램이 새 코드를 불러올 수 없습니다. - **부팅 입력 불신**: 부팅 때 넘겨받는 하드웨어 설명은 공격자가 작성한 것처럼 검사합니다. - **선택 사항인 서명 오라클**: 빌드 옵션으로 다른 태스크를 위해 메시지에 서명하고 키는 절대 내주지 않는 태스크를 추가합니다. 기본값은 꺼짐이고, Ed25519 구현은 검증받지 않았으며, 키는 하나를 메모리에만 둡니다. [INTRODUCTION_KR.md](INTRODUCTION_KR.md)를 참고하세요. +- **선택 사항인 운영자 터미널**: 빌드 옵션으로 시리얼 줄에서 사람이 명령을 입력하는 화면을 추가합니다. 서명 오라클의 키를 만들고, 공개 키를 읽고, 키를 지울 수 있지만 서명은 할 수 없습니다. 기본값은 꺼짐입니다. + +> [!NOTE] +> 터미널에는 인증이 없어서 시리얼 줄을 쥔 사람이 곧 운영자입니다. 입력은 PL011과 SBSA UART에만 있고, 실제 하드웨어에서는 실행해 본 적이 없습니다. 첫 프로그램이 부팅할 때마다 자가 테스트로 위 성질들을 확인합니다. @@ -48,6 +52,12 @@ $ cd k0 $ cargo virt ``` +터미널을 켠 이미지를 빌드해 QEMU에서 실행하려면 다음과 같이 입력할 수 있습니다. `cargo run` 아래에서는 Ctrl-A가 QEMU의 탈출 키라서 K0에 닿지 않습니다. + +```sh +$ cargo run -p k0-kernel --features console,terminal,vault-ed25519 +``` + 필요한 도구, 출력 읽는 법 및 자동 테스트 실행 방법은 [USAGE_KR.md](USAGE_KR.md)에 있습니다. ## 문서 diff --git a/SECURITY.md b/SECURITY.md index e6f23e3..edd1d86 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -47,7 +47,7 @@ Treat every task as fully trusted in those versions. ### The current `main` branch (unreleased) -The current `main` branch contains task isolation. No release or tag contains it yet, and its system call ABI is incompatible with `v0.1.0` (bootinfo layout version 3). +The current `main` branch contains task isolation. No release or tag contains it yet, and its system call ABI is incompatible with `v0.1.0` (bootinfo layout version 4). A confined task has the following properties: @@ -55,7 +55,7 @@ A confined task has the following properties: - **Address space**: every task runs in the address space named by an `AddrSpace` capability. A task reaches exactly the memory that the holder of its `AddrSpace` capability mapped into that address space. - **Bindings**: both bindings are held as capabilities inside the task's TCB. If either capability is revoked or deleted, the task is torn down. - **Scope of isolation**: isolation holds between tasks bound to different CNodes and address spaces. Tasks that share them, as the root task's helper threads do, are threads of one another. Whoever holds a task's TCB, CNode or AddrSpace capability controls that task. -- **Rights**: capabilities carry rights (R, W, X). Rights can only be removed by `CAP_COPY`, never added. `Endpoint` capabilities can carry a badge, set once by `CAP_COPY`, which the receiver sees. Retyped frames never gain X, and X exists only on the root task's text frames, so no physical frame is writable in one place and executable in another. +- **Rights**: capabilities carry rights (R, W, X). Rights can only be removed by `CAP_COPY`, never added. `Endpoint` capabilities can carry a badge, set once by `CAP_COPY`, which the receiver sees. The `Console` capability carries R (read input) and W (write output) in the same way. Retyped frames never gain X, and X exists only on the root task's text frames, so no physical frame is writable in one place and executable in another. - **Derivation and teardown**: capabilities form a derivation list. `CAP_REVOKE` removes everything derived from a capability, `CAP_DELETE` also removes the slot, an object is finalized when its original capability is removed, and the underlying `Untyped` memory can then be retyped again. Retyped objects are zeroed before a capability to them exists. - **Fault isolation**: a fault, an exit, or an unknown system call in a confined task terminates only that task. @@ -71,15 +71,16 @@ What is still NOT provided on `main`: - **Missing features**: no fault delivery to a handler task, no notifications, and no capability transfer over IPC. - **Time visible to EL0**: EL0 still cannot read any hardware counter or timer. IPC timeouts give a task a clock as coarse as the scheduler tick (1 second) and a wake-up aligned to the timer interrupt. Whether that can be amplified into a usable timing source for cache or speculation attacks has not been analysed. - **Sender after revoke**: a sender already queued on an endpoint still delivers once after its capability is revoked. +- **Serial line**: in an image built with the features `console-input` or `terminal`, an outside party can reach the kernel through the serial line. The operator terminal has no authentication, an outside party can cause interrupts while tasks run, and input waits behind running tasks. See "Serial input and the operator terminal". - **Cores**: one core only. - **Executable code**: new executable code cannot be loaded after boot, so a confined task runs code from the root task image. - **Supported scope**: only the evidence tiers in [INTRODUCTION.md](INTRODUCTION.md) count as supported. Real boards, KVM and other hypervisors, the 16550 console driver, and processors with `HCR_EL2.E2H` fixed to 1 have never been booted. - **Device tree**: the device tree is not trusted, but it now supplies device addresses. A wrong or hostile device tree can point the console at another device. The kernel limits this: it checks the platform descriptor against the memory map, checks the identification registers of the GIC and the PL011 (the PL011 through a temporary probe mapping, so a device that fails the check is not left mapped; no such register exists for a 16550 or an SBSA UART, so those have no such check), maps a device page only after validation, bounds every console wait, and offers a pinned build (`K0_PIN`) that refuses a different platform. The pinned build compares values that come from the device tree, so it does not stop a hostile boot chain. - **Device tree address**: the address of the device tree cannot be checked before the first read. The boot loader passes it in `x0`, and the kernel has no memory map until it has read that blob. The kernel refuses a null or misaligned address, an address at or above 2^47 and a range that overlaps the kernel image. It then maps the address as read-only normal memory and reads eight bytes. It reads further, up to 2 MiB, only if those bytes look like a device tree header. A boot loader that passes the address of a device therefore makes the kernel read device registers as if they were memory, and reading some registers has side effects. The mapping is cacheable, so the processor may fetch more of that page than the eight bytes the kernel asks for. The later check that the device tree lies inside declared memory uses the memory map from the same blob. The only write through this mapping happens once, after the blob was parsed and validated: right before the kernel enters the root task, it zeroes the `rng-seed` and `kaslr-seed` values (see "Boot seed and seed wipe" under "The signing oracle"). A second `/chosen` node is refused. -- **Source of output**: kernel output and task output share one boot log, and in an image built with a console driver also one console. A line does not say who wrote it. A task that holds a `Console` capability can print a line that starts with `k0:`. The kernel replaces control bytes and limits how much of the boot log task output may use, but nothing that reads the console or the log, including `tools/qemu-boot-test.sh`, can treat a `k0:` line printed after `k0: entering root task (el0)` as written by the kernel. This includes the `k0: console drivers [...]` line (see "Optional console output"). +- **Source of output**: kernel output and task output share one boot log, and in an image built with a console driver also one console. A line does not say who wrote it. A task that holds a `Console` capability with the write right can print a line that starts with `k0:`. The kernel replaces control bytes and limits how much of the boot log task output may use, but nothing that reads the console or the log, including `tools/qemu-boot-test.sh`, can treat a `k0:` line printed after `k0: entering root task (el0)` as written by the kernel. This includes the `k0: console drivers [...]` line (see "Optional console output"). - **Trap to EL2**: isolation covers confidentiality and integrity, not availability. A trap to EL2 after the kernel has stepped down to EL1 parks the whole machine by design. - **Entry at EL2**: entry at EL2 relies on the firmware contract that Linux also uses: an EL3 firmware must enable the fine-grained-trap and HCRX controls when those features exist. -- **Root task**: the root task is still trusted and holds the initial `Untyped` capabilities, and `write_bootinfo` still exposes their physical addresses to it. In an image with the signing oracle it also builds the vault and could read the vault's memory (see "The signing oracle"). +- **Root task**: the root task is still trusted and holds the initial `Untyped` capabilities, and `write_bootinfo` still exposes their physical addresses to it. In an image with the signing oracle it also builds the vault and could read the vault's memory (see "The signing oracle"). In an image with the feature `terminal` it also starts the terminal task and is not restarted if the terminal or the vault dies. > [!WARNING] > Even on `main`, treat running untrusted code as experimental. The availability limits above still apply. @@ -120,9 +121,9 @@ Limits and residual risks of the loader: Input and output are optional in K0. You can select them with Cargo features of the kernel crate. > [!NOTE] -> A feature for input or for a terminal does not exist yet. Console output is the only thing you can select today. +> Input exists only in an image built with the feature `console-input`, and only for the PL011 and the SBSA UART. A 16550 console has output and no input. See "Serial input and the operator terminal". -Console output exists only in an image built with a console feature. No image has input. The following table lists the console features of `k0-kernel`. +Console output exists only in an image built with a console feature. An image built without `console-input` has no input code at all. The following table lists the console features of `k0-kernel`. | Feature | Drivers it includes | | --- | --- | @@ -130,7 +131,7 @@ Console output exists only in an image built with a console feature. No image ha | `console-16550` | A transmit driver for the 16550 family | | `console` | Both drivers above | -These features only add console output and are never in `default`, so every build command names them. The following commands build the 4 KiB image with console and an image without console: +These features only add console output and are never in `default`, like every feature of `k0-kernel`, so every build command names them. The following commands build the 4 KiB image with console and an image without console: ```sh $ cargo build -p k0-kernel --features console --offline @@ -148,7 +149,7 @@ What **an image without a console feature** removes: What stays in **every image**: - The kernel still finds and checks the console node of the device tree, with the same judgement, the same `K0_PIN` line and the same self-check in the UEFI loader. A device tree whose console fails the checks is refused even by an image that would never use the console. -- The `DEBUG_PUTC` system call and the `Console` capability stay, and what a task prints still reaches the boot log. +- The `DEBUG_PUTC` system call and the `Console` capability stay, and what a task prints still reaches the boot log. `DEBUG_PUTC` needs the write right (W) of the `Console` capability. - The boot log stays. - The UEFI loader prints its own lines through the firmware console before it exits boot services, whatever its embedded kernel was built with. @@ -169,10 +170,58 @@ The limits are as follows: 1. The empty serial log of the `quiet` rows shows only that no byte reached the serial port of QEMU virt, which is a PL011. It says nothing about register reads. Those are covered by the symbol check and by the device page list, which is the kernel's own report. 2. The symbol check runs on debug images. Release (LTO) images of the feature sets without console are not built or booted by the matrix, and no image without console is booted through UEFI. -3. The 16550 driver has never been executed by any test, because QEMU virt has no such UART. Its code was checked by review only. The SBSA UART uses the PL011 driver without an identity check. Nothing has run on real hardware. +3. The 16550 driver has never been executed by any test, because QEMU virt has no such UART, and it has no input path. Its code was checked by review only. The SBSA UART uses the PL011 driver without an identity check. Nothing has run on real hardware. 4. An image without console reduces the output path, not what the kernel holds in memory. The boot log is plain kernel memory, and anyone who can read RAM or attach a debugger sees it. 5. A task that holds a `Console` capability can print lines that look like kernel lines, and that includes `k0: console drivers [...]`. Only the first occurrence of that line in the log, or the image file, identifies a build. The line is a label, not proof. +## Serial input and the operator terminal + +Input is a second path for outside data into the kernel, so it is off by default and gets its own features. In the following table, both features of `k0-kernel` only add code and are never in `default`. + +| Feature | Adds | +| --- | --- | +| `console-input` | The kernel's receive path for the console UART and the system call `CONSOLE_READ`. It needs a console driver feature to do anything. Receive exists for the PL011 and the SBSA UART only. | +| `terminal` | The operator terminal task in the root task image, started as a service after the self-tests. It turns `console-input` on. With `vault` the terminal is the vault's operator, and with `vault-ed25519` it can make an Ed25519 key. | + +> [!WARNING] +> There is no authentication on the serial line. Whoever holds the line is the operator and can do exactly the operator's four operations (`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`), including erasing the key. The operator cannot get a signature, cannot deliver a seed and cannot change the policy. + +An image without `console-input` contains no receive code, no `CONSOLE_READ` and none of the new log lines (a static boot matrix row, `input-symbols`, checks this). An image without `terminal` has no terminal code. + +What the kernel does with input: + +- **Receive path**: the kernel's UART driver puts received bytes into a ring of 256 bytes. The kernel never interprets a byte. Loss (a FIFO overrun, a break, a framing or parity error) is marked on the byte after the hole. +- **Reading input**: `CONSOLE_READ` (system call 16). The caller names a `Console` slot and flags (`NONBLOCK`, `FLUSH`, a timeout in ticks in bits 63..32, other bits refused with `BAD_FLAGS`). It returns one byte per call. Only one task can wait at a time, and a second reader gets `BUSY`. It returns `NO_DEVICE` when there is no input path or it was turned off. A waiter whose capability is deleted, revoked or moved wakes at once with `REVOKED`. A woken reader goes to the end of the ready queue, so input does not preempt. +- **Console capability rights**: R (read input) and W (write output). `CAP_COPY` can only remove them. The root task's capability has W, and R only in images with `console-input`. `bootinfo::VERSION` is 4. +- **Output filter**: unchanged, except that a `Console` capability with R (the terminal's) may also emit backspace (0x08). Every other control byte is still printed as `?`. +- **Receive interrupts stay off** until a task first reads console input with the right. That first read discards what the device holds, and the periodic `k0: tick N` lines stop after one line `k0: tick lines off (console input in use)`. Ticks, preemption and timeouts keep working. +- **Bound on interrupt work**: when the ring is full, the kernel masks the UART's receive interrupt itself and reopens it after the reader has taken half of the ring. Under a flood the interrupt rate is therefore bounded by the reader. The same drain also runs once per tick, so input still arrives, up to a tick late, when the interrupt does not. +- **Interrupt number**: it comes from the device tree (`interrupts` of the console node: one SPI, level, active high, of the discovered GIC) or, through the UEFI loader, from the ACPI SPCR table. It is printed in the platform line (`k0: platform con=pl011@0x9000000,irq33 ...`) and is therefore pinned by `K0_PIN`. Pin strings made before this change no longer match and must be made again. +- **A wrong interrupt number costs only the input path**: out of range or not available gives `k0: console input off (...)` at boot, and a line that keeps firing without a UART cause is switched off after 8 entries with `k0: console input off (interrupt N fired without a uart cause)`. A console node without a usable interrupt is not a boot refusal, and input is just off. +- **Boot log**: `k0: console input on (pl011 irq 33)` or `k0: console input off ()`. + +What the terminal is: + +- **Isolation**: the terminal is a task in its own address space with two capabilities: a `Console` copy with R and W, and the vault endpoint with the send right and the operator badge. The vault's response frame is mapped read-only for it. +- **Start**: after the self-tests, the root task starts a new vault, hands it the boot seed, runs two hostile tasks wired exactly like the terminal (they must be refused and end in a fault), drops its admin capability, starts the terminal and blocks for ever. The lines `root: terminal wiring holds` and `root: service started` report this. On a machine without an input path the root task prints `root: no console input, terminal not started`. +- **Input rules**: a line is at most 64 printable ASCII characters. The terminal drops what reached the UART before the prompt, and a reported loss discards everything up to the next line end (`err input-lost`). + +The limits are as follows: + +1. The serial line is as trusted as whoever can reach it. The operator can erase the key, which is a denial of service by design. +2. The kernel's receive code runs at EL1. It is small and never interprets bytes, but it is kernel code driven by an outside party. A user-space driver needs device and interrupt delegation, which K0 does not have. +3. An outside party can now cause interrupts while tasks run, bounded by the reader. The reader learns arrival times finer than the tick, and other tasks can notice the stolen time. This is a timing channel that has not been analysed. +4. Input waits behind running tasks. There are no priorities, so the latency is up to a tick per ready task. +5. A 16550 console has no input. The SBSA UART path, FIFO overruns and the receive timeout interrupt are not exercised by QEMU, and host tests with a fake UART (`crates/k0-conin`) are their only coverage. The cut-off for an interrupt line that fires without a UART cause is covered by host tests only. +6. No test measures kernel time under a flood on a machine. The bound is argued from the gate and shown in host tests. +7. "Dropped before the prompt" counts bytes that reached the UART. An emulator or adapter that holds bytes back delivers them later, and QEMU does. +8. If a kernel line appears while the operator is typing, the screen line is split but the buffer is whole, and Enter runs the whole buffer. +9. Any task with `Console` output can still print lines that look like kernel or root task lines, and nothing authenticates the prefix. The terminal can additionally erase within its current line. +10. No signing client exists in service mode. The vault's key is made and shown but not used by another task. Client signing is shown by the self-test. +11. The terminal and the vault are not restarted if they die. The root task is trusted. +12. Terminal output counts against the user share of the in-memory boot log. Once that share is full, later task output is not recorded there. +13. The vault limits under "The signing oracle" all stay. Nothing ran on real hardware. + ## The signing oracle The signing oracle is the first service on top of the isolation core. A vault task holds one Ed25519 key. Client tasks get signatures and the public key over IPC and never the key. It is optional and off by default. @@ -183,28 +232,30 @@ The signing oracle is the first service on top of the isolation core. A vault ta What the oracle claims: - **Key separation**: the key lives in the vault's own address space and stack. The root task builds the vault, and no other task can map the vault's memory. A client's CNode holds only a send-only, badged copy of the vault endpoint. -- **Frame rights**: per caller there is a request frame (caller read-write, vault read-only) and a response frame (vault read-write, caller read-only), enforced by reduced-rights copies of the frame capabilities. -- **Fixed policy**: the policy is fixed at build time and keyed by the endpoint badge, which the kernel delivers and a client cannot forge. Roles: admin (the root task: STATUS, INIT, ZEROIZE, not SIGN), signer (STATUS, PUBLIC_KEY, SIGN) and reader (STATUS, PUBLIC_KEY). A call without a badge or with an unknown badge is refused. No operation changes the policy. +- **Frame rights**: per caller there is a request frame (caller read-write, vault read-only) and a response frame (vault read-write, caller read-only), enforced by reduced-rights copies of the frame capabilities. The operator has a response frame and no request frame. The vault decides from the badge and the operation alone which frame it reads or writes, and a request that claims a body its role cannot have is refused without touching memory. +- **Fixed policy**: the policy is fixed at build time and keyed by the endpoint badge, which the kernel delivers and a client cannot forge. Four roles are fixed at build time: admin (the root task: STATUS, INIT, KEYGEN, ZEROIZE, not SIGN), operator (the terminal: STATUS, PUBLIC_KEY, KEYGEN, ZEROIZE, not SIGN and not INIT), signer (STATUS, PUBLIC_KEY, SIGN) and reader (STATUS, PUBLIC_KEY). A call without a badge or with an unknown badge is refused. No operation changes the policy. - **Fixed image**: the vault code is part of the root task image, which is checked by SHA-256 at boot like before. Nothing is loaded after boot. - **Single read of the request**: the vault reads the request body once into a private buffer, with the length fixed first, and uses only that copy. A reply always sets four registers: status, length, indicator bits and the caller's nonce. A client must trust the response frame only after an OK reply that carries its own nonce. -- **Failure state**: a failed known-answer self-test (two RFC 8032 vectors) or a failed pairwise consistency test after key generation puts the vault into a failed state that refuses everything but STATUS. Verification is strict (`verify_strict`). There is no key export, and ZEROIZE drops the key and ends SIGN and PUBLIC_KEY. +- **Failure state**: a failed known-answer self-test (two RFC 8032 vectors) or a failed pairwise consistency test after key generation puts the vault into a failed state that refuses everything but STATUS. Every way into the failed state wipes seed and key. Verification is strict (`verify_strict`). There is no key export, and ZEROIZE drops the key and ends SIGN and PUBLIC_KEY. What the oracle does not claim: 1. The algorithm is Ed25519 (PureEdDSA with SHA-512, as in FIPS 186-5 and RFC 8032). The implementation is the vendored crate `ed25519-dalek` 2.2.0 and has no validation of any kind. The key does not come from an approved random bit generator. 2. There is no side-channel analysis of the crate on this kernel. -3. There is one key, no persistence, no key import or export, no DRBG and no operator input. No post-quantum algorithm exists yet. +3. There is one key per boot (a second KEYGEN is refused with `key-exists`, and after ZEROIZE a reboot is needed), no persistence, no key import or export and no DRBG. The only operator input is the serial terminal, which has no authentication (see "Serial input and the operator terminal"). No post-quantum algorithm exists yet. 4. All signers share the one key, so a signature carries no client identity. -5. Availability of the vault is not protected. Clients share one endpoint and must use timeouts. +5. Availability of the vault is not protected. Clients share one endpoint and must use timeouts, and the operator can erase the key. 6. The root task is trusted and could read the vault. 7. The oracle was only run in QEMU (TCG and HVF). The scrubs of stack copies (kernel boot stack, vault stack after signing) are best effort. -8. The self-test runs its clients one after another in one client address space, so it shows isolation between the vault and a client, not between clients. +8. The self-test runs its clients one after another in one client address space, so it shows isolation between the vault and a client, not between clients. It makes its key from the public RFC 8032 test seed, with the real seed information, so the entropy rule is still exercised. + +Seed and key: the vault has the states `fresh`, `seeded`, `ready`, `zeroized` and `failed`. INIT (admin only, once) only delivers the seed. The vault checks the entropy rule and holds the seed (`seeded`). KEYGEN (admin and operator) makes the key from the held seed with the chosen algorithm and wipes the seed (`ready`). A vault in an image without an algorithm refuses the seed and stays `fresh`, and an all-zero seed is refused. -Entropy rule: the vault refuses to make a key (status `NO_ENTROPY`) unless the boot seed contains at least 32 bytes of `rng-seed` or 256 bits from RNDR. QEMU virt provides a 32-byte `rng-seed`. Every reply carries indicator bits: the algorithm is in FIPS 186-5, the self-tests passed, at least 32 `rng-seed` bytes went into the key seed, and RNDR went into the key seed. These bits report what happened. They are not a validation claim. +Entropy rule: the vault refuses the boot seed (status `NO_ENTROPY`) unless the boot seed contains at least 32 bytes of `rng-seed` or 256 bits from RNDR. QEMU virt provides a 32-byte `rng-seed`. Every reply carries indicator bits: the algorithm is in FIPS 186-5, the self-tests passed, at least 32 `rng-seed` bytes went into the key seed, and RNDR went into the key seed. These bits report what happened. They are not a validation claim. The STATUS reply packs the state, the key's algorithm and the algorithms in the image into one word. ### Boot seed and seed wipe -The kernel derives 32 bytes for the root task with SHA-256 under its own domain string from the device tree entropy, the counter and, when the CPU has RNDR, four fresh RNDR words. It is independent of the PAC keys by domain separation. The seed is as good as its inputs and no better. It reaches the root task in the entry registers `x0` to `x3`, and `x4` tells how many `rng-seed` bytes were used and whether RNDR contributed. It is not in the bootinfo page, and the root task prints only the source, never the seed. +The kernel derives 32 bytes for the root task with SHA-256 under its own domain string from the device tree entropy, the counter and, when the CPU has RNDR, four fresh RNDR words. It is independent of the PAC keys by domain separation. The seed is as good as its inputs and no better. It reaches the root task in the entry registers `x0` to `x3`, and `x4` tells how many `rng-seed` bytes were used and whether RNDR contributed. It is not in the bootinfo page, and the root task prints only the source, never the seed. The real boot seed is used exactly once, by the service vault in images with `terminal` and `vault`. In every other image the root task wipes it at entry. Right before the kernel enters the root task it zeroes the `rng-seed` and `kaslr-seed` bytes in the device tree: it switches the read-only alias entry of that page to read-write in place, writes zeros, cleans and invalidates the cache lines, switches it back and reads the bytes back. It then wipes its own copy in `BootInfo`, prints `k0: dtb seeds wiped B` and zeroes the boot stack below the live frames. Copies that the firmware or the UEFI loader keep, and anything in the live frames of the boot stack, are not wiped. @@ -233,7 +284,7 @@ You can report a problem in the following ways: - **Preferred**: open a draft security advisory at . - **Alternative**: email the maintainer at . Include the affected commit hash, the platform (QEMU machine and CPU model, hypervisor, or board), the entry level (EL1 or EL2), the page size (4 KiB or 16 KiB), the `k0: platform ...` line from the boot log, and a reproduction if you have one. -Isolation gaps in `v0.1.0` and earlier commits, and the availability and resource limits listed under "What is still NOT provided on `main`", are already known and **do not need to be filed again**. Isolation bypasses on the current `main` branch are welcome, for example a task reaching another task's memory or capabilities, a revoked capability that keeps working, or a stale mapping that survives unmap, revoke or address space destruction. Reports about the signing oracle are welcome, for example a key disclosure to a client, a policy bypass, or a reply that reaches the wrong caller. Reports about the UEFI loader are welcome too, for example a memory map or device tree that makes it hand the kernel memory that firmware still uses, or a refusal that does not happen. Reports about anything else, including boot-time memory map validation, exception handling, scheduler policy, and IPC state machines, are welcome. +Isolation gaps in `v0.1.0` and earlier commits, and the availability and resource limits listed under "What is still NOT provided on `main`", are already known and **do not need to be filed again**. Isolation bypasses on the current `main` branch are welcome, for example a task reaching another task's memory or capabilities, a revoked capability that keeps working, or a stale mapping that survives unmap, revoke or address space destruction. Reports about the signing oracle are welcome, for example a key disclosure to a client, a policy bypass, or a reply that reaches the wrong caller. Reports about the serial input path and the operator terminal are welcome too, for example a byte stream that makes the kernel misbehave, a wake-up of the wrong task, or an operator operation beyond the four listed. Reports about the UEFI loader are welcome too, for example a memory map or device tree that makes it hand the kernel memory that firmware still uses, or a refusal that does not happen. Reports about anything else, including boot-time memory map validation, exception handling, scheduler policy, and IPC state machines, are welcome. ## Scope @@ -243,7 +294,7 @@ The following picture shows how this document divides what is in scope, what is The scope and trust boundaries of K0: the boot chain before the kernel entry point is out of scope, the loader, the kernel and the root task are in scope, and the device tree, confined tasks and k0: lines printed by tasks are not trusted

-**In scope**: everything under `kernel/`, `crates/` (including `crates/k0-efi`), `loader/`, `userspace/root-task/` and `userspace/k0-vault` with its wiring in the root task. The UEFI loader is part of the boot chain, but it is code of this repository, so its handling of the memory map, the device tree and the kernel image is in scope. +**In scope**: everything under `kernel/`, `crates/` (including `crates/k0-efi`), `loader/`, `userspace/root-task/` and `userspace/k0-vault` and `userspace/k0-term` with their wiring in the root task. The UEFI loader is part of the boot chain, but it is code of this repository, so its handling of the memory map, the device tree and the kernel image is in scope. **Out of scope**: the rest of the boot chain before the kernel entry point (for example firmware, any other boot loader and the hypervisor), and the integrity of the kernel image itself. Kernel image signing is the boot chain's responsibility. Under UEFI that means Secure Boot in the firmware, because the loader's SHA-256 check is not a signature (see "The UEFI loader"). diff --git a/SECURITY_KR.md b/SECURITY_KR.md index 84ff69f..29a5b96 100644 --- a/SECURITY_KR.md +++ b/SECURITY_KR.md @@ -47,7 +47,7 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다. ### 현재 `main` 브랜치(릴리즈 전) -현재 `main` 브랜치에는 태스크 격리가 들어 있습니다. 아직 어떤 릴리즈나 태그에도 포함되지 않았고, 시스템 콜 ABI가 `v0.1.0`과 호환되지 않습니다(bootinfo 레이아웃 버전 3). +현재 `main` 브랜치에는 태스크 격리가 들어 있습니다. 아직 어떤 릴리즈나 태그에도 포함되지 않았고, 시스템 콜 ABI가 `v0.1.0`과 호환되지 않습니다(bootinfo 레이아웃 버전 4). 격리된 태스크의 성질은 다음과 같습니다. @@ -55,7 +55,7 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다. - **주소 공간**: 태스크는 `AddrSpace` 케이퍼빌리티가 가리키는 주소 공간에서 실행됩니다. 태스크는 그 `AddrSpace` 케이퍼빌리티를 가진 쪽이 해당 주소 공간에 매핑해 준 메모리에만 접근합니다. - **바인딩**: 두 바인딩은 모두 태스크의 TCB 안에 케이퍼빌리티로 보관됩니다. 둘 중 하나가 revoke되거나 삭제되면 그 태스크는 해체됩니다. - **격리의 범위**: 격리는 서로 다른 CNode와 주소 공간에 묶인 태스크 사이에서 성립합니다. 루트 태스크의 보조 스레드처럼 같은 것을 함께 사용하는 태스크끼리는 서로의 스레드입니다. 태스크의 TCB, CNode, AddrSpace 케이퍼빌리티를 가진 쪽이 그 태스크를 통제합니다. -- **권한**: 케이퍼빌리티는 권한(R, W, X)을 가집니다. 권한은 `CAP_COPY`로 줄이기만 할 수 있고 늘릴 수는 없습니다. `Endpoint` 케이퍼빌리티는 `CAP_COPY`로 한 번 설정하는 배지를 가질 수 있고, 수신자가 이 배지를 받습니다. retype된 프레임은 X를 얻을 수 없고 X는 루트 태스크의 text 프레임에만 있으므로, 어떤 물리 프레임도 한 곳에서 쓰기 가능하면서 다른 곳에서 실행 가능하지 않습니다. +- **권한**: 케이퍼빌리티는 권한(R, W, X)을 가집니다. 권한은 `CAP_COPY`로 줄이기만 할 수 있고 늘릴 수는 없습니다. `Endpoint` 케이퍼빌리티는 `CAP_COPY`로 한 번 설정하는 배지를 가질 수 있고, 수신자가 이 배지를 받습니다. `Console` 케이퍼빌리티도 같은 방식으로 R(입력 읽기)과 W(출력 쓰기) 권한을 가집니다. retype된 프레임은 X를 얻을 수 없고 X는 루트 태스크의 text 프레임에만 있으므로, 어떤 물리 프레임도 한 곳에서 쓰기 가능하면서 다른 곳에서 실행 가능하지 않습니다. - **파생과 해체**: 케이퍼빌리티는 파생 목록을 이룹니다. `CAP_REVOKE`는 파생된 모든 케이퍼빌리티를 제거하고, `CAP_DELETE`는 슬롯까지 제거합니다. 오브젝트는 원본 케이퍼빌리티가 제거될 때 finalize되며, 그 뒤 해당 `Untyped` 메모리를 다시 retype할 수 있습니다. retype된 오브젝트는 케이퍼빌리티가 만들어지기 전에 0으로 지워집니다. - **폴트 격리**: 격리된 태스크의 폴트, 종료, 알 수 없는 시스템 콜은 그 태스크만 종료시킵니다. @@ -71,15 +71,16 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다. - **미구현 기능**: 핸들러 태스크로의 폴트 전달, 알림(notification), IPC를 통한 케이퍼빌리티 전송이 아직 없습니다. - **EL0에서 보이는 시간**: EL0는 여전히 하드웨어 카운터나 타이머를 읽을 수 없습니다. IPC 타임아웃은 태스크에 스케줄러 틱(1초)만큼 거친 시계와 타이머 인터럽트에 맞춰진 깨어남을 제공합니다. 이것이 캐시나 추측 실행 공격에 쓸 만한 시간 원천으로 증폭될 수 있는지는 분석하지 않았습니다. - **revoke 뒤의 송신자**: 엔드포인트에 이미 대기 중인 송신자는 케이퍼빌리티가 revoke된 뒤에도 한 번 전달됩니다. +- **직렬 회선**: feature `console-input` 또는 `terminal`을 포함해 빌드한 이미지에서는 외부 당사자가 직렬 회선으로 커널에 닿을 수 있습니다. 운영자 터미널에는 인증이 없고, 외부 당사자가 태스크 실행 중에 인터럽트를 일으킬 수 있으며, 입력은 실행 중인 태스크 뒤에서 기다립니다("직렬 입력과 운영자 터미널" 참고). - **코어 수**: 단일 코어만 지원합니다. - **실행 코드**: 부팅 후에는 새 실행 코드를 로드할 수 없으므로, 격리된 태스크는 루트 태스크 이미지의 코드를 실행합니다. - **지원 범위**: [INTRODUCTION_KR.md](INTRODUCTION_KR.md)의 증거 단계에 든 것만 지원한다고 봅니다. 실제 보드, KVM 등 다른 하이퍼바이저, 16550 콘솔 드라이버, `HCR_EL2.E2H`가 1로 고정된 프로세서는 한 번도 부팅한 적이 없습니다. - **디바이스 트리**: 디바이스 트리는 신뢰하지 않지만, 이제 장치 주소를 여기서 가져옵니다. 잘못되었거나 악의적인 디바이스 트리가 콘솔을 다른 장치로 향하게 할 수 있습니다. 커널은 이를 다음과 같이 제한합니다. 플랫폼 기술자를 메모리 맵과 대조합니다. GIC와 PL011의 식별 레지스터를 확인합니다(PL011은 임시 프로브 매핑으로 확인하므로 확인에 실패한 장치는 매핑된 채 남지 않습니다. 16550과 SBSA UART에는 그런 레지스터가 없어서 이 확인이 없습니다). 검증이 끝난 뒤에만 장치 페이지를 매핑합니다. 콘솔 대기는 모두 시간 제한으로 묶습니다. 다른 플랫폼을 거부하는 고정 빌드(`K0_PIN`)도 제공합니다. 고정 빌드는 디바이스 트리에서 나온 값을 비교하므로 악의적인 부트 체인은 막지 못합니다. - **디바이스 트리의 주소**: 디바이스 트리의 주소는 처음 읽기 전에 검사할 방법이 없습니다. 부트로더가 이 주소를 `x0`로 넘기는데, 커널은 그 블롭을 읽기 전에는 메모리 맵을 모릅니다. 커널은 널이거나 정렬이 맞지 않는 주소, 2^47 이상인 주소, 커널 이미지와 겹치는 구간을 거부합니다. 그런 다음 그 주소를 읽기 전용 일반 메모리로 매핑하고 8바이트를 읽습니다. 그 바이트가 디바이스 트리 헤더처럼 보일 때만 더 읽습니다(최대 2 MiB). 따라서 부트로더가 장치의 주소를 넘기면 커널은 장치 레지스터를 메모리처럼 읽게 되고, 일부 레지스터는 읽기만 해도 부작용이 생깁니다. 이 매핑은 캐시 가능한 메모리라서 프로세서가 커널이 요청한 8바이트보다 그 페이지를 더 많이 가져올 수 있습니다. 디바이스 트리가 선언된 메모리 안에 있는지 보는 나중의 검사는 같은 블롭에서 나온 메모리 맵을 사용합니다. 이 매핑으로 쓰기를 하는 것은 단 한 번뿐이며, 블롭을 파싱하고 검증한 뒤에 일어납니다. 커널은 루트 태스크에 진입하기 직전에 `rng-seed`와 `kaslr-seed` 값을 0으로 지웁니다("서명 오라클" 절의 "부트 시드와 시드 삭제" 참고). 두 번째 `/chosen` 노드는 거부합니다. -- **출력의 출처**: 커널 출력과 태스크 출력은 부트 로그 하나를 함께 사용합니다. 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔 하나도 함께 사용합니다. 줄에는 누가 썼는지 표시가 없습니다. `Console` 케이퍼빌리티를 가진 태스크는 `k0:`로 시작하는 줄을 출력할 수 있습니다. 커널은 제어 바이트를 바꾸고 태스크 출력이 부트 로그에서 차지할 수 있는 양을 제한합니다. 그래도 콘솔이나 로그를 읽는 쪽은 `tools/qemu-boot-test.sh`를 포함해 누구도 `k0: entering root task (el0)` 뒤에 나온 `k0:` 줄을 커널이 쓴 것으로 믿을 수 없습니다. `k0: console drivers [...]` 줄도 여기에 포함됩니다("선택적 콘솔 출력" 참고). +- **출력의 출처**: 커널 출력과 태스크 출력은 부트 로그 하나를 함께 사용합니다. 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔 하나도 함께 사용합니다. 줄에는 누가 썼는지 표시가 없습니다. 쓰기 권한이 있는 `Console` 케이퍼빌리티를 가진 태스크는 `k0:`로 시작하는 줄을 출력할 수 있습니다. 커널은 제어 바이트를 바꾸고 태스크 출력이 부트 로그에서 차지할 수 있는 양을 제한합니다. 그래도 콘솔이나 로그를 읽는 쪽은 `tools/qemu-boot-test.sh`를 포함해 누구도 `k0: entering root task (el0)` 뒤에 나온 `k0:` 줄을 커널이 쓴 것으로 믿을 수 없습니다. `k0: console drivers [...]` 줄도 여기에 포함됩니다("선택적 콘솔 출력" 참고). - **EL2 트랩**: 격리는 기밀성과 무결성을 다루고 가용성은 다루지 않습니다. 커널이 EL1로 내려온 뒤 EL2로 트랩이 오면 설계상 기계 전체를 멈춥니다. - **EL2 진입**: EL2 진입은 Linux와 같은 펌웨어 약속을 전제로 합니다. EL3 펌웨어는 세분화된 트랩과 HCRX 제어 기능이 있으면 이를 켜 주어야 합니다. -- **루트 태스크**: 루트 태스크는 여전히 신뢰 대상이며 최초의 `Untyped` 케이퍼빌리티를 가지고, `write_bootinfo`는 그 물리 주소를 루트 태스크에 계속 노출합니다. 서명 오라클이 있는 이미지에서는 루트 태스크가 볼트도 만들며 볼트의 메모리를 읽을 수 있습니다("서명 오라클" 참고). +- **루트 태스크**: 루트 태스크는 여전히 신뢰 대상이며 최초의 `Untyped` 케이퍼빌리티를 가지고, `write_bootinfo`는 그 물리 주소를 루트 태스크에 계속 노출합니다. 서명 오라클이 있는 이미지에서는 루트 태스크가 볼트도 만들며 볼트의 메모리를 읽을 수 있습니다("서명 오라클" 참고). feature `terminal`이 있는 이미지에서는 터미널 태스크도 시작하며, 터미널이나 볼트가 죽어도 다시 시작하지 않습니다. > [!WARNING] > `main`에서도 신뢰하지 않는 코드의 실행은 실험적인 것으로 취급하세요. 위의 가용성 한계는 그대로 적용됩니다. @@ -120,9 +121,9 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다. K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Cargo features로 선택할 수 있습니다. > [!NOTE] -> 입력 또는 터미널용 feature는 아직 없습니다. 지금 선택할 수 있는 것은 콘솔 출력뿐입니다. +> 입력은 feature `console-input`을 포함해 빌드한 이미지에만 있고, PL011과 SBSA UART에만 있습니다. 16550 콘솔에는 출력만 있고 입력이 없습니다("직렬 입력과 운영자 터미널" 참고). -콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다. 입력은 어떤 이미지에도 없습니다. `k0-kernel`의 콘솔 feature는 다음과 같습니다. +콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다. `console-input` 없이 빌드한 이미지에는 입력 코드가 전혀 없습니다. `k0-kernel`의 콘솔 feature는 다음과 같습니다. | feature | 포함하는 드라이버 | | --- | --- | @@ -130,7 +131,7 @@ K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Car | `console-16550` | 16550 계열의 송신 드라이버 | | `console` | 위의 두 드라이버 모두 | -이 feature는 콘솔 출력을 더하기만 하며 `default`에는 절대 추가하지 않습니다. 따라서 모든 빌드 명령이 이름을 직접 적습니다. 다음 명령은 각각 콘솔이 있는 4 KiB 이미지와 콘솔이 없는 이미지를 만듭니다. +이 feature는 콘솔 출력을 더하기만 하며 `k0-kernel`의 모든 feature와 마찬가지로 `default`에는 절대 추가하지 않습니다. 따라서 모든 빌드 명령이 이름을 직접 적습니다. 다음 명령은 각각 콘솔이 있는 4 KiB 이미지와 콘솔이 없는 이미지를 만듭니다. ```sh $ cargo build -p k0-kernel --features console --offline @@ -148,7 +149,7 @@ $ cargo build -p k0-kernel --offline **모든 이미지**에는 다음이 남습니다. - 커널은 여전히 디바이스 트리의 콘솔 노드를 찾아 검사합니다. 판단 기준, `K0_PIN` 줄, UEFI 로더의 자가 검사가 모두 같습니다. 콘솔이 검사를 통과하지 못하는 디바이스 트리는 콘솔을 전혀 쓰지 않을 이미지도 거부합니다. -- `DEBUG_PUTC` 시스템 콜과 `Console` 케이퍼빌리티가 남고, 태스크가 출력한 것은 여전히 부트 로그에 닿습니다. +- `DEBUG_PUTC` 시스템 콜과 `Console` 케이퍼빌리티가 남고, 태스크가 출력한 것은 여전히 부트 로그에 닿습니다. `DEBUG_PUTC`에는 `Console` 케이퍼빌리티의 쓰기 권한(W)이 필요합니다. - 부트 로그가 남습니다. - UEFI 로더는 내장한 커널을 어떻게 빌드했든, 부트 서비스를 종료하기 전에는 자기 줄을 펌웨어 콘솔로 출력합니다. @@ -169,10 +170,58 @@ $ grep -a 'k0: console drivers' <이미지 파일> 1. `quiet` 행의 비어 있는 직렬 로그는 PL011인 QEMU virt의 직렬 포트로 한 바이트도 나오지 않았다는 것만 보여 줍니다. 레지스터 읽기에 대해서는 아무것도 말하지 않습니다. 그것은 심볼 검사와, 커널 자신의 보고인 장치 페이지 목록이 다룹니다. 2. 심볼 검사는 디버그 이미지에서 실행합니다. 콘솔 없는 feature 조합의 릴리즈(LTO) 이미지는 매트릭스가 빌드하거나 부팅하지 않으며, 콘솔 없는 이미지를 UEFI로 부팅해 본 적도 없습니다. -3. 16550 드라이버는 어떤 테스트로도 실행된 적이 없습니다. QEMU virt에 그런 UART가 없기 때문입니다. 코드는 리뷰로만 확인했습니다. SBSA UART는 식별 확인 없이 PL011 드라이버를 사용합니다. 실제 하드웨어에서 실행한 것은 없습니다. +3. 16550 드라이버는 어떤 테스트로도 실행된 적이 없습니다. QEMU virt에 그런 UART가 없기 때문이며, 입력 경로도 없습니다. 코드는 리뷰로만 확인했습니다. SBSA UART는 식별 확인 없이 PL011 드라이버를 사용합니다. 실제 하드웨어에서 실행한 것은 없습니다. 4. 콘솔 없는 이미지가 줄이는 것은 출력 경로이지 커널이 메모리에 가진 내용이 아닙니다. 부트 로그는 평범한 커널 메모리이며, RAM을 읽거나 디버거를 붙일 수 있는 사람은 누구나 봅니다. 5. `Console` 케이퍼빌리티를 가진 태스크는 커널 줄처럼 보이는 줄을 출력할 수 있으며, `k0: console drivers [...]`도 여기에 포함됩니다. 로그에서 그 줄의 첫 번째 등장 또는 이미지 파일만이 빌드를 식별합니다. 이 줄은 증거가 아니라 표지입니다. +## 직렬 입력과 운영자 터미널 + +입력은 외부 데이터가 커널로 들어오는 두 번째 경로이므로 기본으로 꺼져 있고 자체 feature를 가집니다. 다음 표의 두 feature는 `k0-kernel`에서 코드를 더하기만 하며 `default`에는 절대 추가하지 않습니다. + +| feature | 추가하는 것 | +| --- | --- | +| `console-input` | 콘솔 UART용 커널 수신 경로와 시스템 콜 `CONSOLE_READ`입니다. 콘솔 드라이버 feature가 있어야 동작합니다. 수신은 PL011과 SBSA UART에만 있습니다. | +| `terminal` | 루트 태스크 이미지 안의 운영자 터미널 태스크이며, 자가 시험 뒤에 서비스로 시작합니다. `console-input`을 켭니다. `vault`와 함께면 터미널이 볼트의 운영자가 되고, `vault-ed25519`와 함께면 Ed25519 키를 만들 수 있습니다. | + +> [!WARNING] +> 직렬 회선에는 인증이 없습니다. 회선을 쥔 쪽이 운영자이며, 키를 지우는 것을 포함해 운영자의 네 연산(`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`)을 정확히 할 수 있습니다. 운영자는 서명을 받을 수 없고, 시드를 전달할 수 없으며, 정책을 바꿀 수 없습니다. + +`console-input` 없이 빌드한 이미지에는 수신 코드, `CONSOLE_READ`, 새 로그 줄이 전혀 없습니다(정적 부팅 매트릭스 행 `input-symbols`가 확인합니다). `terminal` 없이 빌드한 이미지에는 터미널 코드가 없습니다. + +커널이 입력으로 하는 일은 다음과 같습니다. + +- **수신 경로**: 커널의 UART 드라이버가 받은 바이트를 256바이트 링에 넣습니다. 커널은 바이트를 해석하지 않습니다. 손실(FIFO 오버런, 브레이크, 프레이밍 또는 패리티 오류)은 구멍 뒤의 바이트에 표시합니다. +- **입력 읽기**: `CONSOLE_READ`(시스템 콜 16번). 호출자가 `Console` 슬롯과 플래그(`NONBLOCK`, `FLUSH`, 63..32비트의 틱 단위 타임아웃, 그 밖의 비트는 `BAD_FLAGS`로 거부)를 지정합니다. 호출마다 한 바이트를 돌려줍니다. 한 번에 한 태스크만 기다릴 수 있고 두 번째 읽는 쪽은 `BUSY`를 받습니다. 입력 경로가 없거나 꺼져 있으면 `NO_DEVICE`를 돌려줍니다. 기다리던 태스크의 케이퍼빌리티가 삭제, revoke 또는 이동되면 즉시 `REVOKED`로 깨어납니다. 깨어난 읽는 쪽은 준비 큐의 맨 뒤로 가므로 입력은 선점하지 않습니다. +- **Console 케이퍼빌리티의 권한**: R(입력 읽기)과 W(출력 쓰기)입니다. `CAP_COPY`는 이를 줄이기만 할 수 있습니다. 루트 태스크의 케이퍼빌리티는 W를 가지며, R은 `console-input`이 있는 이미지에서만 가집니다. `bootinfo::VERSION`은 4입니다. +- **출력 필터**: 바뀌지 않았습니다. 다만 R이 있는 `Console` 케이퍼빌리티(터미널의 것)는 백스페이스(0x08)도 내보낼 수 있습니다. 다른 제어 바이트는 여전히 `?`로 출력됩니다. +- **수신 인터럽트는 꺼진 채로 둡니다**: 어떤 태스크가 권한을 가지고 처음 콘솔 입력을 읽을 때까지입니다. 그 첫 읽기가 장치에 있던 것을 버리고, 주기적인 `k0: tick N` 줄은 `k0: tick lines off (console input in use)` 한 줄을 남기고 멈춥니다. 틱, 선점, 타임아웃은 계속 동작합니다. +- **인터럽트 작업의 상한**: 링이 가득 차면 커널이 UART의 수신 인터럽트를 스스로 마스크하고, 읽는 쪽이 링의 절반을 가져간 뒤 다시 엽니다. 따라서 폭주 중에도 인터럽트 빈도는 읽는 쪽이 정하는 만큼으로 제한됩니다. 같은 비우기가 틱마다 한 번 더 실행되므로, 인터럽트가 오지 않아도 입력은 최대 한 틱 늦게 도착합니다. +- **인터럽트 번호**: 디바이스 트리(콘솔 노드의 `interrupts`: 찾아낸 GIC의 SPI 하나, 레벨, active high)에서, UEFI 로더를 거치면 ACPI SPCR 테이블에서 가져옵니다. 플랫폼 줄(`k0: platform con=pl011@0x9000000,irq33 ...`)에 출력되므로 `K0_PIN`이 고정합니다. 이 변경 이전에 만든 고정 문자열은 더 이상 맞지 않으므로 다시 만들어야 합니다. +- **잘못된 인터럽트 번호가 치르는 비용은 입력 경로뿐입니다**: 범위를 벗어나거나 쓸 수 없으면 부팅 때 `k0: console input off (...)`가 나오고, UART 원인 없이 계속 발생하는 회선은 8번 진입한 뒤 `k0: console input off (interrupt N fired without a uart cause)`와 함께 꺼집니다. 쓸 수 있는 인터럽트가 없는 콘솔 노드는 부팅 거부 사유가 아니며 입력만 꺼집니다. +- **부트 로그**: `k0: console input on (pl011 irq 33)` 또는 `k0: console input off ()`입니다. + +터미널의 정체는 다음과 같습니다. + +- **격리**: 터미널은 자기 주소 공간을 가진 태스크이며 케이퍼빌리티를 두 개 가집니다. R과 W가 있는 `Console` 사본, 그리고 송신 권한과 운영자 배지가 있는 볼트 엔드포인트입니다. 볼트의 응답 프레임은 터미널에 읽기 전용으로 매핑됩니다. +- **시작**: 자가 시험이 끝나면 루트 태스크가 새 볼트를 시작하고 부트 시드를 넘기며, 터미널과 똑같이 연결한 적대적 태스크 둘을 실행하고(거부되어 폴트로 끝나야 합니다), 자신의 admin 케이퍼빌리티를 버리고, 터미널을 시작한 뒤 영원히 블록됩니다. `root: terminal wiring holds`와 `root: service started` 줄이 이를 보고합니다. 입력 경로가 없는 기계에서는 루트 태스크가 `root: no console input, terminal not started`를 출력합니다. +- **입력 규칙**: 한 줄은 출력 가능한 ASCII 최대 64자입니다. 터미널은 프롬프트 전에 UART에 닿은 것을 버리고, 보고된 손실은 다음 줄 끝까지의 모든 것을 버립니다(`err input-lost`). + +한계는 다음과 같습니다. + +1. 직렬 회선은 그 회선에 닿을 수 있는 쪽만큼만 신뢰할 수 있습니다. 운영자는 키를 지울 수 있으며, 이는 설계상의 서비스 거부입니다. +2. 커널의 수신 코드는 EL1에서 실행됩니다. 작고 바이트를 해석하지 않지만, 외부 당사자가 구동하는 커널 코드입니다. 사용자 공간 드라이버에는 장치와 인터럽트의 위임이 필요한데, K0에는 이것이 없습니다. +3. 외부 당사자가 이제 태스크 실행 중에 인터럽트를 일으킬 수 있으며, 그 빈도는 읽는 쪽이 제한합니다. 읽는 쪽은 틱보다 정밀한 도착 시각을 알게 되고, 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다. 이것은 분석하지 않은 타이밍 채널입니다. +4. 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 지연은 준비된 태스크마다 최대 한 틱입니다. +5. 16550 콘솔에는 입력이 없습니다. SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU에서 실행되지 않으며, 가짜 UART를 쓰는 호스트 테스트(`crates/k0-conin`)가 유일한 검증입니다. UART 원인 없이 발생하는 인터럽트 회선을 끊는 동작도 호스트 테스트로만 검증합니다. +6. 기계에서 폭주 중의 커널 시간을 측정한 테스트는 없습니다. 상한은 게이트에서 논증하고 호스트 테스트로 보입니다. +7. "프롬프트 전에 버림"은 UART에 닿은 바이트를 센 것입니다. 바이트를 붙잡아 두는 에뮬레이터나 어댑터는 나중에 전달하며, QEMU가 그렇게 합니다. +8. 운영자가 입력하는 동안 커널 줄이 나타나면 화면의 줄은 쪼개지지만 버퍼는 온전하며, Enter는 버퍼 전체를 실행합니다. +9. `Console` 출력이 있는 모든 태스크는 여전히 커널 줄이나 루트 태스크 줄처럼 보이는 줄을 출력할 수 있으며, 접두어를 인증하는 것은 없습니다. 터미널은 추가로 자기 현재 줄 안에서 지울 수 있습니다. +10. 서비스 모드에는 서명 클라이언트가 없습니다. 볼트의 키는 만들어지고 표시되지만 다른 태스크가 사용하지 않습니다. 클라이언트의 서명은 자가 시험이 보여 줍니다. +11. 터미널과 볼트는 죽어도 다시 시작하지 않습니다. 루트 태스크는 신뢰 대상입니다. +12. 터미널 출력은 메모리 안 부트 로그의 사용자 몫에 포함됩니다. 그 몫이 차면 이후 태스크 출력은 거기에 기록되지 않습니다. +13. "서명 오라클"의 볼트 한계는 모두 그대로입니다. 실제 하드웨어에서 실행한 것은 없습니다. + ## 서명 오라클 서명 오라클은 격리 코어 위에 올라가는 첫 번째 서비스입니다. 볼트 태스크 하나가 Ed25519 키 하나를 보관합니다. 클라이언트 태스크는 IPC로 서명과 공개 키를 받으며 키 자체는 받지 못합니다. 이 기능은 선택 사항이며 기본으로 꺼져 있습니다. @@ -183,28 +232,30 @@ $ grep -a 'k0: console drivers' <이미지 파일> 오라클이 주장하는 것은 다음과 같습니다. - **키 분리**: 키는 볼트 자신의 주소 공간과 스택에 있습니다. 루트 태스크가 볼트를 만들며, 루트 태스크 외의 어떤 태스크도 볼트의 메모리를 매핑할 수 없습니다. 클라이언트의 CNode에는 볼트 엔드포인트의 송신 전용 배지 사본만 들어 있습니다. -- **프레임 권한**: 호출자마다 요청 프레임(호출자 읽기·쓰기, 볼트 읽기 전용)과 응답 프레임(볼트 읽기·쓰기, 호출자 읽기 전용)이 있으며, 권한을 줄인 프레임 케이퍼빌리티 사본으로 강제합니다. -- **고정 정책**: 정책은 빌드 시점에 고정되고 엔드포인트 배지를 키로 삼습니다. 배지는 커널이 전달하므로 클라이언트가 위조할 수 없습니다. 역할은 admin(루트 태스크: STATUS, INIT, ZEROIZE, SIGN은 불가), signer(STATUS, PUBLIC_KEY, SIGN), reader(STATUS, PUBLIC_KEY)입니다. 배지가 없거나 알 수 없는 배지로 한 호출은 거부합니다. 정책을 바꾸는 연산은 없습니다. +- **프레임 권한**: 호출자마다 요청 프레임(호출자 읽기·쓰기, 볼트 읽기 전용)과 응답 프레임(볼트 읽기·쓰기, 호출자 읽기 전용)이 있으며, 권한을 줄인 프레임 케이퍼빌리티 사본으로 강제합니다. operator에게는 응답 프레임만 있고 요청 프레임은 없습니다. 볼트는 배지와 연산만으로 어느 프레임을 읽고 쓸지 정하며, 역할이 가질 수 없는 본문이 있다고 주장하는 요청은 메모리를 건드리지 않고 거부합니다. +- **고정 정책**: 정책은 빌드 시점에 고정되고 엔드포인트 배지를 키로 삼습니다. 배지는 커널이 전달하므로 클라이언트가 위조할 수 없습니다. 역할 넷이 빌드 시점에 고정됩니다. admin(루트 태스크: STATUS, INIT, KEYGEN, ZEROIZE, SIGN은 불가), operator(터미널: STATUS, PUBLIC_KEY, KEYGEN, ZEROIZE, SIGN과 INIT은 불가), signer(STATUS, PUBLIC_KEY, SIGN), reader(STATUS, PUBLIC_KEY)입니다. 배지가 없거나 알 수 없는 배지로 한 호출은 거부합니다. 정책을 바꾸는 연산은 없습니다. - **고정 이미지**: 볼트 코드는 루트 태스크 이미지의 일부이며 이전처럼 부팅할 때 SHA-256으로 검사합니다. 부팅 후에는 아무것도 로드하지 않습니다. - **요청을 한 번만 읽음**: 볼트는 길이를 먼저 확정한 뒤 요청 본문을 비공개 버퍼로 한 번만 읽고 그 사본만 사용합니다. 응답은 항상 레지스터 네 개(상태, 길이, 표시 비트, 호출자의 nonce)를 채웁니다. 클라이언트는 자신의 nonce가 담긴 OK 응답을 받은 뒤에만 응답 프레임을 신뢰해야 합니다. -- **실패 상태**: 알려진 답 자가 시험(RFC 8032 벡터 두 개)이나 키 생성 뒤의 쌍 일관성 시험이 실패하면 볼트는 STATUS 외의 모든 것을 거부하는 실패 상태가 됩니다. 검증은 엄격 모드(`verify_strict`)입니다. 키를 내보내는 기능은 없고, ZEROIZE는 키를 버려 SIGN과 PUBLIC_KEY를 끝냅니다. +- **실패 상태**: 알려진 답 자가 시험(RFC 8032 벡터 두 개)이나 키 생성 뒤의 쌍 일관성 시험이 실패하면 볼트는 STATUS 외의 모든 것을 거부하는 실패 상태가 됩니다. 실패 상태로 들어가는 모든 경로는 시드와 키를 지웁니다. 검증은 엄격 모드(`verify_strict`)입니다. 키를 내보내는 기능은 없고, ZEROIZE는 키를 버려 SIGN과 PUBLIC_KEY를 끝냅니다. 오라클이 주장하지 않는 것은 다음과 같습니다. 1. 알고리즘은 Ed25519(SHA-512를 쓰는 PureEdDSA, FIPS 186-5와 RFC 8032에 있음)입니다. 구현은 벤더링한 크레이트 `ed25519-dalek` 2.2.0이며 어떤 종류의 검증도 받지 않았습니다. 키는 승인된 난수 비트 생성기에서 나오지 않습니다. 2. 이 커널 위에서 크레이트의 부채널 분석은 하지 않았습니다. -3. 키는 하나이고, 영속성, 키 가져오기·내보내기, DRBG, 운영자 입력이 없습니다. 양자 내성 알고리즘은 아직 없습니다. +3. 키는 부팅마다 하나이고(두 번째 KEYGEN은 `key-exists`로 거부하며, ZEROIZE 뒤에는 재부팅이 필요합니다), 영속성, 키 가져오기·내보내기, DRBG가 없습니다. 운영자 입력은 인증이 없는 직렬 터미널뿐입니다("직렬 입력과 운영자 터미널" 참고). 양자 내성 알고리즘은 아직 없습니다. 4. 모든 signer가 키 하나를 공유하므로 서명에는 클라이언트 신원이 담기지 않습니다. -5. 볼트의 가용성은 보호하지 않습니다. 클라이언트는 엔드포인트 하나를 공유하며 타임아웃을 사용해야 합니다. +5. 볼트의 가용성은 보호하지 않습니다. 클라이언트는 엔드포인트 하나를 공유하며 타임아웃을 사용해야 하고, 운영자는 키를 지울 수 있습니다. 6. 루트 태스크는 신뢰 대상이며 볼트를 읽을 수 있습니다. 7. 오라클은 QEMU(TCG와 HVF)에서만 실행했습니다. 스택 사본(커널 부트 스택, 서명 뒤의 볼트 스택)의 삭제는 최선을 다하는 수준입니다. -8. 자가 시험은 클라이언트를 하나의 클라이언트 주소 공간에서 차례로 실행하므로, 클라이언트 사이가 아니라 볼트와 클라이언트 사이의 격리를 보여 줍니다. +8. 자가 시험은 클라이언트를 하나의 클라이언트 주소 공간에서 차례로 실행하므로, 클라이언트 사이가 아니라 볼트와 클라이언트 사이의 격리를 보여 줍니다. 자가 시험은 공개된 RFC 8032 테스트 시드로 키를 만들며, 실제 시드 정보를 함께 넘기므로 엔트로피 규칙은 여전히 시험됩니다. + +시드와 키는 다음과 같습니다. 볼트의 상태는 `fresh`, `seeded`, `ready`, `zeroized`, `failed`입니다. INIT(admin 전용, 한 번)은 시드를 전달하기만 합니다. 볼트는 엔트로피 규칙을 확인하고 시드를 보관합니다(`seeded`). KEYGEN(admin과 operator)은 보관한 시드에서 선택한 알고리즘으로 키를 만들고 시드를 지웁니다(`ready`). 알고리즘이 없는 이미지의 볼트는 시드를 거부하고 `fresh`에 머물며, 모두 0인 시드도 거부합니다. -엔트로피 규칙은 다음과 같습니다. 볼트는 부트 시드에 `rng-seed` 바이트가 32바이트 이상 있거나 RNDR에서 온 256비트가 있지 않으면 키 생성을 거부합니다(상태 `NO_ENTROPY`). QEMU virt는 32바이트 `rng-seed`를 제공합니다. 모든 응답에는 표시 비트가 담깁니다. 알고리즘이 FIPS 186-5에 있는지, 자가 시험이 통과했는지, `rng-seed`가 32바이트 이상 키 시드에 들어갔는지, RNDR이 키 시드에 들어갔는지입니다. 이 비트는 일어난 일을 보고할 뿐 검증 주장이 아닙니다. +엔트로피 규칙은 다음과 같습니다. 볼트는 부트 시드에 `rng-seed` 바이트가 32바이트 이상 있거나 RNDR에서 온 256비트가 있지 않으면 부트 시드를 거부합니다(상태 `NO_ENTROPY`). QEMU virt는 32바이트 `rng-seed`를 제공합니다. 모든 응답에는 표시 비트가 담깁니다. 알고리즘이 FIPS 186-5에 있는지, 자가 시험이 통과했는지, `rng-seed`가 32바이트 이상 키 시드에 들어갔는지, RNDR이 키 시드에 들어갔는지입니다. 이 비트는 일어난 일을 보고할 뿐 검증 주장이 아닙니다. STATUS 응답은 상태, 키의 알고리즘, 이미지에 있는 알고리즘을 한 워드에 담습니다. ### 부트 시드와 시드 삭제 -커널은 루트 태스크용 32바이트를 디바이스 트리 엔트로피, 카운터, CPU에 RNDR이 있으면 새 RNDR 워드 네 개로부터 자기만의 도메인 문자열을 붙인 SHA-256으로 유도합니다. 도메인 분리 덕분에 PAC 키와는 독립입니다. 시드는 입력만큼만 좋고 그 이상은 아닙니다. 시드는 진입 레지스터 `x0`~`x3`로 루트 태스크에 전달되며, `x4`가 사용한 `rng-seed` 바이트 수와 RNDR 기여 여부를 알려 줍니다. bootinfo 페이지에는 없고, 루트 태스크는 시드가 아니라 출처만 출력합니다. +커널은 루트 태스크용 32바이트를 디바이스 트리 엔트로피, 카운터, CPU에 RNDR이 있으면 새 RNDR 워드 네 개로부터 자기만의 도메인 문자열을 붙인 SHA-256으로 유도합니다. 도메인 분리 덕분에 PAC 키와는 독립입니다. 시드는 입력만큼만 좋고 그 이상은 아닙니다. 시드는 진입 레지스터 `x0`~`x3`로 루트 태스크에 전달되며, `x4`가 사용한 `rng-seed` 바이트 수와 RNDR 기여 여부를 알려 줍니다. bootinfo 페이지에는 없고, 루트 태스크는 시드가 아니라 출처만 출력합니다. 실제 부트 시드는 `terminal`과 `vault`가 있는 이미지의 서비스 볼트가 정확히 한 번 사용합니다. 그 밖의 모든 이미지에서는 루트 태스크가 진입할 때 지웁니다. 커널은 루트 태스크에 진입하기 직전에 디바이스 트리의 `rng-seed`와 `kaslr-seed` 바이트를 0으로 지웁니다. 그 페이지의 읽기 전용 별칭 항목을 제자리에서 읽기·쓰기로 바꾸고, 0을 쓰고, 캐시 줄을 비우고 무효화한 뒤, 다시 되돌리고 바이트를 읽어 확인합니다. 그런 다음 `BootInfo` 안의 자기 사본을 지우고, `k0: dtb seeds wiped B`를 출력하고, 활성 프레임 아래의 부트 스택을 0으로 지웁니다. 펌웨어나 UEFI 로더가 보관한 사본과 부트 스택의 활성 프레임에 있는 것은 지우지 않습니다. @@ -233,7 +284,7 @@ $ grep -a 'k0: console drivers' <이미지 파일> - **권장**: 에서 draft advisory를 작성하세요. - **대안**: 메인테이너 에게 메일을 보내세요. 영향을 받는 커밋 해시, 플랫폼(QEMU 머신과 CPU 모델, 하이퍼바이저 또는 보드), 진입 단계(EL1 또는 EL2), 페이지 크기(4 KiB 또는 16 KiB), 부트 로그의 `k0: platform ...` 줄, 재현 방법이 있으면 포함해 주세요. -`v0.1.0` 이하의 격리 공백과, "`main`에서도 여전히 제공하지 않는 것"에 적은 가용성·자원 한계는 이미 알려진 문제이기 때문에 **다시 신고하실 필요는 없습니다**. 현재 `main` 브랜치의 격리 우회는 환영합니다. 예를 들어 한 태스크가 다른 태스크의 메모리나 케이퍼빌리티에 닿는 경우, revoke된 케이퍼빌리티가 계속 동작하는 경우, unmap·revoke·주소 공간 파괴 뒤에도 낡은 매핑이 남는 경우입니다. 서명 오라클에 관한 신고도 환영합니다. 예를 들어 클라이언트에 키가 노출되는 경우, 정책 우회, 엉뚱한 호출자에게 응답이 가는 경우입니다. UEFI 로더에 관한 신고도 환영합니다. 예를 들어 펌웨어가 아직 쓰는 메모리를 커널에 넘기게 만드는 메모리 맵이나 디바이스 트리, 일어나야 할 거부가 일어나지 않는 경우입니다. 그 외의 문제, 예를 들어 부팅 시 메모리 맵 검증, 예외 처리, 스케줄러 정책, IPC 상태 기계에 관한 신고는 언제든 환영합니다. +`v0.1.0` 이하의 격리 공백과, "`main`에서도 여전히 제공하지 않는 것"에 적은 가용성·자원 한계는 이미 알려진 문제이기 때문에 **다시 신고하실 필요는 없습니다**. 현재 `main` 브랜치의 격리 우회는 환영합니다. 예를 들어 한 태스크가 다른 태스크의 메모리나 케이퍼빌리티에 닿는 경우, revoke된 케이퍼빌리티가 계속 동작하는 경우, unmap·revoke·주소 공간 파괴 뒤에도 낡은 매핑이 남는 경우입니다. 서명 오라클에 관한 신고도 환영합니다. 예를 들어 클라이언트에 키가 노출되는 경우, 정책 우회, 엉뚱한 호출자에게 응답이 가는 경우입니다. 직렬 입력 경로와 운영자 터미널에 관한 신고도 환영합니다. 예를 들어 커널을 오동작하게 만드는 바이트 열, 엉뚱한 태스크를 깨우는 경우, 나열한 네 가지를 넘는 운영자 연산입니다. UEFI 로더에 관한 신고도 환영합니다. 예를 들어 펌웨어가 아직 쓰는 메모리를 커널에 넘기게 만드는 메모리 맵이나 디바이스 트리, 일어나야 할 거부가 일어나지 않는 경우입니다. 그 외의 문제, 예를 들어 부팅 시 메모리 맵 검증, 예외 처리, 스케줄러 정책, IPC 상태 기계에 관한 신고는 언제든 환영합니다. ## 범위 @@ -243,7 +294,7 @@ $ grep -a 'k0: console drivers' <이미지 파일> K0의 범위와 신뢰 경계: 커널 진입점 이전의 부트 체인은 범위 밖이고, 로더, 커널, 루트 태스크는 범위 안이며, 디바이스 트리와 격리된 태스크와 태스크가 출력한 k0: 줄은 신뢰하지 않습니다

-**범위 안**: `kernel/`, `crates/`(`crates/k0-efi` 포함), `loader/`, `userspace/root-task/`, `userspace/k0-vault`(루트 태스크 안의 연결 코드 포함) 하위의 모든 코드입니다. UEFI 로더는 부트 체인의 일부이지만 이 저장소의 코드이므로, 메모리 맵과 디바이스 트리와 커널 이미지를 다루는 부분은 범위 안입니다. +**범위 안**: `kernel/`, `crates/`(`crates/k0-efi` 포함), `loader/`, `userspace/root-task/`, `userspace/k0-vault`와 `userspace/k0-term`(루트 태스크 안의 연결 코드 포함) 하위의 모든 코드입니다. UEFI 로더는 부트 체인의 일부이지만 이 저장소의 코드이므로, 메모리 맵과 디바이스 트리와 커널 이미지를 다루는 부분은 범위 안입니다. **범위 밖**: 커널 진입점 이전의 나머지 부트 체인(예: 펌웨어, 다른 부트로더, 하이퍼바이저)과 커널 이미지 자체의 무결성입니다(커널 이미지 서명은 부트 체인의 책임입니다). UEFI에서는 이것이 펌웨어의 Secure Boot를 뜻합니다. 로더의 SHA-256 검사는 서명이 아니기 때문입니다("UEFI 로더" 절 참고). diff --git a/USAGE.md b/USAGE.md index 7e8e692..87135b6 100644 --- a/USAGE.md +++ b/USAGE.md @@ -33,9 +33,9 @@ This builds the kernel with a console driver and starts it in QEMU. The boot mes Input and output are optional in K0. You can select them with Cargo features of the kernel crate. > [!NOTE] -> A feature for input or for a terminal does not exist yet. Console output is the only thing you can select today. +> Console input and the operator terminal are features too, but they are off by default. They are described in "Operator terminal" below. -Console output exists only in an image built with a console feature. No image has input. `cargo virt` is an alias for `cargo run -p k0-kernel --features console`, so it always includes the console. The following picture shows where the output goes, depending on the features in the build. +Console output exists only in an image built with a console feature. An image has input only if it was built with `console-input` or `terminal`. `cargo virt` is an alias for `cargo run -p k0-kernel --features console`, so it always includes the console. The following picture shows where the output goes, depending on the features in the build.

Output path by console feature. An image built without a feature writes only to the boot log in memory, and an image built with a console feature also writes to the matching UART. @@ -189,12 +189,112 @@ In the boot log you should see these lines, in addition to the lines in "Reading - `k0: dtb seeds wiped 40B` and `root: boot seed from rng-seed bytes 0x0000000000000020 without rndr` (with `K0_QEMU_CPU=max` the second line ends with `and rndr`). QEMU virt provides a 32-byte `rng-seed`, which is `0x20`. - Two more `k0: task fault` lines, 8 in total. They come from two clients that the self-test lets break the memory rules on purpose. -- `root: oracle tests pass` before `root: sched tests pass`. This line means that all the checks of the oracle passed: the vault made its key from the boot seed, a signer got a signature that verifies, a changed message or signature does not verify, the admin and a reader were refused when they asked to sign, and signing was refused after the key was erased. +- `root: oracle tests pass` before `root: sched tests pass`. This line means that all the checks of the oracle passed: the vault made its key from the public RFC 8032 test seed, a signer got a signature that verifies, a changed message or signature does not verify, the admin and a reader were refused when they asked to sign, and signing was refused after the key was erased. The vault makes a key only if the boot seed holds at least 32 `rng-seed` bytes or 256 bits from RNDR. If it does not, for example on a machine whose device tree has no `rng-seed` and whose CPU has no RNDR, the vault answers `NO_ENTROPY` and makes no key. The root task then prints `root: oracle made no key (boot seed has no entropy)` and stops the oracle test there. `root: oracle tests pass` does not appear, so a boot test that requires it fails, which is the intended result. > [!NOTE] -> The implementation of Ed25519 is the vendored crate `ed25519-dalek` 2.2.0 and has no validation of any kind, and the key does not come from an approved random bit generator. There is one key, no persistence, no key import or export and no input from an operator. The availability of the vault is not protected, because all clients share one endpoint and must use timeouts. The root task is trusted and could read the vault. The oracle was only run in QEMU (TCG and HVF). The details and the limits are in [SECURITY.md](SECURITY.md). +> The implementation of Ed25519 is the vendored crate `ed25519-dalek` 2.2.0 and has no validation of any kind, and the key does not come from an approved random bit generator. There is one key, no persistence, no key import or export and no authentication of the operator. The availability of the vault is not protected, because all clients share one endpoint and must use timeouts. The root task is trusted and could read the vault. The oracle was only run in QEMU (TCG and HVF). The details and the limits are in [SECURITY.md](SECURITY.md). + +### Operator terminal + +The operator terminal is a small task that lets you type commands on the serial line and talk to the vault. It is optional and off by default. Two features of `k0-kernel` select it, and features only add. + +| Feature | Adds | +| --- | --- | +| `console-input` | The kernel's receive path for the console UART and the system call `CONSOLE_READ`. It needs a console driver feature to do anything. Receive exists for PL011 and SBSA UART only, so a 16550 console has output and no input | +| `terminal` | The terminal task in the root task image, started as a service after the self-tests. It turns `console-input` on. With `vault` the terminal is the vault's operator. With `vault-ed25519` it can make an Ed25519 key | + +An image without `console-input` has no receive code, no `CONSOLE_READ` and none of the new log lines. An image without `terminal` has no terminal code. You can build and run it as follows: + +```sh +$ cargo build -p k0-kernel --features console,terminal,vault-ed25519 +$ cargo run -p k0-kernel --features console,terminal,vault-ed25519 +``` + +`cargo run` starts QEMU with the serial port on your terminal. QEMU's own escape key is `Ctrl-A` there (`Ctrl-A`, then `X` quits QEMU), so `Ctrl-A` never reaches K0. + +After the self-tests, the root task starts the vault, hands it the boot seed, runs two hostile tasks wired like the terminal (they must be refused and end in a fault), drops its admin capability and starts the terminal. The boot log shows `root: vault seeded`, `root: terminal console filter [...]`, `root: terminal wiring holds`, two `k0: task fault` lines, `root: service started` and then the banner. On a machine without an input path it shows `root: no console input, terminal not started`. After the first read, the periodic `k0: tick N` lines stop, and one line `k0: tick lines off (console input in use)` marks that. In the following session, every command ends with exactly one line, `ok` or `err `: + +``` +K0 operator console, type 'help' +k0> vault status +state=seeded +alg=none +selftest=passed +seed=rng-seed +validated=no +ok +k0> vault keygen ed25519 +state=ready +alg=ed25519 +ok +k0> vault pubkey +pubkey=<32 hex characters> + <32 hex characters> +ok +k0> vault zeroize +hint=type 'vault zeroize confirm' to erase the key +err confirm-required +k0> +``` + +Values are printed as `name=value`. The screen prompt is `k0> `. In the following table, the first column is what you type: + +| Command | Argument | What it does | +| --- | --- | --- | +| `help` | | Lists the commands | +| `vault status` | | Prints the vault state (see below) | +| `vault pubkey` | | Prints the public key | +| `vault keygen ` | `ed25519` | Makes the key from the held seed with the chosen algorithm and wipes the seed | +| `vault zeroize confirm` | | Erases the key. `vault zeroize` alone prints `hint=type 'vault zeroize confirm' to erase the key` and `err confirm-required` | + +`vault status` prints `state=fresh|seeded|ready|zeroized|failed`, `alg=none|ed25519`, `selftest=passed|failed`, `seed=none|rng-seed|rndr|rng-seed+rndr` and `validated=no`. `seed=rng-seed` means that the bytes were present, not that they were unpredictable. `validated=no` is always printed, because the implementation has no validation of any kind. `vault pubkey` prints `pubkey=` and 32 hex characters, then a second line indented by 7 spaces with the other 32. A vault makes one key per boot: a second `vault keygen` gives `err key-exists`, and after `vault zeroize confirm` you have to reboot. Without the `vault` feature, `help` lists only `help` and `vault ...` answers `err no-vault`. + +In the following table, the keys work on the line you are typing: + +| Key | Effect | +| --- | --- | +| Enter (CR or LF) | Runs the line. A line has at most 64 characters, printable ASCII only | +| Backspace or DEL | Erases one character | +| `Ctrl-C` or `Ctrl-U` | Cancels the line (shown as `^C` or `^U`) | +| ESC sequences (arrow keys) | Ignored | + +Bytes that reached the UART before the prompt are dropped. If the input was lost (a FIFO overrun, a break, a framing or parity error), everything up to the next line end is discarded and the command answers `err input-lost`. A keygen or zeroize that was delivered but not answered in time adds `hint=run 'vault status' to see whether it took effect`. In the following table, the error names are what comes after `err `: + +| Error | Meaning | +| --- | --- | +| `unknown-command` | The command is not known | +| `bad-argument` | An argument is wrong or missing | +| `line-too-long` | The line is longer than 64 characters | +| `input-lost` | Input was lost before the line end | +| `confirm-required` | `vault zeroize` without `confirm` | +| `denied` | The operation is not allowed for the operator | +| `no-vault` | The image has no vault | +| `no-key` | The vault has no key | +| `key-exists` | The vault already made its key this boot | +| `no-entropy` | The boot seed has no entropy | +| `unsupported-algorithm` | The algorithm is not in this image | +| `zeroized` | The key was erased; a reboot is needed | +| `vault-failed` | The vault failed and wiped seed and key | +| `vault-timeout` | The vault did not answer in time | + +> [!WARNING] +> There is no authentication on the serial line. Whoever holds the line is the operator and can do exactly the operator's four operations (`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`), including erasing the key. The operator cannot get a signature, cannot deliver a seed and cannot change policy. + +What stays true, and what is not covered: + +- **Kernel code**: the receive code runs at EL1. It is small and never interprets a byte, but it is kernel code driven by an outside party. A user-space driver needs device and interrupt delegation, which K0 does not have. +- **Timing**: an outside party can now cause interrupts while tasks run (bounded by the reader), and the reader learns arrival times finer than the tick. Other tasks can notice the stolen time. This timing channel is not analysed. +- **Latency**: input waits behind running tasks. There are no priorities, so the latency is up to a tick per ready task. +- **Hardware**: a 16550 console has no input. The SBSA UART path, FIFO overruns and the receive timeout interrupt are not exercised by QEMU, only by host tests with a fake UART. The cut-off for an interrupt line that fires without a UART cause is also covered only by host tests. No test measures kernel time under a flood on a machine. Nothing ran on real hardware. +- **Screen**: if a kernel line appears while you are typing, the screen line is split but the buffer is whole, and Enter runs the whole buffer. Any task with `Console` output can still print lines that look like kernel or root task lines, and nothing authenticates the prefix. The terminal can additionally erase within its current line. +- **Bytes held back**: "dropped before the prompt" counts bytes that reached the UART. An emulator or adapter that holds bytes back delivers them later (QEMU does). +- **Service**: no signing client exists in service mode yet. The key is made and shown but not used by another task. The terminal and the vault are not restarted if they die. The root task is trusted. +- **Boot log**: terminal output counts against the user share of the in-memory boot log. Once that share is full, later task output is not recorded there. +- **Vault**: all earlier limits stay. The implementation is unvalidated, there is no side-channel analysis, the key does not come from an approved random bit generator, there is no persistence and there is no PQC. The availability of the vault and of the terminal is not protected. + +If the console interrupt number is wrong, only the input path is lost: the boot log shows `k0: console input off (...)`. The reasons are `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range` and `interrupt not available`. A line that keeps firing without a UART cause is switched off after 8 entries with `k0: console input off (interrupt N fired without a uart cause)`. With input on, the boot log shows `k0: console input on (pl011 irq 33)`. The interrupt number is part of the platform line (`k0: platform con=pl011@0x9000000,irq33 ...`), so a `K0_PIN` made before this change no longer matches and must be made again. ## Booting through UEFI @@ -307,9 +407,9 @@ $ tools/qemu-boot-test.sh # boot in QEMU and che $ tools/boot-matrix.sh # boot every supported configuration (builds the 16 KiB, pinned and UEFI loader images too) ``` -- `tools/host-test.sh` runs the 276 host tests (190 on an x86-64 computer): small tests of single parts of the kernel (unit tests) as ordinary programs on your computer. It also does **fuzzing**: it feeds the device tree parser and the UEFI loader's planning code random, broken input to find crashes. The 276 are 14 (`k0-abi`), 42 (`k0-cap`), 82 (`k0-boot`), 32 (`k0-efi`), 20 (`k0-vault`, which is 13 with Ed25519 and 7 without) and 43 for each of the two page sizes (`k0-mm`). The memory management tests use ARM instructions, so they run only on an ARM computer (an Apple Silicon Mac or Linux arm64), and the x86-64 count leaves out those 86. +- `tools/host-test.sh` runs the 354 host tests (268 on other hosts): small tests of single parts of the kernel (unit tests) as ordinary programs on your computer. It also does **fuzzing**: it feeds the device tree parser and the UEFI loader's planning code random, broken input to find crashes. The 354 are 15 (`k0-abi`), 44 (`k0-cap`), 85 (`k0-boot`), 33 (`k0-efi`), 15 (`k0-conin`), 31 (`k0-vault`, which is 20 with Ed25519 and 11 without), 45 (`k0-term`, which is 24 with the vault feature and 21 without) and 43 for each of the two page sizes (`k0-mm`). The memory management tests use ARM instructions, so they run only on an ARM computer (an Apple Silicon Mac or Linux arm64), and the count on other hosts leaves out those 86. - `tools/qemu-boot-test.sh` boots the kernel and reads the log line by line in a fixed order. It fails on any error line, checks the exact number of intentional fault lines, and stops QEMU when it is done. The root task's timeout tests wait for real timer ticks, so a boot takes about 4 seconds longer than it did before they existed. The test also counts the tick lines between `root: teardown tests pass` and `root: timeout tests pass` and wants at least 4, which is how it checks that a timeout does not end early. It prints `boot-test: pass` on success and saves the full log in `target/qemu-boot-test.log`. It takes the machine from the `K0_QEMU_*` variables above. It accepts `K0_BOOT_REUSE=skip` for memory layouts that have no untyped region of the right size, where the root task skips its reuse test. It reads the kernel lines from the **serial port**, so it needs an image with a console driver. For an image without one, see "Testing an image without console" below. If the serial log has no kernel line, it prints a hint about a kernel built without a console feature. -- `tools/boot-matrix.sh` boots the kernel in **each** configuration that K0 calls supported and checks the result. It boots QEMU virt with GICv3 and GICv2 at EL1 and EL2, and also three CPU models, 4 cores, the 16 KiB image, other load addresses, `xlnx-versal-virt`, a pinned image and the images with the signing oracle. It also checks statically that the image does not touch the physical timer. The matrix has 61 rows on a Mac with HVF and 51 in CI. You can name single rows as arguments. CI runs it. +- `tools/boot-matrix.sh` boots the kernel in **each** configuration that K0 calls supported and checks the result. It boots QEMU virt with GICv3 and GICv2 at EL1 and EL2, and also three CPU models, 4 cores, the 16 KiB image, other load addresses, `xlnx-versal-virt`, a pinned image and the images with the signing oracle. It also checks statically that the image does not touch the physical timer. The matrix has 76 rows on a Mac with HVF and 65 in CI. You can name single rows as arguments. CI runs it. The console rows check the console features. The following table lists the console rows and what they check. @@ -336,7 +436,24 @@ The `uefi-*` rows boot the kernel through the UEFI loader on EDK2: GICv3 and GIC For configurations that must be refused, it reads the reason from the boot log in memory, or for the loader from the serial log. These are a 16 KiB kernel on `cortex-a72` and a kernel with one changed byte. -On an Apple Silicon Mac, `K0_MATRIX_HVF=1 tools/boot-matrix.sh` adds rows that run the kernel, also through the UEFI loader, on the real CPU cores through QEMU's HVF accelerator. Among them are `hvf-quiet` for the image without console and `hvf-vault` for the image with the oracle. +On an Apple Silicon Mac, `K0_MATRIX_HVF=1 tools/boot-matrix.sh` adds rows that run the kernel, also through the UEFI loader, on the real CPU cores through QEMU's HVF accelerator. Among them are `hvf-quiet` for the image without console, `hvf-vault` for the image with the oracle and `hvf-term` for the terminal image. + +The input and terminal rows check the receive path and the terminal. In the following table, the rows `input-only`, `input-gicv2`, `input-16550` and `input-bad-irq` boot images with `console-input` and no terminal: + +| Row | What it checks | +| --- | --- | +| `input-only` | An image with `console-input` and no terminal | +| `input-gicv2` | The same on GICv2 | +| `input-16550` | An image with only the 16550 driver: input is off (`console not attached`) and the log says so | +| `input-bad-irq` | A device tree with an interrupt number out of range costs only the input path (`interrupt number out of range`) | +| `input-symbols` | Static check. An image without `console-input` contains no receive code, no `CONSOLE_READ` and none of the new log lines | +| `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k` | The terminal image, run through `tools/term-test.py` on the default CPU, on the `max` CPU, at EL2, on GICv2 and with a 16 KiB image | +| `term-no-vault` | A terminal without the vault: `help` lists only `help` | +| `term-no-alg` | A terminal with `vault` but no algorithm | +| `term-uefi`, `term-uefi-acpi` | The terminal image through the UEFI loader (device tree path and ACPI path) | +| `hvf-term` | The terminal image under HVF (Mac only) | + +`tools/term-test.py ` boots the image with QEMU's serial port on pipes and runs a scripted session. It covers every command and error, erase and cancel, CR LF, an ESC sequence, a line that is too long, key generation, the public key format, zeroize, 200 kB without a line end, 2000 lines in a row and a serial break. `tools/qemu-boot-test.sh` also knows `K0_BOOT_INPUT=on|off` and `K0_BOOT_SERVICE=vault|plain|none` to say what the image should show, and a judge-only mode `K0_BOOT_JUDGE`. A terminal image prints two more `k0: task fault` lines than the same image without the terminal (8 without the vault, 10 with it), so use `K0_BOOT_FAULTS` for it. ### Testing an image without console @@ -397,3 +514,7 @@ The following table lists what to do for each problem. | `build-loader: kernel ELF not found` | Build the kernel first with `cargo build -p k0-kernel --features console --offline` | | `build-loader: embedding a kernel with: k0: console drivers [none]` | The loader will carry a kernel without console. It still prints its own lines, and the kernel prints nothing after them. Build the kernel with `--features console` and run `tools/build-loader.sh` again if you want output | | The screen shows only firmware messages, or the firmware menu | The firmware could not start the loader, or the loader refused and the firmware went on. Look for `k0-loader:` lines. With none, check that the `.efi` file exists and, with `K0_QEMU_ESP`, that the drive is found | +| The terminal shows no `k0> ` prompt | Either the image was built without `terminal` (and `console-input`), or the log shows `k0: console input off (...)` or `root: no console input, terminal not started`. Build with `--features console,terminal,vault-ed25519` and read the reason in the boot log | +| Nothing happens when I type, or `Ctrl-A` does not arrive | Under `cargo run` QEMU keeps `Ctrl-A` for itself. A 16550 console has no input at all | +| `boot-test` fails on the number of `k0: task fault` lines for a terminal image | That image prints 2 more than without the terminal (8 or 10). Use `K0_BOOT_FAULTS` | +| A `K0_PIN` made earlier no longer matches | The platform line now contains the console interrupt (`irq33`). Make the pin again | diff --git a/USAGE_KR.md b/USAGE_KR.md index 9ca5f66..ccae298 100644 --- a/USAGE_KR.md +++ b/USAGE_KR.md @@ -33,9 +33,9 @@ $ cargo virt K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Cargo features로 선택할 수 있습니다. > [!NOTE] -> 입력 또는 터미널용 feature는 아직 없습니다. 지금 선택할 수 있는 것은 콘솔 출력뿐입니다. +> 콘솔 입력과 운영자 터미널도 feature이지만 기본으로는 꺼져 있습니다. 뒤의 "운영자 터미널"에서 설명합니다. -콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다. 입력은 어떤 이미지에도 없습니다. `cargo virt`는 `cargo run -p k0-kernel --features console`의 별칭이므로 항상 콘솔을 포함합니다. 다음 그림은 빌드에 포함한 feature에 따라 출력이 어디에 닿는지 보여 줍니다. +콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다. 입력은 `console-input` 또는 `terminal`을 포함해 빌드한 이미지에만 있습니다. `cargo virt`는 `cargo run -p k0-kernel --features console`의 별칭이므로 항상 콘솔을 포함합니다. 다음 그림은 빌드에 포함한 feature에 따라 출력이 어디에 닿는지 보여 줍니다.

빌드에 포함한 feature에 따른 출력 경로. feature 없이 빌드한 이미지는 메모리의 부트 로그에만 출력하고, 콘솔 feature로 빌드한 이미지는 해당 UART에도 출력합니다. @@ -189,12 +189,112 @@ $ K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE='k0: dtb seeds wiped 40B|root: oracle tests p - `k0: dtb seeds wiped 40B`와 `root: boot seed from rng-seed bytes 0x0000000000000020 without rndr`입니다(`K0_QEMU_CPU=max`에서는 두 번째 줄이 `and rndr`로 끝납니다). QEMU virt는 32바이트 `rng-seed`를 제공하며, 이것이 `0x20`입니다. - `k0: task fault` 줄이 두 개 더 나와 모두 8개입니다. 자가 테스트가 일부러 메모리 규칙을 어기게 하는 클라이언트 둘에서 나온 줄입니다. -- `root: sched tests pass` 앞의 `root: oracle tests pass`입니다. 이 줄은 오라클의 검사가 모두 통과했다는 뜻입니다. 볼트가 부트 시드로 키를 만들었고, 서명자가 검증되는 서명을 받았으며, 메시지나 서명을 바꾸면 검증되지 않고, 관리자와 읽기 전용 클라이언트는 서명을 요청했을 때 거부되었으며, 키를 지운 뒤에는 서명이 거부되었습니다. +- `root: sched tests pass` 앞의 `root: oracle tests pass`입니다. 이 줄은 오라클의 검사가 모두 통과했다는 뜻입니다. 볼트가 공개 RFC 8032 테스트 시드로 키를 만들었고, 서명자가 검증되는 서명을 받았으며, 메시지나 서명을 바꾸면 검증되지 않고, 관리자와 읽기 전용 클라이언트는 서명을 요청했을 때 거부되었으며, 키를 지운 뒤에는 서명이 거부되었습니다. 볼트는 부트 시드에 `rng-seed` 바이트가 32개 이상 있거나 RNDR에서 온 256비트가 있을 때만 키를 만듭니다. 그렇지 않으면, 예를 들어 디바이스 트리에 `rng-seed`가 없고 CPU에 RNDR도 없는 머신에서는 볼트가 `NO_ENTROPY`로 답하고 키를 만들지 않습니다. 그러면 루트 태스크가 `root: oracle made no key (boot seed has no entropy)`를 출력하고 오라클 테스트를 거기서 멈춥니다. `root: oracle tests pass`는 나오지 않으므로 이 줄을 요구하는 부팅 테스트는 실패하며, 이것이 의도한 결과입니다. > [!NOTE] -> Ed25519 구현은 vendor에 넣은 `ed25519-dalek` 2.2.0 크레이트이며 어떤 종류의 검증도 받지 않았고, 키는 승인된 난수 비트 생성기에서 나오지 않습니다. 키는 하나뿐이고, 영속성도 키의 가져오기나 내보내기도 운영자 입력도 아직 없습니다. 클라이언트가 엔드포인트 하나를 함께 사용하므로 볼트의 가용성은 보호되지 않으며 타임아웃을 써야 합니다. 루트 태스크는 신뢰 대상이며 볼트를 읽을 수 있습니다. 오라클은 QEMU(TCG와 HVF)에서만 실행해 보았습니다. 자세한 내용과 한계는 [SECURITY_KR.md](SECURITY_KR.md)에 있습니다. +> Ed25519 구현은 vendor에 넣은 `ed25519-dalek` 2.2.0 크레이트이며 어떤 종류의 검증도 받지 않았고, 키는 승인된 난수 비트 생성기에서 나오지 않습니다. 키는 하나뿐이고, 영속성도 키의 가져오기나 내보내기도 운영자 인증도 아직 없습니다. 클라이언트가 엔드포인트 하나를 함께 사용하므로 볼트의 가용성은 보호되지 않으며 타임아웃을 써야 합니다. 루트 태스크는 신뢰 대상이며 볼트를 읽을 수 있습니다. 오라클은 QEMU(TCG와 HVF)에서만 실행해 보았습니다. 자세한 내용과 한계는 [SECURITY_KR.md](SECURITY_KR.md)에 있습니다. + +### 운영자 터미널 + +운영자 터미널은 직렬 포트에서 명령을 입력해 볼트와 대화하는 작은 태스크입니다. 선택 사항이며 기본으로는 꺼져 있습니다. 커널 크레이트의 feature 두 개로 선택하며, feature는 더하기만 합니다. + +| Feature | 추가하는 것 | +| --- | --- | +| `console-input` | 콘솔 UART용 커널 수신 경로와 시스템 콜 `CONSOLE_READ`. 동작하려면 콘솔 드라이버 feature가 필요함. 수신은 PL011과 SBSA UART에만 있으므로 16550 콘솔에는 출력만 있고 입력은 없음 | +| `terminal` | 루트 태스크 이미지 안의 터미널 태스크로, 자가 테스트 뒤에 서비스로 시작함. `console-input`을 켬. `vault`를 포함하면 터미널이 볼트의 운영자가 되고, `vault-ed25519`를 포함하면 Ed25519 키를 만들 수 있음 | + +`console-input` 없이 빌드한 이미지에는 수신 코드도 `CONSOLE_READ`도 새 로그 줄도 없습니다. `terminal` 없이 빌드한 이미지에는 터미널 코드가 없습니다. 다음과 같이 빌드하고 실행할 수 있습니다. + +```sh +$ cargo build -p k0-kernel --features console,terminal,vault-ed25519 +$ cargo run -p k0-kernel --features console,terminal,vault-ed25519 +``` + +`cargo run`은 직렬 포트를 내 터미널에 연결해 QEMU를 시작합니다. 이때 QEMU 자신의 이스케이프 키는 `Ctrl-A`입니다(`Ctrl-A`를 누른 다음 `X`로 QEMU 종료). 따라서 `Ctrl-A`는 K0에 전달되지 않습니다. + +자가 테스트가 끝나면 루트 태스크가 볼트를 시작해 부트 시드를 넘기고, 터미널과 똑같이 연결한 적대적 태스크 둘을 돌리고(둘 다 거부되어 폴트로 끝나야 함), 관리자 케이퍼빌리티를 버린 뒤 터미널을 시작합니다. 부트 로그에는 `root: vault seeded`, `root: terminal console filter [...]`, `root: terminal wiring holds`, `k0: task fault` 두 줄, `root: service started`, 그다음 배너가 나옵니다. 입력 경로가 없는 머신에서는 `root: no console input, terminal not started`가 나옵니다. 처음 읽은 뒤에는 주기적인 `k0: tick N` 줄이 멈추고, `k0: tick lines off (console input in use)` 한 줄이 그 사실을 알립니다. 다음 세션에서 모든 명령은 `ok` 또는 `err ` 중 정확히 한 줄로 끝납니다. + +``` +K0 operator console, type 'help' +k0> vault status +state=seeded +alg=none +selftest=passed +seed=rng-seed +validated=no +ok +k0> vault keygen ed25519 +state=ready +alg=ed25519 +ok +k0> vault pubkey +pubkey=<32 hex characters> + <32 hex characters> +ok +k0> vault zeroize +hint=type 'vault zeroize confirm' to erase the key +err confirm-required +k0> +``` + +값은 `name=value` 형태로 출력됩니다. 화면 프롬프트는 `k0> `입니다. 다음 표의 첫 열이 입력하는 명령입니다. + +| 명령 | 인자 | 하는 일 | +| --- | --- | --- | +| `help` | | 명령 목록을 출력함 | +| `vault status` | | 볼트 상태를 출력함(아래 참고) | +| `vault pubkey` | | 공개 키를 출력함 | +| `vault keygen ` | `ed25519` | 보관 중인 시드로 고른 알고리즘의 키를 만들고 시드를 지움 | +| `vault zeroize confirm` | | 키를 지움. `vault zeroize`만 입력하면 `hint=type 'vault zeroize confirm' to erase the key`와 `err confirm-required`를 출력함 | + +`vault status`는 `state=fresh|seeded|ready|zeroized|failed`, `alg=none|ed25519`, `selftest=passed|failed`, `seed=none|rng-seed|rndr|rng-seed+rndr`, `validated=no`를 출력합니다. `seed=rng-seed`는 바이트가 있었다는 뜻이지 예측할 수 없다는 뜻이 아닙니다. 구현이 어떤 종류의 검증도 받지 않았으므로 `validated=no`는 항상 출력됩니다. `vault pubkey`는 `pubkey=`와 16진수 32자를 출력하고, 7칸 들여쓴 둘째 줄에 나머지 32자를 출력합니다. 볼트는 부팅 한 번에 키를 하나만 만듭니다. `vault keygen`을 한 번 더 하면 `err key-exists`가 나오고, `vault zeroize confirm` 뒤에는 재부팅해야 합니다. `vault` feature가 없으면 `help`는 `help`만 나열하고 `vault ...`는 `err no-vault`로 답합니다. + +다음 표의 키는 입력 중인 줄에 작용합니다. + +| 키 | 효과 | +| --- | --- | +| Enter(CR 또는 LF) | 줄을 실행함. 한 줄은 최대 64자이며 출력 가능한 ASCII만 허용함 | +| Backspace 또는 DEL | 한 글자를 지움 | +| `Ctrl-C` 또는 `Ctrl-U` | 줄을 취소함(`^C` 또는 `^U`로 표시) | +| ESC 시퀀스(방향키) | 무시함 | + +프롬프트가 나오기 전에 UART에 도착한 바이트는 버려집니다. 입력이 유실되면(FIFO 오버런, 브레이크, 프레이밍 또는 패리티 오류) 다음 줄 끝까지 모두 버리고 명령은 `err input-lost`로 답합니다. 전달은 됐지만 제때 응답받지 못한 keygen 또는 zeroize는 `hint=run 'vault status' to see whether it took effect`를 덧붙입니다. 다음 표의 오류 이름은 `err ` 뒤에 나오는 것입니다. + +| 오류 | 뜻 | +| --- | --- | +| `unknown-command` | 모르는 명령 | +| `bad-argument` | 인자가 틀렸거나 빠짐 | +| `line-too-long` | 한 줄이 64자를 넘음 | +| `input-lost` | 줄이 끝나기 전에 입력이 유실됨 | +| `confirm-required` | `confirm` 없는 `vault zeroize` | +| `denied` | 운영자에게 허용되지 않은 동작 | +| `no-vault` | 이미지에 볼트가 없음 | +| `no-key` | 볼트에 키가 없음 | +| `key-exists` | 볼트가 이번 부팅에서 이미 키를 만듦 | +| `no-entropy` | 부트 시드에 엔트로피가 없음 | +| `unsupported-algorithm` | 이 이미지에 없는 알고리즘 | +| `zeroized` | 키가 지워짐. 재부팅이 필요함 | +| `vault-failed` | 볼트가 실패해 시드와 키를 지움 | +| `vault-timeout` | 볼트가 제때 응답하지 않음 | + +> [!WARNING] +> 직렬 포트에는 인증이 없습니다. 포트를 쥔 사람이 곧 운영자이며, 키 삭제를 포함해 운영자의 네 가지 동작(`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`)을 그대로 할 수 있습니다. 운영자는 서명을 받을 수 없고, 시드를 넘길 수 없으며, 정책을 바꿀 수 없습니다. + +계속 유효한 한계와 다루지 않는 부분은 다음과 같습니다. + +- **커널 코드**: 수신 코드는 EL1에서 실행됩니다. 작고 바이트를 해석하지 않지만, 외부 당사자가 구동하는 커널 코드입니다. 사용자 공간 드라이버에는 장치 및 인터럽트 위임이 필요한데, K0에는 그것이 없습니다. +- **타이밍**: 외부 당사자가 이제 태스크가 도는 동안 인터럽트를 일으킬 수 있고(읽는 쪽이 상한을 정함), 읽는 쪽은 틱보다 정밀한 도착 시각을 알게 됩니다. 다른 태스크가 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널은 분석하지 않았습니다. +- **지연**: 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 지연은 준비된 태스크마다 최대 한 틱입니다. +- **하드웨어**: 16550 콘솔에는 입력이 없습니다. SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU로 실행되지 않고 가짜 UART를 쓰는 호스트 테스트로만 다룹니다. UART 원인 없이 발생하는 인터럽트 선을 끊는 동작도 호스트 테스트로만 다룹니다. 플러드 상황에서 커널이 쓰는 시간을 머신에서 측정하는 테스트는 없습니다. 실제 하드웨어에서는 아무것도 돌려 보지 않았습니다. +- **화면**: 입력 중에 커널 줄이 나타나면 화면의 줄은 갈라지지만 버퍼는 온전하며, Enter는 버퍼 전체를 실행합니다. `Console` 출력이 있는 태스크는 여전히 커널이나 루트 태스크 줄처럼 보이는 줄을 출력할 수 있고, 접두어를 인증하는 것은 없습니다. 터미널은 추가로 자기 현재 줄 안을 지울 수 있습니다. +- **붙잡힌 바이트**: "프롬프트 전에 버림"은 UART에 도착한 바이트를 말합니다. 바이트를 붙잡아 두는 에뮬레이터나 어댑터는 나중에 전달합니다(QEMU가 그렇습니다). +- **서비스**: 서비스 모드에는 서명 클라이언트가 아직 없습니다. 키는 만들어지고 보이지만 다른 태스크가 사용하지 않습니다. 터미널과 볼트는 죽어도 다시 시작되지 않습니다. 루트 태스크는 신뢰 대상입니다. +- **부트 로그**: 터미널 출력은 메모리 부트 로그의 사용자 몫을 소모합니다. 그 몫이 차면 이후 태스크 출력은 거기에 기록되지 않습니다. +- **볼트**: 이전의 한계는 모두 유지됩니다. 구현은 검증을 받지 않았고, 부채널 분석이 없으며, 키는 승인된 난수 비트 생성기에서 나오지 않고, 영속성도 PQC도 없습니다. 볼트와 터미널의 가용성은 보호되지 않습니다. + +콘솔 인터럽트 번호가 틀려도 잃는 것은 입력 경로뿐이며, 부트 로그에 `k0: console input off (...)`가 나옵니다. 이유는 `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range`, `interrupt not available`입니다. UART 원인 없이 계속 발생하는 인터럽트 선은 8번 진입한 뒤 `k0: console input off (interrupt N fired without a uart cause)`와 함께 꺼집니다. 입력이 켜지면 부트 로그에 `k0: console input on (pl011 irq 33)`이 나옵니다. 인터럽트 번호는 플랫폼 줄(`k0: platform con=pl011@0x9000000,irq33 ...`)에 들어 있으므로, 이번 변경 이전에 만든 `K0_PIN`은 더 이상 맞지 않아 다시 만들어야 합니다. ## UEFI로 부팅 @@ -307,9 +407,9 @@ $ tools/qemu-boot-test.sh # QEMU에서 부팅하 $ tools/boot-matrix.sh # 지원하는 구성을 전부 부팅(16 KiB 이미지, 고정 이미지, UEFI 로더 이미지도 빌드함) ``` -- `tools/host-test.sh`는 호스트 테스트 276개를 실행합니다(x86-64 컴퓨터에서는 190개). 커널의 부분 하나하나를 내 컴퓨터에서 일반 프로그램처럼 돌리는 작은 테스트(단위 테스트)입니다. **퍼징**도 합니다. 디바이스 트리 파서와 UEFI 로더의 계획 코드에 무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법입니다. 276개는 `k0-abi` 14개, `k0-cap` 42개, `k0-boot` 82개, `k0-efi` 32개, `k0-vault` 20개(Ed25519를 포함하면 13개, 없으면 7개), `k0-mm` 43개씩 두 페이지 크기분입니다. 메모리 관리 테스트는 ARM 명령을 사용하므로 ARM 컴퓨터(Apple Silicon Mac이나 Linux arm64)에서만 돌고, x86-64의 개수는 그 86개를 뺀 것입니다. +- `tools/host-test.sh`는 호스트 테스트 354개를 실행합니다(그 밖의 호스트에서는 268개). 커널의 부분 하나하나를 내 컴퓨터에서 일반 프로그램처럼 돌리는 작은 테스트(단위 테스트)입니다. **퍼징**도 합니다. 디바이스 트리 파서와 UEFI 로더의 계획 코드에 무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법입니다. 354개는 `k0-abi` 15개, `k0-cap` 44개, `k0-boot` 85개, `k0-efi` 33개, `k0-conin` 15개, `k0-vault` 31개(Ed25519를 포함하면 20개, 없으면 11개), `k0-term` 45개(`vault` feature를 포함하면 24개, 없으면 21개), `k0-mm` 43개씩 두 페이지 크기분입니다. 메모리 관리 테스트는 ARM 명령을 사용하므로 ARM 컴퓨터(Apple Silicon Mac이나 Linux arm64)에서만 돌고, 그 밖의 호스트의 개수는 그 86개를 뺀 것입니다. - `tools/qemu-boot-test.sh`는 커널을 부팅하고, 로그를 정해진 순서대로 한 줄씩 확인합니다. 에러 줄이 하나라도 나오면 실패하고, 일부러 일으킨 폴트 줄의 개수를 정확히 맞춘 뒤 QEMU를 끕니다. 루트 태스크의 타임아웃 테스트는 실제 타이머 틱을 기다리므로, 부팅 한 번이 그 테스트가 생기기 전보다 약 4초 더 걸립니다. `root: teardown tests pass`와 `root: timeout tests pass` 사이의 틱 줄도 세어 4개 이상을 요구하는데, 이것이 타임아웃이 일찍 끝나지 않는지 확인하는 방법입니다. 성공하면 `boot-test: pass`를 출력하고 전체 로그를 `target/qemu-boot-test.log`에 남깁니다. 머신은 앞의 `K0_QEMU_*` 변수에서 가져옵니다. 맞는 크기의 untyped 영역이 없는 메모리 배치에서는 루트 태스크가 재사용 시험을 건너뛰므로, 그때는 `K0_BOOT_REUSE=skip`을 받습니다. 커널 줄을 **직렬 포트**에서 읽으므로 콘솔 드라이버가 있는 이미지가 필요합니다. 콘솔 없는 이미지는 뒤의 "콘솔 없는 이미지 시험"을 보세요. 직렬 로그에 커널 줄이 하나도 없으면 콘솔 feature 없이 빌드한 커널이 아닌지 알려 주는 힌트를 출력합니다. -- `tools/boot-matrix.sh`는 K0가 지원한다고 말하는 **구성마다** 커널을 부팅해서 결과를 확인합니다. GICv3와 GICv2의 QEMU virt를 EL1과 EL2에서 부팅하고, CPU 모델 세 가지, 코어 4개, 16 KiB 이미지, 다른 적재 주소, `xlnx-versal-virt`, 고정 이미지, 서명 오라클이 있는 이미지도 부팅합니다. 이미지가 물리 타이머를 건드리지 않는지는 정적으로 검사합니다. 행렬은 HVF가 있는 Mac에서 61행, CI에서 51행입니다. 행 이름을 인자로 주면 그 행만 돌립니다. CI가 이것을 실행합니다. +- `tools/boot-matrix.sh`는 K0가 지원한다고 말하는 **구성마다** 커널을 부팅해서 결과를 확인합니다. GICv3와 GICv2의 QEMU virt를 EL1과 EL2에서 부팅하고, CPU 모델 세 가지, 코어 4개, 16 KiB 이미지, 다른 적재 주소, `xlnx-versal-virt`, 고정 이미지, 서명 오라클이 있는 이미지도 부팅합니다. 이미지가 물리 타이머를 건드리지 않는지는 정적으로 검사합니다. 행렬은 HVF가 있는 Mac에서 76행, CI에서 65행입니다. 행 이름을 인자로 주면 그 행만 돌립니다. CI가 이것을 실행합니다. 콘솔 행은 콘솔 feature를 확인합니다. 다음 표는 콘솔 행과 확인하는 내용입니다. @@ -336,7 +436,24 @@ $ tools/boot-matrix.sh # 지원하는 구성 거부해야 하는 구성에서는 커널의 사유를 메모리에 남은 부트 로그에서 읽고, 로더의 사유는 직렬 로그에서 읽습니다. 이런 구성으로 `cortex-a72`에서의 16 KiB 커널과 한 바이트를 바꾼 커널이 있습니다. -Apple Silicon Mac에서는 `K0_MATRIX_HVF=1 tools/boot-matrix.sh`로 QEMU의 HVF 가속기를 통해 실제 CPU 코어에서 커널을 (UEFI 로더를 거치는 경우도 포함해) 돌리는 행을 더할 수 있습니다. 콘솔 없는 이미지용으로는 `hvf-quiet`이, 오라클이 있는 이미지용으로는 `hvf-vault`가 있습니다. +Apple Silicon Mac에서는 `K0_MATRIX_HVF=1 tools/boot-matrix.sh`로 QEMU의 HVF 가속기를 통해 실제 CPU 코어에서 커널을 (UEFI 로더를 거치는 경우도 포함해) 돌리는 행을 더할 수 있습니다. 콘솔 없는 이미지용으로는 `hvf-quiet`이, 오라클이 있는 이미지용으로는 `hvf-vault`가, 터미널 이미지용으로는 `hvf-term`이 있습니다. + +입력 및 터미널 행은 수신 경로와 터미널을 확인합니다. 다음 표에서 `input-only`, `input-gicv2`, `input-16550`, `input-bad-irq` 행은 `console-input`을 포함하고 터미널은 없는 이미지를 부팅합니다. + +| 행 | 확인하는 것 | +| --- | --- | +| `input-only` | `console-input`을 포함하고 터미널이 없는 이미지 | +| `input-gicv2` | GICv2에서 같은 이미지 | +| `input-16550` | 16550 드라이버만 있는 이미지. 입력이 꺼지고(`console not attached`) 로그에 그렇게 남음 | +| `input-bad-irq` | 디바이스 트리의 인터럽트 번호가 범위를 벗어나도 입력 경로만 잃는지(`interrupt number out of range`) | +| `input-symbols` | 정적 검사. `console-input` 없는 이미지에 수신 코드도 `CONSOLE_READ`도 새 로그 줄도 없음 | +| `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k` | 터미널 이미지를 `tools/term-test.py`로 실행. 기본 CPU, `max` CPU, EL2, GICv2, 16 KiB 이미지 | +| `term-no-vault` | 볼트가 없는 터미널. `help`가 `help`만 나열함 | +| `term-no-alg` | `vault`는 있고 알고리즘은 없는 터미널 | +| `term-uefi`, `term-uefi-acpi` | UEFI 로더를 거치는 터미널 이미지(디바이스 트리 경로와 ACPI 경로) | +| `hvf-term` | HVF에서의 터미널 이미지(Mac 전용) | + +`tools/term-test.py <이미지>`는 QEMU의 직렬 포트를 파이프에 연결해 이미지를 부팅하고 정해진 세션을 실행합니다. 모든 명령과 오류, 지우기와 취소, CR LF, ESC 시퀀스, 너무 긴 줄, 키 생성, 공개 키 형식, zeroize, 줄 끝 없는 200 kB, 연속 2000줄, 직렬 브레이크를 다룹니다. `tools/qemu-boot-test.sh`는 이미지가 보여야 할 것을 알려 주는 `K0_BOOT_INPUT=on|off`와 `K0_BOOT_SERVICE=vault|plain|none`, 그리고 판정만 하는 모드 `K0_BOOT_JUDGE`도 이해합니다. 터미널 이미지는 터미널 없는 같은 이미지보다 `k0: task fault` 줄이 두 개 더 나오므로(볼트 없이 8개, 볼트와 함께 10개) `K0_BOOT_FAULTS`를 사용하세요. ### 콘솔 없는 이미지 시험 @@ -397,3 +514,7 @@ GitHub도 풀 리퀘스트와 `main` 푸시가 있을 때마다 이 테스트를 | `build-loader: kernel ELF not found` | 먼저 `cargo build -p k0-kernel --features console --offline`로 커널을 빌드하세요 | | `build-loader: embedding a kernel with: k0: console drivers [none]` | 로더가 콘솔 없는 커널을 품게 됩니다. 로더는 자기 줄을 계속 출력하고, 그 뒤로 커널은 아무것도 출력하지 않습니다. 출력이 필요하면 `--features console`로 커널을 빌드하고 `tools/build-loader.sh`를 다시 실행하세요 | | 화면에 펌웨어 메시지나 펌웨어 메뉴만 나옴 | 펌웨어가 로더를 시작하지 못했거나, 로더가 거부해서 펌웨어가 다음으로 넘어간 것입니다. `k0-loader:` 줄이 있는지 보세요. 없다면 `.efi` 파일이 있는지, `K0_QEMU_ESP`를 사용했다면 드라이브가 보이는지 확인하세요 | +| 터미널에 `k0> ` 프롬프트가 나오지 않음 | 이미지를 `terminal`(과 `console-input`) 없이 빌드했거나, 로그에 `k0: console input off (...)` 또는 `root: no console input, terminal not started`가 있습니다. `--features console,terminal,vault-ed25519`로 빌드하고 부트 로그에서 이유를 읽으세요 | +| 입력해도 반응이 없거나 `Ctrl-A`가 전달되지 않음 | `cargo run`에서는 QEMU가 `Ctrl-A`를 자기 몫으로 씁니다. 16550 콘솔에는 입력이 전혀 없습니다 | +| 터미널 이미지에서 `boot-test`가 `k0: task fault` 줄 수 때문에 실패 | 그 이미지는 터미널 없는 이미지보다 2개 더 출력합니다(8개 또는 10개). `K0_BOOT_FAULTS`를 사용하세요 | +| 이전에 만든 `K0_PIN`이 더 이상 맞지 않음 | 플랫폼 줄에 이제 콘솔 인터럽트(`irq33`)가 들어 있습니다. 핀을 다시 만드세요 | diff --git a/assets/terminal-flow.svg b/assets/terminal-flow.svg new file mode 100644 index 0000000..44e9405 --- /dev/null +++ b/assets/terminal-flow.svg @@ -0,0 +1,60 @@ + + Serial input and the operator terminal + Bytes from the serial line go into a 256-byte receive ring in the kernel. The terminal task reads one byte per CONSOLE_READ call. The terminal holds two capabilities: a Console copy with read and write rights, and the vault endpoint with the send right and the operator badge. + + + + + + + + + + Serial line + the operator's keys + + bytes + + + Kernel (EL1) + UART receive driver + 256-byte ring + never reads a byte + + + CONSOLE_READ + one byte + + + Terminal task + own address space, two capabilities + 1: Console copy, R and W + 2: vault endpoint, send, operator + + + CALL, operator badge + + + Vault endpoint + the badge fixes the role + + + RECV + + + Vault task + holds the key + diff --git a/assets/terminal-flow_KR.svg b/assets/terminal-flow_KR.svg new file mode 100644 index 0000000..5e542aa --- /dev/null +++ b/assets/terminal-flow_KR.svg @@ -0,0 +1,60 @@ + + 시리얼 입력과 운영자 터미널 + 시리얼 선으로 들어온 바이트는 커널의 256바이트 수신 링에 쌓입니다. 터미널 태스크는 CONSOLE_READ 호출 한 번에 한 바이트를 읽습니다. 터미널은 케이퍼빌리티를 둘 가집니다. 읽기와 쓰기 권한이 있는 Console 복사본, 그리고 송신 권한과 운영자 배지가 있는 볼트 엔드포인트입니다. + + + + + + + + + + 시리얼 선 + 운영자의 키 입력 + + 바이트 + + + 커널 (EL1) + UART 수신 드라이버 + 256바이트 링 + 바이트를 해석하지 않음 + + + CONSOLE_READ + 한 번에 한 바이트 + + + 터미널 태스크 + 자체 주소 공간, 케이퍼빌리티 둘 + 1: Console 복사본, R과 W + 2: 볼트 엔드포인트, 송신, 운영자 + + + CALL, 운영자 배지 + + + 볼트 엔드포인트 + 배지가 역할을 정함 + + + RECV + + + 볼트 태스크 + 키를 보관 + diff --git a/ci/threat_model.md b/ci/threat_model.md index f9df62f..767a6a4 100644 --- a/ci/threat_model.md +++ b/ci/threat_model.md @@ -1,6 +1,6 @@ # Threat model: K0 -K0 is a capability-based microkernel for AArch64, written in Rust `no_std` in the style of seL4 and licensed under PolyForm Noncommercial 1.0.0. The kernel runs at EL1. The only user-space code today is the root task, which runs at EL0 and doubles as the self-test harness. Console output is optional: it exists only in an image built with a console feature (see "Optional console output" in `SECURITY.md`). One generic image finds the console, the interrupt controller (GICv2 or GICv3) and the timer in the device tree at boot, and it may be entered at EL1 or at EL2. The 4 KiB granule is the default and the 16 KiB granule is a build option. It can also be started by a UEFI loader (`loader/`) that embeds the kernel. Only QEMU machines can be exercised in this image, with the EDK2 firmware package installed for the loader. +K0 is a capability-based microkernel for AArch64, written in Rust `no_std` in the style of seL4 and licensed under PolyForm Noncommercial 1.0.0. The kernel runs at EL1. The user-space code is the root task, which runs at EL0 and doubles as the self-test harness, and the vault and terminal tasks that it starts in images built with those features. Console output is optional: it exists only in an image built with a console feature (see "Optional console output" in `SECURITY.md`). Serial input and the operator terminal are optional too: they exist only in an image built with the feature `console-input` or `terminal`, and an image without them has no input code at all (see "Serial input and the operator terminal" in `SECURITY.md`). One generic image finds the console, the interrupt controller (GICv2 or GICv3) and the timer in the device tree at boot, and it may be entered at EL1 or at EL2. The 4 KiB granule is the default and the 16 KiB granule is a build option. It can also be started by a UEFI loader (`loader/`) that embeds the kernel. Only QEMU machines can be exercised in this image, with the EDK2 firmware package installed for the loader. Read `SECURITY.md` at the repository root first. It describes the isolation model of the released version 0.1.0, the unreleased isolation work on the current `main` branch, and the issues that are already known. This model describes the current `main` branch. @@ -15,7 +15,8 @@ Trust boundaries, from least to most trusted: 5. **The root task image** is embedded in the kernel at build time together with its SHA-256 (`crates/k0-boot/build.rs`, `verify_root_task`). It is part of the trusted computing base today. The hash detects corruption, not a malicious image; signature verification is a documented TODO. 6. **The UEFI loader** (`loader/`, `crates/k0-efi`) sits between the firmware and the kernel, and it is in scope. Its inputs come from firmware and are treated as wrong or hostile data: the UEFI memory map, the firmware device tree or, without one, the ACPI static tables (RSDP, XSDT, MADT, GTDT, SPCR) from the configuration table, the random number protocol and the embedded kernel image. It decides which memory the kernel sees as RAM, so a mistake there hands firmware memory to user space without any kernel bug. Entry path: `loader/src/load.rs` (flow) -> `crates/k0-efi/src/prepare.rs` (plan, rewrite, self-check with the kernel's own parser, discovery, `Platform::validate` and `boot_window`) -> `loader/src/handoff.rs` (cache flush, MMU off, jump). The pure logic is in `memmap.rs`, `fdtw.rs`, `verify.rs` and `image.rs` of `k0-efi`, none of it `unsafe`. The loader does not verify a signature: its SHA-256 over the embedded kernel is a corruption check, and authenticity is the firmware's Secure Boot job. -7. **The vault task and its clients** (optional, features `vault` and `vault-ed25519` of `k0-kernel`). The vault holds one Ed25519 key in its own address space. Clients send requests over one endpoint with a badge that the kernel delivers; the badge selects the role (admin, signer, reader) in a policy fixed at build time. Everything in a request (operation, algorithm, length, message, nonce) is attacker controlled, and the vault reads the body once into a private buffer. The root task builds the vault and is trusted, so a root task that reads the vault is not a finding. Entry path: `userspace/k0-vault` (`server`, `proto`, `provider`) and the wiring and self-test in `userspace/root-task/src/oracle.rs`. The Ed25519 code is the vendored crate `ed25519-dalek` 2.2.0, which has no validation of any kind. +7. **The vault task and its clients** (optional, features `vault` and `vault-ed25519` of `k0-kernel`). The vault holds one Ed25519 key in its own address space. Clients send requests over one endpoint with a badge that the kernel delivers; the badge selects the role (admin, operator, signer, reader) in a policy fixed at build time. The operator is the terminal of boundary 8. Everything in a request (operation, algorithm, length, message, nonce) is attacker controlled, and the vault reads the body once into a private buffer. The root task builds the vault and is trusted, so a root task that reads the vault is not a finding. Entry path: `userspace/k0-vault` (`server`, `proto`, `provider`) and the wiring and self-test in `userspace/root-task/src/oracle.rs`. The Ed25519 code is the vendored crate `ed25519-dalek` 2.2.0, which has no validation of any kind. +8. **The serial line and the operator terminal** (optional, features `console-input` and `terminal` of `k0-kernel`). Every byte that arrives on the console UART is attacker controlled, and so is its timing. The kernel's receive path runs at EL1 in interrupt context: it puts bytes into a ring of 256 bytes and never interprets them, and the console interrupt is the second interrupt source after the timer. `CONSOLE_READ` hands one byte at a time to the one task that holds a `Console` capability with the read right (R). The terminal task (`userspace/k0-term`) parses lines in its own address space and, when the vault is built in, acts as the vault's operator: it can ask for `STATUS`, `PUBLIC_KEY`, `KEYGEN` and `ZEROIZE`, nothing else. There is no authentication on the serial line, so whoever reaches it is the operator, and erasing the key is a denial of service by design. Entry path: `crates/k0-arch/src/conin.rs` and `crates/k0-conin` (receive logic), `crates/k0-ipc/src/console.rs` and `kernel/src/syscall.rs` (`CONSOLE_READ`, the rights of `Console`), `userspace/k0-term` (`lib.rs`, `wire.rs`) and its wiring in `userspace/root-task/src/oracle.rs`. The interrupt number comes from the device tree or the ACPI SPCR table, which are inputs of boundary 4 and 6. Out of the kernel's control and therefore trusted: the rest of the boot chain (firmware, any other boot loader, the hypervisor), the integrity of the kernel image itself, and the hardware. Under UEFI the firmware is trusted to run honestly, but the loader must still not trust what it describes. @@ -36,6 +37,8 @@ Highest value, all in scope: - `userspace/k0-vault` and `userspace/root-task/src/oracle.rs`: the request state machine (`Vault::handle`), the badge policy, the provider boundary around the crypto crate, the entropy rule (`NO_ENTROPY`), the rights of the request and response frames, and the nonce handshake. Reports that are welcome: a key disclosed to a client, a policy bypass (an operation a role must not have), and a reply that reaches the wrong caller. +- The input path: `crates/k0-conin` (ring, drain, gate and loss marking), `crates/k0-arch/src/conin.rs` and the PL011 and SBSA receive code in `earlycon/uart.rs`, the receive interrupt handling in `irq.rs`, the `Console` rights (R and W) and the output filter, `CONSOLE_READ` and its waiter (`crates/k0-ipc/src/console.rs`), and `userspace/k0-term` with its wiring check in `oracle.rs`. Reports that are welcome: a byte stream that makes the kernel misbehave, interrupt work that is not bounded by the reader, a wake-up of the wrong task, a `Console` right that is gained instead of removed, and an operator operation beyond the four listed. + Lower value: - `userspace/root-task` (other than `oracle.rs`): the trusted root task and test harness. Bugs here are not kernel vulnerabilities, but it is the right place to write reproducers. @@ -45,12 +48,12 @@ Lower value: ## How to exercise it -- Build: `cargo build -p k0-kernel --features console --offline` (generic 4 KiB image with console, dev profile with debug info; `panic = "abort"` in every profile). Input and output are Cargo features that only add and are never in `default`, so every command names them. `cargo build -p k0-kernel --offline` builds an image without console: it has no UART driver, never maps the console page and prints nothing on the serial port, and `tools/qemu-boot-test.sh` cannot judge it from the serial log (it prints a hint). All feature sets write the same ELF path, so give an image without console its own directory, for example `--target-dir target/quiet`. The 16 KiB image is `cargo build -p k0-kernel --offline --no-default-features --features granule-16k,console --target-dir target/g16`. It boots only on a CPU model with 16 KiB pages: `K0_QEMU_CPU=max tools/qemu-boot-test.sh target/g16/aarch64-unknown-none-softfloat/debug/k0-kernel`. `grep -a 'k0: console drivers' ` tells which I/O an image was built with. +- Build: `cargo build -p k0-kernel --features console --offline` (generic 4 KiB image with console, dev profile with debug info; `panic = "abort"` in every profile). Input and output are Cargo features that only add and are never in `default`, so every command names them. The operator terminal image is `cargo build -p k0-kernel --features console,terminal,vault-ed25519`, and `cargo run -p k0-kernel --features console,terminal,vault-ed25519` boots it under QEMU with the serial port on the terminal (QEMU's own escape key is Ctrl-A, so it never reaches K0 there). `tools/term-test.py ` boots an image with QEMU's serial port on pipes and runs a scripted session (every command and error, a line that is too long, 200 kB without a line end, 2000 lines in a row, a serial break), and `tools/qemu-boot-test.sh` takes `K0_BOOT_INPUT=on|off` and `K0_BOOT_SERVICE=vault|plain|none`. `cargo build -p k0-kernel --offline` builds an image without console: it has no UART driver, never maps the console page and prints nothing on the serial port, and `tools/qemu-boot-test.sh` cannot judge it from the serial log (it prints a hint). All feature sets write the same ELF path, so give an image without console its own directory, for example `--target-dir target/quiet`. The 16 KiB image is `cargo build -p k0-kernel --offline --no-default-features --features granule-16k,console --target-dir target/g16`. It boots only on a CPU model with 16 KiB pages: `K0_QEMU_CPU=max tools/qemu-boot-test.sh target/g16/aarch64-unknown-none-softfloat/debug/k0-kernel`. `grep -a 'k0: console drivers' ` tells which I/O an image was built with. - Run: `tools/qemu-virt-runner.sh target/aarch64-unknown-none-softfloat/debug/k0-kernel`, which is what `cargo virt` (alias of `cargo run -p k0-kernel --features console`) does. A plain `cargo run -p k0-kernel` boots the image without console, and the runner then prints `runner: this kernel has no console driver and prints nothing here (build with --features console to see output)`. It converts the ELF to a raw image with `llvm-objcopy` and boots `qemu-system-aarch64 -machine virt,gic-version=3 -cpu cortex-a72 -smp 1 -m 512M -nographic`. `K0_QEMU_MACHINE`, `K0_QEMU_CPU`, `K0_QEMU_SMP` and `K0_QEMU_MEM` change the machine, for example `K0_QEMU_MACHINE=virt,gic-version=2` or `K0_QEMU_MACHINE=virt,gic-version=3,virtualization=on` (entry at EL2). `tools/boot-matrix.sh` runs every configuration that K0 calls supported. The kernel never exits: once the root task finishes its self-tests it yields forever and an image with a console driver prints `k0: tick N` on the console once a second (every image logs only the first 4 tick lines in the boot log). Wrap every run in `timeout`, or use `tools/qemu-boot-test.sh`, which checks the expected log lines in order, requires an exact number of `k0: task fault` lines and exactly one `k0: unknown syscall` line, and stops QEMU once they appear. -- A healthy boot log is in `/src/bootcheck.log`, captured when this image was built. The lines that matter are `k0: w^x checks pass`, `k0: user w^x checks pass`, `root: retype/map tests pass`, `root: child exit test pass`, `root: ipc tests pass`, `root: fault isolation tests pass`, `root: preempt test pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: timeout tests pass`, `root: revocation tests pass`, `root: kernel reserve tests pass` and `root: sched tests pass`. Every image also prints `k0: dtb seeds wiped B` (40B on QEMU virt) and `root: boot seed from rng-seed bytes ...`. An image built with the feature `vault` also prints `root: oracle tests pass` and two more `k0: task fault` lines (8 instead of 6). +- A healthy boot log is in `/src/bootcheck.log`, captured when this image was built. The lines that matter are `k0: w^x checks pass`, `k0: user w^x checks pass`, `root: retype/map tests pass`, `root: child exit test pass`, `root: ipc tests pass`, `root: fault isolation tests pass`, `root: preempt test pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: timeout tests pass`, `root: revocation tests pass`, `root: kernel reserve tests pass` and `root: sched tests pass`. Every image also prints `k0: dtb seeds wiped B` (40B on QEMU virt) and `root: boot seed from rng-seed bytes ...`. An image built with the feature `vault` also prints `root: oracle tests pass` and two more `k0: task fault` lines (8 instead of 6). An image built with the feature `terminal` shows two more `k0: task fault` lines than the same image without it (the hostile wiring checks: 8 in total without `vault`, 10 with it), `root: terminal wiring holds` and `root: service started`. An image with `console-input` prints `k0: console input on (pl011 irq 33)` or `k0: console input off ()` and `root: console input tests pass`. When a task first reads console input the `k0: tick N` lines stop after `k0: tick lines off (console input in use)`. - Reproducers: the root task (`userspace/root-task/src/main.rs`) is the only EL0 image and already contains the test harness and thin `sys*` wrappers around `svc`. Add a test there; when the reproducer needs its own thread, build a task with its own CNode and address space (`RETYPE`, `TCB_CONFIGURE`, `TCB_RESUME`), which then runs code from the root task image, rebuild and run. `crates/k0-boot/build.rs` rebuilds and re-embeds the root task automatically. - UEFI loader: `cargo build -p k0-kernel --features console --offline`, then `tools/build-loader.sh`, which embeds that kernel into the loader, prints `build-loader: embedding a kernel with: k0: console drivers [...]` so that nobody embeds a silent kernel unknowingly, and prints the path (`.efi`). `tools/qemu-virt-runner.sh .efi` boots it through EDK2 with `-machine virt,gic-version=3,acpi=off` (firmware from `K0_QEMU_FIRMWARE`, else Homebrew's `edk2-aarch64-code.fd`, else `/usr/share/AAVMF/AAVMF_CODE.fd`, which is the Debian package in this image). `K0_QEMU_ESP=1` boots it from a FAT drive instead of `-kernel`, and `K0_QEMU_EXTRA` passes extra QEMU arguments. `tools/qemu-boot-test.sh .efi` judges the run from the loader's first line, `k0-loader: start`, so firmware messages before it do not count. The loader prints `k0-loader: ...` lines before the kernel's, and a refusal reads `k0-loader: refused: `. `K0_QEMU_MACHINE=virt,gic-version=3` (ACPI on, no device tree) boots through the static tables. `tools/pe-check.py .efi` checks the PE form and the order of the cache and MMU instructions. `K0_LOADER_FEATURES=refuse-halt tools/build-loader.sh` builds a loader that parks instead of returning to the firmware. The UEFI rows of `tools/boot-matrix.sh` (`uefi-*`) cover GICv2 and GICv3 at EL1 and EL2, the max CPU, 4 cores, the 16 KiB image, a firmware RNG, the FAT drive, the ACPI rows (`uefi-acpi-*`) and the refusals. -- Host tests: `tools/host-test.sh` runs the unit tests of `k0-abi`, `k0-cap`, `k0-boot` and `k0-efi` on any host and those of `k0-mm` on AArch64 hosts. `k0-cap` includes a model test over random retype, copy, move, delete and revoke sequences, and `k0-mm` runs the real user page table walkers and the address space registry. The DTB parser has a deterministic mutation fuzzer: `K0_FUZZ_ITERS=5000000 cargo test --release --offline --target "$(rustc -vV | sed -n 's/^host: //p')" -p k0-boot fuzz -- --nocapture`. A failing case prints `K0_FUZZ_CASE=0x...`, which replays it and dumps the input. The fuzzer's DTB builder in `crates/k0-boot/src/fdt/builder.rs` is a convenient way to write a crafted DTB for a reproducer. `k0-efi` has three more deterministic fuzzers (`fuzz_plan_with_random_maps`, `fuzz_rewrite_with_mutated_trees`, `fuzz_prepare_end_to_end`) with the same `K0_FUZZ_ITERS`, `K0_FUZZ_SEED` and `K0_FUZZ_CASE` variables: run them with `-p k0-efi fuzz`. The unit tests of `k0-efi` use measured firmware memory maps as vectors; a crafted memory map or firmware DTB is the natural reproducer for the loader. +- Host tests: `tools/host-test.sh` runs the unit tests of `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-conin`, `k0-vault` and `k0-term` on any host and those of `k0-mm` on AArch64 hosts. `k0-cap` includes a model test over random retype, copy, move, delete and revoke sequences, and `k0-mm` runs the real user page table walkers and the address space registry. The DTB parser has a deterministic mutation fuzzer: `K0_FUZZ_ITERS=5000000 cargo test --release --offline --target "$(rustc -vV | sed -n 's/^host: //p')" -p k0-boot fuzz -- --nocapture`. A failing case prints `K0_FUZZ_CASE=0x...`, which replays it and dumps the input. The fuzzer's DTB builder in `crates/k0-boot/src/fdt/builder.rs` is a convenient way to write a crafted DTB for a reproducer. `k0-efi` has three more deterministic fuzzers (`fuzz_plan_with_random_maps`, `fuzz_rewrite_with_mutated_trees`, `fuzz_prepare_end_to_end`) with the same `K0_FUZZ_ITERS`, `K0_FUZZ_SEED` and `K0_FUZZ_CASE` variables: run them with `-p k0-efi fuzz`. The unit tests of `k0-efi` use measured firmware memory maps as vectors; a crafted memory map or firmware DTB is the natural reproducer for the loader. - PAC, PAN and RNDR paths: the default `cortex-a72` model has none of them. `tools/qemu-boot-test.sh target/aarch64-unknown-none-softfloat/debug/k0-kernel -cpu max` (an image built with `--features console`) boots on a CPU that has all three. - A boot that the kernel refuses before it has a console prints nothing, and an image without a console feature prints nothing on the serial port at all. The reason is in the boot log in memory: start QEMU with `K0_QEMU_MONITOR=` and read it with `tools/boot-log.py ` (the load address on QEMU `virt` is `0x40080000`). - Debugging: append `-s -S` to the runner (`tools/qemu-virt-runner.sh -s -S`) and attach with `gdb-multiarch target/aarch64-unknown-none-softfloat/debug/k0-kernel -ex 'target remote :1234'`. `-d int,guest_errors` prints exception traces. `llvm-objdump -d` (from the pinned toolchain, linked into `/usr/local/bin`) disassembles both images. @@ -63,6 +66,7 @@ Rate by what EL0 code can do to EL1 or, on the current `main` branch, to another - **Critical**: any EL0 -> EL1 privilege escalation, and on the current `main` branch any break of task isolation (reading or writing another task's memory, using a slot or capability of another task, a revoked capability or stale mapping that still works). Executing attacker-chosen code at EL1; reading or writing kernel memory or arbitrary physical memory through a system call; obtaining a mapping, capability or object that the caller's slot arguments do not grant (bypassing a capability or permission check); mapping memory that is both writable and executable for EL0, or kernel memory into TTBR0; getting the kernel to restore EL1 state (mode, exception level, interrupt masks) that came from user input. - **High**: memory-safety bugs in kernel code reachable from EL0, with or without a demonstrated exploit (out-of-bounds index, integer overflow or truncation in size or address arithmetic, stale raw pointers, aliasing `&mut`, unsound `unsafe`); a system call or fault sequence that halts the whole system (kernel panic, `exception_fatal`, an unbounded loop with interrupts masked, or a scheduler that cannot continue); missing TLB or cache maintenance that lets a task keep using memory after it was unmapped or retyped; kernel register or memory contents leaking to EL0 (registers not restored or cleared on the return path, uninitialised memory handed out by `retype` or `map`); checks that a race between the timer interrupt and a system call can bypass. - **Loader findings** are rated by what the kernel ends up trusting. **Critical**: a memory map or firmware device tree that makes the loader pass the kernel a RAM range that includes memory firmware still uses (runtime or boot services memory, MMIO, a reservation) so that it can reach user space, or that makes the loader start a kernel image that fails its own check. **High**: memory-safety bugs in the loader, a refusal that is skipped (the loader boots on input it should refuse), or an `ExitBootServices` path that leaves the system in an undefined state. **Medium**: a panic or an overly cautious refusal on a valid map, a leak of memory the loader should have wiped, a plan that loses RAM beyond the stated policy. Findings that need hostile firmware are Low (see "Anything to leave alone"). +- **Input findings** are rated by what an outside party on the serial line gains. **Critical**: a byte stream or timing that gives code execution or memory access at EL1, or that makes a task do more than the operator's four operations. **High**: a stream that halts the machine or lets kernel work in interrupt context grow without the reader's bound; a wake-up or a byte delivered to a task that does not hold the read right. **Medium**: a stream that wedges the terminal or the input path until reboot. The lack of authentication on the serial line and the operator's power to erase the key are known (see "Anything to leave alone"). - **Medium**: malformed DTB input that panics, reads out of bounds, produces an unsafe memory map or gets a device mapped over memory that is handed out (the boot chain is trusted, so cap these at Medium unless they give code execution); exhaustion of kernel resources (for example untyped memory, TCB or endpoint objects; the kernel page tables and the address space registry are reserved at boot and no longer run out) by a single task that denies service to others without halting the kernel; scheduler starvation; mistakes in `write_bootinfo` beyond the known physical address exposure. - **Low**: problems that need a misbehaving root task to trigger; `build.rs` issues with trusted source inputs; console formatting and diagnostic wording; hardening that is missing but has no exploitable consequence today. - A root-cause analysis plus a patch is welcome at every level. A reproducer counts for more than a severity argument. @@ -85,9 +89,10 @@ These are known, tracked in `SECURITY.md`, and are not new findings: - DTB memory regions are not bounded by the physical address width (GHSA-hj3f-38h9-hrpj). The current `main` branch stops the boot on such a region; the advisory itself is still a draft. - No KASLR: the kernel image always sits at the same virtual address. `write_bootinfo` exposes the physical addresses of `Untyped` regions to the root task. - A wrong or hostile DTB can stop the boot, or point the console at another device that passes the checks (a 16550 and an SBSA UART have no identification register). An image without a console driver never maps or writes the console page, but it still refuses a device tree whose console node fails the checks. A pinned build (`K0_PIN`) compares values that come from the DTB, so it does not stop a hostile boot chain. -- Signing oracle limits, all in `SECURITY.md` under "The signing oracle": the Ed25519 implementation is unvalidated and the key does not come from an approved random bit generator; no side-channel analysis; one key shared by all signers; no persistence, import, export or DRBG; the availability of the vault is not protected; the root task is trusted and could read the vault; only run in QEMU. The kernel zeroes the `rng-seed` and `kaslr-seed` bytes in the DTB once, right before it enters the root task; copies kept by firmware or the loader and live boot stack frames are not wiped. +- Signing oracle limits, all in `SECURITY.md` under "The signing oracle": the Ed25519 implementation is unvalidated and the key does not come from an approved random bit generator; no side-channel analysis; one key shared by all signers, one key per boot; no persistence, import, export or DRBG; the availability of the vault is not protected; the root task is trusted and could read the vault; only run in QEMU. The kernel zeroes the `rng-seed` and `kaslr-seed` bytes in the DTB once, right before it enters the root task; copies kept by firmware or the loader and live boot stack frames are not wiped. +- Serial input limits, all in `SECURITY.md` under "Serial input and the operator terminal": there is no authentication on the serial line, and the operator can erase the key (denial of service by design) but cannot sign, deliver a seed or change policy; the receive code runs at EL1 and a user-space driver would need device and interrupt delegation, which K0 does not have; an outside party can cause interrupts while tasks run (bounded by the reader), the reader learns arrival times finer than the tick and other tasks can notice the stolen time, a timing channel that has not been analysed; input waits behind running tasks (no priorities, up to a tick per ready task); a 16550 console has no input; the SBSA UART path, FIFO overruns, the receive timeout interrupt and the cut-off of an interrupt line without a UART cause are covered only by host tests with a fake UART; no test measures kernel time under a flood on a machine; "dropped before the prompt" counts bytes that reached the UART, and an emulator that holds bytes back delivers them later; a kernel line that appears while the operator types splits the screen line but not the buffer; the terminal can erase within its current line; no signing client exists in service mode; the terminal and the vault are not restarted if they die; terminal output counts against the user share of the in-memory boot log. Nothing ran on real hardware. - The DTB pointer in `x0` is mapped read-only and read before any memory map exists. A boot loader that passes the address of a device makes the kernel read device registers as memory. -- A task with a `Console` capability can print lines that look like kernel output (`k0: ...`), in the boot log and, in an image with a console driver, on the console. Its output is filtered for control bytes but not marked. That includes the `k0: console drivers [...]` line, so only its first occurrence, or the image file, identifies a build. +- A task with a `Console` capability that has the write right can print lines that look like kernel output (`k0: ...`), in the boot log and, in an image with a console driver, on the console. Its output is filtered for control bytes (only a capability with the read right may also emit backspace) but not marked. That includes the `k0: console drivers [...]` line, so only its first occurrence, or the image file, identifies a build. - Optional console output: an empty serial log shows only that no byte reached the serial port of QEMU virt (a PL011), not that no register was read; the symbol check runs on debug images and release (LTO) images without console are not booted; no image without console is booted through UEFI; the boot log in kernel memory is readable by anyone who can read RAM or attach a debugger. See "Optional console output" in `SECURITY.md`. - A trap to EL2 after the kernel has dropped to EL1 parks the whole machine by design. - PAC keys are shared between EL0 and EL1. No `pac-ret` code generation is enabled yet, so there is nothing to forge today. @@ -96,5 +101,5 @@ These are known, tracked in `SECURITY.md`, and are not new findings: - The root task is trusted; its image is embedded and hashed, not signed. Kernel image integrity belongs to the boot chain. - The UEFI loader's known limits, all in `SECURITY.md` under "The UEFI loader": hostile firmware is not defended against, only wrong firmware; the SHA-256 of the embedded kernel is a corruption check and not a signature (only the firmware's Secure Boot gives authenticity); only this loader may start the kernel under UEFI, since a generic loader that passes the firmware device tree through hands firmware memory to user space; a refusal returns to the firmware unless the loader was built with `refuse-halt`; the cache flush and MMU-off sequence cannot be tested under QEMU (TCG has no caches) and is checked only for presence by `tools/pe-check.py`; a pinned build under UEFI is untested; a device left running by firmware can still write to memory (no IOMMU); the loader's entropy stays readable in the device tree in memory; the kernel never calls UEFI runtime services; firmware that types device registers as `EfiReservedMemoryType` or gives one malformed descriptor makes the loader refuse (fail closed); the block re-placement and free-on-refusal paths were not exercised; the loader file is not bit-for-bit reproducible across build directories. About 23 to 32 MiB of boot services memory is left unused on purpose. Firmware with neither a device tree nor ACPI static tables is refused. The ACPI path reads only the static tables (RSDP, XSDT, MADT, GTDT and SPCR, never AML) and has been booted only on QEMU virt. - Real boards, U-Boot's EFI implementation, Raspberry Pi UEFI, firmware other than EDK2 `ArmVirtQemu`, and KVM have never been booted under UEFI either; do not report "untested on hardware". -- Only QEMU runs in this image. Real boards, KVM and other hypervisors, the 16550 console driver (no test has executed it), the SBSA UART and CPUs with `HCR_EL2.E2H` fixed to 1 have never been booted. Review of those paths is welcome; do not report "untested on hardware". +- Only QEMU runs in this image. Real boards, KVM and other hypervisors, the 16550 console driver (no test has executed it, and it has no input path), the SBSA UART and CPUs with `HCR_EL2.E2H` fixed to 1 have never been booted. Review of those paths is welcome; do not report "untested on hardware". - Upstream issues in vendored crates that are not reachable from the kernel's SHA-256 use. diff --git a/design/en/README.md b/design/en/README.md index 14f7abb..baa07cf 100644 --- a/design/en/README.md +++ b/design/en/README.md @@ -26,5 +26,6 @@ Read them in the order of the following table the first time. This order follows | [scheduling.md](scheduling.md) | TCBs and their bound CNode and address space, task creation and teardown, the round-robin scheduler, and timer preemption | | [ipc.md](ipc.md) | Endpoints and badges, `SEND`, `RECV`, `CALL` and `REPLY_RECV`, the single-use reply right, and what happens to waiting tasks when an endpoint is deleted | | [vault.md](vault.md) | The signing oracle: the vault task and its frames, the `CALL` protocol and nonce, the fixed badge policy, the provider boundary, the boot seed and its wipe, features, tests, and known gaps | +| [terminal.md](terminal.md) | Serial input and the operator terminal: why the kernel receives, the receive ring and its bounds, `CONSOLE_READ` and the Console rights, waiting and waking, the terminal's wiring and the hostile-task check, the screen and command rules, tests, and known gaps | Every note ends with a "**Known gaps**" section. The open security advisories are listed in [SECURITY.md](../../SECURITY.md). diff --git a/design/en/boot.md b/design/en/boot.md index dc537a5..37c8e50 100644 --- a/design/en/boot.md +++ b/design/en/boot.md @@ -108,7 +108,8 @@ In the following table, each row gives a log line and the step it stands for, in | `k0: dtb rejected: ...` (only on failure) | `map_dtb` maps the DTB read-only through the alias. It checks the pointer (not null, 8-byte aligned) and `dtb_span`, which reads only the magic and total size. | | `k0: memory ...` | The DTB is parsed through the alias. [dtb.md](dtb.md) covers the parser. | | `k0: console drivers [...]` | The first line of platform bring-up, printed even when the platform is later refused. It names the console drivers built into this image (see "Optional console output"). | -| `k0: platform ...` | `bring_up_platform` finds the console, the interrupt controller and the timer interrupt in the DTB and builds one immutable platform descriptor. It checks the descriptor against the memory map before it maps any device page: RAM must lie below 2^47, the kernel image and the DTB must lie inside declared memory, and no device range, widened to whole granules, may overlap memory or a reserved range or reach beyond the CPU's physical address width (`k0_mm::pa_bits`). In pinned mode it then compares the line with the expected one. Only after that does it attach the console. An image with a driver for this kind of console maps it and attaches it, which replays the buffered log. An image without one maps nothing and prints `k0: no console (driver not built in)`. If the platform is refused, the kernel attaches the console first when the console alone passes the checks (and the image is not pinned, and a driver exists), so that the reason is visible. `k0: no console (...)` names the reason when there is none. See [dtb.md](dtb.md). | +| `k0: platform ...` | `bring_up_platform` finds the console, its interrupt (if the console node has a usable one), the interrupt controller and the timer interrupt in the DTB and builds one immutable platform descriptor. It checks the descriptor against the memory map before it maps any device page: RAM must lie below 2^47, the kernel image and the DTB must lie inside declared memory, and no device range, widened to whole granules, may overlap memory or a reserved range or reach beyond the CPU's physical address width (`k0_mm::pa_bits`). The line carries the console interrupt number, for example `k0: platform con=pl011@0x9000000,irq33 ...`. In pinned mode it then compares the line with the expected one, so a pin string made before this field existed no longer matches and must be made again. Only after that does it attach the console. An image with a driver for this kind of console maps it and attaches it, which replays the buffered log. An image without one maps nothing and prints `k0: no console (driver not built in)`. If the platform is refused, the kernel attaches the console first when the console alone passes the checks (and the image is not pinned, and a driver exists), so that the reason is visible. `k0: no console (...)` names the reason when there is none. See [dtb.md](dtb.md). | +| `k0: console input on (pl011 irq 33)` or `k0: console input off ()` | Printed only by an image built with `console-input`, right after the platform is accepted. See "Optional console input". | | `k0: root task integrity ok (...)` | The embedded root task image is hashed again and compared with the hash fixed at build time. | | `k0: entropy ...`, `k0: pac=... bti=... pan=...` | PAC keys are derived and loaded, and the key words are wiped from the boot stack. The 32-byte seed for the root task is derived here too, independent of the PAC keys, and kept for the handoff. PAN is enabled and EL0 access to counters, debug and PMU is turned off. See [hardening.md](hardening.md). | | `k0: irq on (timer 1s)` | `setup_irq` maps only the interrupt controller pages it needs. For GICv3 it looks at the redistributor frames one at a time to find the boot CPU's frame, then maps that frame and its SGI frame. The driver checks the GIC identification registers against what the DTB claimed. The EL1 virtual timer is programmed with the interrupt number from the platform descriptor. IRQ and SError are unmasked. | @@ -116,7 +117,7 @@ In the following table, each row gives a log line and the step it stands for, in | `k0: root task loaded (entry ...)` | The root task is copied into frames from the window, its root TCB is made in the window, and its address space is built. The kernel does not print the physical address of the user root table. The address space is then entered in the address space registry. See [user-address-space.md](user-address-space.md). | | `k0: memory + not handed out ()` (only when it happens), `k0: kernel reserve tables + address space entries = bytes in ranges` | `reserve_kernel_share` carves the kernel share out of each free physical range before any untyped capability exists (see "Carving the kernel share out of untyped memory"). A range that cannot hold its share is not handed out, and the kernel prints the first kind of line with the reason. The second line is printed once, for example `k0: kernel reserve 262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges` on QEMU virt with 512 MiB and the 4 KiB granule. | | `k0: untyped ...`, `k0: root cnode ready (N caps, N untyped, N image frames, N slots)` | The root CNode (an object in the window with `ROOT_CNODE_SLOTS` = 512 slots, as the log shows) is filled: slot 1 the root TCB, slot 2 the root address space, slot 3 the console, slot 4 the root CNode itself, then every free physical range that was handed out as an untyped capability, then one Frame capability per mapped granule of the root task image (text with R and X, read-only data with R, data with R and W). Finally the root task is bound to its CNode and address space, exactly as any other task is: copies of those two capabilities go into its TCB. See [capabilities.md](capabilities.md). | -| `k0: bootinfo page ready` | The capability list is written into the read-only bootinfo page (layout version 3): a header and one descriptor per slot, with the VA, size and rights of every image Frame. The page does not hold the boot seed. | +| `k0: bootinfo page ready` | The capability list is written into the read-only bootinfo page (layout version 4): a header and one descriptor per slot, with the VA, size and rights of every image Frame. The page does not hold the boot seed. | | `k0: user w^x checks pass` | `TTBR0` now points at the user tables, the identity map is gone, and the user mappings are checked from both EL0 and EL1. | | `k0: dtb seeds wiped B` | The DTB is not needed any more, so the kernel zeroes the `rng-seed` and `kaslr-seed` bytes in it (through the read-only alias, switched to read-write for the write), reads them back, and wipes its own copy. The line is `40B` on QEMU virt. If the read-back is not zero, the line is `k0: WARNING dtb seeds not wiped`. See [hardening.md](hardening.md). | | `k0: device pages [...] of 0x1000 bytes` | Every device page the kernel keeps mapped. After this line the kernel maps no further device. | @@ -159,12 +160,9 @@ Every line the kernel prints also goes into a **16 KiB buffer** in kernel memory ## Optional console output -Input and output are optional in K0. You can select them with Cargo features of the kernel crate (`k0-kernel`). +Input and output are optional in K0. You can select them with Cargo features of the kernel crate (`k0-kernel`). Console output is selected with the console features below. Console input and the operator terminal have their own features, described in "Optional console input". -> [!NOTE] -> A feature for input or for a terminal does not exist yet. Console output is the only thing you can select today. - -Console output exists only in an image built with a console feature (opt-in). No image has input. The following figure shows where the output goes, depending on the features in the build. +Console output exists only in an image built with a console feature (opt-in). An image built without `console-input` has no input code at all. The following figure shows where the output goes, depending on the features in the build.

An image built without a console feature writes only to the boot log in memory, and an image built with a console feature also writes to the matching UART @@ -225,11 +223,30 @@ All feature sets write the same ELF path, so a separate `--target-dir`, for exam **Rule for contributors**: you must follow these rules. -- Every new input or output path goes behind a Cargo feature from the start (today the only one is console output). +- Every new input or output path goes behind a Cargo feature from the start (today: console output, `console-input` and `terminal`). - Features only add and are never in `default`. - Every supported combination gets a row in the boot matrix. - The scripts, the `virt` alias and CI name the features explicitly. +### Optional console input + +Console input is a second opt-in layer. It is off by default, and features only add. The following table lists the features of `k0-kernel`. + +| Feature | Adds | +| --- | --- | +| `console-input` | the kernel's receive path for the console UART and the system call `CONSOLE_READ` (see [exceptions.md](exceptions.md)). It needs a console driver feature to do anything. Receive exists for the PL011 and the SBSA UART only, so a 16550 console has output and no input. | +| `terminal` | the operator terminal task in the root task image. It turns `console-input` on. | + +> [!NOTE] +> An image built without `console-input` contains no receive code, no `CONSOLE_READ` and none of the log lines below. The static matrix row `input-symbols` checks this. + +- **Bring-up**: the console interrupt number comes from the device tree (see [dtb.md](dtb.md)) or, under UEFI, from the ACPI SPCR table, and it is part of the `k0: platform` line. The receive interrupt stays off until a task first reads console input with the read right. A console node without a usable interrupt is not a boot refusal, input is just off. +- **Log lines**: `k0: console input on (pl011 irq 33)` or `k0: console input off ()`. The reasons are `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range` and `interrupt not available`. A wrong interrupt number costs only the input path. +- **First read**: it discards what the device holds and stops the periodic `k0: tick N` lines after one line `k0: tick lines off (console input in use)`. Ticks, preemption and timeouts keep working. +- **Evidence**: the rows `input-only`, `input-gicv2`, `input-16550`, `input-bad-irq`, `input-symbols` (static), `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi` and `hvf-term` are in `tools/boot-matrix.sh`. `tools/qemu-boot-test.sh` reads `K0_BOOT_INPUT=on|off`, `K0_BOOT_SERVICE=vault|plain|none` and, for judging only, `K0_BOOT_JUDGE`. `tools/term-test.py ` runs a scripted terminal session over QEMU's serial port. + +The SBSA UART path, FIFO overruns and the receive timeout interrupt are not exercised by QEMU. They are covered only by host tests with a fake UART (`crates/k0-conin`). + ## Trust The DTB now supplies device addresses, so a wrong or hostile DTB can point the console at some other device. The kernel limits this in five ways: @@ -308,5 +325,5 @@ The self-checks inside `kernel_main` are themselves tests: if a mapping is wrong - Only one core runs, and the boot loader must enter exactly one CPU. K0 has no code to start or park other CPUs. - The kernel always sits at the same virtual address. There is no address randomization. - A release build prints nothing on panic. That is intentional, but it also means a release build gives no diagnosis on panic. -- No image has input. Console output exists only in an image built with a console feature, and the limits of that evidence are listed in "Optional console output". +- Console output exists only in an image built with a console feature, and console input only in an image built with `console-input`. The limits of that evidence are listed in "Optional console output" and "Optional console input". - Under UEFI, the cache flush and the MMU switch-off in the loader cannot be tested by QEMU (it has no caches), and ACPI-only firmware boots only through the three static tables (only QEMU virt has been booted). [uefi.md](uefi.md) lists all the limits of the loader. diff --git a/design/en/capabilities.md b/design/en/capabilities.md index d2de923..c9aa54b 100644 --- a/design/en/capabilities.md +++ b/design/en/capabilities.md @@ -23,7 +23,7 @@ The related code is in the files of the following table. | `crates/k0-abi/src/lib.rs` | numbers and error codes (the source of truth for the ABI) | > [!IMPORTANT] -> The system call ABI changed incompatibly with this model (bootinfo version 2, now 3). Read the "Known gaps" section before relying on any of this. +> The system call ABI changed incompatibly with this model (bootinfo version 2, now 4). Read the "Known gaps" section before relying on any of this. Capability-based isolation covers confidentiality and integrity between tasks. It does not cover availability. @@ -66,14 +66,15 @@ In the following table, each kind is listed with the time it is created and what | `Endpoint` | by `RETYPE` | a rendezvous point for synchronous IPC | | `CNode` | by `RETYPE`, and at boot for the root CNode | an array of slots, used as a capability space and as a destination for copies and moves | | `AddrSpace` | by `RETYPE`, and at boot for the root task | an address space: the right to map into it and to run a task in it | -| `Console` | at boot | the right to write bytes to the debug output: the boot log, and the console in an image built with a console driver | +| `Console` | at boot | the right to write bytes to the debug output (`W`): the boot log, and the console in an image built with a console driver. With `R` it also grants reading console input in an image built with `console-input` | ### Rights -The **rights bits** are `R` = 1, `W` = 2 and `X` = 4. They have meaning on two kinds only. +The **rights bits** are `R` = 1, `W` = 2 and `X` = 4. They have meaning on three kinds only. - **Frame**: the ceiling for mapping permissions. `RO` needs `R`, `RW` needs `R|W`, `RX` needs `R|X`. A frame made by `RETYPE` has `R|W` and can never gain `X`. - **Endpoint**: `R` is the right to receive, `W` the right to send. A new endpoint capability has both. +- **Console**: `W` is the right to write output (`DEBUG_PUTC`), and `R` is the right to read input (`CONSOLE_READ`). `CAP_COPY` can only remove them, and a copy that would keep no right fails with `NO_RIGHTS`. A `Console` capability with `R` may also emit the backspace byte (0x08) through `DEBUG_PUTC`. Every other control byte is still printed as `?`. All other kinds carry no rights, and the rights mask of `CAP_COPY` is ignored for them. **Rights can only be removed**, and only by `CAP_COPY`. @@ -114,7 +115,7 @@ The root task's CNode is the root CNode. It has `ROOT_CNODE_SLOTS` (512) slots a | 0 | null | | 1 | `Tcb` of the root task | | 2 | `AddrSpace` of the root task | -| 3 | `Console` | +| 3 | `Console`, with `W`. It has `R` only in an image built with `console-input` | | 4 | `CNode`, a capability to the root CNode itself, so it can be used as a copy or move destination | | 5 and up | `Untyped` capabilities, then one `Frame` capability per mapped granule of the root task image | @@ -138,7 +139,7 @@ Running out of slots also stops the boot. A DTB memory region beyond the CPU's p ## The bootinfo page -Just before the handoff, the kernel writes a description of the root CNode into the bootinfo page, which is mapped read-only for the root task at `bootinfo::VA`. The version is 3 (`bootinfo::VERSION`). The page layout did not change from version 2; the version changed because the root task now receives a boot seed in its entry registers (the seed in `x0..x3`, its description in `x4`; see [boot.md](boot.md)), and the seed is not in this page. A root task that sees another version must not proceed. +Just before the handoff, the kernel writes a description of the root CNode into the bootinfo page, which is mapped read-only for the root task at `bootinfo::VA`. The version is 4 (`bootinfo::VERSION`). The page layout did not change from version 2. Version 3 came because the root task receives a boot seed in its entry registers (the seed in `x0..x3`, its description in `x4`; see [boot.md](boot.md)), and the seed is not in this page. Version 4 came because the `Console` capability now carries rights. A root task that sees another version must not proceed. The page starts with a header `{version, frame_size, cap_count, cnode_slots}`, followed by `cap_count` descriptors `{kind, base, size, rights}`. The index of a descriptor is its slot number in the root CNode, and every slot at or beyond `cap_count` is empty. A descriptor is filled in by kind as follows: @@ -232,6 +233,7 @@ When an original capability is removed, its object is finalized by the callbacks - **Frame**: the mapping this capability made is removed. This happens for any `Frame` capability that has a mapping record, including copies. - **PageTable**: it is detached from its address space (the same, for any capability with a record). - **Endpoint** (original): every queued task is woken with `REVOKED`. +- **Console**: a task that waits in `CONSOLE_READ` on this capability wakes at once with `REVOKED` when the capability is deleted, revoked or moved (see [ipc.md](ipc.md)). - **Tcb** (original), and any capability bound to a task: the task is torn down, see [scheduling.md](scheduling.md) and [ipc.md](ipc.md). - **AddrSpace** (original): it is released in the registry (which bumps its generation). If it is installed in TTBR0, TTBR0 is switched to an empty table from the kernel pool. @@ -247,7 +249,8 @@ The following table lists the capabilities and rights each system call requires. | System call | Capabilities and rights it requires | | --- | --- | -| `DEBUG_PUTC` | `Console` | +| `DEBUG_PUTC` | a `Console` with `W` | +| `CONSOLE_READ` | a `Console` with `R` (only in images built with `console-input`) | | `RETYPE` | an `Untyped`, and a free destination slot in the caller's CNode | | `MAP` | a `Frame` whose rights cover the permission (`RO` needs `R`, `RW` needs `R\|W`, `RX` needs `R\|X`) or a `PageTable`, and an `AddrSpace` naming the target | | `UNMAP` | a `Frame` or `PageTable` that is mapped | @@ -280,7 +283,7 @@ The following table lists the error codes for slot problems and their meaning. | `BAD_PERM` | the mapping permission or the rights mask is not valid | | `BAD_BADGE` | a badge on a kind that cannot carry one, or a different badge on an already badged capability | | `TOO_DEEP` | the derivation depth limit would be exceeded | -| `REVOKED` | returned to a task that was waiting on an endpoint that was deleted | +| `REVOKED` | returned to a task that was waiting on an endpoint that was deleted, or in `CONSOLE_READ` on a `Console` capability that was deleted, revoked or moved | | `KERNEL_RESOURCE` | an internal resource is missing. It is still a defined code, but neither the kernel alias tables nor the address space registry can cause it any more | ## How it is tested diff --git a/design/en/dtb.md b/design/en/dtb.md index a967d72..6485bba 100644 --- a/design/en/dtb.md +++ b/design/en/dtb.md @@ -95,9 +95,10 @@ Every violation returns a `BootError`, and the kernel then prints `k0: dtb rejec ## The platform descriptor -Besides memory, the kernel finds exactly three devices in the DTB and nothing else (`discover` in `crates/k0-boot/src/platform.rs`): +Besides memory, the kernel finds exactly three devices in the DTB, plus the console's interrupt, and nothing else (`discover` in `crates/k0-boot/src/platform.rs`): - **The console**: only the node named by `/chosen/stdout-path` (an absolute path, or an alias that resolves to one). The node must be enabled, and its `compatible` must name a PL011 (`arm,pl011`), an SBSA UART (`arm,sbsa-uart`) or a 16550-family UART (`ns16550a`, `ns16550`, `snps,dw-apb-uart`, `brcm,bcm2835-aux-uart`). Any other UART, a missing or unresolvable `stdout-path`, or a node the kernel cannot translate to a CPU physical address gives a boot with no console. That is not an error. The kernel prints `k0: no console (...)` with the reason, and the boot log buffer is the only record (see [boot.md](boot.md)). Every image does this discovery and validation, also an image built without a console driver, which then maps nothing and prints `k0: no console (driver not built in)`. Such an image refuses a device tree whose console fails the checks like any other. The register range the driver touches must lie inside the declared `reg` and inside one granule. + - **The console interrupt** (read only in an image built with `console-input`, see [boot.md](boot.md)): the `interrupts` property of the console node, taken only when the interrupt parent is the discovered GIC and the property is exactly one SPI (three cells, first cell 0) with a level type and active high. The number is the SPI number plus 32. A console node with no property, another form or another parent is not an error: the platform has no console interrupt and input is off. A number that is out of range is caught later, when input is brought up (`k0: console input off (...)`). - **The interrupt controller**: the node that the timer node's interrupt parent points to (`arm,armv8-timer` or `arm,armv7-timer`, exactly one enabled node). It must be a GICv3 (`arm,gic-v3`) or a GICv2 (`arm,gic-400`, `arm,cortex-a15-gic`, `arm,cortex-a7-gic`) with the expected cell counts and frame alignment. Up to four GICv3 redistributor ranges are accepted. A duplicate phandle, a disabled node, an `interrupt-map`, or a GICv2 without per-CPU banked interfaces (`cpu-offset`) is refused. - **The EL1 virtual timer interrupt number**: taken from the timer node's `interrupts` (the `virt` entry when `interrupt-names` exists, else the third entry) as a PPI number plus 16. A timer node that declares a timer erratum (`fsl,erratum-a008585`, `hisilicon,erratum-161010101` or `allwinner,erratum-unknown1`) is refused, because the kernel has no workaround code. @@ -106,7 +107,7 @@ Besides memory, the kernel finds exactly three devices in the DTB and nothing el Register addresses are translated through the `ranges` of the parent buses to CPU physical addresses. A bus without `ranges` cannot be translated. -The result is one immutable `Platform` value. The kernel prints it as the single line `k0: platform con=... gic=... tmr=...`, in a fixed format. Before any device page is mapped, `Platform::validate` checks it against the memory map. The checks are the following: +The result is one immutable `Platform` value. The kernel prints it as the single line `k0: platform con=... gic=... tmr=...`, in a fixed format. The console field carries the interrupt number when there is one, for example `con=pl011@0x9000000,irq33`. Before any device page is mapped, `Platform::validate` checks it against the memory map. The checks are the following: - RAM must lie below 2^47. - The kernel image and the DTB must lie inside declared memory. @@ -126,7 +127,7 @@ A mismatch makes the kernel refuse or, for the console, continue without one. ### Pinned mode -The platform line, the entry exception level and the RAM range form the string ` el= ram=-`. If `K0_PIN` was set at build time to the text after `k0: platform ` from a boot log of the target, the image refuses to boot when this string differs. It catches a wrong board or a swapped DTB. It **does not defend against a hostile boot chain**, because the compared values are derived from the DTB. +The platform line, the entry exception level and the RAM range form the string ` el= ram=-`. If `K0_PIN` was set at build time to the text after `k0: platform ` from a boot log of the target, the image refuses to boot when this string differs. It catches a wrong board or a swapped DTB. Pin strings made before the console interrupt joined the platform line no longer match and must be made again. It **does not defend against a hostile boot chain**, because the compared values are derived from the DTB. ## How it is tested diff --git a/design/en/exceptions.md b/design/en/exceptions.md index 465b3fe..04727c3 100644 --- a/design/en/exceptions.md +++ b/design/en/exceptions.md @@ -20,7 +20,7 @@ The following figure shows the path that the kernel follows for each kind of exc ## The vector table -AArch64 has 16 vector entries: four kinds of exception (synchronous, IRQ, FIQ, SError) for each of four origins. K0 gives each entry one of four behaviors. The kernel takes only IRQs, so a FIQ is a state that should not happen. The FIQ entries call a dispatcher that prints `k0: UNEXPECTED fiq intid=0` and parks. The following table lists the behavior of each entry. +AArch64 has 16 vector entries: four kinds of exception (synchronous, IRQ, FIQ, SError) for each of four origins. K0 gives each entry one of four behaviors. The kernel takes only IRQs (never FIQs), so a FIQ is a state that should not happen. The FIQ entries call a dispatcher that prints `k0: UNEXPECTED fiq intid=0` and parks. The following table lists the behavior of each entry. | Origin | Sync | IRQ | FIQ | SError | | --- | --- | --- | --- | --- | @@ -86,7 +86,7 @@ The system call number is in `x8`. Arguments are in `x0` to `x5`, and the result | Number | Call | Description | | --- | --- | --- | -| 0 | `DEBUG_PUTC` | write one filtered byte to the boot log, and to the console in an image built with a console driver; needs a `Console` capability | +| 0 | `DEBUG_PUTC` | write one filtered byte to the boot log, and to the console in an image built with a console driver; needs a `Console` capability with the write right | | 1 | `YIELD` | go to the back of the ready queue | | 2 | `EXIT` | terminate the calling task | | 3 | `RETYPE` | create a kernel object from untyped memory, into a destination slot the caller names | @@ -102,6 +102,7 @@ The system call number is in `x8`. Arguments are in `x0` to `x5`, and the result | 13 | `CAP_MOVE` | move a capability to another slot | | 14 | `CAP_DELETE` | delete a capability and everything derived from it | | 15 | `CAP_REVOKE` | delete everything derived from a capability and keep the capability | +| 16 | `CONSOLE_READ` | read one byte of console input (only in an image built with `console-input`, see below); needs a `Console` capability with the read right | > [!IMPORTANT] > An unknown number is not just an error code. K0 treats it as a sign that the task is broken or hostile, prints `k0: unknown syscall N, killing task`, and terminates the caller. @@ -134,19 +135,29 @@ When no task is ready (for example the last runnable task died, or every task is | `k0: idle (waiting for a timeout)` | the first time the kernel idles while at least one waiter has a deadline | | `k0: all tasks stopped (none ready, no timeout pending)` | the first time the kernel idles while no waiter has a deadline | -In the second state nothing can wake a task today, because there are no notification objects and no device interrupts for tasks. The machine stays idle. `tools/qemu-boot-test.sh` treats any line that starts with `k0: all tasks` as a failure. +In the second state nothing can wake a task today, because there are no notification objects and no device interrupts for tasks other than console input. The machine stays idle. In an image with `console-input`, a task that waits for console input counts as a waiter: when that is the only thing left to wait for, the kernel prints nothing, which is the normal state of a terminal image. The second line is printed only when there is neither a timed waiter nor a console waiter. `tools/qemu-boot-test.sh` treats any line that starts with `k0: all tasks` as a failure. ## Timer interrupts from EL0 -The only interrupt the kernel enables is **the EL1 virtual timer**. Its interrupt number comes from the DTB, and the kernel uses no physical timer. The interrupt controller is GICv2 or GICv3, whichever the DTB says is the timer's interrupt parent. Before it writes anything, the driver checks the identification registers against that description and refuses to boot if they differ. See [dtb.md](dtb.md). +The interrupt the kernel always enables is **the EL1 virtual timer**. An image built with `console-input` takes a second one, the console UART's receive interrupt (see below). Its interrupt number comes from the DTB, and the kernel uses no physical timer. The interrupt controller is GICv2 or GICv3, whichever the DTB says is the timer's interrupt parent. Before it writes anything, the driver checks the identification registers against that description and refuses to boot if they differ. See [dtb.md](dtb.md). An IRQ taken from EL0 is saved the same way as a system call. The handler acknowledges the interrupt. If it was the timer, it re-arms the timer for one second, and prints `k0: tick N`. In an image built with a console driver, the line also goes to the console; only the first 4 tick lines are logged. Then it calls `k0_preempt`. That function first expires the IPC timeouts that are due (`k0_ipc::expire_timeouts`), so a waiter whose deadline has passed is ready before the round-robin switch, and then rotates to the next ready task. Spurious interrupt numbers 1020 to 1023 are ignored. Any other interrupt number, or any FIQ, cannot happen by design, so the kernel prints `k0: UNEXPECTED ...` and parks. +Once a tick has been counted, the handler also drains the console receive ring (an image with `console-input`), and after a task has started reading console input it stops printing the periodic tick lines (see [boot.md](boot.md)). Ticks, preemption and timeouts are unchanged. + +## Console interrupt + +An image built with `console-input` takes one more interrupt: the console UART's receive interrupt. The dispatcher tells the two apart by interrupt number (the timer's, then the console's), in the same function for IRQs taken at EL0 and at EL1. Anything else is still `k0: UNEXPECTED ...`. The console branch drains the UART into a ring of 256 bytes and never interprets a byte. It reports to the kernel binary through `k0_console_event`, a policy function like `k0_preempt`, which wakes a waiting `CONSOLE_READ` caller. The woken task goes to the end of the ready queue, so input does not preempt a running task. + +The interrupt is bounded by the reader. When the ring is full the kernel masks the UART's receive interrupt itself and reopens it after the reader has taken half of the ring. The same drain also runs once per tick, so input still arrives, up to a tick late, when the interrupt does not. A line that fires without a UART cause is switched off after 8 entries with `k0: console input off (interrupt N fired without a uart cause)`. The cut-off is covered only by host tests. Receive interrupts stay off until a task first reads console input with the read right. + +`CONSOLE_READ` takes the `Console` slot in `x0` and flags in `x1` (`NONBLOCK` = 1, `FLUSH` = 2, a timeout in ticks in bits 63..32, other bits refused with `BAD_FLAGS`). It returns the byte in `x1`, and `x2` is 1 if input was lost right before this byte. Only one task can wait at a time, a second reader gets `BUSY`, and `NO_DEVICE` means there is no input path or it was turned off. A waiter whose capability is deleted, revoked or moved wakes at once with `REVOKED`. + ## How it is tested The root task self-tests start tasks that fault in each way that matters. They check that only the faulting task dies, that the code after the faulting instruction never runs, and that the root task and the other tasks continue. The faults are a store through a null pointer, an FP/SIMD instruction, a read of an address that is mapped only in the root task, a write to a read-only page, a branch into a stack page, and a read of a kernel address. The test also kills a task with one unknown system call, and checks that thread pointer registers stay separate per task. -`tools/qemu-boot-test.sh` counts the lines **exactly**. It requires exactly six `k0: task fault ` lines (overridable with `K0_BOOT_FAULTS`) and exactly one `k0: unknown syscall ` line, and it requires that the fault line for the root-only address shows that address in `far`. A task that is resumed after it was destroyed, or that dies for a different reason, adds or removes a line and fails the test. +`tools/qemu-boot-test.sh` counts the lines **exactly**. It requires exactly six `k0: task fault ` lines (overridable with `K0_BOOT_FAULTS`; an image with the terminal shows two more than the same image without it, 8 without the vault and 10 with it) and exactly one `k0: unknown syscall ` line, and it requires that the fault line for the root-only address shows that address in `far`. A task that is resumed after it was destroyed, or that dies for a different reason, adds or removes a line and fails the test. The test also requires the ordered markers, among them `k0: task fault dabort-lower`, `k0: task fault fp-simd`, `k0: task fault iabort-lower`, `k0: unknown syscall 65535, killing task` and `root: fault isolation tests pass`. It fails on `k0: FATAL`, `k0: EXCEPTION`, `k0: PANIC` and `k0: UNEXPECTED`. diff --git a/design/en/hardening.md b/design/en/hardening.md index 8b408a1..9b86d73 100644 --- a/design/en/hardening.md +++ b/design/en/hardening.md @@ -46,7 +46,7 @@ Because the inputs are hashed together, a hostile or predictable input cannot ca The kernel also derives a 32-byte seed for the root task (`k0_boot::derive_root_seed`). It is SHA-256 over its own domain string (`k0-root-task-seed-v1`), the length of the DTB entropy, the DTB entropy itself, the counter and, when the CPU has `RNDR`, four fresh `RNDR` words. The domain string differs from the one of the PAC keys, so the two outputs are independent of each other by domain separation: knowing one does not give the other. They do share the DTB entropy and the counter, so the seed is as good as its inputs and no better. -The seed is not in the bootinfo page. The kernel puts it into the saved context of the root task, so it arrives in the entry registers `x0` to `x3`. Register `x4` is the seed info word: bits 15..0 hold how many `rng-seed` bytes went into the seed, and bit 16 is set when `RNDR` contributed. The layout of the bootinfo page is now version 3 (`bootinfo::VERSION`), and a root task that sees another version stops. The kernel wipes its own copies of the seed from the boot stack. The root task prints only the material, never the seed: `root: boot seed from rng-seed bytes 0x... and rndr` or `... without rndr`. +The seed is not in the bootinfo page. The kernel puts it into the saved context of the root task, so it arrives in the entry registers `x0` to `x3`. Register `x4` is the seed info word: bits 15..0 hold how many `rng-seed` bytes went into the seed, and bit 16 is set when `RNDR` contributed. The layout of the bootinfo page is now version 4 (`bootinfo::VERSION`), and a root task that sees another version stops. The kernel wipes its own copies of the seed from the boot stack. The root task prints only the material, never the seed: `root: boot seed from rng-seed bytes 0x... and rndr` or `... without rndr`. ### Wiping the seed from the DTB @@ -106,9 +106,12 @@ EL0 still cannot read any hardware counter or timer. IPC timeouts, however, give The EL0 thread pointer registers `TPIDR_EL0` and `TPIDRRO_EL0` are part of each task's saved context. `TCB_CONFIGURE` zeroes them, so a new task starts without the creator's values. -`DEBUG_PUTC` requires the `Console` capability and replaces every byte that is neither printable ASCII nor a newline with `?`. A task cannot send terminal escape sequences to whoever reads the console (in an image built with a console driver) or the boot log. +`DEBUG_PUTC` requires the `Console` capability with the write right (W) and replaces every byte that is neither printable ASCII nor a newline with `?`. The one exception is backspace (0x08), which a `Console` capability with the read right (R), the terminal's, may also emit. A task cannot send terminal escape sequences to whoever reads the console (in an image built with a console driver) or the boot log. -The filter does not mark who wrote a line. Kernel output and task output share the boot log, and in an image built with a console driver also the console. +The filter does not mark who wrote a line. Kernel output and task output share the boot log, and in an image built with a console driver also the console. The terminal can additionally erase within its current line. + +> [!NOTE] +> In an image built with `console-input`, an outside party can cause interrupts while tasks run. The kernel masks the receive interrupt itself when the ring is full, so the rate is bounded by the reader. The reader still learns arrival times finer than the tick, and other tasks can notice the stolen time. This timing channel has not been analysed. The kernel's receive code runs at EL1 and never interprets a byte, but it is kernel code driven by an outside party, and a user-space driver would need device and interrupt delegation, which K0 does not have. > [!WARNING] > A task with a `Console` capability can print a newline followed by text that starts with `k0:`. A reader of the console or the log, including `tools/qemu-boot-test.sh`, cannot treat a `k0:` line that appears after `k0: entering root task (el0)` as written by the kernel. diff --git a/design/en/ipc.md b/design/en/ipc.md index 38b030e..fc12cc6 100644 --- a/design/en/ipc.md +++ b/design/en/ipc.md @@ -13,7 +13,7 @@ This note describes K0's inter-process communication. It covers the following: - the badge that tells a server its clients apart - the single-use reply right that makes `CALL` safe -The code is in `crates/k0-ipc/src/lib.rs`, with the endpoint queue in `crates/k0-task/src/lib.rs`. +The code is in `crates/k0-ipc/src/lib.rs`, with the endpoint queue in `crates/k0-task/src/lib.rs`. The system call `CONSOLE_READ` waits like an IPC call and shares its timeouts, its teardown and its `REVOKED` wake-up. It is described in "Waiting for console input". It exists only in images built with `console-input`. ## Design in one paragraph @@ -101,6 +101,7 @@ The teardown looks only at the task's state and cuts every kernel pointer to it: - **Ready**: removed from the ready queue. - **Blocked in SEND, RECV or CALL**: removed from the queue of the endpoint it waits on, whether it is the head, the middle or the tail. +- **Waiting for console input** (`BlockedConsole`): removed from the one waiter place of the console. - **Waiting for a reply** (`BlockedReply`): the reply right is cut in both directions. So the server holds no right to answer it, and a late reply cannot wake a dead task. - **Holding a reply right**: the caller waiting for it wakes with `NO_REPLY`. - **Inactive, stopped or running**: nothing to unlink. @@ -127,6 +128,7 @@ The following table lists what the caller gets when a wait ends by timeout. | `RECV`, `REPLY_RECV` | in the endpoint queue | `TIMEOUT` | nothing received (a reply given by `REPLY_RECV` was already delivered) | | `CALL` | in the endpoint queue | `TIMEOUT` | not delivered | | `CALL` | `BlockedReply` | `REPLY_TIMEOUT` | delivered, and the server may or may not have acted | +| `CONSOLE_READ` | the console waiter place | `TIMEOUT` | no byte read | When a `CALL` ends with `REPLY_TIMEOUT`, the kernel clears the reply right of the server that holds it. If the server answers later, its `REPLY_RECV` finds no reply right to use, and the late reply is dropped. The next caller receives its own reply. @@ -154,13 +156,43 @@ A task that has to wait is marked with its blocked state and linked into the end If no task is ready at that point, the kernel does not stop. It idles in `idle_until_ready` (`kernel/src/syscall.rs`): it waits for the next interrupt, wakes every waiter whose deadline has passed, and switches to a ready task if there is one. Timer ticks keep being counted and handled meanwhile. The idle loop prints one of two lines, each at most once per boot: - `k0: idle (waiting for a timeout)`: at least one waiter has a deadline, so something will wake a task. -- `k0: all tasks stopped (none ready, no timeout pending)`: no waiter has a deadline. Nothing can wake a task in that state today, because K0 has no notification objects and no device interrupts for tasks, so the machine stays idle. `tools/qemu-boot-test.sh` treats any line that starts with `k0: all tasks` as a failure. +- `k0: all tasks stopped (none ready, no timeout pending)`: no waiter has a deadline and no task waits for console input. Nothing can wake a task in that state today, because K0 has no notification objects and the only device interrupt that wakes a task is console input, so the machine stays idle. `tools/qemu-boot-test.sh` treats any line that starts with `k0: all tasks` as a failure. + +When the only thing left to wait for is console input, the kernel prints neither line. That is the normal state of a terminal image. > [!WARNING] > The kernel no longer halts when every task is blocked, and a task can bound its own waits with timeouts. Availability is still not protected. A task that waits without a timeout can wait forever if its partner never acts, and a confined task that holds a capability to an endpoint can still make others wait. This is the subject of advisory GHSA-q99x-2wrv-358p in [SECURITY.md](../../SECURITY.md). The advisory is updated at release time. A server, or the root task, that must stay responsive has to give a timeout on every wait. Task isolation does not change this. +## Waiting for console input + +`CONSOLE_READ` (number 16) reads one byte of console input. It exists only in an image built with `console-input` and a console driver that can receive (PL011 and SBSA UART, not 16550). The arguments and results are the following: + +| Register | Meaning | +| --- | --- | +| `x0` (in) | the slot of a `Console` capability with `R` | +| `x1` (in) | flags: `NONBLOCK` = 1, `FLUSH` = 2, a timeout in ticks in bits 63 to 32. Any other bit fails with `BAD_FLAGS` | +| `x0` (out) | 0, or an error code | +| `x1` (out) | the byte | +| `x2` (out) | 1 if input was lost right before this byte, otherwise 0 | + +One call returns one byte. The kernel never interprets a byte. `FLUSH` discards what the kernel and the device hold before the read, so that input that arrived before a prompt is not read as a command. `NONBLOCK` returns `WOULD_BLOCK` when no byte is ready. + +If no byte is ready, the task waits in the state `BlockedConsole`. The wait works like the waits above: + +- **One waiter**: only one task can wait at a time. A second reader gets `BUSY`. +- **Timeouts**: the timeout uses the same timed list as IPC, and a wait that runs out returns `TIMEOUT`. +- **Revocation**: a waiter whose `Console` capability is deleted, revoked or moved wakes at once with `REVOKED`, and gets no byte. +- **No input path**: `NO_DEVICE` means that the image has no receive driver for this console, or that the input path was turned off. A waiter wakes with it when the path is turned off while it waits. +- **Teardown**: a task that dies while it waits is removed from the waiter place. +- **Wake-up order**: a woken reader goes to the end of the ready queue. Input does not preempt a running task. + +Receive interrupts stay off until a task first reads console input with the right. That first read discards what the device holds and stops the periodic `k0: tick N` lines after one line `k0: tick lines off (console input in use)`. Ticks, preemption and timeouts keep working. The receive path and its limits are described in [USAGE.md](../../USAGE.md) and [exceptions.md](exceptions.md). + +> [!NOTE] +> Input waits behind running tasks. There are no priorities, so the latency of a byte is up to one tick per ready task. + ## Errors The following table lists the error codes and their causes. @@ -172,10 +204,12 @@ The following table lists the error codes and their causes. | `NO_RIGHTS` | the endpoint capability lacks `W` (`SEND`, `CALL`) or `R` (`RECV`, `REPLY_RECV`) | | `WOULD_BLOCK` | `NONBLOCK` was set and the other side was not ready | | `NO_REPLY` | the receiver of a `CALL` exited, faulted or took a newer `CALL` without replying, or was destroyed | -| `REVOKED` | the original capability of the endpoint was deleted while the caller was queued on it | +| `REVOKED` | the original capability of the endpoint was deleted while the caller was queued on it. For `CONSOLE_READ`, the `Console` capability was deleted, revoked or moved while the caller waited | | `TIMEOUT` | the wait ended before a partner arrived, and the message was not delivered | | `REPLY_TIMEOUT` | a `CALL` was delivered but no reply came in time, and the server may or may not have acted | -| `BAD_FLAGS` | a reserved bit (31 to 1) of the flags register was set | +| `BAD_FLAGS` | a reserved bit (31 to 1) of the flags register was set. For `CONSOLE_READ`, any bit other than `NONBLOCK`, `FLUSH` and the timeout | +| `BUSY` (-23) | `CONSOLE_READ` found another task already waiting for console input | +| `NO_DEVICE` (-24) | `CONSOLE_READ` found no input path: the image has no receive driver for the console, or the path was turned off | ## How it is tested @@ -199,6 +233,8 @@ The timeout tests (`test_timeouts` in `userspace/root-task/src/main.rs`) wait fo The timeout tests take their objects from the largest untyped. The tests wait for real ticks, so a boot test takes about 4 seconds longer. +The input tests are part of the root task self-test in images built with `console-input`. They print `root: backspace without the input right [?]` and `root: console input tests pass`, or `root: console input tests pass (no input path)`, or `... cut short (the line is busy)` when bytes arrive during the test. The receive logic is in the separate crate `crates/k0-conin` and is tested on the host with a fake UART. `tools/term-test.py` runs a scripted session against a terminal image. + The capability tests check that a badge can be set once and is refused a second time, that a copy keeps the badge, that a send-only capability cannot receive and a receive-only one cannot send (`NO_RIGHTS`), and that revoking an endpoint removes every copy while the original stays. The isolation tests start a confined task whose CNode holds only a send-only, badged endpoint capability. The root task checks that the task receives the badge it was given in `x1` and that slot numbers of the root task mean nothing in the confined CNode (`BAD_SLOT`). @@ -224,6 +260,7 @@ The boot test script also requires an exact number of `k0: task fault` lines and - **Timeouts say when a task becomes ready, not when it runs**: there is no priority and no CPU budget, and the scheduler is round robin with a one-tick slice (see [scheduling.md](scheduling.md)). - **Long system calls**: the kernel is not preemptible, so a long call such as `CAP_REVOKE` on an untyped with many objects delays every other task and every timeout. - **Fatal stops**: a `k0_arch::fatal` or a kernel panic still stops the machine. -- **Timing source for EL0**: whether the tick-aligned wake-up can be used for timing attacks has not been analysed. +- **Timing source for EL0**: whether the tick-aligned wake-up can be used for timing attacks has not been analysed. In an image with console input, an outside party can cause interrupts while tasks run (bounded by the reader), and the reader learns arrival times finer than the tick. Other tasks can notice the stolen time. This timing channel is not analysed either. +- **Input latency**: a `CONSOLE_READ` waiter is woken behind running tasks, so a byte can wait up to a tick per ready task. - **A queued sender**: it delivers once after revocation. A sender that is already waiting on an endpoint keeps the badge of the send that queued it. If its capability is revoked while it waits, its message is still delivered once to the next receiver. - **Four words per message**: larger data needs shared memory. The holder of a task's `AddrSpace` capability must map it into that task's address space, since tasks can now run in separate address spaces. diff --git a/design/en/scheduling.md b/design/en/scheduling.md index 063b9f9..6b1a435 100644 --- a/design/en/scheduling.md +++ b/design/en/scheduling.md @@ -56,9 +56,10 @@ The following figure shows the task states and the transitions between them. The | `Running` | the current task | | `BlockedSend`, `BlockedRecv`, `BlockedCall` | waiting in an endpoint queue | | `BlockedReply` | waiting for the answer to a `CALL` | +| `BlockedConsole` | waiting for console input in `CONSOLE_READ` (only in an image built with `console-input`). The task is in no queue. One kernel waiter slot points at it, and only one task can wait at a time. | | `Dead` | exited, killed, or torn down | -A task in any of the blocked states can also become `Ready` when its deadline passes (see [Timeouts](#timeouts)). +A task in any of the blocked states can also become `Ready` when its deadline passes. A `BlockedConsole` task also becomes `Ready` when a byte arrives or when its capability is deleted, revoked or moved (for deadlines see [Timeouts](#timeouts)). `Inactive` has the value 0. A freshly retyped frame is all zeroes, so it already is a valid `Inactive` TCB with empty queue links, empty embedded slots and no reply right. Retype needs no constructor. @@ -107,12 +108,12 @@ Three operations use this switch, as shown in the following table. ## Preemption -The timer fires once per second. When it fires while EL0 is running, the IRQ path acknowledges it, re-arms the timer, prints `k0: tick N` and calls `k0_preempt`, which calls `rotate`. The `k0: tick N` line goes to the console in an image built with a console driver, and only the first 4 tick lines are logged. A task that never yields therefore **loses the CPU after at most one second**. +The timer fires once per second. When it fires while EL0 is running, the IRQ path acknowledges it, re-arms the timer, prints `k0: tick N` and calls `k0_preempt`, which calls `rotate`. The `k0: tick N` line goes to the console in an image built with a console driver, and only the first 4 tick lines are logged. A task that never yields therefore **loses the CPU after at most one second**. Once a task has read console input, the tick lines stop after one line `k0: tick lines off (console input in use)`, but the tick, the preemption and the timeouts go on. > [!IMPORTANT] > The kernel itself is never preempted. Exception entry masks interrupts, and the kernel keeps them masked while it handles a system call or fault. -A timer interrupt that arrives at EL1 is possible only during boot, before the handoff, and it only counts the tick. +A timer interrupt that arrives at EL1 is possible only during boot, before the handoff, and it only counts the tick. In an image with `console-input`, an arriving input byte does not preempt: the woken reader goes to the end of the ready queue like any other woken task. There are no priorities, so input latency is up to a tick per ready task. ## Timeouts @@ -145,6 +146,7 @@ The following table shows what teardown does in each state. | `Ready` | removes the task from the ready queue | | `BlockedSend`, `BlockedRecv`, `BlockedCall` | removes the task from the endpoint queue named by `blocked_on`, and from the timed list if it has a deadline | | `BlockedReply` | clears the reply right in the task that holds it (`reply_from`), and removes the task from the timed list if it has a deadline | +| `BlockedConsole` | clears the kernel's console waiter slot and removes the task from the timed list if it has a deadline | | `Running` | nothing is unlinked. See below. | For every state it then withdraws any reply right the task itself holds, so that the caller waiting for that reply wakes with `NO_REPLY` and does not stay blocked forever. Finally it sets the state to `Dead`, clears the queue links, `blocked_on`, `reply_from`, `ipc_badge` and `ttbr0_pa`, and, unless the task is `Running`, zeroes its saved registers. A queue or reply link that does not match what the state promises is a kernel invariant violation, and the kernel halts with `k0: FATAL ...` (see [exceptions.md](exceptions.md)). @@ -164,7 +166,9 @@ The kernel no longer parks the core when no task can run. If the current task bl Timer ticks keep being counted and handled while the kernel idles. The idle loop prints one of two lines, each at most once per boot: - `k0: idle (waiting for a timeout)`: at least one waiter has a deadline. -- `k0: all tasks stopped (none ready, no timeout pending)`: no waiter has a deadline. Nothing can wake a task in that state today, because there are no notification objects and no device interrupts for tasks, so the machine stays idle. +- `k0: all tasks stopped (none ready, no timeout pending)`: no waiter has a deadline and no task waits for console input. Nothing can wake a task in that state today, because there are no notification objects and no device interrupts for tasks other than console input, so the machine stays idle. + +When the only thing left to wait for is console input (an image with `console-input`), the kernel prints nothing: that is the normal state of a terminal image. The idle loop also looks for arrived input after each interrupt and wakes the reader. > [!WARNING] > Availability is still not protected. A task that waits without a timeout can wait forever if its partner never acts, and a confined task that is the last one to block can still leave the system with nothing to run (advisory GHSA-q99x-2wrv-358p in [SECURITY.md](../../SECURITY.md), updated at release time). Isolation protects confidentiality and integrity between tasks, not availability. diff --git a/design/en/terminal.md b/design/en/terminal.md new file mode 100644 index 0000000..fedecaa --- /dev/null +++ b/design/en/terminal.md @@ -0,0 +1,165 @@ +# Serial input and the operator terminal + +

+ +English | [한국어](../kr/terminal_KR.md) + +
+ +This note describes how a person can talk to K0 over the serial line. The kernel receives bytes from the console UART and hands them to one task, the **terminal**, with the system call `CONSOLE_READ`. The terminal is the operator of the vault (see [vault.md](vault.md)): it shows the vault's state, makes the key and erases it. The code is in `crates/k0-conin` (the receive logic), `kernel/src/syscall.rs` (`CONSOLE_READ`), `userspace/k0-term` (the terminal) and `userspace/root-task/src/service.rs` (wiring and the check). + +> [!NOTE] +> Input and the terminal are optional and off by default. An image built without `console-input` has no receive code, no `CONSOLE_READ` and none of the log lines in this note. An image built without `terminal` has no terminal code. + +## Purpose and scope + +The vault of the previous note makes its key once from the boot seed and then only answers calls. Without an operator nobody can look at its state, and nobody can erase the key on purpose. The terminal closes this gap with a small, fixed text interface on the serial line. + +Scope: one console UART, one reader at a time, one byte per call, and four vault operations for the operator (`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`). The terminal cannot sign and cannot deliver a seed. + +

+ Bytes from the serial line go into a 256-byte receive ring in the kernel. The terminal task reads one byte per CONSOLE_READ call. The terminal holds two capabilities: a Console copy with read and write rights, and the vault endpoint with the send right and the operator badge. +

+ +## Why the kernel receives + +A user-space driver would need the UART's registers and its interrupt. K0 cannot delegate a device or an interrupt to a task yet. So the receive code runs in the kernel, at EL1, and the kernel gives the bytes to user space. + +The kernel code is kept small and never interprets a byte. It does not know what a line, a command or a control key is. All of that is the terminal's job, in user space. + +> [!NOTE] +> The receive code is still kernel code that an outside party drives. A user-space driver does not exist yet, because device and interrupt delegation does not exist yet. + +The features are the following, and features only add: + +| Feature of `k0-kernel` | Adds | +| --- | --- | +| `console-input` | The kernel's receive path for the console UART and `CONSOLE_READ`. It needs a console driver feature to do anything. Receive exists for PL011 and SBSA UART only. | +| `terminal` | The terminal task in the root task image, started as a service after the self-tests. It turns `console-input` on. With `vault` it is the vault's operator, and with `vault-ed25519` it can make an Ed25519 key. | + +You can build and run it as follows: + +```sh +$ cargo build -p k0-kernel --features console,terminal,vault-ed25519 +$ cargo run -p k0-kernel --features console,terminal,vault-ed25519 +``` + +QEMU shows the serial port on your terminal. Under `cargo run`, QEMU's own escape key is Ctrl-A (Ctrl-A x quits QEMU), so Ctrl-A never reaches K0 there. + +## The receive path and its bounds + +The kernel's UART driver puts every received byte into a ring of 256 bytes. The receive logic is a separate crate, `crates/k0-conin`, written against a small register trait, so that the host tests can drive it with a fake UART. + +- **Receive interrupts stay off** until a task first reads console input with the right. That first read discards what the device holds. It also stops the periodic `k0: tick N` lines after one line `k0: tick lines off (console input in use)`. Ticks, preemption and timeouts keep working. +- **Bound on kernel work**: when the ring is full, the kernel masks the UART's receive interrupt itself. It reopens the interrupt after the reader has taken half of the ring. So the interrupt rate under a flood is bounded by the reader, not by the sender. +- **A drain on every tick**: the same drain also runs once per tick, so input still arrives (up to a tick late) when the interrupt does not. +- **Loss is marked**: a FIFO overrun, a break, a framing error or a parity error is marked on the byte after the hole. `CONSOLE_READ` returns that mark to the reader. +- **The interrupt number** comes from the device tree (the `interrupts` property of the console node: one SPI, level, active high, of the discovered GIC) or, through the UEFI loader, from the ACPI SPCR table. It is printed in the platform line, for example `k0: platform con=pl011@0x9000000,irq33 ...`, and therefore pinned by `K0_PIN`. Pin strings made before this change no longer match and must be made again. A console node without a usable interrupt is not a boot refusal. Input is just off. +- **A wrong interrupt number costs only input**: an out-of-range or unavailable number gives `k0: console input off (...)` at boot. A line that keeps firing without a UART cause is switched off after 8 entries with `k0: console input off (interrupt N fired without a uart cause)`. + +At boot the kernel prints `k0: console input on (pl011 irq 33)` or `k0: console input off ()`. The reasons are `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range` and `interrupt not available`. + +## CONSOLE_READ and the Console rights + +`CONSOLE_READ` is system call number 16. It returns one byte per call. + +| Register | In | Out | +| --- | --- | --- | +| x0 | the `Console` capability slot | 0 on success, or an error | +| x1 | flags | the byte | +| x2 | | 1 if input was lost right before this byte | + +The flags are `NONBLOCK` (1) and `FLUSH` (2), and a timeout in ticks in bits 63 to 32. Any other bit is refused with `BAD_FLAGS`. `NO_DEVICE` (-24) means that there is no input path or that it was turned off. + +The `Console` capability now has rights: **R** reads input and **W** writes output. `CAP_COPY` can only remove them. The root task's capability has W, and R only in images with `console-input`. `DEBUG_PUTC` needs W. `bootinfo::VERSION` is 4. + +The output filter is unchanged, except for one thing: a `Console` capability with R (the terminal's) may also emit backspace (0x08). Every other control byte is still printed as `?`. + +## Waiting and waking + +Only one task can wait for input at a time. A second reader gets `BUSY` (-23). A reader that finds the ring empty and did not ask for `NONBLOCK` goes to sleep, with the timeout from its flags if there is one. + +- **Waking on a byte**: a received byte wakes the waiter. It goes to the end of the ready queue. There is no preemption on input. +- **Waking on a capability change**: a waiter whose capability is deleted, revoked or moved wakes at once with `REVOKED`. +- **Waking on a timeout**: a reader that gave a timeout in its flags is woken when it runs out (see [scheduling.md](scheduling.md) for timeouts). +- **Quiet idle**: when the only thing left to wait for is console input, the kernel prints nothing. That is the normal state of a terminal image. `k0: all tasks stopped (none ready, no timeout pending)` is printed only when there is neither a timed waiter nor a console waiter. + +## The terminal's wiring and the hostile-task check + +A terminal image runs all self-tests first. Then the root task does the following: + +1. It starts a new vault (if one is built in) and hands it the boot seed. The log line is `root: vault seeded`, or `root: vault has no seed (boot seed has no entropy)`, or `root: vault has no seed (no algorithm in this image)`. +2. It runs two hostile tasks wired exactly like the terminal. They must be refused and must end in a fault. The lines are `root: terminal console filter [...]`, `root: terminal wiring holds` and two `k0: task fault` lines. +3. It drops its own admin capability, starts the terminal and blocks for ever. The line is `root: service started`, then the banner follows. + +On a machine without an input path the root task prints `root: no console input, terminal not started`. + +The terminal task has its own address space and two capabilities: + +- a `Console` copy with R and W, and +- the vault endpoint with the send right and the operator badge. + +The vault's response frame is mapped read-only for it. The vault decides from the badge and the operation alone which frame it reads or writes. The operator has a response frame and no request frame. A request that claims a body it cannot have is refused without touching memory. + +The two hostile tasks are the check that the wiring means what it says. They are wired exactly like the terminal, and the root task expects both to be refused and to end in a fault. If one of them is not refused, the check fails. + +> [!WARNING] +> There is no authentication on the serial line. Whoever holds the line is the operator and can do exactly the operator's four operations, including erasing the key. The operator cannot sign, cannot deliver a seed and cannot change the policy. + +## The screen and command rules + +The screen is plain text. The banner is `K0 operator console, type 'help'`, the prompt is `k0> `, values are printed as `name=value`, and every command ends with exactly one line, `ok` or `err `. + +| Command | What it does | +| --- | --- | +| `help` | Lists the commands. | +| `vault status` | Prints the state of the vault. | +| `vault pubkey` | Prints the public key. | +| `vault keygen ` | Makes the key from the held seed. The only algorithm is `ed25519`. | +| `vault zeroize confirm` | Erases the key. `vault zeroize` alone prints `hint=type 'vault zeroize confirm' to erase the key` and `err confirm-required`. | + +`vault status` prints `state=fresh|seeded|ready|zeroized|failed`, `alg=none|ed25519`, `selftest=passed|failed`, `seed=none|rng-seed|rndr|rng-seed+rndr` and `validated=no`. The value `seed=rng-seed` means that the bytes were present, not that they were unpredictable. The line `validated=no` is always printed, because the implementation has no validation of any kind. + +`vault pubkey` prints `pubkey=` and 32 hex characters, then a second line indented by 7 spaces with the other 32. + +The error names are `unknown-command`, `bad-argument`, `line-too-long`, `input-lost`, `confirm-required`, `denied`, `no-vault`, `no-key`, `key-exists`, `no-entropy`, `unsupported-algorithm`, `zeroized`, `vault-failed` and `vault-timeout`. A keygen or zeroize that was delivered but not answered in time adds `hint=run 'vault status' to see whether it took effect`. + +The input rules are the following. The state machine is `feed` in `userspace/k0-term/src/lib.rs`. + +- A line ends with CR or LF, has at most 64 characters, and contains printable ASCII only. +- Backspace and DEL erase one character. Ctrl-C and Ctrl-U cancel the line and are shown as `^C` and `^U`. +- ESC sequences (arrow keys) are ignored. +- What reached the UART before the prompt is dropped. +- A reported loss discards everything up to the next line end and prints `err input-lost`. +- Without the vault feature, `help` lists only `help` and `vault ...` answers `err no-vault`. + +The vault side changed with this feature. There are four roles by endpoint badge, fixed at build time: admin (the root task), operator (the terminal), signer and reader. `INIT` (admin only, once) now only delivers the seed. The vault checks the entropy rule and holds the seed in the state `seeded`. The new operation `KEYGEN` (admin and operator) makes the key from the held seed and wipes the seed (state `ready`). One key per boot: a second `KEYGEN` is refused with `key-exists`, and after `ZEROIZE` a reboot is needed. Every way into `failed` wipes seed and key. + +## How it is tested + +**Host tests** (`tools/host-test.sh`): `k0-conin` has 15 tests with a fake UART, `k0-term` has 24 with the vault feature and 21 without, and `k0-vault` has 20 with Ed25519 and 11 without. The suite has 354 tests on an ARM host and 268 on other hosts. + +**Boot matrix**: the new rows are `input-only`, `input-gicv2`, `input-16550`, `input-bad-irq`, the static row `input-symbols` (an image without `console-input` has no receive code and none of the new log lines), `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi` and `hvf-term`. The matrix has 76 rows on a Mac with HVF and 65 in CI. + +**Scripted session**: `tools/term-test.py ` boots the image with QEMU's serial port on pipes and runs a session. It covers every command and every error, erase and cancel, CR LF, an ESC sequence, a line that is too long, key generation, the public key format, zeroize, 200 kB without a line end, 2000 lines in a row and a serial break. `tools/qemu-boot-test.sh` reads `K0_BOOT_INPUT=on|off`, `K0_BOOT_SERVICE=vault|plain|none` and a judge-only mode `K0_BOOT_JUDGE`. + +**Root task self-test** (images with `console-input`): `root: backspace without the input right [?]` and `root: console input tests pass`. The second line may also read `... pass (no input path)` or `... cut short (the line is busy)` when bytes arrive during the test. A terminal image also shows two more `k0: task fault` lines than the same image without the terminal (8 without the vault, 10 with it). + +## Known gaps + +> [!NOTE] +> Nothing ran on real hardware. The SBSA UART path, FIFO overruns and the receive timeout interrupt are not exercised by QEMU, and they are covered only by host tests with a fake UART. The cut-off for an interrupt line that fires without a UART cause is covered only by host tests. + +- **No authentication**: the serial line is as trusted as whoever can reach it. The operator can erase the key (a denial of service by design) but gets no signature and cannot change policy. +- **Kernel code driven from outside**: the receive code runs at EL1. +- **A timing channel that is not analysed**: an outside party can now cause interrupts while tasks run, bounded by the reader. The reader learns arrival times finer than the tick, and other tasks can notice the stolen time. +- **Latency**: input waits behind running tasks. There are no priorities, so the latency is up to a tick per ready task. +- **No input on a 16550 console**: a 16550 console has output and no input. +- **No measurement under a flood**: no test measures kernel time under a flood on a machine. The bound is argued from the gate and shown in host tests. +- **Dropped before the prompt**: this counts bytes that reached the UART. An emulator or adapter that holds bytes back delivers them later (QEMU does). +- **Split screen line**: if a kernel line appears while the operator is typing, the screen line is split but the buffer is whole. Enter runs the whole buffer. +- **Lines can be imitated**: any task with `Console` output can still print lines that look like kernel or root task lines, because nothing authenticates the prefix. The terminal can additionally erase within its current line. +- **No signing client in service mode**: the key is made and shown, but no other task uses it yet. Client signing is shown by the self-test. +- **No restart**: the terminal and the vault are not restarted if they die. The root task is trusted. +- **Boot log share**: terminal output counts against the user share of the in-memory boot log. Once that share is full, later task output is not recorded there. +- **All earlier limits of the vault stay**: the implementation is unvalidated, there is no side-channel analysis, the key does not come from an approved random bit generator, there is no persistence and there is no post-quantum algorithm. Availability is not protected (see [ipc.md](ipc.md)). diff --git a/design/en/uefi.md b/design/en/uefi.md index cd5691c..6c016a2 100644 --- a/design/en/uefi.md +++ b/design/en/uefi.md @@ -183,7 +183,7 @@ The loader has no signature code. Under Secure Boot the firmware verifies the wh - **Host unit tests**: `crates/k0-efi/src/tests.rs` holds 32 tests. The vectors are measured firmware memory maps. They cover the descriptor rules, overlap, the entry limit, the writer, the rewrite, the verifier, the ACPI reader and the tree synthesis. A fourth fuzzer, `fuzz_acpi_with_mutated_tables`, mutates table images. Campaigns of 2 to 3 million cases passed on 2026-11-12, and it found one real mismatch earlier (the reader accepted a GIC frame alignment that the kernel's discovery refuses), which is fixed by applying the kernel's placement rules in the reader. - **Three deterministic fuzzers**: `fuzz_plan_with_random_maps`, `fuzz_rewrite_with_mutated_trees` and `fuzz_prepare_end_to_end` in `k0-efi`. They use the same variables as the other fuzzers: `K0_FUZZ_ITERS`, `K0_FUZZ_SEED`, `K0_FUZZ_CASE`. The defaults are 20,000, 20,000 and 5,000 cases. The weekly workflow runs all three at 5 million cases. Campaigns of 5 million cases each passed on 2026-11-12. The planner fuzzer found one real bug earlier (a block at physical address 0 was accepted). It is fixed. -- **Host test script**: `tools/host-test.sh` now runs 276 tests on an ARM host (`k0-abi` 14, `k0-cap` 42, `k0-boot` 82, `k0-efi` 32, `k0-vault` 13 with Ed25519 and 7 without, and `k0-mm` 43 for each of the two granules) and 190 on other hosts, where the `k0-mm` tests are skipped. +- **Host test script**: `tools/host-test.sh` now runs 354 tests on an ARM host (`k0-abi` 15, `k0-cap` 44, `k0-boot` 85, `k0-efi` 33, `k0-conin` 15, `k0-vault` 20 with Ed25519 and 11 without, `k0-term` 24 with the vault feature and 21 without, and `k0-mm` 43 for each of the two granules) and 268 on other hosts, where the `k0-mm` tests are skipped. - **PE check**: `tools/pe-check.py .efi` checks the PE form (four sections, none both writable and executable) and the order of the cache and MMU instructions, and prints `pe-check: ok (...)`. - **Boot tests under EDK2**: `tools/qemu-virt-runner.sh` boots a `.efi` argument through EDK2 firmware. The default machine is `virt,gic-version=3,acpi=off`, so it uses the device tree path. The ACPI rows pass `K0_QEMU_MACHINE=virt,gic-version=3` or `virt,gic-version=2`. `tools/qemu-boot-test.sh` judges a failure from the loader's first line, `k0-loader: start`, so firmware messages do not count. `tools/build-loader.sh ` embeds an already built kernel and prints the path of the `.efi`, which is `.efi`. This way the UEFI rows boot the same kernel binary as the other rows. The usage notes in [USAGE.md](../../USAGE.md) show the commands. @@ -253,6 +253,7 @@ Also: firmware that gives a device tree uses it, and ACPI is then not read. Firm - **GIC from the MADT**: there is one distributor entry. Version 2 is GICv2, 3 or 4 is GICv3, 0 is decided by whether redistributors are described, and anything else is refused. GICv2 frame sizes are not in the table, so the loader uses 4 KiB for the distributor and 8 KiB for the CPU interface (the values Linux uses). GICv3 redistributors come from GICR entries (at most 4) or, without those, from the CPU entries, merged when adjacent at the 128 KiB or 256 KiB stride. The boot CPU's entry must be among them. Frames must be aligned, must not overlap each other, and must not lie in RAM or firmware memory according to the memory map, otherwise the loader refuses. - **Timer from the GTDT**: the virtual EL1 timer interrupt must be 16 to 31. - **Console from the SPCR** (optional): PL011 (type 0x03), SBSA UART (0x0D, 0x0E), and a 16550 (0x00, 0x01, 0x12) only with 8-bit registers and byte access, because the SPCR cannot express the register stride. +- **Console interrupt from the SPCR** (optional): the interrupt type must be GIC only (bit 3 and no other) and the global system interrupt must be an SPI (32 to 1019). The loader writes it as the `interrupts` property of the console node (SPI number, level, active high), and the kernel reads it as described in [dtb.md](dtb.md). A table too short to hold the field, or any other form, gives a console without an interrupt, which is not a refusal: input is just off. The number appears in the `k0: platform` line (`irq33`), so a pin string made before this field existed no longer matches. - **Refused versus booted without console**: a bad table, GIC, timer or a device in memory is refused (`ACPI tables: `). A console the kernel has no driver for, a wrong SPCR, or a console that lies in memory means a boot without console. The loader prints `k0-loader: device tree built from ACPI tables (MADT, GTDT and SPCR)` or `(MADT and GTDT, no usable SPCR console)`. - **Entropy**: a tree built from ACPI has no firmware seed. The kernel gets 32 bytes when the firmware has `EFI_RNG_PROTOCOL` and nothing otherwise (it logs `k0: entropy dtb=0B` and continues). - **Flushing the work area**: the loader also flushes its work area from the data cache before the jump. `tools/pe-check.py` requires three flush calls (block, work area, trampoline). diff --git a/design/en/vault.md b/design/en/vault.md index fda9683..893eb05 100644 --- a/design/en/vault.md +++ b/design/en/vault.md @@ -6,26 +6,28 @@ English | [한국어](../kr/vault_KR.md) -This note describes the first service on top of K0's isolation core. A **vault** task holds one Ed25519 key. Client tasks get signatures and the public key over IPC, and they never get the key. The code is in `userspace/k0-vault` (the crate), `userspace/root-task/src/oracle.rs` (wiring and self-test) and `crates/k0-boot` (the boot seed). +This note describes the first service on top of K0's isolation core. A **vault** task holds one Ed25519 key. Client tasks get signatures and the public key over IPC, and they never get the key. The code is in `userspace/k0-vault` (the crate), `userspace/root-task/src/oracle.rs` (wiring and self-test), `userspace/root-task/src/service.rs` (the service that starts after the self-tests) and `crates/k0-boot` (the boot seed). In an image built with `terminal`, the operator of the vault is the serial terminal (see "The service vault and the operator"). > [!NOTE] > The vault is optional and off by default. The default image has no vault and no crypto code. ## Purpose and scope -The vault shows that the isolation core can keep a secret away from the tasks that use it. It offers a small, fixed service: report status, return the public key, and sign a message of up to 1024 bytes. +The vault shows that the isolation core can keep a secret away from the tasks that use it. It offers a small, fixed service: report status, return the public key, and sign a message of up to 1024 bytes. The key is made in two steps. The root task delivers a seed, and then the admin or the operator asks for a key. The algorithm is Ed25519 (PureEdDSA with SHA-512, as in FIPS 186-5 and RFC 8032). The implementation is the vendored crate `ed25519-dalek` 2.2.0 and has no validation of any kind. The key does not come from an approved random bit generator. 14 crates were added to `vendor/` for it, and half of them are build-time or other-target code that is not compiled into a K0 image. ## Objects and who can map what -![The root task builds the vault, the client, one endpoint and two frames. The client holds a send-only badged endpoint capability. The request frame is read-write for the client and read-only for the vault. The response frame is read-write for the vault and read-only for the client.](../../assets/vault-flow.svg) +

+ The root task builds the vault, the client, one endpoint and two frames. The client holds a send-only badged endpoint capability. The request frame is read-write for the client and read-only for the vault. The response frame is read-write for the vault and read-only for the client. +

The root task creates the following objects: -- **one endpoint**: the vault receives on it. A client's CNode holds only a send-only, badged copy of it (and a report endpoint in the self-test). +- **one endpoint**: the vault receives on it. A client's CNode holds only a send-only, badged copy of it (and a report endpoint in the self-test). The terminal gets the same kind of copy with the operator badge. - **the vault task**: it has its own address space and its own stack. The key lives there. -- **per caller, a request frame and a response frame**: the request frame is read-write for the caller and read-only for the vault. The response frame is read-write for the vault and read-only for the caller. This is enforced by reduced-rights copies of the frame capabilities. +- **per caller, a request frame and a response frame**: the request frame is read-write for the caller and read-only for the vault. The response frame is read-write for the vault and read-only for the caller. This is enforced by reduced-rights copies of the frame capabilities. The operator is the exception: it has a response frame, mapped read-only for it, and no request frame. > [!WARNING] > The root task builds all of this, so it is outside the isolation and could read the vault. The statement that holds is "no task other than the root task can map the vault's memory". @@ -49,46 +51,82 @@ The reply sets all four registers: | MR2 | the indicator bits | | MR3 | the nonce | -The operations are `STATUS`, `PUBLIC_KEY`, `SIGN` (a message of up to 1024 bytes in the request frame) and, for the admin badge only, `INIT` (the seed and the seed info, 40 bytes, once) and `ZEROIZE`. +The operations are the following: + +| Operation | Meaning | +| --- | --- | +| `STATUS` | the state, the algorithm of the key and the algorithms in the image | +| `PUBLIC_KEY` | the public key, in the response frame | +| `SIGN` | signs a message of up to 1024 bytes in the request frame | +| `INIT` | delivers the seed and the seed info (40 bytes, once, admin only). It makes no key | +| `KEYGEN` | makes the key from the held seed with the algorithm chosen in MR0, and wipes the seed | +| `ZEROIZE` | wipes the key and the held seed | + +`STATUS` packs the state, the algorithm of the key and the algorithms built into the image into the one word of MR1 (`proto::status_word`). **The single fetch**: `server::fetch` fixes the length first, then reads the body once into a private buffer with volatile reads. Only the copy is used, so a caller that changes the frame during the call gains nothing. The response frame starts with the nonce and the length, and `server::publish` writes the nonce last. A client must trust the frame only after an `OK` reply that carries its own nonce. -The state machine is `Vault::handle` in `userspace/k0-vault/src/server.rs`. +The vault decides from the badge and the operation alone which frame it reads or writes (`proto::fetch_plan` and `proto::publish_plan`). Only `SIGN` and `INIT` carry a request body, and only `PUBLIC_KEY` and `SIGN` give a response body. A request that claims a body it cannot have is refused with `BAD_REQUEST`, and the vault touches no memory for it. This matters for the operator, which has no request frame: a made-up length cannot make the vault read an address that is not mapped. + +The state machine is `Vault::handle` in `userspace/k0-vault/src/server.rs`. The vault is in one of five states: + +| State | Meaning | +| --- | --- | +| `fresh` | no seed and no key | +| `seeded` | `INIT` delivered a seed that passed the entropy rule, and the vault holds it | +| `ready` | `KEYGEN` made the key and wiped the seed | +| `zeroized` | `ZEROIZE` wiped the key and the seed. Only a reboot makes a new key | +| `failed` | a self-test or the pairwise test failed. Every way into this state wipes the seed and the key | + +There is one key per boot. A second `KEYGEN` is refused with `KEY_EXISTS` (`key-exists` on the terminal). ## The fixed policy and badges -The policy is fixed at build time and keyed by the endpoint badge. The kernel delivers the badge, and a client cannot forge it (see [ipc.md](ipc.md)). The roles are the following: +The policy is fixed at build time and keyed by the endpoint badge. The kernel delivers the badge, and a client cannot forge it (see [ipc.md](ipc.md)). There are four roles, fixed at build time: | Role | Operations | | --- | --- | -| admin (the root task) | `STATUS`, `INIT`, `ZEROIZE`, not `SIGN` | +| admin (the root task) | `STATUS`, `INIT`, `KEYGEN`, `ZEROIZE`, not `SIGN` and not `PUBLIC_KEY` | +| operator (the terminal) | `STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`, not `SIGN` and not `INIT` | | signer | `STATUS`, `PUBLIC_KEY`, `SIGN` | | reader | `STATUS`, `PUBLIC_KEY` | -A call without a badge or with an unknown badge is refused. No operation changes the policy. All signers share the one key, so a signature carries no client identity. +The operator can neither get a signature nor deliver a seed. A call without a badge or with an unknown badge is refused. No operation changes the policy. All signers share the one key, so a signature carries no client identity. ## The provider boundary `userspace/k0-vault/src/provider.rs` is the only place that touches the crypto crate. - **Self-test**: at start the vault runs a known-answer test with two RFC 8032 vectors (public key, signature, verification, and rejection of a changed message and of a changed signature). -- **Key generation and the entropy rule**: the vault refuses to make a key (status `NO_ENTROPY`) unless the boot seed contains at least 32 bytes of `rng-seed` or 256 bits from RNDR. QEMU virt provides a 32-byte `rng-seed`. -- **Pairwise test**: after key generation the vault checks that its own signature verifies. A failed self-test or a failed pairwise test puts the vault into a failed state that refuses everything but `STATUS`. +- **Seed check and the entropy rule**: `INIT` refuses the seed (status `NO_ENTROPY`) unless the boot seed contains at least 32 bytes of `rng-seed` or 256 bits from RNDR, and it refuses an all-zero seed. A vault in an image without an algorithm refuses the seed (`UNSUPPORTED`) and stays `fresh`. QEMU virt provides a 32-byte `rng-seed`. +- **Key generation**: `KEYGEN` makes the key from the held seed with the chosen algorithm and wipes the seed whether or not a key came out. +- **Pairwise test**: after key generation the vault checks that its own signature verifies. A failed self-test or a failed pairwise test puts the vault into the `failed` state that refuses everything but `STATUS`. - **Strict verification**: verification uses `verify_strict`. - **No key export**: no operation returns the key. -- **Zeroization**: `ZEROIZE` drops the key (the crate wipes it). The vault then refuses `SIGN` and `PUBLIC_KEY`. -- **Indicator bits**: every reply carries four bits: the algorithm is in FIPS 186-5, the self-tests passed, at least 32 `rng-seed` bytes went into the key seed, and RNDR went into the key seed. +- **Zeroization**: `ZEROIZE` drops the key (the crate wipes it) and the held seed. The vault then refuses `SIGN`, `PUBLIC_KEY` and `KEYGEN`. +- **Indicator bits**: every reply carries four bits: the algorithm is in FIPS 186-5, the self-tests passed, at least 32 `rng-seed` bytes went into the key seed, and RNDR went into the key seed. `STATUS` reports the last two also for a seed that the vault still holds. A bit means that the bytes were present, not that they were unpredictable. ## The boot seed path The kernel derives 32 bytes for the root task with SHA-256 under its own domain string from the DTB entropy, the counter and, when the CPU has RNDR, four fresh RNDR words (`k0_boot::derive_root_seed`). It is independent of the PAC keys by domain separation. The seed is as good as its inputs and no better. -The seed is delivered in the root task's entry registers `x0` to `x3`. `x4` holds how many `rng-seed` bytes were used (bits 15 to 0), and bit 16 says that RNDR contributed. It is not in the bootinfo page, and `bootinfo::VERSION` is 3. The root task prints only `root: boot seed from rng-seed bytes 0x... and rndr` or `... without rndr`, never the seed. It then gives the seed to the vault with `INIT`. +The seed is delivered in the root task's entry registers `x0` to `x3`. `x4` holds how many `rng-seed` bytes were used (bits 15 to 0), and bit 16 says that RNDR contributed. It is not in the bootinfo page, and `bootinfo::VERSION` is 4. The root task prints only `root: boot seed from rng-seed bytes 0x... and rndr` or `... without rndr`, never the seed. It then gives the seed to a vault with `INIT`, which only delivers it. The key is made later by `KEYGEN`. **Seed wipe**: the FDT parser records where the `rng-seed` and `kaslr-seed` values are, and a second `/chosen` node is refused (`DuplicateChosen`, also in the UEFI loader's pre-check, which shares the parser). Right before the kernel enters the root task, it zeroes those bytes. `k0_mm::wipe_ro_alias` switches the read-only alias entry of the page to read-write in place (break-before-make), writes zeros, cleans and invalidates the cache lines, and switches it back. The kernel then reads the bytes back, wipes its own copy in `BootInfo`, prints `k0: dtb seeds wiped B` (40B on QEMU virt) and zeroes the boot stack below the live frames. This is the only write the kernel makes through the DTB mapping, and it happens after the DTB was parsed and validated. > [!NOTE] -> Copies that the firmware or the UEFI loader keep are not wiped, and neither is anything in the live frames of the boot stack. The scrubs of stack copies (the kernel boot stack, the vault stack after signing) are best effort. +> Copies that the firmware or the UEFI loader keep are not wiped, and neither is anything in the live frames of the boot stack. The scrubs of stack copies (the kernel boot stack, the vault stack after key generation and signing) are best effort. + +## The service vault and the operator + +The real boot seed is used exactly once. In an image built with `terminal` and `vault`, the root task first runs all self-tests. Then it starts a new vault, the **service vault**, and hands it the boot seed with `INIT`. It prints `root: vault seeded`, or `root: vault has no seed (boot seed has no entropy)`, or `root: vault has no seed (no algorithm in this image)`. In every other image the root task wipes the seed at entry. + +The root task then runs two hostile tasks that are wired exactly like the terminal. They must be refused and end in a fault. After that it drops its own admin capability, starts the terminal and blocks for ever. The terminal can ask the service vault for `STATUS`, `PUBLIC_KEY`, `KEYGEN` and `ZEROIZE` through the operator badge, and for nothing else. The commands, the screen and the limits of the terminal are described in [USAGE.md](../../USAGE.md). + +> [!WARNING] +> The serial line has no authentication. Whoever holds the line is the operator and can run exactly the four operator operations, including erasing the key. The operator cannot get a signature and cannot change the policy. + +The self-test vault is a different vault. It makes its key from the public RFC 8032 test seed, with the real seed info, so the entropy rule is still exercised, and the real seed never reaches it. ## Features and the fixed image @@ -97,7 +135,13 @@ The `k0-kernel` crate has two features, and features only add: - `vault`: the service, its protocol, policy and self-test, with no signing algorithm. Every signing request answers `UNSUPPORTED`. - `vault-ed25519`: adds Ed25519. -You can build it as follows: +The feature `terminal` of the same crate adds the operator terminal. With `vault` the terminal is the operator of the vault, and with `vault-ed25519` it can make an Ed25519 key. It is off by default and needs a console driver. A terminal image is built as follows: + +```sh +$ cargo build -p k0-kernel --features console,terminal,vault-ed25519 +``` + +You can build an image with the vault as follows: ```sh $ cargo build -p k0-kernel --features console,vault-ed25519 @@ -107,17 +151,18 @@ $ cargo build -p k0-kernel --features console,vault-ed25519 ## How it is tested -**Host tests** (`tools/host-test.sh` runs `k0-vault` with and without the algorithm feature). The tests are in `userspace/k0-vault/src/tests.rs`: 13 with Ed25519 and 7 without. The test names are the following: +**Host tests** (`tools/host-test.sh` runs `k0-vault` with and without the algorithm feature). The tests are in `userspace/k0-vault/src/tests.rs`: 20 with Ed25519 and 11 without. The test names are the following: -- always: `badges_map_to_fixed_roles`, `policy_is_enforced_before_anything_else`, `malformed_requests_are_refused_whole`, `a_seed_without_real_entropy_makes_no_key`, `init_happens_once_and_zeroize_is_final`, `fetch_clamps_the_length_and_publish_writes_header_and_body`, and `without_an_algorithm_every_signing_request_is_unsupported` (the last one without the algorithm only). -- with Ed25519: `the_self_test_passes_and_is_reported`, `signatures_verify_and_the_key_follows_the_seed`, `a_public_key_request_carries_no_body`, `unknown_algorithms_are_unsupported`, `nothing_is_served_after_zeroize`, `a_small_order_public_key_is_refused_even_with_a_matching_signature`, `a_failed_vault_refuses_everything_but_status`. +- always: `badges_map_to_fixed_roles_and_frames`, `each_role_may_do_exactly_its_operations`, `no_frame_is_touched_for_a_request_that_cannot_have_a_body`, `a_request_that_claims_a_body_it_cannot_have_is_refused`, `the_status_word_packs_state_algorithm_and_what_is_built`, `a_call_without_a_known_badge_is_denied`, `malformed_requests_are_refused_whole`, `a_seed_without_real_entropy_makes_no_key`, `the_seed_is_taken_once_and_zeroize_is_final`, `fetch_clamps_the_length_and_publish_writes_header_and_body`, and `without_an_algorithm_the_vault_takes_no_seed_and_serves_nothing` (the last one without the algorithm only). +- with Ed25519: `the_self_test_passes_and_is_reported`, `key_generation_follows_the_states`, `the_operator_gets_the_public_key_and_never_a_signature`, `a_vault_that_fails_holds_no_secret`, `signatures_verify_and_the_key_follows_the_seed`, `a_public_key_request_carries_no_body`, `unknown_algorithms_are_unsupported`, `nothing_is_served_after_zeroize`, `a_small_order_public_key_is_refused_even_with_a_matching_signature`, `a_failed_vault_refuses_everything_but_status`. -With the other crates, the host suite has 276 tests on an ARM host and 190 on other hosts (without `k0-mm`). +With the other crates, the host suite has 354 tests on an ARM host and 268 on other hosts (without `k0-mm`). **Root task self-test** (`test_oracle` in `userspace/root-task/src/oracle.rs`, only in images built with `vault`). It checks the following: - the self-test is reported, and an unbadged call is refused, -- a key is made from the boot seed, and a second `INIT` is refused, +- the self-test vault gets the public RFC 8032 test seed with `INIT` (state `seeded`), the operator cannot seed or sign, and a second `INIT` is refused, +- `KEYGEN` makes the key from that seed, and a second `KEYGEN` is refused (`KEY_EXISTS`), - the admin cannot sign, - a signer client gets a signature that verifies, and that does not verify for a changed message or a changed signature, - a reader is refused `SIGN`, @@ -128,14 +173,16 @@ With the other crates, the host suite has 276 tests on an ARM host and 190 on ot The marker is `root: oracle tests pass`. The client tasks run one after another in one client address space, because root CNode slots are scarce. The test shows isolation between the vault and a client, not between clients. -**Boot matrix rows**: `vault`, `vault-max` (RNDR), `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`, and the static row `vault-symbols` (the default image has no vault or crypto code, and the vault image has no writable static from them). The matrix has 61 rows on a Mac with HVF and 51 in CI. Every image now also prints `k0: dtb seeds wiped B` and `root: boot seed from rng-seed bytes ...`. +**Boot matrix rows**: `vault`, `vault-max` (RNDR), `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`, and the static row `vault-symbols` (the default image has no vault or crypto code, and the vault image has no writable static from them). The matrix has 76 rows on a Mac with HVF and 65 in CI. The rows for the terminal are `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi` and `hvf-term`. `tools/term-test.py ` boots a terminal image with QEMU's serial port on pipes and runs a scripted session. Every image now also prints `k0: dtb seeds wiped B` and `root: boot seed from rng-seed bytes ...`. ## Known gaps > [!NOTE] > The implementation is unvalidated, there is no side-channel analysis of the crate on this kernel, and the oracle was only run in QEMU (TCG and HVF). -- **One key**: there is no persistence, no key import or export, no DRBG, no operator input and no post-quantum algorithm yet. +- **One key**: there is no persistence, no key import or export, no DRBG and no post-quantum algorithm yet. A new key needs a reboot. +- **No signing client in service mode**: the service vault's key is made and shown, but no other task uses it yet. Client signing is shown by the self-test. +- **The terminal and the vault are not restarted**: if they die, they stay dead. The root task is trusted. - **Availability is not protected**: clients share one endpoint and must use timeouts on every call (see [ipc.md](ipc.md)). - **The root task is trusted**: it builds the vault and could read it. - **No client identity**: all signers share the one key. diff --git a/design/kr/README.md b/design/kr/README.md index 88976b7..faa7f0f 100644 --- a/design/kr/README.md +++ b/design/kr/README.md @@ -26,5 +26,6 @@ | [scheduling_KR.md](scheduling_KR.md) | TCB와 거기에 묶인 CNode, 주소 공간, 태스크 생성과 정리, 라운드 로빈 스케줄러, 타이머 선점 | | [ipc_KR.md](ipc_KR.md) | 엔드포인트와 배지, `SEND`, `RECV`, `CALL`, `REPLY_RECV`, 1회성 응답 자격, 엔드포인트가 삭제될 때 대기 중인 태스크의 처리 | | [vault_KR.md](vault_KR.md) | 서명 오라클: 볼트 태스크와 프레임, `CALL` 프로토콜과 nonce, 고정된 배지 정책, 프로바이더 경계, 부팅 시드와 지우기, feature, 테스트, 알려진 공백 | +| [terminal_KR.md](terminal_KR.md) | 시리얼 입력과 운영자 터미널: 커널이 입력을 받는 이유, 수신 링과 그 한계, `CONSOLE_READ`와 Console 권한, 대기와 깨우기, 터미널의 연결과 적대적 태스크 점검, 화면과 명령 규칙, 테스트, 알려진 공백 | 모든 노트는 "**알려진 공백**" 절로 끝납니다. 열려 있는 보안 어드바이저리는 [SECURITY_KR.md](../../SECURITY_KR.md)에 정리되어 있습니다. diff --git a/design/kr/boot_KR.md b/design/kr/boot_KR.md index 771c4e8..4511bf9 100644 --- a/design/kr/boot_KR.md +++ b/design/kr/boot_KR.md @@ -102,7 +102,7 @@ $ cargo build -p k0-kernel --offline --no-default-features --features granule-16 | `k0: dtb rejected: ...` (실패할 때만) | `map_dtb`가 별칭을 통해 DTB를 읽기 전용으로 매핑합니다. 포인터(null이 아니고 8바이트 정렬)와, 매직과 전체 크기만 읽는 `dtb_span`을 검사합니다. | | `k0: memory ...` | 별칭을 통해 DTB를 파싱합니다. 파서는 [dtb_KR.md](dtb_KR.md)에서 다룹니다. | | `k0: console drivers [...]` | 플랫폼 기동의 첫 줄이며, 나중에 플랫폼이 거부되더라도 출력됩니다. 이 이미지에 들어 있는 콘솔 드라이버를 알려 줍니다("선택적 콘솔 출력" 참고). | -| `k0: platform ...` | `bring_up_platform`이 DTB에서 콘솔, 인터럽트 컨트롤러, 타이머 인터럽트를 찾아 불변인 플랫폼 기술서 하나를 만듭니다. 디바이스 페이지를 매핑하기 전에 기술서를 메모리 맵과 대조합니다. RAM은 2^47 아래여야 하고, 커널 이미지와 DTB는 선언된 메모리 안에 있어야 하며, 그래뉼 단위로 넓힌 디바이스 구간은 메모리나 예약 구간과 겹치거나 CPU의 물리 주소 폭(`k0_mm::pa_bits`)을 넘으면 안 됩니다. 고정 모드에서는 이어서 이 줄을 기대값과 비교합니다. 그 뒤에야 콘솔을 연결합니다. 이 종류의 콘솔 드라이버가 있는 이미지는 콘솔을 매핑하고 연결하며, 이때 버퍼에 쌓인 로그가 재생됩니다. 드라이버가 없는 이미지는 아무것도 매핑하지 않고 `k0: no console (driver not built in)`을 출력합니다. 플랫폼이 거부되더라도 콘솔만으로 대조를 통과하면(그리고 이미지가 고정 모드가 아니고 드라이버가 있으면) 사유가 보이도록 콘솔을 먼저 연결합니다. 콘솔이 없으면 `k0: no console (...)`이 이유를 알려 줍니다. [dtb_KR.md](dtb_KR.md)를 참고하세요. | +| `k0: platform ...` | `bring_up_platform`이 DTB에서 콘솔, 콘솔의 인터럽트(콘솔 노드에 쓸 만한 것이 있을 때), 인터럽트 컨트롤러, 타이머 인터럽트를 찾아 불변인 플랫폼 기술서 하나를 만듭니다. 디바이스 페이지를 매핑하기 전에 기술서를 메모리 맵과 대조합니다. RAM은 2^47 아래여야 하고, 커널 이미지와 DTB는 선언된 메모리 안에 있어야 하며, 그래뉼 단위로 넓힌 디바이스 구간은 메모리나 예약 구간과 겹치거나 CPU의 물리 주소 폭(`k0_mm::pa_bits`)을 넘으면 안 됩니다. 이 줄에는 콘솔 인터럽트 번호가 들어갑니다(예: `k0: platform con=pl011@0x9000000,irq33 ...`). 고정 모드에서는 이어서 이 줄을 기대값과 비교하므로, 이 필드가 생기기 전에 만든 고정 문자열은 더 이상 맞지 않아 다시 만들어야 합니다. 그 뒤에야 콘솔을 연결합니다. 이 종류의 콘솔 드라이버가 있는 이미지는 콘솔을 매핑하고 연결하며, 이때 버퍼에 쌓인 로그가 재생됩니다. 드라이버가 없는 이미지는 아무것도 매핑하지 않고 `k0: no console (driver not built in)`을 출력합니다. 플랫폼이 거부되더라도 콘솔만으로 대조를 통과하면(그리고 이미지가 고정 모드가 아니고 드라이버가 있으면) 사유가 보이도록 콘솔을 먼저 연결합니다. 콘솔이 없으면 `k0: no console (...)`이 이유를 알려 줍니다. [dtb_KR.md](dtb_KR.md)를 참고하세요. | | `k0: root task integrity ok (...)` | 내장 루트 태스크 이미지를 다시 해시하고 빌드 시점에 고정된 해시와 비교합니다. | | `k0: entropy ...`, `k0: pac=... bti=... pan=...` | PAC 키를 파생해 적재하고 키 워드를 부트 스택에서 지웁니다. 루트 태스크에 넘길 32바이트 시드도 여기서 PAC 키와 독립적으로 파생하여 이양까지 보관합니다. PAN을 켜고, 카운터·디버그·PMU에 대한 EL0 접근을 끕니다. [hardening_KR.md](hardening_KR.md)를 참고하세요. | | `k0: irq on (timer 1s)` | `setup_irq`가 필요한 인터럽트 컨트롤러 페이지만 매핑합니다. GICv3는 리디스트리뷰터 프레임을 하나씩 들여다보며 부트 CPU의 프레임을 찾은 뒤, 그 프레임과 SGI 프레임만 매핑합니다. 드라이버는 GIC 식별 레지스터가 DTB의 설명과 맞는지 확인합니다. EL1 가상 타이머는 플랫폼 기술서의 인터럽트 번호로 설정합니다. IRQ와 SError의 마스크를 해제합니다. | @@ -110,7 +110,8 @@ $ cargo build -p k0-kernel --offline --no-default-features --features granule-16 | `k0: root task loaded (entry ...)` | 루트 태스크를 윈도우의 프레임에 복사하고, 윈도우에 루트 TCB를 만들고, 주소 공간을 만듭니다. 커널은 사용자 루트 테이블의 물리 주소를 출력하지 않습니다. 이후 이 주소 공간을 주소 공간 등록부에 올립니다. [user-address-space_KR.md](user-address-space_KR.md)를 참고하세요. | | `k0: memory + not handed out ()`(일어날 때만), `k0: kernel reserve tables + address space entries = bytes in ranges` | `reserve_kernel_share`가 untyped 케이퍼빌리티가 만들어지기 전에 비어 있는 물리 범위마다 커널 몫을 떼어 냅니다("untyped 메모리에서 커널 몫 떼어 내기" 참고). 자기 몫을 담지 못하는 범위는 넘기지 않으며, 이때 커널은 첫 번째 종류의 줄에 이유를 출력합니다. 두 번째 줄은 한 번 출력됩니다. 예를 들어 512 MiB, 4 KiB 그래뉼의 QEMU virt에서는 `k0: kernel reserve 262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges`입니다. | | `k0: untyped ...`, `k0: root cnode ready (N caps, N untyped, N image frames, N slots)` | 루트 CNode(윈도우 안의 오브젝트이며 슬롯은 `ROOT_CNODE_SLOTS` = 512개, 로그에도 그렇게 나옵니다)를 채웁니다. 슬롯 1은 루트 TCB, 2는 루트 주소 공간, 3은 콘솔, 4는 루트 CNode 자신이고, 이어서 넘기기로 한 비어 있는 물리 범위마다 untyped 케이퍼빌리티, 루트 태스크 이미지의 매핑된 그래뉼마다 Frame 케이퍼빌리티 하나(text는 R과 X, 읽기 전용 데이터는 R, 데이터는 R과 W)가 들어갑니다. 마지막으로 루트 태스크를 다른 태스크와 똑같이 자신의 CNode와 주소 공간에 묶습니다. 두 케이퍼빌리티의 복사본이 TCB에 들어갑니다. [capabilities_KR.md](capabilities_KR.md)를 참고하세요. | -| `k0: bootinfo page ready` | 케이퍼빌리티 목록을 읽기 전용 bootinfo 페이지(레이아웃 버전 3)에 기록합니다. 헤더와 슬롯마다 하나의 디스크립터이며, 이미지 Frame마다 VA, 크기, 권한이 들어갑니다. 이 페이지에는 부트 시드가 들어 있지 않습니다. | +| `k0: console input on (pl011 irq 33)` 또는 `k0: console input off ()` | `console-input`으로 빌드한 이미지만 플랫폼이 받아들여진 직후에 출력합니다. "선택적 콘솔 입력"을 참고하십시오. | +| `k0: bootinfo page ready` | 케이퍼빌리티 목록을 읽기 전용 bootinfo 페이지(레이아웃 버전 4)에 기록합니다. 헤더와 슬롯마다 하나의 디스크립터이며, 이미지 Frame마다 VA, 크기, 권한이 들어갑니다. 이 페이지에는 부트 시드가 들어 있지 않습니다. | | `k0: user w^x checks pass` | `TTBR0`가 사용자 테이블을 가리키고, identity 매핑은 사라졌으며, 사용자 매핑을 EL0와 EL1 양쪽에서 검사합니다. | | `k0: dtb seeds wiped B` | 이제 DTB는 필요 없으므로 커널이 그 안의 `rng-seed`와 `kaslr-seed` 바이트를 0으로 지웁니다(읽기 전용 별칭을 쓰는 동안만 읽기·쓰기로 바꿈). 지운 바이트를 다시 읽어 확인하고, 커널이 가진 자기 사본도 지웁니다. QEMU virt에서는 `40B`입니다. 다시 읽은 값이 0이 아니면 줄은 `k0: WARNING dtb seeds not wiped`가 됩니다. [hardening_KR.md](hardening_KR.md)를 참고하세요. | | `k0: device pages [...] of 0x1000 bytes` | 커널이 매핑한 채로 두는 모든 디바이스 페이지입니다. 이 줄 뒤에 커널은 더 이상 디바이스를 매핑하지 않습니다. | @@ -153,12 +154,9 @@ $ cargo build -p k0-kernel --offline --no-default-features --features granule-16 ## 선택적 콘솔 출력 -K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트(`k0-kernel`)의 Cargo features로 선택할 수 있습니다. +K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트(`k0-kernel`)의 Cargo features로 선택할 수 있습니다. 콘솔 출력은 아래 콘솔 feature로 선택합니다. 콘솔 입력과 운영자 터미널에는 별도의 feature가 있으며, "선택적 콘솔 입력"에서 설명합니다. -> [!NOTE] -> 입력 또는 터미널용 feature는 아직 없습니다. 지금 선택할 수 있는 것은 콘솔 출력뿐입니다. - -콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다(옵트인). 입력은 어떤 이미지에도 없습니다. 다음 그림은 빌드에 포함한 feature에 따라 출력이 닿는 곳을 보여 줍니다. +콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다(옵트인). `console-input` 없이 빌드한 이미지에는 입력 코드가 전혀 없습니다. 다음 그림은 빌드에 포함한 feature에 따라 출력이 닿는 곳을 보여 줍니다.

콘솔 feature 없이 빌드한 이미지는 메모리의 부트 로그에만 출력하고, 콘솔 feature로 빌드한 이미지는 해당 UART에도 출력합니다 @@ -219,11 +217,30 @@ $ K0_PIN='...' cargo build -p k0-kernel --features console --offline --target-di **기여자 규칙**: 다음 규칙을 지켜야 합니다. -- 새로운 입력 또는 출력 경로는 처음부터 Cargo feature 뒤에 둡니다(지금 있는 것은 콘솔 출력뿐입니다). +- 새로운 입력 또는 출력 경로는 처음부터 Cargo feature 뒤에 둡니다(지금 있는 것은 콘솔 출력, `console-input`, `terminal`입니다). - feature는 더하기만 하며 `default`에 추가하지 않습니다. - 지원하는 조합마다 부팅 매트릭스에 행을 둡니다. - 스크립트, `virt` 별칭, CI는 feature를 명시합니다. +### 선택적 콘솔 입력 + +콘솔 입력은 두 번째 옵트인 계층입니다. 기본값은 꺼짐이며, feature는 기능을 더하기만 합니다. 다음 표는 `k0-kernel`의 feature를 보여 줍니다. + +| Feature | 추가하는 것 | +| --- | --- | +| `console-input` | 콘솔 UART의 커널 수신 경로와 시스템 콜 `CONSOLE_READ`([exceptions_KR.md](exceptions_KR.md) 참고). 콘솔 드라이버 feature가 있어야 동작합니다. 수신은 PL011과 SBSA UART에만 있어서, 16550 콘솔은 출력만 있고 입력은 없습니다. | +| `terminal` | 루트 태스크 이미지에 들어가는 운영자 터미널 태스크. `console-input`을 함께 켭니다. | + +> [!NOTE] +> `console-input` 없이 빌드한 이미지에는 수신 코드도, `CONSOLE_READ`도, 아래 로그 줄도 없습니다. 정적 매트릭스 행 `input-symbols`가 이를 검사합니다. + +- **기동**: 콘솔 인터럽트 번호는 디바이스 트리([dtb_KR.md](dtb_KR.md) 참고)에서 오고, UEFI에서는 ACPI SPCR 테이블에서 옵니다. 이 번호는 `k0: platform` 줄에 들어갑니다. 수신 인터럽트는 태스크가 읽기 권리로 콘솔 입력을 처음 읽을 때까지 꺼져 있습니다. 쓸 만한 인터럽트가 없는 콘솔 노드는 부팅 거부 사유가 아니며, 입력만 꺼집니다. +- **로그 줄**: `k0: console input on (pl011 irq 33)` 또는 `k0: console input off ()`입니다. 이유는 `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range`, `interrupt not available`입니다. 인터럽트 번호가 틀려도 입력 경로만 잃습니다. +- **첫 읽기**: 장치가 쥐고 있던 바이트를 버리고, 줄 하나 `k0: tick lines off (console input in use)`를 남긴 뒤 주기적인 `k0: tick N` 줄을 멈춥니다. 틱, 선점, 타임아웃은 그대로 동작합니다. +- **증거**: 행 `input-only`, `input-gicv2`, `input-16550`, `input-bad-irq`, `input-symbols`(정적), `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi`, `hvf-term`이 `tools/boot-matrix.sh`에 있습니다. `tools/qemu-boot-test.sh`는 `K0_BOOT_INPUT=on|off`, `K0_BOOT_SERVICE=vault|plain|none`, 판정 전용 `K0_BOOT_JUDGE`를 읽습니다. `tools/term-test.py `는 QEMU 시리얼 포트로 스크립트 터미널 세션을 실행합니다. + +SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU에서 실행되지 않습니다. 가짜 UART를 쓰는 호스트 테스트(`crates/k0-conin`)만 이를 다룹니다. + ## 신뢰 문제 이제 DTB가 디바이스 주소를 제공하므로, 잘못되었거나 적대적인 DTB는 콘솔을 다른 디바이스로 향하게 할 수 있습니다. 커널은 다음 다섯 가지로 이를 제한합니다. @@ -302,5 +319,5 @@ $ cargo build -p k0-kernel --features console --offline - 코어 하나만 실행되며, 부트로더가 CPU를 정확히 하나만 진입시켜야 합니다. K0에는 다른 CPU를 시작하거나 파킹하는 코드가 없습니다. - 커널은 항상 같은 가상 주소에 놓입니다. 주소 무작위화가 없습니다. - 릴리즈 빌드는 패닉 때 아무것도 출력하지 않습니다. 의도한 동작이지만, 릴리즈 빌드에서는 패닉이 나도 진단을 얻을 수 없다는 뜻이기도 합니다. -- 입력은 어떤 이미지에도 없습니다. 콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있으며, 그 증거의 한계는 "선택적 콘솔 출력"에 있습니다. +- 콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있고, 콘솔 입력은 `console-input`으로 빌드한 이미지에만 있습니다. 그 증거의 한계는 "선택적 콘솔 출력"과 "선택적 콘솔 입력"에 있습니다. - UEFI에서는 로더의 캐시 비우기와 MMU 끄기를 QEMU로 테스트할 수 없고(캐시가 없습니다), ACPI만 있는 펌웨어는 세 정적 테이블만으로 부팅합니다(부팅해 본 것은 QEMU virt뿐입니다). 로더의 한계는 [uefi_KR.md](uefi_KR.md)에 모두 있습니다. diff --git a/design/kr/capabilities_KR.md b/design/kr/capabilities_KR.md index a6bdd90..53d7a0c 100644 --- a/design/kr/capabilities_KR.md +++ b/design/kr/capabilities_KR.md @@ -23,7 +23,7 @@ | `crates/k0-abi/src/lib.rs` | 번호와 에러 코드(ABI의 기준) | > [!IMPORTANT] -> 이 모델과 함께 시스템 콜 ABI가 호환되지 않게 바뀌었습니다(bootinfo 버전 2, 현재 3). 이 내용에 의존하기 전에 "알려진 공백" 절을 먼저 읽어 주세요. +> 이 모델과 함께 시스템 콜 ABI가 호환되지 않게 바뀌었습니다(bootinfo 버전 2, 현재 4). 이 내용에 의존하기 전에 "알려진 공백" 절을 먼저 읽어 주세요. 케이퍼빌리티 기반 격리가 다루는 것은 태스크 간 기밀성과 무결성입니다. 가용성은 포함하지 않습니다. @@ -66,14 +66,15 @@ | `Endpoint` | `RETYPE`으로 | 동기 IPC의 랑데부 지점 | | `CNode` | `RETYPE`으로, 그리고 루트 CNode용으로 부팅 시 | 슬롯 배열. 케이퍼빌리티 공간이자 복사와 이동의 목적지로 쓰임 | | `AddrSpace` | `RETYPE`으로, 그리고 루트 태스크용으로 부팅 시 | 주소 공간. 그 안에 매핑하고 그 안에서 태스크를 실행할 권한 | -| `Console` | 부팅 시 | 디버그 출력에 바이트를 쓸 권한. 부트 로그, 그리고 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔 | +| `Console` | 부팅 시 | 디버그 출력에 바이트를 쓸 권한(`W`). 부트 로그, 그리고 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔. `R`이 있으면 `console-input`으로 빌드한 이미지에서 콘솔 입력을 읽을 권한도 됨 | ### 권한 -**권한 비트**는 `R` = 1, `W` = 2, `X` = 4입니다. 의미를 갖는 종류는 둘뿐입니다. +**권한 비트**는 `R` = 1, `W` = 2, `X` = 4입니다. 의미를 갖는 종류는 셋뿐입니다. - **Frame**: 매핑 권한의 상한입니다. `RO`는 `R`, `RW`는 `R|W`, `RX`는 `R|X`가 필요합니다. `RETYPE`으로 만든 프레임은 `R|W`를 갖고, `X`는 영영 얻을 수 없습니다. - **Endpoint**: `R`은 수신, `W`는 송신 권한입니다. 새 엔드포인트 케이퍼빌리티는 둘 다 가집니다. +- **Console**: `W`는 출력 권한(`DEBUG_PUTC`), `R`은 입력을 읽을 권한(`CONSOLE_READ`)입니다. `CAP_COPY`는 이 권한을 줄이는 것만 가능하며, 권한이 하나도 남지 않는 복사는 `NO_RIGHTS`로 실패합니다. `R`이 있는 `Console` 케이퍼빌리티는 `DEBUG_PUTC`로 백스페이스 바이트(0x08)도 내보낼 수 있습니다. 다른 제어 바이트는 여전히 `?`로 출력됩니다. 다른 종류는 권한을 갖지 않으며, 그 종류에서는 `CAP_COPY`의 권한 마스크가 무시됩니다. **권한은 줄이는 것만 가능**하며, 줄이는 방법은 `CAP_COPY`뿐입니다. @@ -114,7 +115,7 @@ | 0 | null | | 1 | 루트 태스크의 `Tcb` | | 2 | 루트 태스크의 `AddrSpace` | -| 3 | `Console` | +| 3 | `W`가 있는 `Console`. `R`은 `console-input`으로 빌드한 이미지에만 있음 | | 4 | `CNode`. 루트 CNode 자신에 대한 케이퍼빌리티로, 복사와 이동의 목적지로 쓸 수 있음 | | 5 이후 | `Untyped` 케이퍼빌리티들, 그다음 루트 태스크 이미지의 매핑된 그래뉼마다 `Frame` 케이퍼빌리티 하나 | @@ -138,7 +139,7 @@ untyped 케이퍼빌리티는 디바이스 트리가 보고한 RAM의 모든 바 ## bootinfo 페이지 -이양 직전에 커널은 루트 CNode의 설명을 bootinfo 페이지에 기록합니다. 이 페이지는 루트 태스크에 읽기 전용으로 `bootinfo::VA`에 매핑됩니다. 버전은 3입니다(`bootinfo::VERSION`). 페이지 레이아웃은 버전 2와 같습니다. 버전이 바뀐 이유는 루트 태스크가 이제 진입 레지스터로 부트 시드를 받기 때문이며(시드는 `x0..x3`, 그 설명은 `x4`)(자세한 내용은 [boot_KR.md](boot_KR.md) 참고), 시드는 이 페이지에 없습니다. 다른 버전이면 루트 태스크는 진행하면 안 됩니다. +이양 직전에 커널은 루트 CNode의 설명을 bootinfo 페이지에 기록합니다. 이 페이지는 루트 태스크에 읽기 전용으로 `bootinfo::VA`에 매핑됩니다. 버전은 4입니다(`bootinfo::VERSION`). 페이지 레이아웃은 버전 2와 같습니다. 버전 3은 루트 태스크가 진입 레지스터로 부트 시드를 받게 되어 생겼으며(시드는 `x0..x3`, 그 설명은 `x4`)(자세한 내용은 [boot_KR.md](boot_KR.md) 참고), 시드는 이 페이지에 없습니다. 버전 4는 `Console` 케이퍼빌리티에 권한이 생겨 만들어졌습니다. 다른 버전이면 루트 태스크는 진행하면 안 됩니다. 페이지는 헤더 `{version, frame_size, cap_count, cnode_slots}`로 시작하고, 그 뒤에 `cap_count`개의 디스크립터 `{kind, base, size, rights}`가 이어집니다. 디스크립터의 인덱스가 곧 루트 CNode의 슬롯 번호이며, `cap_count` 이상의 슬롯은 전부 비어 있습니다. 디스크립터는 종류에 따라 다음과 같이 채워집니다. @@ -232,6 +233,7 @@ untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조 - **Frame**: 이 케이퍼빌리티가 만든 매핑을 지웁니다. 복사본을 포함해 매핑 기록이 있는 모든 `Frame` 케이퍼빌리티에 해당합니다. - **PageTable**: 주소 공간에서 연결을 끊습니다(마찬가지로 기록이 있는 모든 케이퍼빌리티에 해당). - **Endpoint**(원본): 줄 서 있던 태스크를 전부 `REVOKED`로 깨웁니다. +- **Console**: 이 케이퍼빌리티로 `CONSOLE_READ`에서 기다리던 태스크는 케이퍼빌리티가 삭제, 회수, 이동되면 즉시 `REVOKED`로 깨어납니다([ipc_KR.md](ipc_KR.md) 참고). - **Tcb**(원본), 그리고 태스크에 묶인 모든 케이퍼빌리티: 그 태스크를 종료시킵니다. [scheduling_KR.md](scheduling_KR.md)와 [ipc_KR.md](ipc_KR.md)를 참고하세요. - **AddrSpace**(원본): 등록부에서 해제하고(이때 세대가 올라갑니다), TTBR0에 설치돼 있으면 TTBR0를 커널 풀의 빈 테이블로 바꿉니다. @@ -247,7 +249,8 @@ untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조 | 시스템 콜 | 필요한 케이퍼빌리티와 권한 | | --- | --- | -| `DEBUG_PUTC` | `Console` | +| `DEBUG_PUTC` | `W`가 있는 `Console` | +| `CONSOLE_READ` | `R`이 있는 `Console`(`console-input`으로 빌드한 이미지에만 있음) | | `RETYPE` | `Untyped`, 그리고 호출자 CNode의 빈 목적지 슬롯 | | `MAP` | 권한이 요청한 매핑을 덮는 `Frame`(`RO`는 `R`, `RW`는 `R\|W`, `RX`는 `R\|X` 필요) 또는 `PageTable`, 그리고 타겟을 지정하는 `AddrSpace` | | `UNMAP` | 매핑된 `Frame` 또는 `PageTable` | @@ -280,7 +283,7 @@ untyped를 회수하면 거기서 잘라낸 것이 전부 종료됩니다. 조 | `BAD_PERM` | 매핑 권한이나 권한 마스크 값이 올바르지 않음 | | `BAD_BADGE` | 배지를 가질 수 없는 종류에 배지를 요구했거나, 이미 배지가 있는 케이퍼빌리티에 다른 배지를 요구함 | | `TOO_DEEP` | 파생 깊이 상한을 넘게 됨 | -| `REVOKED` | 대기 중이던 엔드포인트가 삭제되어 깨어난 태스크가 받음 | +| `REVOKED` | 대기 중이던 엔드포인트가 삭제되어 깨어난 태스크가 받음. `CONSOLE_READ`로 기다리던 `Console` 케이퍼빌리티가 삭제, 회수, 이동되어 깨어난 태스크도 받음 | | `KERNEL_RESOURCE` | 커널 내부 자원 부족. 여전히 정의된 코드이지만, 커널 별칭 테이블과 주소 공간 등록부는 더 이상 원인이 될 수 없음 | ## 테스트 방법 diff --git a/design/kr/dtb_KR.md b/design/kr/dtb_KR.md index 16fb372..6381254 100644 --- a/design/kr/dtb_KR.md +++ b/design/kr/dtb_KR.md @@ -95,9 +95,10 @@ MMU가 켜진 상태에서 커널이 블롭을 읽으려면 먼저 매핑해야 ## 플랫폼 기술서 -메모리 외에 커널이 DTB에서 찾는 디바이스는 정확히 세 가지이며 그 밖에는 없습니다(`crates/k0-boot/src/platform.rs`의 `discover`). +메모리 외에 커널이 DTB에서 찾는 디바이스는 정확히 세 가지와 콘솔의 인터럽트뿐이며 그 밖에는 없습니다(`crates/k0-boot/src/platform.rs`의 `discover`). - **콘솔**: `/chosen/stdout-path`가 가리키는 노드뿐입니다(절대 경로, 또는 절대 경로로 풀리는 별칭). 노드는 사용 가능해야 하고, `compatible`이 PL011(`arm,pl011`), SBSA UART(`arm,sbsa-uart`), 16550 계열(`ns16550a`, `ns16550`, `snps,dw-apb-uart`, `brcm,bcm2835-aux-uart`) 중 하나여야 합니다. 그 밖의 UART, 없거나 풀리지 않는 `stdout-path`, CPU 물리 주소로 변환할 수 없는 노드는 콘솔 없이 부팅합니다. 에러가 아닙니다. 커널은 이유와 함께 `k0: no console (...)`을 출력하고, 부트 로그 버퍼가 유일한 기록이 됩니다([boot_KR.md](boot_KR.md) 참고). 이 발견과 검증은 모든 이미지가 수행하며, 콘솔 드라이버 없이 빌드한 이미지도 마찬가지입니다. 그런 이미지는 아무것도 매핑하지 않고 `k0: no console (driver not built in)`을 출력하며, 콘솔이 검사를 통과하지 못하는 디바이스 트리는 다른 경우와 똑같이 거부합니다. 드라이버가 건드리는 레지스터 범위는 선언된 `reg` 안, 그리고 한 그래뉼 안에 있어야 합니다. + - **콘솔 인터럽트**(`console-input`으로 빌드한 이미지만 읽음, [boot_KR.md](boot_KR.md) 참고): 콘솔 노드의 `interrupts` 속성입니다. 인터럽트 부모가 발견한 GIC이고 속성이 레벨 타입·액티브 하이의 SPI 하나(셀 3개, 첫 셀 0)일 때만 받습니다. 번호는 SPI 번호에 32를 더한 값입니다. 속성이 없거나 다른 형태이거나 부모가 다른 콘솔 노드는 오류가 아닙니다. 플랫폼에 콘솔 인터럽트가 없고 입력이 꺼질 뿐입니다. 범위를 벗어난 번호는 입력을 기동할 때 걸러집니다(`k0: console input off (...)`). - **인터럽트 컨트롤러**: 타이머 노드(`arm,armv8-timer` 또는 `arm,armv7-timer`, 사용 가능한 노드는 정확히 하나)의 인터럽트 부모가 가리키는 노드입니다. 기대하는 셀 수와 프레임 정렬을 갖춘 GICv3(`arm,gic-v3`) 또는 GICv2(`arm,gic-400`, `arm,cortex-a15-gic`, `arm,cortex-a7-gic`)여야 합니다. GICv3 리디스트리뷰터 구간은 최대 4개까지 받습니다. 중복된 phandle, 비활성 노드, `interrupt-map`, CPU별 뱅크가 없는 GICv2(`cpu-offset`)는 거부합니다. - **EL1 가상 타이머의 인터럽트 번호**: 타이머 노드의 `interrupts`에서 가져오며(`interrupt-names`가 있으면 `virt` 항목, 없으면 세 번째 항목) PPI 번호에 16을 더한 값입니다. 타이머 정오표를 선언한 타이머 노드(`fsl,erratum-a008585`, `hisilicon,erratum-161010101`, `allwinner,erratum-unknown1`)는 우회 코드가 없으므로 거부합니다. @@ -106,7 +107,7 @@ MMU가 켜진 상태에서 커널이 블롭을 읽으려면 먼저 매핑해야 레지스터 주소는 부모 버스의 `ranges`를 따라 CPU 물리 주소로 변환합니다. `ranges`가 없는 버스는 변환할 수 없습니다. -결과는 불변인 `Platform` 값 하나입니다. 커널은 이를 정해진 형식의 한 줄 `k0: platform con=... gic=... tmr=...`로 출력합니다. 디바이스 페이지를 매핑하기 전에 `Platform::validate`가 기술서를 메모리 맵과 대조합니다. 대조 항목은 다음과 같습니다. +결과는 불변인 `Platform` 값 하나입니다. 커널은 이를 정해진 형식의 한 줄 `k0: platform con=... gic=... tmr=...`로 출력합니다. 콘솔 필드에는 인터럽트가 있을 때 그 번호가 들어갑니다(예: `con=pl011@0x9000000,irq33`). 디바이스 페이지를 매핑하기 전에 `Platform::validate`가 기술서를 메모리 맵과 대조합니다. 대조 항목은 다음과 같습니다. - RAM은 2^47 아래여야 합니다. - 커널 이미지와 DTB는 선언된 메모리 안에 있어야 합니다. @@ -126,7 +127,7 @@ MMU가 켜진 상태에서 커널이 블롭을 읽으려면 먼저 매핑해야 ### 고정 모드 -플랫폼 줄, 진입 예외 레벨, RAM 범위는 `<플랫폼 줄> el= ram=-` 문자열이 됩니다. 빌드할 때 `K0_PIN`에 타겟의 부트 로그에서 `k0: platform ` 뒤의 문자열을 설정했다면, 이 문자열이 다를 때 이미지가 부팅을 거부합니다. 잘못된 보드나 바뀐 DTB를 잡아냅니다. 비교하는 값이 DTB에서 나온 값이므로, **적대적인 부트 체인에 대한 방어는 아닙니다**. +플랫폼 줄, 진입 예외 레벨, RAM 범위는 `<플랫폼 줄> el= ram=-` 문자열이 됩니다. 빌드할 때 `K0_PIN`에 타겟의 부트 로그에서 `k0: platform ` 뒤의 문자열을 설정했다면, 이 문자열이 다를 때 이미지가 부팅을 거부합니다. 잘못된 보드나 바뀐 DTB를 잡아냅니다. 콘솔 인터럽트가 플랫폼 줄에 들어오기 전에 만든 고정 문자열은 더 이상 맞지 않아 다시 만들어야 합니다. 비교하는 값이 DTB에서 나온 값이므로, **적대적인 부트 체인에 대한 방어는 아닙니다**. ## 테스트 방법 diff --git a/design/kr/exceptions_KR.md b/design/kr/exceptions_KR.md index 0bb183a..5148536 100644 --- a/design/kr/exceptions_KR.md +++ b/design/kr/exceptions_KR.md @@ -20,7 +20,7 @@ ## 벡터 테이블 -AArch64는 벡터 엔트리를 16개 가집니다. 4가지 발생 위치마다 예외 종류(동기, IRQ, FIQ, SError)가 4개씩입니다. K0는 각 엔트리에 네 가지 동작 중 하나를 부여합니다. 커널은 IRQ만 받으므로 FIQ는 일어나서는 안 되는 상태입니다. FIQ 엔트리는 디스패처를 호출해 `k0: UNEXPECTED fiq intid=0`을 출력하고 파킹합니다. 다음 표는 엔트리별 동작입니다. +AArch64는 벡터 엔트리를 16개 가집니다. 4가지 발생 위치마다 예외 종류(동기, IRQ, FIQ, SError)가 4개씩입니다. K0는 각 엔트리에 네 가지 동작 중 하나를 부여합니다. 커널은 IRQ만 받고 FIQ는 받지 않으므로 FIQ는 일어나서는 안 되는 상태입니다. FIQ 엔트리는 디스패처를 호출해 `k0: UNEXPECTED fiq intid=0`을 출력하고 파킹합니다. 다음 표는 엔트리별 동작입니다. | 발생 위치 | 동기 | IRQ | FIQ | SError | | --- | --- | --- | --- | --- | @@ -86,7 +86,7 @@ FP/SIMD 레지스터는 컨텍스트에 포함되지 않습니다. EL0의 모든 | 번호 | 호출 | 설명 | | --- | --- | --- | -| 0 | `DEBUG_PUTC` | 필터를 거친 바이트 하나를 부트 로그에 기록하고, 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔에도 출력. `Console` 케이퍼빌리티가 필요 | +| 0 | `DEBUG_PUTC` | 필터를 거친 바이트 하나를 부트 로그에 기록하고, 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔에도 출력. 쓰기 권리가 있는 `Console` 케이퍼빌리티가 필요 | | 1 | `YIELD` | 준비 큐의 맨 뒤로 이동 | | 2 | `EXIT` | 호출한 태스크 종료 | | 3 | `RETYPE` | untyped 메모리에서 커널 오브젝트를 만들어 호출자가 지정한 목적지 슬롯에 추가함 | @@ -102,6 +102,7 @@ FP/SIMD 레지스터는 컨텍스트에 포함되지 않습니다. EL0의 모든 | 13 | `CAP_MOVE` | 케이퍼빌리티를 다른 슬롯으로 이동 | | 14 | `CAP_DELETE` | 케이퍼빌리티와 거기서 파생된 모든 것을 삭제 | | 15 | `CAP_REVOKE` | 케이퍼빌리티에서 파생된 모든 것을 삭제하고 케이퍼빌리티 자신은 남김 | +| 16 | `CONSOLE_READ` | 콘솔 입력 바이트 하나를 읽음(`console-input`으로 빌드한 이미지에만 있음, 아래 참고). 읽기 권리가 있는 `Console` 케이퍼빌리티가 필요 | > [!IMPORTANT] > 알 수 없는 번호는 단순한 오류 코드로 끝나지 않습니다. K0는 이를 태스크가 손상되었거나 악의적이라는 신호로 보고, `k0: unknown syscall N, killing task`를 출력한 뒤 호출자를 종료합니다. @@ -134,19 +135,29 @@ k0: task fault dabort-lower (esr 0x92000046 elr 0x400398 far 0x0), killing task | `k0: idle (waiting for a timeout)` | 기한을 가진 대기자가 하나 이상 있는 채로 커널이 처음 대기할 때 | | `k0: all tasks stopped (none ready, no timeout pending)` | 기한을 가진 대기자가 없는 채로 커널이 처음 대기할 때 | -두 번째 상태에서는 지금으로서는 태스크를 깨울 수단이 없습니다. 알림 오브젝트도, 태스크용 장치 인터럽트도 없기 때문입니다. 기계는 대기 상태로 남습니다. `tools/qemu-boot-test.sh`는 `k0: all tasks`로 시작하는 줄이 나오면 실패로 판정합니다. +두 번째 상태에서는 지금으로서는 태스크를 깨울 수단이 없습니다. 알림 오브젝트도, 콘솔 입력을 제외하면 태스크용 장치 인터럽트도 없기 때문입니다. 기계는 대기 상태로 남습니다. `console-input` 이미지에서는 콘솔 입력을 기다리는 태스크도 대기자로 셉니다. 기다릴 것이 콘솔 입력뿐이면 커널은 아무것도 출력하지 않으며, 이것이 터미널 이미지의 정상 상태입니다. 두 번째 줄은 기한이 있는 대기자도 콘솔 대기자도 없을 때만 출력됩니다. `tools/qemu-boot-test.sh`는 `k0: all tasks`로 시작하는 줄이 나오면 실패로 판정합니다. ## EL0의 타이머 인터럽트 -커널이 켜는 인터럽트는 **EL1 가상 타이머 하나뿐**입니다. 인터럽트 번호는 DTB에서 가져오며, 커널은 물리 타이머를 사용하지 않습니다. 인터럽트 컨트롤러는 DTB가 타이머의 인터럽트 부모로 가리키는 GICv2 또는 GICv3입니다. 드라이버는 레지스터에 기록하기 전에 식별 레지스터를 그 기술과 대조하고, 다르면 부팅을 거부합니다. [dtb_KR.md](dtb_KR.md)를 참고하세요. +커널이 항상 켜는 인터럽트는 **EL1 가상 타이머**입니다. `console-input`으로 빌드한 이미지는 콘솔 UART의 수신 인터럽트를 하나 더 받습니다(아래 참고). 인터럽트 번호는 DTB에서 가져오며, 커널은 물리 타이머를 사용하지 않습니다. 인터럽트 컨트롤러는 DTB가 타이머의 인터럽트 부모로 가리키는 GICv2 또는 GICv3입니다. 드라이버는 레지스터에 기록하기 전에 식별 레지스터를 그 기술과 대조하고, 다르면 부팅을 거부합니다. [dtb_KR.md](dtb_KR.md)를 참고하세요. EL0에서 받은 IRQ는 시스템 콜과 같은 방식으로 저장됩니다. 핸들러는 인터럽트를 확인합니다. 타이머였다면 타이머를 1초 뒤로 다시 설정하고 `k0: tick N`을 출력합니다. 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔에 출력하며, 로그에는 처음 4개의 tick 줄만 남깁니다. 그다음 `k0_preempt`를 호출합니다. 이 함수는 먼저 기한이 된 IPC 타임아웃을 만료시키고(`k0_ipc::expire_timeouts`), 그래서 기한이 지난 대기자는 라운드 로빈 전환 전에 준비 상태가 됩니다. 그런 다음 다음 준비 태스크로 순환합니다. 1020부터 1023까지의 가짜 인터럽트 번호는 무시합니다. 그 외의 인터럽트 번호와 모든 FIQ는 설계상 발생할 수 없으므로 커널은 `k0: UNEXPECTED ...`를 출력하고 파킹합니다. +틱을 센 뒤 핸들러는 콘솔 수신 링도 비우며(`console-input` 이미지), 태스크가 콘솔 입력을 읽기 시작한 뒤에는 주기적인 틱 줄을 출력하지 않습니다([boot_KR.md](boot_KR.md) 참고). 틱, 선점, 타임아웃은 그대로입니다. + +## 콘솔 인터럽트 + +`console-input`으로 빌드한 이미지는 인터럽트를 하나 더 받습니다. 콘솔 UART의 수신 인터럽트입니다. 디스패처는 인터럽트 번호로 둘을 구분합니다(타이머, 그다음 콘솔). EL0와 EL1에서 받은 IRQ가 같은 함수를 지납니다. 그 밖의 번호는 여전히 `k0: UNEXPECTED ...`입니다. 콘솔 가지는 UART를 256바이트 링으로 비우며, 바이트를 해석하지 않습니다. 커널 바이너리의 정책 함수 `k0_console_event`(`k0_preempt`와 같은 종류)를 불러 대기 중인 `CONSOLE_READ` 호출자를 깨웁니다. 깨어난 태스크는 준비 큐의 맨 뒤로 가므로 입력은 실행 중인 태스크를 선점하지 않습니다. + +인터럽트는 읽는 쪽이 한도를 정합니다. 링이 차면 커널이 UART의 수신 인터럽트를 스스로 가리고, 읽는 쪽이 링의 절반을 가져가면 다시 엽니다. 같은 비우기가 틱마다 한 번 더 실행되므로, 인터럽트가 오지 않아도 입력은 (최대 한 틱 늦게) 도착합니다. UART 원인 없이 발생하는 선은 8번 진입 뒤 `k0: console input off (interrupt N fired without a uart cause)`와 함께 꺼집니다. 이 차단은 호스트 테스트로만 확인했습니다. 수신 인터럽트는 태스크가 읽기 권리로 콘솔 입력을 처음 읽을 때까지 꺼져 있습니다. + +`CONSOLE_READ`는 `x0`에 `Console` 슬롯, `x1`에 플래그를 받습니다(`NONBLOCK` = 1, `FLUSH` = 2, 비트 63..32는 틱 단위 타임아웃, 나머지 비트는 `BAD_FLAGS`로 거부). 바이트는 `x1`로 돌아오고, 이 바이트 직전에 입력이 유실됐으면 `x2`가 1입니다. 한 번에 한 태스크만 기다릴 수 있으며 두 번째 읽는 쪽은 `BUSY`를 받습니다. `NO_DEVICE`는 입력 경로가 없거나 꺼졌다는 뜻입니다. 케이퍼빌리티가 삭제·회수·이동된 대기자는 `REVOKED`로 즉시 깨어납니다. + ## 테스트 방법 루트 태스크 자가 테스트는 의미 있는 방식으로 각각 폴트를 일으키는 태스크들을 시작합니다. 그리고 폴트를 일으킨 태스크만 죽는지, 폴트를 일으킨 명령 뒤의 코드가 실행되지 않는지, 루트 태스크와 다른 태스크가 계속 실행되는지 검사합니다. 폴트는 널 포인터에 쓰기, FP/SIMD 명령, 루트 태스크에만 매핑된 주소 읽기, 읽기 전용 페이지에 쓰기, 스택 페이지로 분기, 커널 주소 읽기입니다. 또 알 수 없는 시스템 콜 하나로 태스크를 죽이고, 스레드 포인터 레지스터가 태스크별로 분리되어 있는지도 검사합니다. -`tools/qemu-boot-test.sh`는 줄 수를 **정확히** 셉니다. `k0: task fault ` 줄이 정확히 6개(`K0_BOOT_FAULTS`로 바꿀 수 있음), `k0: unknown syscall ` 줄이 정확히 1개여야 하고, 루트 전용 주소에 대한 폴트 줄은 `far`에 그 주소가 찍혀야 합니다. 파괴된 뒤에 다시 실행되는 태스크나 엉뚱한 이유로 죽은 태스크는 줄을 늘리거나 줄여서 테스트를 실패시킵니다. +`tools/qemu-boot-test.sh`는 줄 수를 **정확히** 셉니다. `k0: task fault ` 줄이 정확히 6개(`K0_BOOT_FAULTS`로 바꿀 수 있음, 터미널이 있는 이미지는 터미널이 없는 같은 이미지보다 2개 더 많아 vault 없이 8개, vault와 함께 10개), `k0: unknown syscall ` 줄이 정확히 1개여야 하고, 루트 전용 주소에 대한 폴트 줄은 `far`에 그 주소가 찍혀야 합니다. 파괴된 뒤에 다시 실행되는 태스크나 엉뚱한 이유로 죽은 태스크는 줄을 늘리거나 줄여서 테스트를 실패시킵니다. 순서가 있는 마커도 요구합니다. `k0: task fault dabort-lower`, `k0: task fault fp-simd`, `k0: task fault iabort-lower`, `k0: unknown syscall 65535, killing task`, `root: fault isolation tests pass` 등이 그렇습니다. `k0: FATAL`, `k0: EXCEPTION`, `k0: PANIC`, `k0: UNEXPECTED`가 나오면 실패합니다. diff --git a/design/kr/hardening_KR.md b/design/kr/hardening_KR.md index 6daad77..47727e5 100644 --- a/design/kr/hardening_KR.md +++ b/design/kr/hardening_KR.md @@ -46,7 +46,7 @@ 커널은 루트 태스크에 넘길 32바이트 시드도 파생합니다(`k0_boot::derive_root_seed`). 자체 도메인 문자열(`k0-root-task-seed-v1`), DTB 엔트로피의 길이, DTB 엔트로피 자체, 카운터를 SHA-256으로 해시하고, CPU에 `RNDR`이 있으면 새로 뽑은 `RNDR` 워드 네 개를 더합니다. 도메인 문자열이 PAC 키의 것과 다르므로 두 출력은 도메인 분리로 서로 독립입니다. 하나를 안다고 다른 하나를 알 수는 없습니다. 다만 DTB 엔트로피와 카운터는 공유하므로, 시드는 입력만큼만 좋고 그보다 낫지 않습니다. -시드는 bootinfo 페이지에 없습니다. 커널이 루트 태스크의 저장된 컨텍스트에 넣으므로 진입 레지스터 `x0`부터 `x3`으로 도착합니다. `x4`는 시드 정보 워드입니다. 비트 15..0은 시드에 들어간 `rng-seed` 바이트 수이고, 비트 16은 `RNDR`이 기여했을 때 설정됩니다. bootinfo 페이지의 레이아웃은 이제 버전 3(`bootinfo::VERSION`)이며, 다른 버전을 본 루트 태스크는 멈춥니다. 커널은 부트 스택에 있던 시드 사본을 직접 지웁니다. 루트 태스크는 시드가 아니라 재료만 출력합니다. `root: boot seed from rng-seed bytes 0x... and rndr` 또는 `... without rndr`입니다. +시드는 bootinfo 페이지에 없습니다. 커널이 루트 태스크의 저장된 컨텍스트에 넣으므로 진입 레지스터 `x0`부터 `x3`으로 도착합니다. `x4`는 시드 정보 워드입니다. 비트 15..0은 시드에 들어간 `rng-seed` 바이트 수이고, 비트 16은 `RNDR`이 기여했을 때 설정됩니다. bootinfo 페이지의 레이아웃은 이제 버전 4(`bootinfo::VERSION`)이며, 다른 버전을 본 루트 태스크는 멈춥니다. 커널은 부트 스택에 있던 시드 사본을 직접 지웁니다. 루트 태스크는 시드가 아니라 재료만 출력합니다. `root: boot seed from rng-seed bytes 0x... and rndr` 또는 `... without rndr`입니다. ### DTB에서 시드 지우기 @@ -106,9 +106,12 @@ EL0는 여전히 어떤 하드웨어 카운터나 타이머도 읽을 수 없습 EL0 스레드 포인터 레지스터 `TPIDR_EL0`와 `TPIDRRO_EL0`는 각 태스크의 저장된 컨텍스트에 포함됩니다. `TCB_CONFIGURE`가 이를 0으로 만들기 때문에 새 태스크는 생성자의 값 없이 시작합니다. -`DEBUG_PUTC`는 `Console` 케이퍼빌리티를 요구하며, 출력 가능한 ASCII도 개행도 아닌 모든 바이트를 `?`로 바꿉니다. 태스크는 콘솔을 읽는 쪽에 터미널 이스케이프 시퀀스를 보낼 수 없습니다(콘솔 드라이버를 포함해 빌드한 이미지의 콘솔, 또는 부트 로그). +`DEBUG_PUTC`는 쓰기 권리(W)가 있는 `Console` 케이퍼빌리티를 요구하며, 출력 가능한 ASCII도 개행도 아닌 모든 바이트를 `?`로 바꿉니다. 태스크는 콘솔을 읽는 쪽에 터미널 이스케이프 시퀀스를 보낼 수 없습니다(콘솔 드라이버를 포함해 빌드한 이미지의 콘솔, 또는 부트 로그). -이 필터는 줄을 누가 썼는지 표시하지 않습니다. 커널 출력과 태스크 출력이 부트 로그를 함께 사용하고 (콘솔 드라이버를 포함해 빌드한 이미지에서는) 콘솔도 함께 사용합니다. +이 필터는 줄을 누가 썼는지 표시하지 않습니다. 커널 출력과 태스크 출력이 부트 로그를 함께 사용하고 (콘솔 드라이버를 포함해 빌드한 이미지에서는) 콘솔도 함께 사용합니다. 터미널은 추가로 자신의 현재 줄 안에서 지울 수 있습니다. 읽기 권리(R)가 있는 `Console` 케이퍼빌리티(터미널의 것)만 백스페이스(0x08)도 출력할 수 있습니다. + +> [!NOTE] +> `console-input` 이미지에서는 외부가 태스크 실행 중에 인터럽트를 일으킬 수 있습니다. 링이 차면 커널이 수신 인터럽트를 스스로 가리므로 빈도는 읽는 쪽이 한도를 정합니다. 그래도 읽는 쪽은 틱보다 세밀한 도착 시각을 알게 되고 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널은 분석하지 않았습니다. 커널의 수신 코드는 EL1에서 실행되며 바이트를 해석하지 않지만 외부가 구동하는 커널 코드이고, 사용자 공간 드라이버에는 K0에 없는 장치·인터럽트 위임이 필요합니다. > [!WARNING] > `Console` 케이퍼빌리티를 가진 태스크는 개행 뒤에 `k0:`로 시작하는 글을 출력할 수 있습니다. 콘솔이나 로그를 읽는 쪽은 `tools/qemu-boot-test.sh`를 포함해 누구도 `k0: entering root task (el0)` 뒤에 나온 `k0:` 줄을 커널이 쓴 것으로 믿을 수 없습니다. diff --git a/design/kr/ipc_KR.md b/design/kr/ipc_KR.md index 708b0c3..96af3ed 100644 --- a/design/kr/ipc_KR.md +++ b/design/kr/ipc_KR.md @@ -13,7 +13,7 @@ - 서버가 클라이언트를 구분하게 해 주는 배지 - `CALL`을 안전하게 만드는 1회성 응답 자격 -코드는 `crates/k0-ipc/src/lib.rs`에 있고, 엔드포인트 큐는 `crates/k0-task/src/lib.rs`에 있습니다. +코드는 `crates/k0-ipc/src/lib.rs`에 있고, 엔드포인트 큐는 `crates/k0-task/src/lib.rs`에 있습니다. 시스템 콜 `CONSOLE_READ`는 IPC 호출처럼 기다리며 타임아웃, 해체, `REVOKED`로 깨어나는 방식을 IPC와 공유합니다. "콘솔 입력 대기" 절에서 설명합니다. `console-input`으로 빌드한 이미지에만 있습니다. ## 설계 요약 @@ -101,6 +101,7 @@ K0의 IPC는 seL4 방식의 **동기 랑데부**입니다. 메시지는 레지 - **Ready**: 준비 큐에서 제거합니다. - **SEND, RECV, CALL에서 블록**: 기다리던 엔드포인트의 큐에서, 머리든 중간이든 꼬리든 제거합니다. +- **콘솔 입력 대기**(`BlockedConsole`): 콘솔의 하나뿐인 대기자 자리에서 제거합니다. - **응답 대기**(`BlockedReply`): 응답 자격을 양방향으로 끊습니다. 그래서 서버는 응답할 자격을 잃고, 뒤늦은 응답이 죽은 태스크를 깨우는 일도 없습니다. - **응답 자격 보유**: 그 자격을 기다리던 호출자를 `NO_REPLY`로 깨웁니다. - **Inactive, Stopped, Running**: 풀 것이 없습니다. @@ -127,6 +128,7 @@ K0의 IPC는 seL4 방식의 **동기 랑데부**입니다. 메시지는 레지 | `RECV`, `REPLY_RECV` | 엔드포인트 큐 | `TIMEOUT` | 받은 것 없음(`REPLY_RECV`가 준 응답은 이미 전달됨) | | `CALL` | 엔드포인트 큐 | `TIMEOUT` | 전달되지 않음 | | `CALL` | `BlockedReply` | `REPLY_TIMEOUT` | 전달됨, 서버가 동작했는지는 알 수 없음 | +| `CONSOLE_READ` | 콘솔 대기자 자리 | `TIMEOUT` | 읽은 바이트 없음 | `CALL`이 `REPLY_TIMEOUT`으로 끝나면 커널은 그 응답 자격을 쥔 서버의 자격을 지웁니다. 서버가 나중에 응답해도 그 `REPLY_RECV`에는 사용할 응답 자격이 없으므로 뒤늦은 응답은 버려집니다. 다음 호출자는 자기 응답을 받습니다. @@ -154,13 +156,43 @@ TCB에는 `deadline`, `tnext`, `tprev` 필드가 있습니다. `k0-sched`는 기 그 시점에 준비된 태스크가 없어도 커널은 멈추지 않습니다. 커널은 `idle_until_ready`(`kernel/src/syscall.rs`)에서 idle 상태로 기다립니다. 다음 인터럽트까지 기다렸다가 기한이 지난 대기자를 모두 깨우고, 준비된 태스크가 있으면 그 태스크로 전환합니다. 그동안에도 타이머 틱은 계속 세고 처리합니다. idle 루프는 다음 두 줄 가운데 하나를 부팅당 최대 한 번씩 출력합니다. - `k0: idle (waiting for a timeout)`: 기한이 있는 대기자가 하나 이상 있으므로 태스크를 깨울 것이 있습니다. -- `k0: all tasks stopped (none ready, no timeout pending)`: 기한이 있는 대기자가 없습니다. 지금은 Notification 오브젝트도 태스크용 장치 인터럽트도 없으므로 이 상태에서는 어떤 것도 태스크를 깨울 수 없고, 머신은 idle 상태로 남습니다. `tools/qemu-boot-test.sh`는 `k0: all tasks`로 시작하는 줄을 모두 실패로 처리합니다. +- `k0: all tasks stopped (none ready, no timeout pending)`: 기한이 있는 대기자도 콘솔 입력을 기다리는 태스크도 없습니다. 지금은 Notification 오브젝트가 없고 태스크를 깨우는 장치 인터럽트는 콘솔 입력뿐이므로 이 상태에서는 어떤 것도 태스크를 깨울 수 없고, 머신은 idle 상태로 남습니다. `tools/qemu-boot-test.sh`는 `k0: all tasks`로 시작하는 줄을 모두 실패로 처리합니다. + +기다릴 것이 콘솔 입력뿐이면 커널은 어느 줄도 출력하지 않습니다. 터미널 이미지에서는 이것이 정상 상태입니다. > [!WARNING] > 모든 태스크가 블록되어도 커널은 더 이상 정지하지 않으며, 태스크는 타임아웃으로 자신의 대기에 상한을 걸 수 있습니다. 그래도 가용성은 보호되지 않습니다. 타임아웃 없이 기다리는 태스크는 상대방이 동작하지 않으면 영원히 기다릴 수 있고, 엔드포인트 케이퍼빌리티를 가진 격리 태스크는 여전히 다른 태스크를 기다리게 만들 수 있습니다. 이것이 [SECURITY_KR.md](../../SECURITY_KR.md)의 어드바이저리 GHSA-q99x-2wrv-358p의 주제입니다. 어드바이저리는 릴리즈 시점에 갱신합니다. 응답을 유지해야 하는 서버나 루트 태스크는 모든 대기에 타임아웃을 지정해야 합니다. 태스크 격리로도 이 점은 달라지지 않습니다. +## 콘솔 입력 대기 + +`CONSOLE_READ`(번호 16)는 콘솔 입력을 한 바이트 읽습니다. `console-input`으로 빌드하고 수신이 가능한 콘솔 드라이버(PL011과 SBSA UART, 16550은 아님)가 있는 이미지에만 있습니다. 인자와 결과는 다음과 같습니다. + +| 레지스터 | 의미 | +| --- | --- | +| `x0`(입력) | `R`이 있는 `Console` 케이퍼빌리티의 슬롯 | +| `x1`(입력) | 플래그. `NONBLOCK` = 1, `FLUSH` = 2, 63부터 32비트에 틱 단위 타임아웃. 다른 비트는 `BAD_FLAGS`로 실패 | +| `x0`(출력) | 0 또는 오류 코드 | +| `x1`(출력) | 바이트 | +| `x2`(출력) | 이 바이트 바로 앞에서 입력이 유실되었으면 1, 아니면 0 | + +호출 한 번에 한 바이트를 돌려줍니다. 커널은 바이트를 해석하지 않습니다. `FLUSH`는 읽기 전에 커널과 장치가 쥔 입력을 버려서, 프롬프트 전에 들어온 입력이 명령으로 읽히지 않게 합니다. `NONBLOCK`은 준비된 바이트가 없으면 `WOULD_BLOCK`을 돌려줍니다. + +준비된 바이트가 없으면 태스크는 `BlockedConsole` 상태로 기다립니다. 이 대기는 위의 대기들과 같은 방식으로 동작합니다. + +- **대기자는 하나**: 한 번에 한 태스크만 기다릴 수 있습니다. 두 번째 읽기는 `BUSY`를 받습니다. +- **타임아웃**: 타임아웃은 IPC와 같은 기한 목록을 쓰며, 기한이 지나면 `TIMEOUT`을 돌려줍니다. +- **회수**: `Console` 케이퍼빌리티가 삭제, 회수, 이동된 대기자는 즉시 `REVOKED`로 깨어나며 바이트를 받지 못합니다. +- **입력 경로 없음**: `NO_DEVICE`는 이미지에 이 콘솔용 수신 드라이버가 없거나 입력 경로가 꺼졌다는 뜻입니다. 기다리는 동안 경로가 꺼지면 대기자가 이 값으로 깨어납니다. +- **해체**: 기다리는 동안 죽은 태스크는 대기자 자리에서 제거됩니다. +- **깨우는 순서**: 깨어난 읽기 태스크는 준비 큐의 끝에 섭니다. 입력이 실행 중인 태스크를 선점하지 않습니다. + +수신 인터럽트는 태스크가 권한을 가지고 처음 콘솔 입력을 읽을 때까지 꺼져 있습니다. 그 첫 읽기는 장치가 쥔 입력을 버리고, `k0: tick lines off (console input in use)` 한 줄을 출력한 뒤 주기적인 `k0: tick N` 줄을 멈춥니다. 틱, 선점, 타임아웃은 계속 동작합니다. 수신 경로와 그 한계는 [USAGE_KR.md](../../USAGE_KR.md)와 [exceptions_KR.md](exceptions_KR.md)에 있습니다. + +> [!NOTE] +> 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 바이트의 지연은 준비된 태스크마다 최대 한 틱입니다. + ## 오류 다음 표는 오류 코드와 그 원인입니다. @@ -172,10 +204,12 @@ TCB에는 `deadline`, `tnext`, `tprev` 필드가 있습니다. `k0-sched`는 기 | `NO_RIGHTS` | 엔드포인트 케이퍼빌리티에 `W`(`SEND`, `CALL`) 또는 `R`(`RECV`, `REPLY_RECV`)이 없음 | | `WOULD_BLOCK` | `NONBLOCK`이 지정됐고 상대가 준비되지 않음 | | `NO_REPLY` | `CALL`의 수신자가 응답하지 않고 종료했거나, 폴트를 냈거나, 더 새로운 `CALL`을 받았거나, 파괴됨 | -| `REVOKED` | 호출자가 줄 서 있는 동안 엔드포인트의 원본 케이퍼빌리티가 삭제됨 | +| `REVOKED` | 호출자가 줄 서 있는 동안 엔드포인트의 원본 케이퍼빌리티가 삭제됨. `CONSOLE_READ`에서는 호출자가 기다리는 동안 `Console` 케이퍼빌리티가 삭제, 회수, 이동됨 | | `TIMEOUT` | 상대가 오기 전에 대기가 끝났고, 메시지는 전달되지 않음 | | `REPLY_TIMEOUT` | `CALL`은 전달됐지만 제때 응답이 오지 않았고, 서버가 동작했는지는 알 수 없음 | -| `BAD_FLAGS` | 플래그 레지스터의 예약 비트(31부터 1)가 설정됨 | +| `BAD_FLAGS` | 플래그 레지스터의 예약 비트(31부터 1)가 설정됨. `CONSOLE_READ`에서는 `NONBLOCK`, `FLUSH`, 타임아웃 외의 비트 | +| `BUSY`(-23) | `CONSOLE_READ`가 이미 콘솔 입력을 기다리는 다른 태스크를 만남 | +| `NO_DEVICE`(-24) | `CONSOLE_READ`가 입력 경로를 찾지 못함. 이미지에 콘솔용 수신 드라이버가 없거나 경로가 꺼짐 | ## 테스트 방법 @@ -199,6 +233,8 @@ IPC와 해체는 부팅으로 테스트합니다. 루트 태스크는 서버 태 타임아웃 테스트는 가장 큰 untyped에서 오브젝트를 가져옵니다. 실제 틱을 기다리므로 부팅 테스트는 약 4초 더 걸립니다. +입력 테스트는 `console-input`으로 빌드한 이미지의 루트 태스크 자가 테스트에 포함됩니다. `root: backspace without the input right [?]`와 `root: console input tests pass`를 출력하며, 입력 경로가 없으면 `root: console input tests pass (no input path)`, 테스트 중에 바이트가 도착하면 `... cut short (the line is busy)`를 출력합니다. 수신 로직은 별도 크레이트 `crates/k0-conin`에 있으며 가짜 UART로 호스트에서 테스트합니다. `tools/term-test.py`는 터미널 이미지에 대해 스크립트로 짠 세션을 실행합니다. + 케이퍼빌리티 테스트는 배지를 한 번만 붙일 수 있고 두 번째는 거부되는지, 복사본이 배지를 유지하는지, 송신 전용 케이퍼빌리티로는 수신할 수 없고 수신 전용으로는 송신할 수 없는지(`NO_RIGHTS`), 엔드포인트를 회수하면 복사본이 모두 사라지고 원본은 남는지를 검사합니다. 격리 테스트는 송신 전용이고 배지가 붙은 엔드포인트 케이퍼빌리티 하나만 CNode에 든 격리 태스크를 시작합니다. 루트 태스크는 그 태스크가 `x1`로 자신에게 주어진 배지를 받는지, 그리고 루트 태스크의 슬롯 번호가 격리 CNode에서 아무 의미가 없는지(`BAD_SLOT`)를 검사합니다. @@ -224,6 +260,7 @@ IPC와 해체는 부팅으로 테스트합니다. 루트 태스크는 서버 태 - **타임아웃은 태스크가 준비되는 시점이지 실행되는 시점이 아님**: 우선순위도 CPU 예산도 없으며, 스케줄러는 1틱 슬라이스의 라운드 로빈입니다([scheduling_KR.md](scheduling_KR.md) 참고). - **긴 시스템 콜**: 커널은 선점되지 않으므로, 객체가 많은 untyped에 대한 `CAP_REVOKE` 같은 긴 호출은 다른 모든 태스크와 모든 타임아웃을 지연시킵니다. - **치명적 정지**: `k0_arch::fatal`이나 커널 패닉은 여전히 머신을 정지시킵니다. -- **EL0의 시간 소스**: 틱에 맞춰 깨어나는 성질을 타이밍 공격에 쓸 수 있는지는 분석하지 않았습니다. +- **EL0의 시간 소스**: 틱에 맞춰 깨어나는 성질을 타이밍 공격에 쓸 수 있는지는 분석하지 않았습니다. 콘솔 입력이 있는 이미지에서는 외부의 누군가가 태스크가 실행되는 동안 인터럽트를 일으킬 수 있고(읽는 쪽이 속도를 정함), 읽는 태스크는 틱보다 세밀한 도착 시각을 압니다. 다른 태스크도 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널도 분석하지 않았습니다. +- **입력 지연**: `CONSOLE_READ` 대기자는 실행 중인 태스크 뒤에서 깨어나므로 바이트는 준비된 태스크마다 최대 한 틱을 기다릴 수 있습니다. - **큐에 있던 송신자**: 회수 뒤에도 메시지를 한 번 전달합니다. 엔드포인트에서 이미 기다리는 송신자는 자신을 큐에 세운 송신의 배지를 유지합니다. 기다리는 동안 그 케이퍼빌리티가 회수되어도 메시지는 다음 수신자에게 한 번 전달됩니다. - **메시지당 워드 네 개**: 더 큰 데이터는 공유 메모리가 필요합니다. 태스크가 서로 다른 주소 공간에서 실행될 수 있으므로, 공유 메모리는 그 태스크의 `AddrSpace` 케이퍼빌리티를 가진 쪽이 해당 주소 공간에 매핑해 주어야 합니다. diff --git a/design/kr/scheduling_KR.md b/design/kr/scheduling_KR.md index 7fbae2b..828fffc 100644 --- a/design/kr/scheduling_KR.md +++ b/design/kr/scheduling_KR.md @@ -56,9 +56,10 @@ | `Running` | 현재 태스크 | | `BlockedSend`, `BlockedRecv`, `BlockedCall` | 엔드포인트 큐에서 대기 중 | | `BlockedReply` | `CALL`의 응답을 기다리는 중 | +| `BlockedConsole` | `CONSOLE_READ`에서 콘솔 입력을 기다리는 중(`console-input`으로 빌드한 이미지에만 있음). 태스크는 어떤 큐에도 없으며 커널의 대기자 자리 하나가 가리킵니다. 한 번에 한 태스크만 기다릴 수 있습니다. | | `Dead` | 종료, 강제 종료, 또는 정리됨 | -블록 상태의 태스크는 기한이 지나도 `Ready`가 될 수 있습니다([타임아웃](#타임아웃) 참고). +블록 상태의 태스크는 기한이 지나도 `Ready`가 될 수 있습니다([타임아웃](#타임아웃) 참고). `BlockedConsole` 태스크는 바이트가 도착하거나 케이퍼빌리티가 삭제·회수·이동될 때도 `Ready`가 됩니다. `Inactive`의 값은 0입니다. 방금 retype한 프레임은 전부 0이므로, 큐 링크가 비어 있고 내장 슬롯이 비어 있으며 응답 자격이 없는 유효한 `Inactive` TCB입니다. retype에 생성자가 필요 없습니다. @@ -107,12 +108,12 @@ ## 선점 -타이머는 1초에 한 번 발생합니다. EL0가 실행 중일 때 발생하면 IRQ 경로가 인터럽트를 확인하고 타이머를 다시 설정한 뒤 `k0: tick N`을 출력하고 `k0_preempt`를 호출합니다. `k0_preempt`는 `rotate`를 호출합니다. `k0: tick N`은 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔에 출력하며, 로그에는 처음 4개의 tick 줄만 남깁니다. 양보하지 않는 태스크도 **최대 1초 뒤에는 CPU를 잃습니다**. +타이머는 1초에 한 번 발생합니다. EL0가 실행 중일 때 발생하면 IRQ 경로가 인터럽트를 확인하고 타이머를 다시 설정한 뒤 `k0: tick N`을 출력하고 `k0_preempt`를 호출합니다. `k0_preempt`는 `rotate`를 호출합니다. `k0: tick N`은 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔에 출력하며, 로그에는 처음 4개의 tick 줄만 남깁니다. 양보하지 않는 태스크도 **최대 1초 뒤에는 CPU를 잃습니다**. 태스크가 콘솔 입력을 읽은 뒤에는 줄 하나 `k0: tick lines off (console input in use)`를 남기고 틱 줄이 멈추지만, 틱과 선점과 타임아웃은 계속됩니다. > [!IMPORTANT] > 커널 자체는 선점되지 않습니다. 예외 진입이 인터럽트를 마스크하고, 커널은 시스템 콜이나 폴트를 처리하는 동안 마스크를 유지합니다. -EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중에만 가능하며, 그때는 틱을 세기만 합니다. +EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중에만 가능하며, 그때는 틱을 세기만 합니다. `console-input` 이미지에서 입력 바이트가 도착해도 선점하지 않습니다. 깨어난 읽는 쪽은 다른 깨어난 태스크처럼 준비 큐의 맨 뒤로 갑니다. 우선순위가 없으므로 입력 지연은 준비된 태스크마다 최대 한 틱입니다. ## 타임아웃 @@ -145,6 +146,7 @@ EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중에 | `Ready` | 준비 큐에서 태스크를 뺌 | | `BlockedSend`, `BlockedRecv`, `BlockedCall` | `blocked_on`이 가리키는 엔드포인트 큐에서 태스크를 빼고, 기한이 있으면 기한 목록에서도 뺌 | | `BlockedReply` | 응답 자격을 쥔 태스크(`reply_from`)에서 그 자격을 지우고, 기한이 있으면 기한 목록에서도 뺌 | +| `BlockedConsole` | 커널의 콘솔 대기자 자리를 비우고, 기한이 있으면 기한 목록에서도 뺌 | | `Running` | 뺄 링크 없음. 뒤의 설명 참고 | 모든 상태에서 이어서 태스크 자신이 쥔 응답 자격을 철회하므로, 그 응답을 기다리던 호출자는 `NO_REPLY`로 깨어나 영원히 블록되지 않습니다. 마지막으로 상태를 `Dead`로 바꾸고, 큐 링크, `blocked_on`, `reply_from`, `ipc_badge`, `ttbr0_pa`를 지우며, `Running`이 아니면 저장된 레지스터를 0으로 지웁니다. 상태가 약속하는 것과 큐나 응답 링크가 맞지 않으면 커널 불변식 위반이므로 커널은 `k0: FATAL ...`을 출력하고 정지합니다([exceptions_KR.md](exceptions_KR.md) 참고). @@ -164,7 +166,9 @@ EL1에서 타이머 인터럽트가 도착하는 것은 이양 전 부트 중에 커널이 idle 상태인 동안에도 타이머 틱은 계속 세고 처리합니다. idle 루프는 다음 두 줄 가운데 하나를 부팅당 최대 한 번씩 출력합니다. - `k0: idle (waiting for a timeout)`: 기한이 있는 대기자가 하나 이상 있습니다. -- `k0: all tasks stopped (none ready, no timeout pending)`: 기한이 있는 대기자가 없습니다. 지금은 Notification 오브젝트도 태스크용 장치 인터럽트도 없으므로 이 상태에서는 어떤 것도 태스크를 깨울 수 없고, 머신은 idle 상태로 남습니다. +- `k0: all tasks stopped (none ready, no timeout pending)`: 기한이 있는 대기자도 콘솔 입력을 기다리는 태스크도 없습니다. 지금은 Notification 오브젝트도, 콘솔 입력을 제외한 태스크용 장치 인터럽트도 없으므로 이 상태에서는 어떤 것도 태스크를 깨울 수 없고, 머신은 idle 상태로 남습니다. + +기다릴 것이 콘솔 입력뿐이면(`console-input` 이미지) 커널은 아무것도 출력하지 않으며, 이것이 터미널 이미지의 정상 상태입니다. idle 루프는 인터럽트마다 도착한 입력을 확인해 읽는 쪽을 깨웁니다. > [!WARNING] > 가용성은 여전히 보호되지 않습니다. 타임아웃 없이 기다리는 태스크는 상대방이 동작하지 않으면 영원히 기다릴 수 있고, 마지막으로 블록하는 격리 태스크는 여전히 시스템에 실행할 태스크가 없게 만들 수 있습니다([SECURITY_KR.md](../../SECURITY_KR.md)의 어드바이저리 GHSA-q99x-2wrv-358p, 릴리즈 시점에 갱신). 격리는 태스크 사이의 기밀성과 무결성을 지키는 것이지 가용성을 지키지 않습니다. diff --git a/design/kr/terminal_KR.md b/design/kr/terminal_KR.md new file mode 100644 index 0000000..ac0515d --- /dev/null +++ b/design/kr/terminal_KR.md @@ -0,0 +1,165 @@ +# 시리얼 입력과 운영자 터미널 + +

+ +[English](../en/terminal.md) | 한국어 + +
+ +이 노트는 사람이 시리얼 선으로 K0와 대화하는 방법을 설명합니다. 커널이 콘솔 UART에서 바이트를 받고, 시스템 콜 `CONSOLE_READ`로 태스크 하나, 즉 **터미널**에 넘겨 줍니다. 터미널은 볼트의 운영자입니다([vault_KR.md](vault_KR.md) 참고). 볼트의 상태를 보여 주고, 키를 만들고, 키를 지웁니다. 코드는 `crates/k0-conin`(수신 로직), `kernel/src/syscall.rs`(`CONSOLE_READ`), `userspace/k0-term`(터미널), `userspace/root-task/src/service.rs`(연결과 점검)에 있습니다. + +> [!NOTE] +> 입력과 터미널은 선택 사항이며 기본값은 꺼짐입니다. `console-input` 없이 빌드한 이미지에는 수신 코드도, `CONSOLE_READ`도, 이 노트의 로그 줄도 없습니다. `terminal` 없이 빌드한 이미지에는 터미널 코드가 없습니다. + +## 목적과 범위 + +앞선 노트의 볼트는 부팅 시드로 키를 한 번 만들고, 그 뒤에는 호출에 답하기만 합니다. 운영자가 없으면 아무도 볼트의 상태를 볼 수 없고, 아무도 키를 의도적으로 지울 수 없습니다. 터미널은 시리얼 선 위의 작고 고정된 텍스트 인터페이스로 이 빈틈을 메웁니다. + +범위는 다음과 같습니다. 콘솔 UART 하나, 한 번에 읽는 태스크 하나, 호출 한 번에 바이트 하나, 운영자가 쓸 수 있는 볼트 연산 넷(`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`)입니다. 터미널은 서명할 수 없고 시드를 전달할 수도 없습니다. + +

+ 시리얼 선으로 들어온 바이트는 커널의 256바이트 수신 링에 쌓입니다. 터미널 태스크는 CONSOLE_READ 호출 한 번에 한 바이트를 읽습니다. 터미널은 케이퍼빌리티를 둘 가집니다. 읽기와 쓰기 권한이 있는 Console 복사본, 그리고 송신 권한과 운영자 배지가 있는 볼트 엔드포인트입니다. +

+ +## 커널이 입력을 받는 이유 + +유저 공간 드라이버는 UART의 레지스터와 인터럽트가 필요합니다. K0는 아직 장치나 인터럽트를 태스크에 위임할 수 없습니다. 그래서 수신 코드가 커널의 EL1에서 실행되고, 커널이 바이트를 유저 공간에 넘겨 줍니다. + +커널 코드는 작게 유지하며, 바이트를 해석하지 않습니다. 줄, 명령, 제어 키가 무엇인지 커널은 모릅니다. 그것은 모두 유저 공간에 있는 터미널의 일입니다. + +> [!NOTE] +> 수신 코드는 여전히 외부 당사자가 구동하는 커널 코드입니다. 유저 공간 드라이버는 아직 없습니다. 장치 및 인터럽트 위임이 아직 없기 때문입니다. + +feature는 다음과 같으며, feature는 기능을 더하기만 합니다. + +| `k0-kernel`의 feature | 추가하는 것 | +| --- | --- | +| `console-input` | 콘솔 UART용 커널 수신 경로와 `CONSOLE_READ`입니다. 동작하려면 콘솔 드라이버 feature가 필요합니다. 수신은 PL011과 SBSA UART에만 있습니다. | +| `terminal` | 루트 태스크 이미지 안의 터미널 태스크이며, 자가 테스트 뒤에 서비스로 시작합니다. `console-input`을 함께 켭니다. `vault`가 있으면 볼트의 운영자가 되고, `vault-ed25519`가 있으면 Ed25519 키를 만들 수 있습니다. | + +다음과 같이 빌드하고 실행할 수 있습니다. + +```sh +$ cargo build -p k0-kernel --features console,terminal,vault-ed25519 +$ cargo run -p k0-kernel --features console,terminal,vault-ed25519 +``` + +QEMU는 시리얼 포트를 사용자의 터미널에 연결합니다. `cargo run`에서 QEMU 자체의 이스케이프 키는 Ctrl-A이며(Ctrl-A x로 QEMU를 종료), 그래서 Ctrl-A는 K0에 전달되지 않습니다. + +## 수신 경로와 그 한계 + +커널의 UART 드라이버는 받은 바이트를 모두 256바이트 링에 넣습니다. 수신 로직은 별도 크레이트 `crates/k0-conin`이며, 작은 레지스터 트레이트에 맞춰 작성해 호스트 테스트가 가짜 UART로 구동할 수 있습니다. + +- **수신 인터럽트는 꺼진 채로 둡니다**: 태스크가 읽기 권한으로 콘솔 입력을 처음 읽을 때까지입니다. 그 첫 읽기는 장치가 쥐고 있던 바이트를 버립니다. 또한 `k0: tick lines off (console input in use)` 한 줄 뒤로 주기적인 `k0: tick N` 줄을 멈춥니다. 틱, 선점, 타임아웃은 계속 동작합니다. +- **커널 작업량의 한계**: 링이 가득 차면 커널이 UART의 수신 인터럽트를 스스로 마스크합니다. 읽는 쪽이 링의 절반을 가져간 뒤에 다시 엽니다. 그래서 폭주 상황에서 인터럽트 빈도는 보내는 쪽이 아니라 읽는 쪽이 정한 한계 안에 있습니다. +- **틱마다 비우기**: 같은 비우기를 틱마다 한 번 더 실행하므로, 인터럽트가 오지 않아도 입력은 (최대 한 틱 늦게) 도착합니다. +- **유실 표시**: FIFO 오버런, 브레이크, 프레이밍 오류, 패리티 오류는 구멍 뒤의 바이트에 표시됩니다. `CONSOLE_READ`가 이 표시를 읽는 쪽에 돌려줍니다. +- **인터럽트 번호**는 디바이스 트리(콘솔 노드의 `interrupts` 속성: 발견한 GIC의 SPI 하나, 레벨, active high)에서 가져오고, UEFI 로더를 거치면 ACPI SPCR 테이블에서 가져옵니다. 플랫폼 줄에 출력되며(예: `k0: platform con=pl011@0x9000000,irq33 ...`) 그래서 `K0_PIN`으로 고정됩니다. 이 변경 이전에 만든 핀 문자열은 더 이상 일치하지 않으므로 다시 만들어야 합니다. 사용할 수 있는 인터럽트가 없는 콘솔 노드는 부팅 거부 사유가 아닙니다. 입력만 꺼집니다. +- **잘못된 인터럽트 번호는 입력만 잃습니다**: 범위를 벗어났거나 쓸 수 없는 번호는 부팅 때 `k0: console input off (...)`가 됩니다. UART 원인 없이 계속 발생하는 선은 8번 진입 뒤에 `k0: console input off (interrupt N fired without a uart cause)`와 함께 꺼집니다. + +부팅 때 커널은 `k0: console input on (pl011 irq 33)` 또는 `k0: console input off ()`를 출력합니다. 이유는 `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range`, `interrupt not available`입니다. + +## CONSOLE_READ와 Console 권한 + +`CONSOLE_READ`는 시스템 콜 16번입니다. 호출 한 번에 바이트 하나를 돌려줍니다. + +| 레지스터 | 입력 | 출력 | +| --- | --- | --- | +| x0 | `Console` 케이퍼빌리티 슬롯 | 성공이면 0, 아니면 오류 | +| x1 | 플래그 | 바이트 | +| x2 | | 이 바이트 바로 앞에서 입력이 유실되었으면 1 | + +플래그는 `NONBLOCK`(1), `FLUSH`(2)이고, 63비트부터 32비트까지는 틱 단위 타임아웃입니다. 다른 비트는 `BAD_FLAGS`로 거부됩니다. `NO_DEVICE`(-24)는 입력 경로가 없거나 꺼졌다는 뜻입니다. + +`Console` 케이퍼빌리티에는 이제 권한이 있습니다. **R**은 입력 읽기, **W**는 출력 쓰기입니다. `CAP_COPY`는 권한을 제거하기만 할 수 있습니다. 루트 태스크의 케이퍼빌리티는 W를 가지며, R은 `console-input`이 있는 이미지에서만 가집니다. `DEBUG_PUTC`는 W가 필요합니다. `bootinfo::VERSION`은 4입니다. + +출력 필터는 한 가지를 빼고 그대로입니다. R이 있는 `Console` 케이퍼빌리티(터미널의 것)는 백스페이스(0x08)도 내보낼 수 있습니다. 다른 제어 바이트는 여전히 `?`로 출력됩니다. + +## 대기와 깨우기 + +입력을 기다릴 수 있는 태스크는 한 번에 하나입니다. 두 번째로 읽으려는 태스크는 `BUSY`(-23)를 받습니다. 링이 비어 있고 `NONBLOCK`을 요구하지 않은 읽기는 잠들며, 플래그에 타임아웃이 있으면 그 시간만큼만 잡니다. + +- **바이트로 깨우기**: 바이트를 받으면 대기자를 깨웁니다. 대기자는 준비 큐의 맨 뒤로 갑니다. 입력 때문에 선점하지는 않습니다. +- **케이퍼빌리티 변경으로 깨우기**: 케이퍼빌리티가 삭제, 회수 또는 이동된 대기자는 즉시 `REVOKED`로 깨어납니다. +- **타임아웃으로 깨우기**: 플래그에 타임아웃을 준 읽기는 그 시간이 다 되면 깨어납니다(타임아웃은 [scheduling_KR.md](scheduling_KR.md) 참고). +- **조용한 유휴**: 기다릴 것이 콘솔 입력뿐이면 커널은 아무것도 출력하지 않습니다. 이것이 터미널 이미지의 정상 상태입니다. `k0: all tasks stopped (none ready, no timeout pending)`는 시간 제한이 있는 대기자도, 콘솔 대기자도 없을 때만 출력됩니다. + +## 터미널의 연결과 적대적 태스크 점검 + +터미널 이미지는 자가 테스트를 모두 먼저 실행합니다. 그다음 루트 태스크가 다음을 합니다. + +1. 새 볼트를 시작하고(빌드에 포함된 경우) 부팅 시드를 건넵니다. 로그 줄은 `root: vault seeded`, 또는 `root: vault has no seed (boot seed has no entropy)`, 또는 `root: vault has no seed (no algorithm in this image)`입니다. +2. 터미널과 똑같이 연결한 적대적 태스크 둘을 실행합니다. 둘 다 거부되어야 하며 폴트로 끝나야 합니다. 줄은 `root: terminal console filter [...]`, `root: terminal wiring holds`, 그리고 `k0: task fault` 두 줄입니다. +3. 자신의 admin 케이퍼빌리티를 버리고, 터미널을 시작하고, 영원히 블록합니다. 줄은 `root: service started`이며 그다음 배너가 나옵니다. + +입력 경로가 없는 머신에서 루트 태스크는 `root: no console input, terminal not started`를 출력합니다. + +터미널 태스크는 자체 주소 공간과 케이퍼빌리티 둘을 가집니다. + +- R과 W가 있는 `Console` 복사본 +- 송신 권한과 운영자 배지가 있는 볼트 엔드포인트 + +볼트의 응답 프레임은 터미널에 읽기 전용으로 매핑됩니다. 볼트는 배지와 연산만으로 어느 프레임을 읽고 쓸지 결정합니다. 운영자에게는 응답 프레임이 있고 요청 프레임은 없습니다. 가질 수 없는 본문을 가졌다고 주장하는 요청은 메모리를 건드리지 않고 거부됩니다. + +적대적 태스크 둘은 연결이 말한 대로 작동하는지 확인하는 점검입니다. 터미널과 똑같이 연결되어 있고, 루트 태스크는 둘 다 거부되어 폴트로 끝나리라고 기대합니다. 하나라도 거부되지 않으면 점검이 실패합니다. + +> [!WARNING] +> 시리얼 선에는 인증이 없습니다. 선을 쥔 사람이 운영자이며, 키 삭제를 포함해 운영자의 연산 넷을 그대로 할 수 있습니다. 운영자는 서명할 수 없고, 시드를 전달할 수 없고, 정책을 바꿀 수 없습니다. + +## 화면과 명령 규칙 + +화면은 일반 텍스트입니다. 배너는 `K0 operator console, type 'help'`, 프롬프트는 `k0> `이고, 값은 `name=value`로 출력하며, 모든 명령은 정확히 한 줄 `ok` 또는 `err `으로 끝납니다. + +| 명령 | 하는 일 | +| --- | --- | +| `help` | 명령 목록을 보여 줍니다. | +| `vault status` | 볼트의 상태를 출력합니다. | +| `vault pubkey` | 공개 키를 출력합니다. | +| `vault keygen ` | 쥐고 있는 시드로 키를 만듭니다. 알고리즘은 `ed25519` 하나뿐입니다. | +| `vault zeroize confirm` | 키를 지웁니다. `vault zeroize`만 입력하면 `hint=type 'vault zeroize confirm' to erase the key`와 `err confirm-required`를 출력합니다. | + +`vault status`는 `state=fresh|seeded|ready|zeroized|failed`, `alg=none|ed25519`, `selftest=passed|failed`, `seed=none|rng-seed|rndr|rng-seed+rndr`, `validated=no`를 출력합니다. `seed=rng-seed`는 바이트가 있었다는 뜻이지 예측할 수 없다는 뜻이 아닙니다. 구현에 어떤 종류의 검증도 없으므로 `validated=no` 줄은 항상 출력됩니다. + +`vault pubkey`는 `pubkey=`와 16진수 32자를 출력하고, 7칸 들여 쓴 둘째 줄에 나머지 32자를 출력합니다. + +오류 이름은 `unknown-command`, `bad-argument`, `line-too-long`, `input-lost`, `confirm-required`, `denied`, `no-vault`, `no-key`, `key-exists`, `no-entropy`, `unsupported-algorithm`, `zeroized`, `vault-failed`, `vault-timeout`입니다. 전달되었지만 제때 답을 받지 못한 keygen 또는 zeroize에는 `hint=run 'vault status' to see whether it took effect`가 붙습니다. + +입력 규칙은 다음과 같습니다. 상태 기계는 `userspace/k0-term/src/lib.rs`의 `feed`입니다. + +- 줄은 CR 또는 LF로 끝나고, 64자 이하이며, 출력 가능한 ASCII만 포함합니다. +- Backspace와 DEL은 한 글자를 지웁니다. Ctrl-C와 Ctrl-U는 줄을 취소하며 `^C`, `^U`로 표시됩니다. +- ESC 시퀀스(화살표 키)는 무시합니다. +- 프롬프트 전에 UART에 도착한 것은 버립니다. +- 유실이 보고되면 다음 줄 끝까지 모두 버리고 `err input-lost`를 출력합니다. +- vault feature가 없으면 `help`는 `help`만 나열하고 `vault ...`는 `err no-vault`로 답합니다. + +이 feature와 함께 볼트 쪽도 바뀌었습니다. 엔드포인트 배지에 따른 역할은 빌드 때 고정되는 넷입니다. admin(루트 태스크), operator(터미널), signer, reader입니다. `INIT`(admin 전용, 한 번)은 이제 시드를 전달하기만 합니다. 볼트는 엔트로피 규칙을 검사하고 시드를 `seeded` 상태로 쥐고 있습니다. 새 연산 `KEYGEN`(admin과 operator)은 쥐고 있던 시드로 키를 만들고 시드를 지웁니다(`ready` 상태). 부팅 한 번에 키 하나입니다. 두 번째 `KEYGEN`은 `key-exists`로 거부되고, `ZEROIZE` 뒤에는 재부팅이 필요합니다. `failed`로 들어가는 모든 길은 시드와 키를 지웁니다. + +## 테스트 방법 + +**호스트 테스트**(`tools/host-test.sh`): `k0-conin`은 가짜 UART로 15개, `k0-term`은 vault feature가 있으면 24개, 없으면 21개, `k0-vault`는 Ed25519가 있으면 20개, 없으면 11개입니다. 전체는 ARM 호스트에서 354개, 다른 호스트에서 268개입니다. + +**부팅 매트릭스**: 새 행은 `input-only`, `input-gicv2`, `input-16550`, `input-bad-irq`, 정적 행 `input-symbols`(`console-input`이 없는 이미지에는 수신 코드도 새 로그 줄도 없음), `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi`, `hvf-term`입니다. 매트릭스는 HVF가 있는 Mac에서 76행, CI에서 65행입니다. + +**스크립트 세션**: `tools/term-test.py `는 QEMU의 시리얼 포트를 파이프에 연결해 이미지를 부팅하고 세션을 실행합니다. 모든 명령과 모든 오류, 지우기와 취소, CR LF, ESC 시퀀스, 너무 긴 줄, 키 생성, 공개 키 형식, zeroize, 줄 끝이 없는 200 kB, 연속 2000줄, 시리얼 브레이크를 다룹니다. `tools/qemu-boot-test.sh`는 `K0_BOOT_INPUT=on|off`, `K0_BOOT_SERVICE=vault|plain|none`, 판정 전용 모드 `K0_BOOT_JUDGE`를 읽습니다. + +**루트 태스크 자가 테스트**(`console-input`이 있는 이미지): `root: backspace without the input right [?]`와 `root: console input tests pass`입니다. 테스트 중에 바이트가 도착하면 둘째 줄은 `... pass (no input path)` 또는 `... cut short (the line is busy)`일 수도 있습니다. 터미널 이미지는 터미널이 없는 같은 이미지보다 `k0: task fault` 줄이 둘 더 나옵니다(볼트 없이 8줄, 볼트와 함께 10줄). + +## 알려진 공백 + +> [!NOTE] +> 실제 하드웨어에서는 아무것도 실행하지 않았습니다. SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU에서 실행되지 않으며, 가짜 UART를 쓰는 호스트 테스트로만 확인했습니다. UART 원인 없이 발생하는 인터럽트 선을 끄는 동작도 호스트 테스트로만 확인했습니다. + +- **인증 없음**: 시리얼 선은 그 선에 닿을 수 있는 사람만큼만 신뢰할 수 있습니다. 운영자는 키를 지울 수 있지만(설계상의 서비스 거부) 서명을 얻지 못하고 정책을 바꿀 수 없습니다. +- **외부가 구동하는 커널 코드**: 수신 코드는 EL1에서 실행됩니다. +- **분석하지 않은 타이밍 채널**: 외부 당사자가 이제 태스크가 실행되는 동안 인터럽트를 일으킬 수 있습니다(읽는 쪽이 정한 한계 안에서). 읽는 쪽은 틱보다 세밀한 도착 시각을 알게 되고, 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다. +- **지연**: 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 준비된 태스크마다 최대 한 틱씩 지연됩니다. +- **16550 콘솔에는 입력 없음**: 16550 콘솔에는 출력만 있고 입력은 없습니다. +- **폭주 중 측정 없음**: 어떤 테스트도 머신에서 폭주 중 커널 시간을 측정하지 않습니다. 한계는 게이트로 논증하고 호스트 테스트로 보였습니다. +- **프롬프트 전에 버림**: UART에 도착한 바이트를 센 것입니다. 바이트를 붙잡고 있는 에뮬레이터나 어댑터는 나중에 전달합니다(QEMU가 그렇습니다). +- **갈라진 화면 줄**: 운영자가 입력하는 동안 커널 줄이 나타나면 화면 줄은 갈라지지만 버퍼는 온전합니다. Enter는 버퍼 전체를 실행합니다. +- **줄을 흉내 낼 수 있음**: `Console` 출력이 있는 태스크는 여전히 커널 또는 루트 태스크 줄처럼 보이는 줄을 출력할 수 있습니다. 접두어를 인증하는 것이 없기 때문입니다. 터미널은 추가로 현재 줄 안에서 지울 수 있습니다. +- **서비스 모드에 서명 클라이언트 없음**: 키는 만들어 보여 주지만 다른 태스크가 아직 쓰지 않습니다. 클라이언트 서명은 자가 테스트가 보여 줍니다. +- **재시작 없음**: 터미널과 볼트는 죽어도 다시 시작되지 않습니다. 루트 태스크는 신뢰합니다. +- **부트 로그 몫**: 터미널 출력은 메모리 부트 로그의 사용자 몫을 소모합니다. 그 몫이 가득 차면 이후 태스크 출력은 거기에 기록되지 않습니다. +- **볼트의 이전 한계는 모두 유지**: 구현은 검증되지 않았고, 부채널 분석이 없고, 키는 승인된 난수 비트 생성기에서 나오지 않고, 영속성이 없고, 양자 내성 알고리즘이 없습니다. 가용성은 보호되지 않습니다([ipc_KR.md](ipc_KR.md) 참고). diff --git a/design/kr/uefi_KR.md b/design/kr/uefi_KR.md index f7d606f..0a7b698 100644 --- a/design/kr/uefi_KR.md +++ b/design/kr/uefi_KR.md @@ -183,7 +183,7 @@ $ K0_LOADER_FEATURES=refuse-halt tools/build-loader.sh - **호스트 단위 테스트**: `crates/k0-efi/src/tests.rs`에 32개가 있습니다. 벡터는 실제로 측정한 펌웨어 메모리 맵입니다. 디스크립터 규칙, 겹침, 항목 한계, 작성기와 재작성, 검증기, ACPI 리더, 트리 합성을 다룹니다. 네 번째 퍼저 `fuzz_acpi_with_mutated_tables`는 테이블 이미지를 변형합니다. 2026-11-12에 200만에서 300만 케이스의 캠페인이 통과했고, 앞서 실제 불일치 하나를 찾았습니다(리더가 커널의 디스커버리가 거부하는 GIC 프레임 정렬을 받아들였습니다). 커널의 배치 규칙을 리더에 적용해 수정했습니다. - **결정적 퍼저 셋**: `k0-efi`의 `fuzz_plan_with_random_maps`, `fuzz_rewrite_with_mutated_trees`, `fuzz_prepare_end_to_end`입니다. 다른 퍼저와 같은 변수 `K0_FUZZ_ITERS`, `K0_FUZZ_SEED`, `K0_FUZZ_CASE`를 사용합니다. 기본값은 각각 20,000, 20,000, 5,000개의 케이스입니다. 주간 워크플로가 셋 모두를 500만 케이스로 실행합니다. 2026-11-12에 각각 500만 케이스의 캠페인이 통과했습니다. 계획 퍼저는 앞서 실제 버그 하나를 찾았습니다(물리 주소 0의 블록이 받아들여졌습니다). 수정되었습니다. -- **호스트 테스트 스크립트**: `tools/host-test.sh`는 이제 ARM 호스트에서 276개(`k0-abi` 14, `k0-cap` 42, `k0-boot` 82, `k0-efi` 32, Ed25519 포함 13개와 제외 7개의 `k0-vault`, 두 그래뉼 각각에 `k0-mm` 43)를, `k0-mm` 테스트를 건너뛰는 그 밖의 호스트에서 190개를 실행합니다. +- **호스트 테스트 스크립트**: `tools/host-test.sh`는 이제 ARM 호스트에서 354개(`k0-abi` 15, `k0-cap` 44, `k0-boot` 85, `k0-efi` 33, `k0-conin` 15, Ed25519 포함 20개와 제외 11개의 `k0-vault`, 볼트 feature 포함 24개와 제외 21개의 `k0-term`, 두 그래뉼 각각에 `k0-mm` 43)를, `k0-mm` 테스트를 건너뛰는 그 밖의 호스트에서 268개를 실행합니다. - **PE 검사**: `tools/pe-check.py .efi`는 PE 형태(섹션 4개, 쓰기와 실행이 함께 가능한 섹션 없음)와 캐시 및 MMU 명령의 순서를 검사하고 `pe-check: ok (...)`를 출력합니다. - **EDK2 부팅 테스트**: `tools/qemu-virt-runner.sh`는 `.efi` 인자를 EDK2 펌웨어로 부팅합니다. 기본 머신은 `virt,gic-version=3,acpi=off`이므로 디바이스 트리 경로입니다. ACPI 행은 `K0_QEMU_MACHINE=virt,gic-version=3` 또는 `virt,gic-version=2`를 넘깁니다. `tools/qemu-boot-test.sh`는 로더의 첫 줄 `k0-loader: start`부터 실패를 판정하므로 펌웨어 메시지는 세지 않습니다. `tools/build-loader.sh <커널 ELF>`는 이미 빌드된 커널을 내장하고 `.efi`의 경로(`<커널 ELF>.efi`)를 출력합니다. 그래서 UEFI 행도 다른 행과 같은 커널 바이너리를 부팅합니다. 명령은 [USAGE_KR.md](../../USAGE_KR.md)에 있습니다. @@ -253,6 +253,7 @@ $ K0_LOADER_FEATURES=refuse-halt tools/build-loader.sh - **MADT의 GIC**: 분배기 항목 하나입니다. 버전 2는 GICv2, 3과 4는 GICv3, 0은 리디스트리뷰터가 기술되었는지로 정하고, 그 밖의 값은 거부합니다. GICv2 프레임 크기는 테이블에 없으므로 로더는 분배기에 4 KiB, CPU 인터페이스에 8 KiB를 사용합니다(Linux가 사용하는 값). GICv3 리디스트리뷰터는 GICR 항목(최대 4개)에서 오고, 없으면 CPU 항목에서 오며, 인접하면 128 KiB 또는 256 KiB 간격으로 병합합니다. 부트 CPU의 항목이 그 안에 있어야 합니다. 프레임은 정렬되어 있어야 하고, 서로 겹치지 않아야 하며, 메모리 맵 기준으로 RAM이나 펌웨어 메모리에 있으면 안 됩니다. 그렇지 않으면 로더가 거부합니다. - **GTDT의 타이머**: 가상 EL1 타이머 인터럽트는 16에서 31이어야 합니다. - **SPCR의 콘솔**(선택): PL011(타입 0x03), SBSA UART(0x0D, 0x0E), 그리고 16550(0x00, 0x01, 0x12)은 8비트 레지스터와 바이트 접근일 때만 받습니다. SPCR이 레지스터 간격을 표현할 수 없기 때문입니다. +- **SPCR의 콘솔 인터럽트**(선택): 인터럽트 종류는 GIC 하나뿐(비트 3만)이고 전역 시스템 인터럽트는 SPI(32~1019)여야 합니다. 로더는 이를 콘솔 노드의 `interrupts` 속성(SPI 번호, 레벨, 액티브 하이)으로 쓰고 커널은 [dtb_KR.md](dtb_KR.md)대로 읽습니다. 필드를 담기에 짧은 테이블이나 다른 형태는 인터럽트 없는 콘솔이 되며 거부가 아니라 입력만 꺼집니다. 번호는 `k0: platform` 줄(`irq33`)에 나타나므로, 이 필드가 생기기 전에 만든 고정 문자열은 더 이상 맞지 않습니다. - **거부와 콘솔 없는 부팅의 구분**: 잘못된 테이블, GIC, 타이머, 메모리에 있는 장치는 거부합니다(`ACPI tables: `). 커널에 드라이버가 없는 콘솔, 잘못된 SPCR, 메모리에 있는 콘솔은 콘솔 없는 부팅이 됩니다. 로더는 `k0-loader: device tree built from ACPI tables (MADT, GTDT and SPCR)` 또는 `(MADT and GTDT, no usable SPCR console)`을 출력합니다. - **엔트로피**: ACPI로 만든 트리에는 펌웨어 시드가 없습니다. 펌웨어에 `EFI_RNG_PROTOCOL`이 있으면 커널이 32바이트를 받고, 없으면 아무것도 받지 못합니다(`k0: entropy dtb=0B`를 로그에 남기고 계속합니다). - **작업 영역 비우기**: 로더는 점프 전에 작업 영역도 데이터 캐시에서 비웁니다. `tools/pe-check.py`는 비우기 호출 셋(블록, 작업 영역, 트램펄린)을 요구합니다. diff --git a/design/kr/vault_KR.md b/design/kr/vault_KR.md index f533a7f..4e6ca65 100644 --- a/design/kr/vault_KR.md +++ b/design/kr/vault_KR.md @@ -6,26 +6,28 @@ -이 노트는 K0의 격리 코어 위에 올라가는 첫 번째 서비스를 설명합니다. **볼트** 태스크가 Ed25519 키 하나를 보관합니다. 클라이언트 태스크는 IPC로 서명과 공개 키를 받고, 키는 받지 못합니다. 코드는 `userspace/k0-vault`(크레이트), `userspace/root-task/src/oracle.rs`(연결과 자가 테스트), `crates/k0-boot`(부팅 시드)에 있습니다. +이 노트는 K0의 격리 코어 위에 올라가는 첫 번째 서비스를 설명합니다. **볼트** 태스크가 Ed25519 키 하나를 보관합니다. 클라이언트 태스크는 IPC로 서명과 공개 키를 받고, 키는 받지 못합니다. 코드는 `userspace/k0-vault`(크레이트), `userspace/root-task/src/oracle.rs`(연결과 자가 테스트), `userspace/root-task/src/service.rs`(자가 테스트 뒤에 시작하는 서비스), `crates/k0-boot`(부팅 시드)에 있습니다. `terminal`로 빌드한 이미지에서는 직렬 터미널이 볼트의 운영자입니다("서비스 볼트와 운영자" 절 참고). > [!NOTE] > 볼트는 선택 사항이며 기본값은 꺼짐입니다. 기본 이미지에는 볼트도 암호 코드도 없습니다. ## 목적과 범위 -볼트는 격리 코어가 비밀을 그것을 쓰는 태스크로부터 떼어 놓을 수 있음을 보여 줍니다. 서비스는 작고 고정되어 있습니다. 상태를 알려 주고, 공개 키를 돌려주고, 1024바이트까지의 메시지에 서명합니다. +볼트는 격리 코어가 비밀을 그것을 쓰는 태스크로부터 떼어 놓을 수 있음을 보여 줍니다. 서비스는 작고 고정되어 있습니다. 상태를 알려 주고, 공개 키를 돌려주고, 1024바이트까지의 메시지에 서명합니다. 키는 두 단계로 만들어집니다. 루트 태스크가 시드를 넘기고, 그다음 admin 또는 operator가 키를 만들게 합니다. 알고리즘은 Ed25519입니다(SHA-512를 쓰는 PureEdDSA, FIPS 186-5와 RFC 8032). 구현은 vendor에 넣은 크레이트 `ed25519-dalek` 2.2.0이며 어떤 종류의 검증도 받지 않았습니다. 키는 승인된 난수 비트 생성기에서 나오지 않습니다. 이를 위해 `vendor/`에 크레이트 14개를 추가했고, 그중 절반은 빌드 시점 또는 다른 타겟용 코드라서 K0 이미지에 컴파일되어 들어가지 않습니다. ## 오브젝트와 누가 무엇을 매핑할 수 있는가 -![루트 태스크가 볼트, 클라이언트, 엔드포인트 하나, 프레임 두 개를 만듭니다. 클라이언트는 송신 전용 배지 엔드포인트 케이퍼빌리티를 가집니다. 요청 프레임은 클라이언트가 읽기·쓰기, 볼트가 읽기 전용입니다. 응답 프레임은 볼트가 읽기·쓰기, 클라이언트가 읽기 전용입니다.](../../assets/vault-flow_KR.svg) +

+ 루트 태스크가 볼트, 클라이언트, 엔드포인트 하나, 프레임 두 개를 만듭니다. 클라이언트는 송신 전용 배지 엔드포인트 케이퍼빌리티를 가집니다. 요청 프레임은 클라이언트가 읽기·쓰기, 볼트가 읽기 전용입니다. 응답 프레임은 볼트가 읽기·쓰기, 클라이언트가 읽기 전용입니다. +

루트 태스크는 다음 오브젝트를 만듭니다. -- **엔드포인트 하나**: 볼트가 여기서 받습니다. 클라이언트의 CNode에는 송신 전용 배지 복사본만 있습니다(자가 테스트에서는 보고용 엔드포인트도 있습니다). +- **엔드포인트 하나**: 볼트가 여기서 받습니다. 클라이언트의 CNode에는 송신 전용 배지 복사본만 있습니다(자가 테스트에서는 보고용 엔드포인트도 있습니다). 터미널은 operator 배지가 붙은 같은 종류의 복사본을 받습니다. - **볼트 태스크**: 자체 주소 공간과 자체 스택을 가집니다. 키는 여기에 있습니다. -- **호출자마다 요청 프레임과 응답 프레임**: 요청 프레임은 호출자가 읽기·쓰기, 볼트가 읽기 전용입니다. 응답 프레임은 볼트가 읽기·쓰기, 호출자가 읽기 전용입니다. 프레임 케이퍼빌리티의 권한을 줄인 복사본으로 강제합니다. +- **호출자마다 요청 프레임과 응답 프레임**: 요청 프레임은 호출자가 읽기·쓰기, 볼트가 읽기 전용입니다. 응답 프레임은 볼트가 읽기·쓰기, 호출자가 읽기 전용입니다. 프레임 케이퍼빌리티의 권한을 줄인 복사본으로 강제합니다. operator는 예외입니다. 읽기 전용으로 매핑된 응답 프레임만 있고 요청 프레임은 없습니다. > [!WARNING] > 루트 태스크가 이 모든 것을 만들므로 격리의 바깥에 있으며 볼트를 읽을 수 있습니다. 성립하는 문장은 "루트 태스크 외의 어떤 태스크도 볼트의 메모리를 매핑할 수 없다"입니다. @@ -49,46 +51,82 @@ | MR2 | 지표 비트 | | MR3 | nonce | -연산은 `STATUS`, `PUBLIC_KEY`, `SIGN`(요청 프레임에 1024바이트까지의 메시지)이며, admin 배지에만 `INIT`(시드와 시드 정보 40바이트, 한 번)과 `ZEROIZE`가 있습니다. +연산은 다음과 같습니다. + +| 연산 | 의미 | +| --- | --- | +| `STATUS` | 상태, 키의 알고리즘, 이미지에 들어 있는 알고리즘 | +| `PUBLIC_KEY` | 응답 프레임으로 받는 공개 키 | +| `SIGN` | 요청 프레임에 있는 1024바이트까지의 메시지에 서명 | +| `INIT` | 시드와 시드 정보(40바이트)를 넘깁니다(admin 전용, 한 번). 키는 만들지 않습니다 | +| `KEYGEN` | MR0에 실린 알고리즘으로 쥐고 있는 시드에서 키를 만들고 시드를 지움 | +| `ZEROIZE` | 키와 쥐고 있는 시드를 지움 | + +`STATUS`는 상태, 키의 알고리즘, 이미지에 들어 있는 알고리즘을 MR1의 한 워드에 묶습니다(`proto::status_word`). **단일 가져오기**: `server::fetch`는 길이를 먼저 고정한 뒤 본문을 volatile 읽기로 비공개 버퍼에 한 번만 읽습니다. 사본만 사용하므로 호출 중에 프레임을 바꾸는 호출자는 얻는 것이 없습니다. 응답 프레임은 nonce와 길이로 시작하고, `server::publish`는 nonce를 마지막에 기록합니다. 클라이언트는 자신의 nonce가 담긴 `OK` 응답을 받은 뒤에만 프레임을 믿어야 합니다. -상태 기계는 `userspace/k0-vault/src/server.rs`의 `Vault::handle`입니다. +볼트는 배지와 연산만으로 어느 프레임을 읽고 쓸지 정합니다(`proto::fetch_plan`과 `proto::publish_plan`). 요청 본문이 있는 연산은 `SIGN`과 `INIT`뿐이고, 응답 본문이 있는 연산은 `PUBLIC_KEY`와 `SIGN`뿐입니다. 가질 수 없는 본문을 가졌다고 말하는 요청은 `BAD_REQUEST`로 거부되고, 볼트는 그때 메모리를 건드리지 않습니다. 요청 프레임이 없는 operator에게 이것이 중요합니다. 꾸며 낸 길이로 볼트가 매핑되지 않은 주소를 읽게 할 수 없습니다. + +상태 기계는 `userspace/k0-vault/src/server.rs`의 `Vault::handle`입니다. 볼트는 다섯 상태 중 하나입니다. + +| 상태 | 의미 | +| --- | --- | +| `fresh` | 시드도 키도 없음 | +| `seeded` | `INIT`이 엔트로피 규칙을 통과한 시드를 넘겼고 볼트가 쥐고 있음 | +| `ready` | `KEYGEN`이 키를 만들고 시드를 지움 | +| `zeroized` | `ZEROIZE`가 키와 시드를 지움. 새 키는 재부팅해야 만들 수 있음 | +| `failed` | 자가 테스트 또는 쌍 일관성 테스트가 실패함. 이 상태로 가는 모든 길에서 시드와 키를 지움 | + +키는 부팅당 하나입니다. 두 번째 `KEYGEN`은 `KEY_EXISTS`(터미널에서는 `key-exists`)로 거부됩니다. ## 고정된 정책과 배지 -정책은 빌드 시점에 고정되며 엔드포인트 배지를 키로 사용합니다. 배지는 커널이 전달하며 클라이언트가 위조할 수 없습니다([ipc_KR.md](ipc_KR.md) 참고). 역할은 다음과 같습니다. +정책은 빌드 시점에 고정되며 엔드포인트 배지를 키로 사용합니다. 배지는 커널이 전달하며 클라이언트가 위조할 수 없습니다([ipc_KR.md](ipc_KR.md) 참고). 역할은 빌드 시점에 고정된 네 가지입니다. | 역할 | 연산 | | --- | --- | -| admin (루트 태스크) | `STATUS`, `INIT`, `ZEROIZE`, `SIGN`은 불가 | +| admin (루트 태스크) | `STATUS`, `INIT`, `KEYGEN`, `ZEROIZE`, `SIGN`과 `PUBLIC_KEY`는 불가 | +| operator (터미널) | `STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`, `SIGN`과 `INIT`은 불가 | | signer | `STATUS`, `PUBLIC_KEY`, `SIGN` | | reader | `STATUS`, `PUBLIC_KEY` | -배지가 없거나 알 수 없는 배지의 호출은 거부됩니다. 어떤 연산도 정책을 바꾸지 않습니다. 모든 signer가 키 하나를 공유하므로 서명에는 클라이언트 신원이 담기지 않습니다. +operator는 서명을 받을 수도 시드를 넘길 수도 없습니다. 배지가 없거나 알 수 없는 배지의 호출은 거부됩니다. 어떤 연산도 정책을 바꾸지 않습니다. 모든 signer가 키 하나를 공유하므로 서명에는 클라이언트 신원이 담기지 않습니다. ## 프로바이더 경계 `userspace/k0-vault/src/provider.rs`만 암호 크레이트에 닿습니다. - **자가 테스트**: 시작할 때 RFC 8032 벡터 두 개로 알려진 답 테스트를 합니다(공개 키, 서명, 검증, 바뀐 메시지와 바뀐 서명의 거부). -- **키 생성과 엔트로피 규칙**: 부팅 시드에 `rng-seed` 32바이트 이상 또는 RNDR 256비트가 없으면 볼트는 키 생성을 거부합니다(상태 `NO_ENTROPY`). QEMU virt는 32바이트 `rng-seed`를 제공합니다. -- **쌍 일관성 테스트**: 키 생성 뒤에 자신의 서명이 검증되는지 확인합니다. 자가 테스트 실패 또는 쌍 일관성 테스트 실패는 볼트를 `STATUS` 외의 모든 것을 거부하는 실패 상태로 만듭니다. +- **시드 검사와 엔트로피 규칙**: 부팅 시드에 `rng-seed` 32바이트 이상 또는 RNDR 256비트가 없으면 `INIT`은 시드를 거부하고(상태 `NO_ENTROPY`), 전부 0인 시드도 거부합니다. 알고리즘이 없는 이미지의 볼트는 시드를 거부하고(`UNSUPPORTED`) `fresh`에 머뭅니다. QEMU virt는 32바이트 `rng-seed`를 제공합니다. +- **키 생성**: `KEYGEN`은 고른 알고리즘으로 쥐고 있는 시드에서 키를 만들고, 키가 나오든 아니든 시드를 지웁니다. +- **쌍 일관성 테스트**: 키 생성 뒤에 자신의 서명이 검증되는지 확인합니다. 자가 테스트 실패 또는 쌍 일관성 테스트 실패는 볼트를 `STATUS` 외의 모든 것을 거부하는 `failed` 상태로 만듭니다. - **엄격한 검증**: 검증은 `verify_strict`를 사용합니다. - **키 내보내기 없음**: 키를 돌려주는 연산이 없습니다. -- **제로화**: `ZEROIZE`는 키를 버립니다(크레이트가 지웁니다). 이후 볼트는 `SIGN`과 `PUBLIC_KEY`를 거부합니다. -- **지표 비트**: 모든 응답에 비트 네 개가 있습니다. 알고리즘이 FIPS 186-5에 있음, 자가 테스트 통과, `rng-seed` 32바이트 이상이 키 시드에 들어감, RNDR이 키 시드에 들어감입니다. +- **제로화**: `ZEROIZE`는 키(크레이트가 지웁니다)와 쥐고 있는 시드를 버립니다. 이후 볼트는 `SIGN`, `PUBLIC_KEY`, `KEYGEN`을 거부합니다. +- **지표 비트**: 모든 응답에 비트 네 개가 있습니다. 알고리즘이 FIPS 186-5에 있음, 자가 테스트 통과, `rng-seed` 32바이트 이상이 키 시드에 들어감, RNDR이 키 시드에 들어감입니다. `STATUS`는 뒤의 두 비트를 볼트가 아직 쥐고 있는 시드에 대해서도 알립니다. 비트는 바이트가 있었다는 뜻이지 그 바이트를 예측할 수 없었다는 뜻이 아닙니다. ## 부팅 시드 경로 커널은 루트 태스크용 32바이트를 자체 도메인 문자열로 SHA-256에 넣어 만듭니다. 입력은 DTB 엔트로피, 카운터, 그리고 CPU에 RNDR이 있으면 새 RNDR 워드 네 개입니다(`k0_boot::derive_root_seed`). 도메인 분리로 PAC 키와는 서로 독립입니다. 시드는 입력만큼만 좋습니다. -시드는 루트 태스크의 진입 레지스터 `x0`부터 `x3`로 전달됩니다. `x4`는 사용한 `rng-seed` 바이트 수(비트 15부터 0)이고, 비트 16은 RNDR이 기여했음을 뜻합니다. bootinfo 페이지에는 없으며 `bootinfo::VERSION`은 3입니다. 루트 태스크는 `root: boot seed from rng-seed bytes 0x... and rndr` 또는 `... without rndr`만 출력하고 시드는 출력하지 않습니다. 이후 `INIT`으로 시드를 볼트에 줍니다. +시드는 루트 태스크의 진입 레지스터 `x0`부터 `x3`로 전달됩니다. `x4`는 사용한 `rng-seed` 바이트 수(비트 15부터 0)이고, 비트 16은 RNDR이 기여했음을 뜻합니다. bootinfo 페이지에는 없으며 `bootinfo::VERSION`은 4입니다. 루트 태스크는 `root: boot seed from rng-seed bytes 0x... and rndr` 또는 `... without rndr`만 출력하고 시드는 출력하지 않습니다. 이후 `INIT`으로 시드를 볼트에 주며, `INIT`은 시드를 전달할 뿐입니다. 키는 나중에 `KEYGEN`이 만듭니다. **시드 지우기**: FDT 파서는 `rng-seed`와 `kaslr-seed` 값의 위치를 기록하고, 두 번째 `/chosen` 노드는 거부합니다(`DuplicateChosen`, 파서를 공유하는 UEFI 로더의 사전 검사에서도 같습니다). 커널은 루트 태스크에 진입하기 직전에 그 바이트를 0으로 만듭니다. `k0_mm::wipe_ro_alias`가 페이지의 읽기 전용 별칭 항목을 제자리에서 읽기·쓰기로 바꾸고(break-before-make), 0을 쓰고, 캐시 라인을 clean 및 invalidate한 뒤 되돌립니다. 이어서 커널은 그 바이트를 다시 읽어 확인하고, `BootInfo`에 있는 자신의 사본을 지우고, `k0: dtb seeds wiped B`(QEMU virt에서는 40B)를 출력하고, 살아 있는 프레임 아래의 부트 스택을 0으로 만듭니다. 이것이 커널이 DTB 매핑으로 하는 유일한 쓰기이며, DTB를 파싱하고 검증한 뒤에 일어납니다. > [!NOTE] -> 펌웨어나 UEFI 로더가 보관하는 사본과 부트 스택의 살아 있는 프레임 안의 값은 지워지지 않습니다. 스택 사본 지우기(커널 부트 스택, 서명 뒤의 볼트 스택)는 최선 노력입니다. +> 펌웨어나 UEFI 로더가 보관하는 사본과 부트 스택의 살아 있는 프레임 안의 값은 지워지지 않습니다. 스택 사본 지우기(커널 부트 스택, 키 생성과 서명 뒤의 볼트 스택)는 최선 노력입니다. + +## 서비스 볼트와 운영자 + +진짜 부트 시드는 정확히 한 번 쓰입니다. `terminal`과 `vault`로 빌드한 이미지에서 루트 태스크는 먼저 자가 테스트를 모두 실행합니다. 그다음 새 볼트인 **서비스 볼트**를 띄우고 `INIT`으로 부트 시드를 넘깁니다. 그리고 `root: vault seeded`, `root: vault has no seed (boot seed has no entropy)`, `root: vault has no seed (no algorithm in this image)` 중 하나를 출력합니다. 그 밖의 모든 이미지에서 루트 태스크는 진입하자마자 시드를 지웁니다. + +이어서 루트 태스크는 터미널과 똑같이 배선한 적대적 태스크 둘을 실행합니다. 둘은 거부되어야 하고 폴트로 끝나야 합니다. 그 뒤 루트 태스크는 자신의 admin 케이퍼빌리티를 버리고, 터미널을 시작하고, 영원히 대기합니다. 터미널은 operator 배지로 서비스 볼트에 `STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`만 요청할 수 있습니다. 터미널의 명령, 화면, 한계는 [USAGE_KR.md](../../USAGE_KR.md)에 있습니다. + +> [!WARNING] +> 직렬 선에는 인증이 없습니다. 선에 닿는 사람은 누구나 operator이며, 키 소거를 포함한 operator의 네 연산을 그대로 할 수 있습니다. operator는 서명을 받을 수 없고 정책을 바꿀 수 없습니다. + +자가 테스트 볼트는 다른 볼트입니다. 공개된 RFC 8032 시험 시드와 진짜 시드 정보로 키를 만들어서 엔트로피 규칙은 그대로 실행되고, 진짜 시드는 이 볼트에 닿지 않습니다. ## feature와 고정된 이미지 @@ -97,7 +135,13 @@ - `vault`: 서비스, 프로토콜, 정책, 자가 테스트이며 서명 알고리즘은 없습니다. 모든 서명 요청에 `UNSUPPORTED`로 답합니다. - `vault-ed25519`: Ed25519를 추가합니다. -다음과 같이 빌드할 수 있습니다. +같은 크레이트의 feature `terminal`은 운영자 터미널을 추가합니다. `vault`와 함께 쓰면 터미널이 볼트의 operator가 되고, `vault-ed25519`와 함께 쓰면 Ed25519 키를 만들 수 있습니다. 기본값은 꺼짐이며 콘솔 드라이버가 필요합니다. 터미널 이미지는 다음과 같이 빌드합니다. + +```sh +$ cargo build -p k0-kernel --features console,terminal,vault-ed25519 +``` + +볼트가 든 이미지는 다음과 같이 빌드할 수 있습니다. ```sh $ cargo build -p k0-kernel --features console,vault-ed25519 @@ -107,17 +151,18 @@ $ cargo build -p k0-kernel --features console,vault-ed25519 ## 테스트 방법 -**호스트 테스트**(`tools/host-test.sh`가 알고리즘 feature 유무로 `k0-vault`를 실행합니다). 테스트는 `userspace/k0-vault/src/tests.rs`에 있으며 Ed25519가 있으면 13개, 없으면 7개입니다. 이름은 다음과 같습니다. +**호스트 테스트**(`tools/host-test.sh`가 알고리즘 feature 유무로 `k0-vault`를 실행합니다). 테스트는 `userspace/k0-vault/src/tests.rs`에 있으며 Ed25519가 있으면 20개, 없으면 11개입니다. 이름은 다음과 같습니다. -- 항상: `badges_map_to_fixed_roles`, `policy_is_enforced_before_anything_else`, `malformed_requests_are_refused_whole`, `a_seed_without_real_entropy_makes_no_key`, `init_happens_once_and_zeroize_is_final`, `fetch_clamps_the_length_and_publish_writes_header_and_body`, 그리고 `without_an_algorithm_every_signing_request_is_unsupported`(마지막 것은 알고리즘이 없을 때만). -- Ed25519가 있을 때: `the_self_test_passes_and_is_reported`, `signatures_verify_and_the_key_follows_the_seed`, `a_public_key_request_carries_no_body`, `unknown_algorithms_are_unsupported`, `nothing_is_served_after_zeroize`, `a_small_order_public_key_is_refused_even_with_a_matching_signature`, `a_failed_vault_refuses_everything_but_status`. +- 항상: `badges_map_to_fixed_roles_and_frames`, `each_role_may_do_exactly_its_operations`, `no_frame_is_touched_for_a_request_that_cannot_have_a_body`, `a_request_that_claims_a_body_it_cannot_have_is_refused`, `the_status_word_packs_state_algorithm_and_what_is_built`, `a_call_without_a_known_badge_is_denied`, `malformed_requests_are_refused_whole`, `a_seed_without_real_entropy_makes_no_key`, `the_seed_is_taken_once_and_zeroize_is_final`, `fetch_clamps_the_length_and_publish_writes_header_and_body`, 그리고 `without_an_algorithm_the_vault_takes_no_seed_and_serves_nothing`(마지막 것은 알고리즘이 없을 때만). +- Ed25519가 있을 때: `the_self_test_passes_and_is_reported`, `key_generation_follows_the_states`, `the_operator_gets_the_public_key_and_never_a_signature`, `a_vault_that_fails_holds_no_secret`, `signatures_verify_and_the_key_follows_the_seed`, `a_public_key_request_carries_no_body`, `unknown_algorithms_are_unsupported`, `nothing_is_served_after_zeroize`, `a_small_order_public_key_is_refused_even_with_a_matching_signature`, `a_failed_vault_refuses_everything_but_status`. -다른 크레이트와 합치면 호스트 테스트는 ARM 호스트에서 276개, 그 외 호스트에서 190개입니다(`k0-mm` 제외). +다른 크레이트와 합치면 호스트 테스트는 ARM 호스트에서 354개, 그 외 호스트에서 268개입니다(`k0-mm` 제외). **루트 태스크 자가 테스트**(`userspace/root-task/src/oracle.rs`의 `test_oracle`, `vault`로 빌드한 이미지에만 있음). 다음을 검사합니다. - 자가 테스트가 보고되고, 배지 없는 호출이 거부됩니다. -- 부팅 시드로 키가 만들어지고, 두 번째 `INIT`은 거부됩니다. +- 자가 테스트 볼트가 `INIT`으로 공개된 RFC 8032 시험 시드를 받고(상태 `seeded`), operator는 시드를 넘기거나 서명할 수 없으며, 두 번째 `INIT`은 거부됩니다. +- `KEYGEN`이 그 시드로 키를 만들고, 두 번째 `KEYGEN`은 거부됩니다(`KEY_EXISTS`). - admin은 서명할 수 없습니다. - signer 클라이언트는 검증되는 서명을 받고, 바뀐 메시지나 바뀐 서명에는 검증이 실패합니다. - reader는 `SIGN`을 거부당합니다. @@ -128,14 +173,16 @@ $ cargo build -p k0-kernel --features console,vault-ed25519 표지는 `root: oracle tests pass`입니다. 클라이언트 태스크는 루트 CNode 슬롯이 부족해 하나의 클라이언트 주소 공간에서 차례로 실행됩니다. 이 테스트는 볼트와 클라이언트 사이의 격리를 보여 주며 클라이언트끼리의 격리는 보여 주지 않습니다. -**부팅 매트릭스 행**: `vault`, `vault-max`(RNDR), `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`, 그리고 정적 행 `vault-symbols`(기본 이미지에는 볼트나 암호 코드가 없고, 볼트 이미지에는 그 코드에서 온 쓰기 가능한 정적 변수가 없음)입니다. 매트릭스는 HVF가 있는 Mac에서 61행, CI에서 51행입니다. 이제 모든 이미지는 `k0: dtb seeds wiped B`와 `root: boot seed from rng-seed bytes ...`도 출력합니다. +**부팅 매트릭스 행**: `vault`, `vault-max`(RNDR), `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`, 그리고 정적 행 `vault-symbols`(기본 이미지에는 볼트나 암호 코드가 없고, 볼트 이미지에는 그 코드에서 온 쓰기 가능한 정적 변수가 없음)입니다. 매트릭스는 HVF가 있는 Mac에서 76행, CI에서 65행입니다. 터미널용 행은 `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi`, `hvf-term`입니다. `tools/term-test.py `는 QEMU의 직렬 포트를 파이프에 연결해 터미널 이미지를 부팅하고 스크립트로 짠 세션을 실행합니다. 이제 모든 이미지는 `k0: dtb seeds wiped B`와 `root: boot seed from rng-seed bytes ...`도 출력합니다. ## 알려진 공백 > [!NOTE] > 구현은 검증을 받지 않았고, 이 커널에서 크레이트의 부채널 분석은 없으며, 오라클은 QEMU(TCG와 HVF)에서만 실행했습니다. -- **키 하나**: 영속성, 키 가져오기·내보내기, DRBG, 운영자 입력, 양자 내성 알고리즘이 아직 없습니다. +- **키 하나**: 영속성, 키 가져오기·내보내기, DRBG, 양자 내성 알고리즘이 아직 없습니다. 새 키를 만들려면 재부팅해야 합니다. +- **서비스 모드에 서명 클라이언트 없음**: 서비스 볼트의 키는 만들어지고 표시되지만 아직 다른 태스크가 쓰지 않습니다. 클라이언트 서명은 자가 테스트가 보여 줍니다. +- **터미널과 볼트는 죽어도 다시 시작하지 않습니다**: 죽으면 그대로 멈춥니다. 루트 태스크는 신뢰 대상입니다. - **가용성은 보호되지 않습니다**: 클라이언트는 엔드포인트 하나를 공유하며 모든 호출에 타임아웃을 써야 합니다([ipc_KR.md](ipc_KR.md) 참고). - **루트 태스크는 신뢰 대상입니다**: 볼트를 만들고 읽을 수 있습니다. - **클라이언트 신원 없음**: 모든 signer가 키 하나를 공유합니다.