diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 96fd239..5f9218c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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`, `k0-conin`, `k0-slice`, `k0-vault` and `k0-term` on any host (363 tests on an AArch64 host, 277 elsewhere). `k0-slice` has 9 tests: they run the rule that decides whether a tick cuts the running task on a model of the scheduler. 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/host-test.sh` runs the tests of `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-conin`, `k0-slice`, `k0-vault` and `k0-term` on any host (377 tests on an AArch64 host, 289 elsewhere). `k0-slice` has 9 tests: they run the rule that decides whether a tick cuts the running task on a model of the scheduler. 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. The time slice test runs twice (a task that got the CPU by `YIELD`, then one that got it by blocking) and takes about 4 seconds in all where the preemption test it replaced took about 1. It also expects `root: slice test yield pass` and `root: slice test block pass`, in this order, before `root: preempt test pass`. 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 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. +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 82 rows in total on a Mac with HVF and 71 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 6c799e8..9f4bc41 100644 --- a/CONTRIBUTING_KR.md +++ b/CONTRIBUTING_KR.md @@ -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-conin`, `k0-slice`, `k0-vault`, `k0-term`의 테스트를 어느 호스트에서나 실행합니다(AArch64 호스트에서 363개, 그 밖에서 277개). `k0-slice`는 9개이며, 틱이 실행 중인 태스크를 끊을지 정하는 규칙을 스케줄러 모델로 검사합니다. `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/host-test.sh`는 `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-conin`, `k0-slice`, `k0-vault`, `k0-term`의 테스트를 어느 호스트에서나 실행합니다(AArch64 호스트에서 377개, 그 밖에서 289개). `k0-slice`는 9개이며, 틱이 실행 중인 태스크를 끊을지 정하는 규칙을 스케줄러 모델로 검사합니다. `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초 더 걸립니다. 시간 조각 테스트는 두 번(`YIELD`로 CPU를 받은 태스크, 기다림으로 받은 태스크) 실행해 합계 약 4초가 걸리며, 이를 대신한 이전 선점 테스트는 약 1초가 걸렸습니다. `root: preempt test pass`보다 앞에 `root: slice test yield pass`와 `root: slice test block pass`가 이 순서로 나오는 것도 기대합니다. 느린 환경에서는 `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에서 76행, CI에서 65행입니다. 행 `input-*`와 `term-*`는 콘솔 입력과 터미널을 다룹니다. 터미널 이미지는 `k0: task fault` 줄이 두 개 더 나오며(볼트 없이 8개, 볼트와 함께 10개), `tools/term-test.py <이미지>`가 정해진 직렬 세션을 실행합니다. 행의 내용은 [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에서 82행, CI에서 71행입니다. 행 `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/Cargo.lock b/Cargo.lock index c65ce7c..d9ba5b8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -186,6 +186,7 @@ name = "k0-mm" version = "0.1.0" dependencies = [ "k0-abi", + "k0-cap", ] [[package]] diff --git a/INTRODUCTION.md b/INTRODUCTION.md index 1b3c6d3..3c8c726 100644 --- a/INTRODUCTION.md +++ b/INTRODUCTION.md @@ -56,7 +56,7 @@ K0 is meant to become the isolation core of high-security systems. The targets a - The processor is ARMv8-A or ARMv9-A and little-endian. - The boot loader enters the kernel following the Linux arm64 Image protocol. The memory map is switched off (MMU off), the level is EL1 or the hypervisor level (EL2), and the address of the device tree is in register x0. - The interrupt controller is a GICv2 or GICv3, and the processor has the ARM generic timer. - - RAM lies below 2^47 bytes (128 TiB). + - RAM lies below 2^47 bytes (128 TiB) and inside the physical address width of the CPU. - The boot loader starts exactly one processor core. K0 uses that one core. The image can be loaded at any physical address that fits the page grid, and it always runs at the virtual address `0xFFFF_8000_0000_0000`. If it is started at EL2, the kernel sets up the EL2 state itself, steps down to EL1 once and never goes back. If it is started in any state it does not support, it stops instead of guessing. @@ -183,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). It has 76 rows locally with HVF and 65 in CI. +- **Tier 1**: checked by `tools/boot-matrix.sh` (CI runs it on QEMU 7.2). It has 82 rows locally with HVF and 71 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 @@ -191,6 +191,7 @@ The following picture summarizes what each evidence tier means. - 4 processor cores started by the machine (K0 still uses one) - The 16 KiB image on max and its refusal on cortex-a72 - The same image loaded at three other physical addresses (the header `text_offset` patched) and a refusal for an address off the 16 KiB grid + - Hostile boot input (the rows `dtb-pointer-end`, `dtb-pointer-above-pa`, `redist-stride`, `redist-stride-wide`, `ram-above-pa` and `sub-page-memory`): a device tree pointer at the end of the address range or beyond the physical address width of the CPU, a redistributor stride that would overflow the walk, RAM declared beyond that address width, and a memory range without one whole page. The kernel refuses the first four with a reason in the boot log and boots without handing the last range out. `redist-stride-wide` is the control: the largest stride that is accepted still boots - `xlnx-versal-virt` (RAM at address 0, GICv3 and PL011 elsewhere, entered at EL2) - A pinned image that boots on its own platform and refuses on another - A static check that the image does not touch the physical timer @@ -206,7 +207,7 @@ The following picture summarizes what each evidence tier means. - **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. + - **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, a serial break and, on QEMU 8.0 or later, a flood of 2000 breaks. - **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 @@ -274,9 +275,9 @@ What it does not stop: - The scheduler leaks timing. A task still changes when, and for how long, another task runs by choosing when to yield or block. This has not been analysed. K0 gives no real-time or latency promise: the tick is one second and the kernel cannot be interrupted. The one-to-two periods per turn describe this version, not an interface. - The kernel cannot be interrupted while it handles a system call. A long call, such as taking back a key to a large block of memory, delays every other task and every timeout. - 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 lines the kernel prints when a task ends (a crash, an exit, an unknown system call) share 4 KiB of the boot log and can no longer fill the kernel part. A task that can create tasks can still push such lines of other tasks out of the log. - 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. + - In an image with input, an outside party can cause interrupts while tasks run. Their number is bounded by the reader for bytes and by 256 per tick for characters with a line error, 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, plus one more tick when the running task was switched in between two ticks. - 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. @@ -355,6 +356,6 @@ In the following table, you can find the contents of each path in the repository | `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, terminal session test (`term-test.py`), 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`), device tree editor for hostile boot input (`fdt-patch.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 0ba85cd..244c352 100644 --- a/INTRODUCTION_KR.md +++ b/INTRODUCTION_KR.md @@ -56,7 +56,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - 프로세서는 ARMv8-A 또는 ARMv9-A이고 리틀 엔디언입니다. - 부트로더는 Linux arm64 Image 규약에 따라 커널에 진입시킵니다. 이때 메모리 지도는 꺼져 있고(MMU 꺼짐), 단계는 EL1 또는 하이퍼바이저 단계(EL2)이며, x0 레지스터에 디바이스 트리 주소가 담겨 있습니다. - 인터럽트 컨트롤러는 GICv2 또는 GICv3이고, 프로세서에 ARM 범용 타이머가 있습니다. - - RAM은 2^47 바이트(128 TiB) 아래에 있습니다. + - RAM은 2^47 바이트(128 TiB) 아래이면서 CPU의 물리 주소 폭 안에 있습니다. - 부트로더는 프로세서 코어를 정확히 하나만 시작시킵니다. K0는 그 코어 하나만 사용합니다. 이미지는 페이지 격자에 맞는 어떤 물리 주소에든 적재할 수 있고, 실행은 항상 가상 주소 `0xFFFF_8000_0000_0000`에서 합니다. EL2로 시작되면 커널이 EL2 상태를 직접 설정하고 EL1로 한 번 내려오며, 다시 돌아가지 않습니다. 지원하지 않는 상태로 시작되면 짐작해서 진행하지 않고 멈춥니다. @@ -184,7 +184,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. > [!NOTE] > 앞의 두 단계만 지원한다고 말할 수 있습니다. -- **1단계**: `tools/boot-matrix.sh`가 확인합니다(CI가 QEMU 7.2로 실행). 행은 HVF가 있는 로컬에서 76개, CI에서 65개입니다. +- **1단계**: `tools/boot-matrix.sh`가 확인합니다(CI가 QEMU 7.2로 실행). 행은 HVF가 있는 로컬에서 82개, CI에서 71개입니다. - **직접 부팅 행** - GICv3와 GICv2의 QEMU virt를 각각 EL1과 EL2로 진입 - CPU 모델 cortex-a72, cortex-a53, max @@ -192,6 +192,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - 머신이 코어 4개를 시작시키는 구성(K0는 여전히 코어 하나만 사용합니다) - max에서의 16 KiB 이미지와 cortex-a72에서의 거부 - 같은 이미지를 다른 물리 주소 세 곳에 적재(헤더의 `text_offset`을 고쳐서)한 경우와 16 KiB 격자에 맞지 않는 주소에서의 거부 + - 적대적인 부팅 입력(`dtb-pointer-end`, `dtb-pointer-above-pa`, `redist-stride`, `redist-stride-wide`, `ram-above-pa`, `sub-page-memory` 행): 주소 범위의 맨 끝이나 CPU의 물리 주소 폭 밖을 가리키는 디바이스 트리 포인터, 프레임을 걷는 덧셈을 넘치게 하는 리디스트리뷰터 간격, 그 주소 폭 밖에 선언된 RAM, 온전한 페이지가 하나도 없는 메모리 범위. 커널은 앞의 넷을 부트 로그에 사유를 남기고 거부하고, 마지막 범위는 내주지 않고 부팅합니다. `redist-stride-wide`는 대조용으로, 받아들이는 가장 큰 간격으로도 부팅하는지 봅니다 - `xlnx-versal-virt`(RAM이 주소 0, GICv3와 PL011은 다른 곳, EL2 진입) - 고정 빌드 이미지가 자기 플랫폼에서는 부팅하고 다른 플랫폼에서는 거부하는지 - 이미지가 물리 타이머를 건드리지 않는지 정적 검사 @@ -207,7 +208,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - **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까지 정해 둔 대화를 그대로 실행합니다. + - **터미널 행**: `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, 그리고 QEMU 8.0 이상에서는 break 2000번의 폭주까지 정해 둔 대화를 그대로 실행합니다. - **거부 확인**: 시리얼 로그로 확인하는 거부는 두 가지입니다. - 16 KiB 페이지가 없는 CPU에서의 16 KiB 이미지 - 내장 커널의 한 바이트를 뒤집은 로더 @@ -275,9 +276,9 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. - 스케줄러를 통한 타이밍 채널이 열려 있습니다. 태스크는 양보하거나 기다릴 시점을 골라 다른 태스크가 언제, 얼마나 오래 실행되는지를 여전히 바꿀 수 있습니다. 이는 분석하지 않았습니다. K0는 실시간 또는 지연 시간에 대한 약속을 하지 않습니다. 틱은 1초이고 커널은 중단할 수 없습니다. 한 번에 한 주기에서 두 주기라는 값은 이 버전의 동작이며 인터페이스가 아닙니다. - 커널은 시스템 콜을 처리하는 동안 중단할 수 없습니다. 큰 메모리 블록의 열쇠를 회수하는 것 같은 긴 호출은 다른 모든 태스크와 모든 타임아웃을 늦춥니다. - 커널 안의 치명적 오류, 또는 커널이 한 태스크의 탓으로 돌릴 수 없는 하드웨어 오류는 여전히 기계 전체를 멈춥니다. - - 부트 로그의 커널 부분은 충돌과 종료 줄로 가득 찰 수 있습니다. + - 태스크가 끝날 때 커널이 내는 줄(충돌, 종료, 알 수 없는 시스템 콜)은 부트 로그의 4 KiB를 나눠 쓰며, 더는 커널 부분을 채우지 못합니다. 태스크를 만들 수 있는 태스크는 여전히 다른 태스크의 그런 줄을 로그에서 밀어낼 수 있습니다. - 서명 오라클도 예외가 아닙니다. 클라이언트는 볼트로 가는 우편함 하나를 함께 사용하므로 모든 호출에 타임아웃을 줘야 하며, 그렇지 않으면 멈춘 볼트가 클라이언트를 붙잡습니다. - - 입력을 켠 이미지에서는 바깥 쪽이 태스크가 실행되는 동안에도 인터럽트를 일으킬 수 있습니다. 그 횟수는 읽는 쪽 속도로 제한되지만, 읽는 태스크는 타이머 틱보다 더 잘게 도착 시각을 알 수 있고 다른 태스크도 빼앗긴 시간을 눈치챌 수 있습니다. 이 시간 채널은 분석하지 않았습니다. + - 입력을 켠 이미지에서는 바깥 쪽이 태스크가 실행되는 동안에도 인터럽트를 일으킬 수 있습니다. 그 횟수는 바이트에 대해서는 읽는 쪽 속도로, 선로 오류가 난 문자에 대해서는 틱당 256개로 제한되지만, 읽는 태스크는 타이머 틱보다 더 잘게 도착 시각을 알 수 있고 다른 태스크도 빼앗긴 시간을 눈치챌 수 있습니다. 이 시간 채널은 분석하지 않았습니다. - 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없어서 지연은 준비된 태스크마다 최대 한 틱이며, 실행 중인 태스크가 두 틱 사이에 실행을 넘겨받았다면 한 틱이 더해집니다. - 입력 수신 코드는 커널(EL1)에서 실행됩니다. 작고 바이트를 해석하지 않지만, 바깥 쪽이 움직이는 커널 코드입니다. 이것을 사용자 공간 드라이버로 옮기려면 장치와 인터럽트를 넘겨 주는 기능이 필요한데, K0에는 아직 없습니다. - **열쇠고리와 주소 공간을 함께 사용하는 태스크**: 이런 태스크끼리는 격리되지 않습니다. 모든 것을 함께 사용하는 한 프로그램의 일부, 즉 스레드처럼 동작합니다. @@ -356,6 +357,6 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다. | `userspace/root-task` | 첫 프로그램과 자가 테스트, 서명 오라클의 연결과 자가 테스트(`oracle.rs`), 터미널 서비스의 시작(`service.rs`) | | `userspace/k0-term` | 운영자 터미널. 줄 편집, 명령 해석, 볼트로 보내는 요청 | | `userspace/k0-vault` | 서명 오라클 서비스. 프로토콜과 고정 정책, 요청 처리, 암호 크레이트를 감싸는 경계 | -| `tools/` | QEMU 러너(`.efi`도 지원), 부팅 테스트, 부팅 매트릭스, 터미널 대화 테스트(`term-test.py`), 부트 로그 읽기, 호스트 테스트, 로더 빌드(`build-loader.sh`), PE와 명령 순서 검사(`pe-check.py`) | +| `tools/` | QEMU 러너(`.efi`도 지원), 부팅 테스트, 부팅 매트릭스, 터미널 대화 테스트(`term-test.py`), 부트 로그 읽기, 호스트 테스트, 로더 빌드(`build-loader.sh`), PE와 명령 순서 검사(`pe-check.py`), 적대적인 부팅 입력을 만드는 디바이스 트리 편집(`fdt-patch.py`) | | `ci/` | CI 빌드·테스트 이미지(`Dockerfile`)와 위협 모델(`threat_model.md`) | | `vendor/` | 저장소 안에 함께 넣어 둔 서드파티 크레이트(`sha2`, `ed25519-dalek`과 그 의존성) | diff --git a/SECURITY.md b/SECURITY.md index 2264d96..375cd60 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -69,10 +69,10 @@ What is still NOT provided on `main`: - There is no real-time or latency promise. The kernel is not preemptible and the tick is one second. A task that becomes ready with k tasks to run before it (the running one included) now starts within k + 1 tick periods, where it used to start within k, so a wait can be up to one tick longer. A caller and a server that exchange calls behind one CPU-bound task needed 2 ticks per round trip in the model and need 4 now. A run of one to two periods and a wait of k + 1 periods describe this version of the scheduler and are not an interface. - Some mistakes in connecting the rule to the scheduler would be seen by no test on the real kernel: the tick's own switch passing the wrong entry kind, the idle loop reporting the wrong thing about a tick, and the entry kind at the hand-off to the root task. They change how long a task runs before it is cut, not its share. The host model covers the rule for these cases, not the kernel's use of it. The boot test does catch the old rule and a wrong entry kind on the yield path or the block path. - The measurements used an attacker whose yield point was set for it from a loop count that the root task measured. What an attacker needs to find that point by itself was not measured. Everything ran in QEMU (TCG and HVF), nothing on hardware. - - The kernel is not preemptible. A long system call, for example `CAP_REVOKE` on an `Untyped` with many objects, delays every other task and every timeout. + - The kernel is not preemptible. A long system call, for example `CAP_REVOKE` on an `Untyped` with many objects, delays every other task and every timeout. An `Untyped` capability cannot be split or capped, so a task that is given one can do this with all of it. Hand `Untyped` only to a task that is trusted with the availability of the whole system. The root task gives none to the terminal or the vault. - A `k0_arch::fatal` or a kernel panic still stops the machine, and so does an SError taken from EL0. - - The kernel part of the boot log can be filled by fault and exit lines. -- **Kernel resource exhaustion**: at boot the kernel reserves the page tables and the address space registry entries that the memory it hands out as `Untyped` can need, taking them from the top of each range. `RETYPE` therefore no longer fails with `KERNEL_RESOURCE` for lack of page tables, and the number of address spaces is limited only by memory. The reserve costs about 0.4 % of RAM with the 4 KiB granule (about 0.2 % each for the page tables and for the registry entries). A range that is too small for its own reserve is not handed out as `Untyped`. + - Filling the kernel part of the boot log with fault and exit lines is addressed on `main`. The lines the kernel prints when a task ends (a fault, an exit, an unknown system call) now have their own share of the log, 4 KiB, and stop before the last 2 KiB, which stay for the kernel. The kernel says so once (`k0: task lines over the log quota, later ones go to the console only`). Past that share such a line goes to the console only, so an image without a console driver loses it. What this protects is the kernel's own lines and that last part. All tasks share the one share, so a task that can create tasks can still push the fault and exit lines of other tasks out of the log. A boot with the terminal and the vault uses about a quarter of the share. +- **Kernel resource exhaustion**: at boot the kernel reserves the page tables and the address space registry entries that the memory it hands out as `Untyped` can need, taking them from the top of each range. `RETYPE` therefore no longer fails with `KERNEL_RESOURCE` for lack of page tables, and the number of address spaces is limited only by memory. The reserve costs about 0.4 % of RAM with the 4 KiB granule (about 0.2 % each for the page tables and for the registry entries). A range that is too small for its own reserve is not handed out as `Untyped`, and neither is a range without one whole page. - **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. @@ -81,7 +81,7 @@ What is still NOT provided on `main`: - **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. +- **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 or beyond the physical address width of the CPU, 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 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. @@ -196,11 +196,11 @@ An image without `console-input` contains no receive code, no `CONSOLE_READ` and 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. +- **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`. The read right is meant for one task: every holder takes bytes from the same ring, so a second holder can take input that was meant for the first, or occupy the wait. 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. +- **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 of bytes the interrupt rate is therefore bounded by the reader. A character with a break, framing or parity error uses no place in the ring, so it has its own bound: after 256 such characters in one tick the kernel masks the receive interrupt until the next tick. Bytes that arrive in between wait in the device FIFO and are marked as lost if it overruns. 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 ()`. @@ -215,10 +215,10 @@ 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. +3. An outside party can now cause interrupts while tasks run, bounded by the reader for bytes and by 256 per tick for characters with a line error. 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, plus one more tick when the running task got the CPU between two ticks. 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. +6. No test measures kernel time under a flood on a machine. The bounds are argued from the gate and the per-tick count and shown in host tests. The terminal test sends 2000 breaks under QEMU and checks only that the input path is not cut off and answers again. That step runs on QEMU 8.0 or later, so CI (QEMU 7.2) does not run it: an older QEMU puts a break into its PL011 receive FIFO without checking the depth, and breaks pile up there while the kernel keeps the interrupt masked. 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. diff --git a/SECURITY_KR.md b/SECURITY_KR.md index 27b5b33..9b7eff1 100644 --- a/SECURITY_KR.md +++ b/SECURITY_KR.md @@ -69,10 +69,10 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다. - 실시간이나 지연 시간에 대한 약속은 없습니다. 커널은 선점되지 않고 틱은 1초입니다. 자기보다 먼저 실행될 태스크가 k개(실행 중인 태스크 포함)일 때 준비된 태스크는 이제 k + 1 틱 주기 안에 시작하며, 전에는 k 주기 안에 시작했으므로 대기가 최대 한 틱 길어질 수 있습니다. CPU를 쓰는 태스크 하나 뒤에서 호출과 응답을 주고받는 호출자와 서버는 모델에서 왕복당 2틱이 걸렸고 이제는 4틱이 걸립니다. 한 번에 한 주기에서 두 주기를 실행한다는 것과 k + 1 주기를 기다린다는 수치는 이 버전의 스케줄러를 설명할 뿐 인터페이스가 아닙니다. - 규칙을 스케줄러에 연결하는 과정의 일부 실수는 실제 커널에 대한 어떤 테스트로도 발견되지 않습니다. 틱 자신의 전환이 잘못된 진입 종류를 넘기는 경우, 유휴 루프가 틱에 대해 잘못 보고하는 경우, 루트 태스크로 넘기는 시점의 진입 종류입니다. 이것은 태스크의 몫이 아니라 잘리기 전까지 실행되는 시간에 영향을 줍니다. 호스트 모델은 이 경우들에 대한 규칙을 검증할 뿐 커널이 규칙을 쓰는 방식은 검증하지 않습니다. 부팅 테스트는 이전 규칙과, 양보 경로나 블록 경로의 잘못된 진입 종류는 잡아냅니다. - 측정에 쓴 공격자는 루트 태스크가 잰 루프 횟수로 양보 시점을 미리 맞춰 준 공격자입니다. 공격자가 그 시점을 스스로 찾는 데 무엇이 필요한지는 측정하지 않았습니다. 모든 실행은 QEMU(TCG와 HVF)에서 했고 하드웨어에서는 실행하지 않았습니다. - - 커널은 선점되지 않습니다. 긴 시스템 콜(예: 오브젝트가 많은 `Untyped`에 대한 `CAP_REVOKE`)은 다른 모든 태스크와 모든 타임아웃을 지연시킵니다. + - 커널은 선점되지 않습니다. 긴 시스템 콜(예: 오브젝트가 많은 `Untyped`에 대한 `CAP_REVOKE`)은 다른 모든 태스크와 모든 타임아웃을 지연시킵니다. `Untyped` 케이퍼빌리티는 나누거나 상한을 걸 수 없으므로, 이것을 받은 태스크는 그 전체로 이 일을 할 수 있습니다. `Untyped`는 시스템 전체의 가용성을 맡길 수 있는 태스크에만 넘기세요. 루트 태스크는 터미널과 볼트에 `Untyped`를 주지 않습니다. - `k0_arch::fatal`이나 커널 패닉은 여전히 기계를 멈추며, EL0에서 발생한 SError도 마찬가지입니다. - - 부트 로그의 커널 부분이 폴트 및 종료 줄로 채워질 수 있습니다. -- **커널 자원 고갈**: 커널은 부팅할 때 `Untyped`로 내주는 메모리가 필요로 할 수 있는 페이지 테이블과 주소 공간 레지스트리 항목을 각 범위의 끝에서 떼어 미리 확보합니다. 따라서 `RETYPE`가 페이지 테이블 부족으로 `KERNEL_RESOURCE`와 함께 실패하는 일은 없고, 주소 공간의 수는 메모리로만 제한됩니다. 이 예약분은 4 KiB 그래뉼에서 RAM의 약 0.4 %입니다(페이지 테이블과 등록 항목이 각각 약 0.2 %). 자기 예약분을 담기에 너무 작은 범위는 `Untyped`로 내주지 않습니다. + - 폴트 및 종료 줄로 부트 로그의 커널 부분을 채우는 문제는 `main`에서 대응했습니다. 태스크가 끝날 때 커널이 내는 줄(폴트, 종료, 알 수 없는 시스템 콜)은 이제 로그에서 자기 몫 4 KiB만 쓰고, 커널용으로 남겨 둔 마지막 2 KiB 앞에서 멈춥니다. 커널은 이 사실을 한 번 알립니다(`k0: task lines over the log quota, later ones go to the console only`). 몫을 넘긴 줄은 콘솔에만 나가므로 콘솔 드라이버가 없는 이미지에서는 사라집니다. 이것이 지키는 것은 커널 자신의 줄과 그 마지막 부분입니다. 몫 하나를 모든 태스크가 나눠 쓰므로, 태스크를 만들 수 있는 태스크는 여전히 다른 태스크의 폴트 줄과 종료 줄을 로그에서 밀어낼 수 있습니다. 터미널과 볼트가 든 이미지의 부팅은 이 몫의 4분의 1쯤을 씁니다. +- **커널 자원 고갈**: 커널은 부팅할 때 `Untyped`로 내주는 메모리가 필요로 할 수 있는 페이지 테이블과 주소 공간 레지스트리 항목을 각 범위의 끝에서 떼어 미리 확보합니다. 따라서 `RETYPE`가 페이지 테이블 부족으로 `KERNEL_RESOURCE`와 함께 실패하는 일은 없고, 주소 공간의 수는 메모리로만 제한됩니다. 이 예약분은 4 KiB 그래뉼에서 RAM의 약 0.4 %입니다(페이지 테이블과 등록 항목이 각각 약 0.2 %). 자기 예약분을 담기에 너무 작은 범위는 `Untyped`로 내주지 않고, 온전한 페이지가 하나도 없는 범위도 내주지 않습니다. - **미구현 기능**: 핸들러 태스크로의 폴트 전달, 알림(notification), IPC를 통한 케이퍼빌리티 전송이 아직 없습니다. - **EL0에서 보이는 시간**: EL0는 여전히 하드웨어 카운터나 타이머를 읽을 수 없습니다. IPC 타임아웃은 태스크에 스케줄러 틱(1초)만큼 거친 시계와 타이머 인터럽트에 맞춰진 깨어남을 제공합니다. 이것이 캐시나 추측 실행 공격에 쓸 만한 시간 원천으로 증폭될 수 있는지는 분석하지 않았습니다. - **revoke 뒤의 송신자**: 엔드포인트에 이미 대기 중인 송신자는 케이퍼빌리티가 revoke된 뒤에도 한 번 전달됩니다. @@ -81,7 +81,7 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다. - **실행 코드**: 부팅 후에는 새 실행 코드를 로드할 수 없으므로, 격리된 태스크는 루트 태스크 이미지의 코드를 실행합니다. - **지원 범위**: [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` 노드는 거부합니다. +- **디바이스 트리의 주소**: 디바이스 트리의 주소는 처음 읽기 전에 검사할 방법이 없습니다. 부트로더가 이 주소를 `x0`로 넘기는데, 커널은 그 블롭을 읽기 전에는 메모리 맵을 모릅니다. 커널은 널이거나 정렬이 맞지 않는 주소, 2^47 이상이거나 CPU의 물리 주소 폭을 넘는 주소, 커널 이미지와 겹치는 구간을 거부합니다. 그런 다음 그 주소를 읽기 전용 일반 메모리로 매핑하고 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 [...]` 줄도 여기에 포함됩니다("선택적 콘솔 출력" 참고). - **EL2 트랩**: 격리는 기밀성과 무결성을 다루고 가용성은 다루지 않습니다. 커널이 EL1로 내려온 뒤 EL2로 트랩이 오면 설계상 기계 전체를 멈춥니다. - **EL2 진입**: EL2 진입은 Linux와 같은 펌웨어 약속을 전제로 합니다. EL3 펌웨어는 세분화된 트랩과 HCRX 제어 기능이 있으면 이를 켜 주어야 합니다. @@ -196,11 +196,11 @@ $ grep -a 'k0: console drivers' <이미지 파일> 커널이 입력으로 하는 일은 다음과 같습니다. - **수신 경로**: 커널의 UART 드라이버가 받은 바이트를 256바이트 링에 넣습니다. 커널은 바이트를 해석하지 않습니다. 손실(FIFO 오버런, 브레이크, 프레이밍 또는 패리티 오류)은 구멍 뒤의 바이트에 표시합니다. -- **입력 읽기**: `CONSOLE_READ`(시스템 콜 16번). 호출자가 `Console` 슬롯과 플래그(`NONBLOCK`, `FLUSH`, 63..32비트의 틱 단위 타임아웃, 그 밖의 비트는 `BAD_FLAGS`로 거부)를 지정합니다. 호출마다 한 바이트를 돌려줍니다. 한 번에 한 태스크만 기다릴 수 있고 두 번째 읽는 쪽은 `BUSY`를 받습니다. 입력 경로가 없거나 꺼져 있으면 `NO_DEVICE`를 돌려줍니다. 기다리던 태스크의 케이퍼빌리티가 삭제, revoke 또는 이동되면 즉시 `REVOKED`로 깨어납니다. 깨어난 읽는 쪽은 준비 큐의 맨 뒤로 가므로 입력은 선점하지 않습니다. +- **입력 읽기**: `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의 수신 인터럽트를 스스로 마스크하고, 읽는 쪽이 링의 절반을 가져간 뒤 다시 엽니다. 따라서 폭주 중에도 인터럽트 빈도는 읽는 쪽이 정하는 만큼으로 제한됩니다. 같은 비우기가 틱마다 한 번 더 실행되므로, 인터럽트가 오지 않아도 입력은 최대 한 틱 늦게 도착합니다. +- **인터럽트 작업의 상한**: 링이 가득 차면 커널이 UART의 수신 인터럽트를 스스로 마스크하고, 읽는 쪽이 링의 절반을 가져간 뒤 다시 엽니다. 따라서 바이트가 폭주해도 인터럽트 빈도는 읽는 쪽이 정하는 만큼으로 제한됩니다. 브레이크, 프레이밍 오류, 패리티 오류가 난 문자는 링의 자리를 쓰지 않으므로 따로 상한을 둡니다. 한 틱 동안 그런 문자가 256개 들어오면 커널은 다음 틱까지 수신 인터럽트를 마스크합니다. 그 사이에 온 바이트는 장치의 FIFO에서 기다리고, FIFO가 넘치면 유실로 표시됩니다. 같은 비우기가 틱마다 한 번 더 실행되므로, 인터럽트가 오지 않아도 입력은 최대 한 틱 늦게 도착합니다. - **인터럽트 번호**: 디바이스 트리(콘솔 노드의 `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 ()`입니다. @@ -215,10 +215,10 @@ $ grep -a 'k0: console drivers' <이미지 파일> 1. 직렬 회선은 그 회선에 닿을 수 있는 쪽만큼만 신뢰할 수 있습니다. 운영자는 키를 지울 수 있으며, 이는 설계상의 서비스 거부입니다. 2. 커널의 수신 코드는 EL1에서 실행됩니다. 작고 바이트를 해석하지 않지만, 외부 당사자가 구동하는 커널 코드입니다. 사용자 공간 드라이버에는 장치와 인터럽트의 위임이 필요한데, K0에는 이것이 없습니다. -3. 외부 당사자가 이제 태스크 실행 중에 인터럽트를 일으킬 수 있으며, 그 빈도는 읽는 쪽이 제한합니다. 읽는 쪽은 틱보다 정밀한 도착 시각을 알게 되고, 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다. 이것은 분석하지 않은 타이밍 채널입니다. +3. 외부 당사자가 이제 태스크 실행 중에 인터럽트를 일으킬 수 있으며, 그 빈도는 바이트에 대해서는 읽는 쪽이, 선로 오류가 난 문자에 대해서는 틱당 256개라는 상한이 제한합니다. 읽는 쪽은 틱보다 정밀한 도착 시각을 알게 되고, 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다. 이것은 분석하지 않은 타이밍 채널입니다. 4. 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 지연은 준비된 태스크마다 최대 한 틱이고, 실행 중인 태스크가 두 틱 사이에 CPU를 받았다면 한 틱이 더 붙습니다. 5. 16550 콘솔에는 입력이 없습니다. SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU에서 실행되지 않으며, 가짜 UART를 쓰는 호스트 테스트(`crates/k0-conin`)가 유일한 검증입니다. UART 원인 없이 발생하는 인터럽트 회선을 끊는 동작도 호스트 테스트로만 검증합니다. -6. 기계에서 폭주 중의 커널 시간을 측정한 테스트는 없습니다. 상한은 게이트에서 논증하고 호스트 테스트로 보입니다. +6. 기계에서 폭주 중의 커널 시간을 측정한 테스트는 없습니다. 상한은 게이트와 틱당 개수에서 논증하고 호스트 테스트로 보입니다. 터미널 테스트는 QEMU에서 브레이크를 2000번 보내고, 입력 경로가 끊기지 않고 다시 답하는지만 확인합니다. 이 단계는 QEMU 8.0부터만 실행하므로 CI(QEMU 7.2)에서는 실행되지 않습니다. 그 전의 QEMU는 브레이크를 PL011 수신 FIFO에 넣을 때 깊이를 확인하지 않는데, 커널이 인터럽트를 마스크해 둔 동안 브레이크가 거기에 쌓이기 때문입니다. 7. "프롬프트 전에 버림"은 UART에 닿은 바이트를 센 것입니다. 바이트를 붙잡아 두는 에뮬레이터나 어댑터는 나중에 전달하며, QEMU가 그렇게 합니다. 8. 운영자가 입력하는 동안 커널 줄이 나타나면 화면의 줄은 쪼개지지만 버퍼는 온전하며, Enter는 버퍼 전체를 실행합니다. 9. `Console` 출력이 있는 모든 태스크는 여전히 커널 줄이나 루트 태스크 줄처럼 보이는 줄을 출력할 수 있으며, 접두어를 인증하는 것은 없습니다. 터미널은 추가로 자기 현재 줄 안에서 지울 수 있습니다. diff --git a/USAGE.md b/USAGE.md index e544319..f89727b 100644 --- a/USAGE.md +++ b/USAGE.md @@ -88,7 +88,7 @@ The following table lists the lines that an image with a console driver prints, | `root: secret at 0x...`, then `k0: task fault ... far 0x...` with the same address | A confined task tried to read memory that only the root task may see, and it was stopped at exactly that address | | `k0: task fault ...` and `k0: unknown syscall 65535, killing task` | Rule violations that the tests cause on purpose. Each one stops only the task that broke the rule. A normal run has exactly 6 `k0: task fault` lines and 1 `k0: unknown syscall` line. An image built with a `vault` feature has 8 `k0: task fault` lines | | `k0: kernel reserve tables + address space entries = bytes in ranges` | The kernel set aside memory at the top of each range it hands out, for its own page tables and for the list of address spaces. It is printed before the `k0: untyped` lines. On QEMU virt with 512 MiB it reads `262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges`. The entry count depends on the image size | -| `k0: memory + not handed out ()` | A memory range was too small to hold its own share of that reserve, or the share could not be mapped, so the kernel did not hand the range out. The boot continues. A normal run on QEMU virt does not print it | +| `k0: memory + not handed out ()` | A memory range was too small to hold its own share of that reserve, the share could not be mapped, or the range holds no whole page, so the kernel did not hand the range out. The boot continues. A normal run on QEMU virt does not print it | | `root: timeout tests pass` | The self-tests of IPC timeouts passed | | `root: slice test yield pass` and `root: slice test block pass` | A task that got the CPU between two ticks (by `YIELD`, or after the previous task blocked) was not cut by the first tick it met. They come before `root: preempt test pass` | | `root: preempt test pass` | A task that never yields is still cut by the timer | @@ -124,6 +124,7 @@ The runner script `tools/qemu-virt-runner.sh` builds the QEMU command line from | `K0_QEMU_MEM` | `512M` | | `K0_QEMU_ACCEL` | none (QEMU's software emulation, TCG) | | `K0_IMAGE_TEXT_OFFSET` | none. Boots a copy of the image whose header `text_offset` is changed, so the same image is loaded at another physical address | +| `K0_IMAGE_DTB_POINTER` | none. Boots a copy of the image that replaces the device tree pointer it receives in `x0`: `end` for the last aligned address (0xFFFFFFFFFFFFFFF8), or an address with one 16-bit part set, such as 0x4a000000. The boot matrix uses it to pass a bad pointer and to boot from a device tree that QEMU has not edited, loaded with `-device loader` | | `K0_QEMU_MONITOR` | none. Path of a Unix socket for the QEMU monitor, used to read the boot log from memory | Everything after `--` is still passed to QEMU. @@ -287,7 +288,7 @@ Bytes that reached the UART before the prompt are dropped. If the input was lost 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. +- **Timing**: an outside party can now cause interrupts while tasks run (bounded by the reader for bytes and by 256 per tick for characters with a line error), 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, plus one more tick when the running task was switched in between two ticks. - **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. @@ -409,9 +410,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 363 host tests (277 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 363 are 15 (`k0-abi`), 44 (`k0-cap`), 85 (`k0-boot`), 33 (`k0-efi`), 15 (`k0-conin`), 9 (`k0-slice`, the rule that decides whether a tick cuts the running task, run on a model of the scheduler), 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/host-test.sh` runs the 377 host tests (289 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 377 are 15 (`k0-abi`), 52 (`k0-cap`), 85 (`k0-boot`), 33 (`k0-efi`), 19 (`k0-conin`), 9 (`k0-slice`, the rule that decides whether a tick cuts the running task, run on a model of the scheduler), 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 44 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 88. - `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 time slice test adds two runs of about 4 seconds in total where the preemption test it replaced took about 1. 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 76 rows on a Mac with HVF and 65 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 82 rows on a Mac with HVF and 71 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. @@ -455,7 +456,7 @@ The input and terminal rows check the receive path and the terminal. In the foll | `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. +`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, a serial break and, on QEMU 8.0 or later, a flood of 2000 breaks. `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 @@ -506,7 +507,7 @@ The following table lists what to do for each problem. | `runner: this kernel has no console driver and prints nothing here (build with --features console to see output)` | The image was built without a console feature, or the runner found `k0: console drivers [none]` in it. Build with `--features console` to see output, or read the boot log from memory | | `boot-test: the serial log has no kernel line` | The same cause: a kernel built without a console feature writes nothing to the serial port. Build with `--features console`, or judge the log in guest memory with `K0_BOOT_MEMLOG=` | | `boot-test` fails on a line that starts with `k0: all tasks` | Every task is waiting and no wait has a time limit, so nothing can wake a task. In the normal self-tests this does not happen. If you changed the root task, give each wait a timeout | -| `k0: memory + not handed out ()` appears in the boot log | The kernel found a memory range that is too small for its own reserve, or whose reserve it could not map. It left that range out and kept booting. The range is simply not usable as untyped memory. Check the memory size and the load address you gave QEMU | +| `k0: memory + not handed out ()` appears in the boot log | The kernel found a memory range that is too small for its own reserve, whose reserve it could not map, or that holds no whole page. It left that range out and kept booting. The range is simply not usable as untyped memory. Check the memory size and the load address you gave QEMU | | `root: oracle made no key (boot seed has no entropy)` appears, or `root: oracle tests pass` is missing | The boot seed held fewer than 32 `rng-seed` bytes and no RNDR. Use a machine whose device tree has an `rng-seed`, as QEMU virt does, or a CPU with RNDR (`K0_QEMU_CPU=max`) | | `boot-test` fails on the number of `k0: task fault` lines for an image with a `vault` feature | That image prints 8 of them. Run the test with `K0_BOOT_FAULTS=8` | | The boot test times out on a slow computer | Give it more time, for example `K0_BOOT_TIMEOUT=300 tools/qemu-boot-test.sh` | diff --git a/USAGE_KR.md b/USAGE_KR.md index 8f86415..373b600 100644 --- a/USAGE_KR.md +++ b/USAGE_KR.md @@ -88,7 +88,7 @@ $ grep -a 'k0: console drivers' <이미지 파일> | `root: secret at 0x...` 다음에 같은 주소의 `k0: task fault ... far 0x...` | 격리된 태스크가 루트 태스크만 볼 수 있는 메모리를 읽으려다 정확히 그 주소에서 멈춤 | | `k0: task fault ...`와 `k0: unknown syscall 65535, killing task` | 테스트가 일부러 일으킨 규칙 위반. 매번 규칙을 어긴 태스크만 멈춤. 정상 실행에서는 `k0: task fault` 줄이 정확히 6개, `k0: unknown syscall` 줄이 1개 나옴. `vault` feature를 포함해 빌드한 이미지에서는 `k0: task fault` 줄이 8개 나옴 | | `k0: kernel reserve tables + address space entries = bytes in ranges` | 커널이 넘겨 주는 메모리 범위마다 맨 위에 자기 페이지 테이블과 주소 공간 목록용 메모리를 따로 떼어 둠. `k0: untyped` 줄보다 먼저 출력됨. QEMU virt 512 MiB에서는 `262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges`로 나오며, 항목 수는 이미지 크기에 따라 달라짐 | -| `k0: memory + not handed out ()` | 메모리 범위가 너무 작아 그 예비 몫을 담지 못하거나 몫을 매핑하지 못해서, 커널이 그 범위를 넘겨 주지 않음. 부팅은 계속됨. QEMU virt의 정상 실행에서는 나오지 않음 | +| `k0: memory + not handed out ()` | 메모리 범위가 너무 작아 그 예비 몫을 담지 못하거나, 몫을 매핑하지 못하거나, 온전한 페이지가 하나도 없어서 커널이 그 범위를 넘겨 주지 않음. 부팅은 계속됨. QEMU virt의 정상 실행에서는 나오지 않음 | | `root: timeout tests pass` | IPC 타임아웃 자가 테스트가 통과함 | | `root: slice test yield pass`, `root: slice test block pass` | 두 틱 사이에 CPU를 받은 태스크(`YIELD` 또는 앞선 태스크가 기다림)가 처음 만난 틱에 끊기지 않았음. `root: preempt test pass`보다 앞에 나옴 | | `root: preempt test pass` | 양보하지 않는 태스크는 여전히 타이머가 끊음 | @@ -124,6 +124,7 @@ $ K0_QEMU_MEM=4G cargo virt # 메모리 | `K0_QEMU_MEM` | `512M` | | `K0_QEMU_ACCEL` | 없음(QEMU의 소프트웨어 에뮬레이션, TCG) | | `K0_IMAGE_TEXT_OFFSET` | 없음. 이미지 헤더의 `text_offset`을 바꾼 사본으로 부팅해서 같은 이미지를 다른 물리 주소에 적재함 | +| `K0_IMAGE_DTB_POINTER` | 없음. 커널이 `x0`으로 받는 디바이스 트리 포인터를 바꾼 사본으로 부팅함. `end`는 정렬된 마지막 주소(0xFFFFFFFFFFFFFFF8)이고, 그 밖에는 16비트 조각 하나만 채워진 주소(예: 0x4a000000)를 줌. 부팅 매트릭스가 잘못된 포인터를 넘길 때와, QEMU가 고치지 않은 디바이스 트리를 `-device loader`로 실어 부팅할 때 씀 | | `K0_QEMU_MONITOR` | 없음. QEMU 모니터용 유닉스 소켓 경로로, 메모리에서 부트 로그를 읽을 때 사용함 | `--` 뒤의 인자도 여전히 그대로 QEMU에 전달됩니다. @@ -287,7 +288,7 @@ k0> 계속 유효한 한계와 다루지 않는 부분은 다음과 같습니다. - **커널 코드**: 수신 코드는 EL1에서 실행됩니다. 작고 바이트를 해석하지 않지만, 외부 당사자가 구동하는 커널 코드입니다. 사용자 공간 드라이버에는 장치 및 인터럽트 위임이 필요한데, K0에는 그것이 없습니다. -- **타이밍**: 외부 당사자가 이제 태스크가 도는 동안 인터럽트를 일으킬 수 있고(읽는 쪽이 상한을 정함), 읽는 쪽은 틱보다 정밀한 도착 시각을 알게 됩니다. 다른 태스크가 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널은 분석하지 않았습니다. +- **타이밍**: 외부 당사자가 이제 태스크가 도는 동안 인터럽트를 일으킬 수 있고(바이트는 읽는 쪽이, 선로 오류가 난 문자는 틱당 256개가 상한을 정함), 읽는 쪽은 틱보다 정밀한 도착 시각을 알게 됩니다. 다른 태스크가 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널은 분석하지 않았습니다. - **지연**: 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 지연은 준비된 태스크마다 최대 한 틱이며, 실행 중인 태스크가 두 틱 사이에 실행을 넘겨받았다면 한 틱이 더해집니다. - **하드웨어**: 16550 콘솔에는 입력이 없습니다. SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU로 실행되지 않고 가짜 UART를 쓰는 호스트 테스트로만 다룹니다. UART 원인 없이 발생하는 인터럽트 선을 끊는 동작도 호스트 테스트로만 다룹니다. 플러드 상황에서 커널이 쓰는 시간을 머신에서 측정하는 테스트는 없습니다. 실제 하드웨어에서는 아무것도 돌려 보지 않았습니다. - **화면**: 입력 중에 커널 줄이 나타나면 화면의 줄은 갈라지지만 버퍼는 온전하며, Enter는 버퍼 전체를 실행합니다. `Console` 출력이 있는 태스크는 여전히 커널이나 루트 태스크 줄처럼 보이는 줄을 출력할 수 있고, 접두어를 인증하는 것은 없습니다. 터미널은 추가로 자기 현재 줄 안을 지울 수 있습니다. @@ -409,9 +410,9 @@ $ tools/qemu-boot-test.sh # QEMU에서 부팅하 $ tools/boot-matrix.sh # 지원하는 구성을 전부 부팅(16 KiB 이미지, 고정 이미지, UEFI 로더 이미지도 빌드함) ``` -- `tools/host-test.sh`는 호스트 테스트 363개를 실행합니다(그 밖의 호스트에서는 277개). 커널의 부분 하나하나를 내 컴퓨터에서 일반 프로그램처럼 돌리는 작은 테스트(단위 테스트)입니다. **퍼징**도 합니다. 디바이스 트리 파서와 UEFI 로더의 계획 코드에 무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법입니다. 363개는 `k0-abi` 15개, `k0-cap` 44개, `k0-boot` 85개, `k0-efi` 33개, `k0-conin` 15개, `k0-slice` 9개(틱이 실행 중인 태스크를 끊을지 정하는 규칙을 스케줄러 모델로 검사), `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/host-test.sh`는 호스트 테스트 377개를 실행합니다(그 밖의 호스트에서는 289개). 커널의 부분 하나하나를 내 컴퓨터에서 일반 프로그램처럼 돌리는 작은 테스트(단위 테스트)입니다. **퍼징**도 합니다. 디바이스 트리 파서와 UEFI 로더의 계획 코드에 무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법입니다. 377개는 `k0-abi` 15개, `k0-cap` 52개, `k0-boot` 85개, `k0-efi` 33개, `k0-conin` 19개, `k0-slice` 9개(틱이 실행 중인 태스크를 끊을지 정하는 규칙을 스케줄러 모델로 검사), `k0-vault` 31개(Ed25519를 포함하면 20개, 없으면 11개), `k0-term` 45개(`vault` feature를 포함하면 24개, 없으면 21개), `k0-mm` 44개씩 두 페이지 크기분입니다. 메모리 관리 테스트는 ARM 명령을 사용하므로 ARM 컴퓨터(Apple Silicon Mac이나 Linux arm64)에서만 돌고, 그 밖의 호스트의 개수는 그 88개를 뺀 것입니다. - `tools/qemu-boot-test.sh`는 커널을 부팅하고, 로그를 정해진 순서대로 한 줄씩 확인합니다. 에러 줄이 하나라도 나오면 실패하고, 일부러 일으킨 폴트 줄의 개수를 정확히 맞춘 뒤 QEMU를 끕니다. 루트 태스크의 타임아웃 테스트는 실제 타이머 틱을 기다리므로, 부팅 한 번이 그 테스트가 생기기 전보다 약 4초 더 걸립니다. 시간 조각 테스트는 두 번 실행해 합계 약 4초가 걸리며, 이를 대신한 이전 선점 테스트는 약 1초가 걸렸습니다. `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에서 76행, CI에서 65행입니다. 행 이름을 인자로 주면 그 행만 돌립니다. CI가 이것을 실행합니다. +- `tools/boot-matrix.sh`는 K0가 지원한다고 말하는 **구성마다** 커널을 부팅해서 결과를 확인합니다. GICv3와 GICv2의 QEMU virt를 EL1과 EL2에서 부팅하고, CPU 모델 세 가지, 코어 4개, 16 KiB 이미지, 다른 적재 주소, `xlnx-versal-virt`, 고정 이미지, 서명 오라클이 있는 이미지도 부팅합니다. 이미지가 물리 타이머를 건드리지 않는지는 정적으로 검사합니다. 행렬은 HVF가 있는 Mac에서 82행, CI에서 71행입니다. 행 이름을 인자로 주면 그 행만 돌립니다. CI가 이것을 실행합니다. 콘솔 행은 콘솔 feature를 확인합니다. 다음 표는 콘솔 행과 확인하는 내용입니다. @@ -455,7 +456,7 @@ Apple Silicon Mac에서는 `K0_MATRIX_HVF=1 tools/boot-matrix.sh`로 QEMU의 HVF | `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`를 사용하세요. +`tools/term-test.py <이미지>`는 QEMU의 직렬 포트를 파이프에 연결해 이미지를 부팅하고 정해진 세션을 실행합니다. 모든 명령과 오류, 지우기와 취소, CR LF, ESC 시퀀스, 너무 긴 줄, 키 생성, 공개 키 형식, zeroize, 줄 끝 없는 200 kB, 연속 2000줄, 직렬 브레이크, 그리고 QEMU 8.0 이상에서는 브레이크 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`를 사용하세요. ### 콘솔 없는 이미지 시험 @@ -506,7 +507,7 @@ GitHub도 풀 리퀘스트와 `main` 푸시가 있을 때마다 이 테스트를 | `runner: this kernel has no console driver and prints nothing here (build with --features console to see output)` | 이미지를 콘솔 feature 없이 빌드했거나, 러너가 이미지에서 `k0: console drivers [none]` 줄을 찾았습니다. 출력을 보려면 `--features console`로 빌드하거나 메모리에서 부트 로그를 읽으세요 | | `boot-test: the serial log has no kernel line` | 같은 원인입니다. 콘솔 feature 없이 빌드한 커널은 직렬 포트에 아무것도 쓰지 않습니다. `--features console`로 빌드하거나 `K0_BOOT_MEMLOG=<적재 주소>`로 게스트 메모리의 로그를 판정하세요 | | `boot-test`가 `k0: all tasks`로 시작하는 줄에서 실패함 | 모든 태스크가 기다리는 중인데 시간 제한이 있는 대기가 없어서 태스크를 깨울 수 있는 것이 없습니다. 기본 자가 테스트에서는 일어나지 않습니다. 루트 태스크를 바꿨다면 대기마다 타임아웃을 지정하세요 | -| 부트 로그에 `k0: memory + not handed out ()`가 나옴 | 커널이 자기 예비 공간을 담기에 너무 작거나 그 몫을 매핑하지 못하는 메모리 범위를 찾았습니다. 그 범위를 제외하고 부팅을 계속했으며, 해당 범위는 untyped 메모리로 쓸 수 없습니다. QEMU에 준 메모리 크기와 적재 주소를 확인하세요 | +| 부트 로그에 `k0: memory + not handed out ()`가 나옴 | 커널이 자기 예비 공간을 담기에 너무 작거나, 그 몫을 매핑하지 못하거나, 온전한 페이지가 하나도 없는 메모리 범위를 찾았습니다. 그 범위를 제외하고 부팅을 계속했으며, 해당 범위는 untyped 메모리로 쓸 수 없습니다. QEMU에 준 메모리 크기와 적재 주소를 확인하세요 | | `root: oracle made no key (boot seed has no entropy)`가 나오거나 `root: oracle tests pass`가 없음 | 부트 시드에 `rng-seed` 바이트가 32개보다 적고 RNDR도 없었음. QEMU virt처럼 디바이스 트리에 `rng-seed`가 있는 머신이나 RNDR이 있는 CPU(`K0_QEMU_CPU=max`)를 사용하세요 | | `vault` feature를 포함한 이미지에서 `boot-test`가 `k0: task fault` 줄 수 때문에 실패 | 그 이미지는 8개를 출력함. `K0_BOOT_FAULTS=8`로 테스트를 실행하세요 | | 느린 컴퓨터에서 부팅 테스트가 시간 초과 | 시간을 늘리세요. 예: `K0_BOOT_TIMEOUT=300 tools/qemu-boot-test.sh` | diff --git a/ci/threat_model.md b/ci/threat_model.md index e32828d..e960cc9 100644 --- a/ci/threat_model.md +++ b/ci/threat_model.md @@ -37,7 +37,7 @@ 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. +- 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 bounded neither by the reader nor by the count of 256 characters with a line error per tick, 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: @@ -83,7 +83,7 @@ These are known, tracked in `SECURITY.md`, and are not new findings: - No isolation between tasks in `v0.1.0` and earlier commits: one static root CNode, one address space, no capability derivation tree, no `MINT`, no `revoke`, no capability transfer over IPC (GHSA-vmpv-qc49-3p6r). Findings that only apply to those versions are not new. The current `main` branch (unreleased) has per-task CNodes and address spaces, rights, badges, a derivation list and revocation, so isolation bypasses there ARE in scope. EL0 reaching EL1 memory is always in scope. - Known limits of isolation on `main`: no fault delivery to a handler, no notifications, no capability transfer over IPC, a single core, and a sender already queued on an endpoint still delivers once after its capability is revoked. Availability is not protected in general (see below). New executable code cannot be loaded after boot by design, so a confined task runs code from the root task image. -- Availability limits (GHSA-q99x-2wrv-358p is still listed as affecting 0.1.0 and earlier, with no fixed version; `main` contains a change that addresses its subject). The kernel no longer halts when every task is blocked: it idles and prints `k0: idle (waiting for a timeout)` or `k0: all tasks stopped (none ready, no timeout pending)` once. A task can bound its own waits with the timeout in the upper 32 bits of `x1` (scheduler ticks of 1 second; `TIMEOUT`, `REPLY_TIMEOUT`, `BAD_FLAGS`). Still known: a wait without a timeout can last forever if the partner never acts; a timeout says when a task becomes ready, not when it runs (round-robin with a tick of one second, no priority or CPU budget, so a task with `Untyped` memory can dilute everybody's share by creating tasks, which stays known); the kernel is not preemptible, so a long system call such as `CAP_REVOKE` on an `Untyped` with many objects delays every task and every timeout; `k0_arch::fatal`, a kernel panic and an SError from EL0 stop the machine; fault and exit lines can fill the kernel part of the boot log. +- Availability limits (GHSA-q99x-2wrv-358p is still listed as affecting 0.1.0 and earlier, with no fixed version; `main` contains a change that addresses its subject). The kernel no longer halts when every task is blocked: it idles and prints `k0: idle (waiting for a timeout)` or `k0: all tasks stopped (none ready, no timeout pending)` once. A task can bound its own waits with the timeout in the upper 32 bits of `x1` (scheduler ticks of 1 second; `TIMEOUT`, `REPLY_TIMEOUT`, `BAD_FLAGS`). Still known: a wait without a timeout can last forever if the partner never acts; a timeout says when a task becomes ready, not when it runs (round-robin with a tick of one second, no priority or CPU budget, so a task with `Untyped` memory can dilute everybody's share by creating tasks, which stays known); the kernel is not preemptible, so a long system call such as `CAP_REVOKE` on an `Untyped` with many objects delays every task and every timeout; `k0_arch::fatal`, a kernel panic and an SError from EL0 stop the machine; the lines the kernel prints when a task ends share 4 KiB of the boot log and no longer reach its kernel part, but a task that can create tasks can still push such lines of other tasks out of the log. - Scheduler timing, addressed on `main`: taking the CPU from the next task by calling `YIELD` (no capability needed) or blocking just before the tick. A task that gets the CPU between two ticks is no longer preempted by the first tick it meets (`crates/k0-slice`, used by `on_tick` and `resume_from_idle` in `crates/k0-sched`), so it is not cut before it has run one full period, and with N ready tasks a task that never yields or blocks keeps at least 1/N of the CPU. This was checked by search in a model (up to 6 tasks) and by host tests, not proven, and a self-test at every boot (`root: slice test yield pass`, `root: slice test block pass`) covers the kernel's use of it. A report that breaks this is still welcome. Known limits that stay: the share has no budget and N grows with every task created; the timing channel through the scheduler is open (a task changes when, and for how long, another task runs by choosing when to yield or block, and this has not been analysed); there is no latency promise (a task that becomes ready can wait up to one tick longer than before); three connections of the rule to the scheduler (the tick's own switch, the idle loop's report of a tick, the entry kind at the hand-off to the root task) are covered only by the host model and by no test on the real kernel, so a report that one of them is wrong is still welcome, as a latency finding; the measurements ran in QEMU only, with an attacker whose yield point was set for it. - EL0 still cannot read a hardware counter or timer. Timeouts give it a clock as coarse as the scheduler tick; whether that can be amplified into a timing source for cache or speculation attacks has not been analysed. - The kernel tables are sized at boot: alias page tables and address space entries are reserved from the top of every range handed out as `Untyped` (`k0: kernel reserve ...` line), so `RETYPE` no longer fails with `KERNEL_RESOURCE` for lack of tables and the number of address spaces is limited only by memory. The 40-table static pool is used only during boot. @@ -91,7 +91,7 @@ These are known, tracked in `SECURITY.md`, and are not new findings: - 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, 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, plus one more when the running task got the CPU between two ticks); 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. +- 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 for bytes and by 256 per tick for characters with a line error), 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, plus one more when the running task got the CPU between two ticks); 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 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`. diff --git a/crates/k0-arch/src/conin.rs b/crates/k0-arch/src/conin.rs index 04de2ef..7c911d4 100644 --- a/crates/k0-arch/src/conin.rs +++ b/crates/k0-arch/src/conin.rs @@ -98,6 +98,10 @@ mod pl011 { with(|rx, regs| rx.poll(regs)); } + pub fn tick() { + with(|rx, regs| rx.tick(regs)); + } + pub fn has_data() -> bool { with(|rx, _| rx.has_data()).unwrap_or(false) } @@ -133,6 +137,8 @@ mod pl011 { pub fn poll() {} + pub fn tick() {} + pub fn has_data() -> bool { false } @@ -183,12 +189,18 @@ pub fn flush() { pl011::flush(); } -/// 인터럽트 없이 장치의 FIFO를 들여다보는 함수입니다. 틱마다, 그리고 읽는 -/// 태스크가 잠들기 직전에 부릅니다. +/// 인터럽트 없이 장치의 FIFO를 들여다보는 함수입니다. 읽는 태스크가 잠들기 +/// 직전에 부릅니다. pub fn poll() { pl011::poll(); } +/// 틱마다 한 번 부르는 함수입니다. 버린 오류 문자의 수를 다시 세기 시작하고 +/// 장치의 FIFO를 들여다봅니다. +pub fn tick() { + pl011::tick(); +} + /// 꺼낼 바이트가 있는지 알려 주는 함수입니다. pub fn has_data() -> bool { pl011::has_data() diff --git a/crates/k0-arch/src/earlycon.rs b/crates/k0-arch/src/earlycon.rs index 87f7a6b..f76a991 100644 --- a/crates/k0-arch/src/earlycon.rs +++ b/crates/k0-arch/src/earlycon.rs @@ -15,7 +15,9 @@ //! //! 로그는 앞에서부터 채우고 가득 차면 버립니다(되감지 않음). EL0가 Console //! 케이퍼빌리티로 내는 출력은 정해진 몫까지만 기록해, 사용자 출력이 커널의 -//! 진단을 밀어내지 못하게 합니다. +//! 진단을 밀어내지 못하게 합니다. 태스크가 끝날 때 커널이 내는 줄(폴트, 종료, +//! 모르는 시스템 콜)에도 따로 몫을 두고([TaskLine]), 두 몫 모두 커널 진단용으로 +//! 남긴 꼬리 앞에서 멈춥니다. //! //! # Examples //! ```rust,ignore @@ -27,6 +29,7 @@ use core::arch::asm; use core::cell::UnsafeCell; use core::fmt; +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; #[cfg(any(feature = "console-pl011", feature = "console-16550"))] mod uart; @@ -70,6 +73,19 @@ const LOG_USER_CAP: usize = 6 * 1024; /// 커널 진단 전용으로 남겨 두는 로그 꼬리. 사용자 출력은 이 앞에서 멈춤 const LOG_KERNEL_TAIL: usize = 2 * 1024; +/// 태스크가 일으킨 커널 줄(폴트, 종료, 모르는 시스템 콜)에 허용하는 로그 몫 +const LOG_TASK_CAP: usize = 4 * 1024; + +/// 그런 줄 하나가 로그에서 차지하는 길이의 상한(줄 끝 포함) +const TASK_LINE_MAX: usize = 128; + +/// 태스크가 일으킨 줄이 지금까지 로그에 쓴 바이트 수. 하니스가 읽는 [BootLog]의 +/// 배치를 바꾸지 않으려고 로그 밖에 둠 +static TASK_LEN: AtomicUsize = AtomicUsize::new(0); + +/// 그 몫을 넘겼다는 줄을 이미 남겼는지 +static TASK_NOTED: AtomicBool = AtomicBool::new(false); + /// 로그 머리의 식별값. 시험 하니스가 메모리에서 로그를 찾는 표지 pub const LOG_MAGIC: u64 = 0x6B30_2D62_6F6F_746C; @@ -201,6 +217,57 @@ impl fmt::Write for EarlyCon { } } +/// 태스크가 일으킨 커널 줄 하나를 쓰는 핸들입니다. +/// +/// 태스크 하나가 끝날 때마다 한 줄씩 나오는 진단(폴트, 종료, 모르는 시스템 +/// 콜)에 씁니다. 태스크를 만들 권한이 있는 쪽은 이런 줄을 원하는 만큼 만들 수 +/// 있으므로, 로그에는 정해진 몫까지만 줄 단위로 남기고 커널 진단용 꼬리는 +/// 건드리지 않습니다. 콘솔에는 몫과 상관없이 그대로 나갑니다. 몫을 처음 넘길 +/// 때 그 사실을 한 줄로 남깁니다. 핸들 하나로 줄 하나만 씁니다. +pub struct TaskLine { + /// 이 줄이 로그에 남는지 + logged: bool, + /// 이 줄이 로그에 쓴 바이트 수 + used: usize, +} + +impl TaskLine { + /// 줄 하나를 시작하는 함수입니다. 줄 하나가 통째로 들어갈 자리가 로그에 + /// 있는지 여기서 한 번 정하므로 줄이 중간에 끊겨 남지 않습니다. + pub fn begin() -> Self { + let daif = mask_irqs(); + // SAFETY: 인터럽트가 마스크된 단일 코어 구간에서 길이만 읽음 + let len = unsafe { (*K0_BOOT_LOG.0.get()).len as usize }; + restore_irqs(daif); + let logged = TASK_LEN.load(Ordering::Relaxed) <= LOG_TASK_CAP - TASK_LINE_MAX + && len <= LOG_SIZE - LOG_KERNEL_TAIL - TASK_LINE_MAX; + if !logged && !TASK_NOTED.load(Ordering::Relaxed) { + TASK_NOTED.store(true, Ordering::Relaxed); + EarlyCon.put_str("k0: task lines over the log quota, later ones go to the console only\n"); + } + Self { logged, used: 0 } + } +} + +impl fmt::Write for TaskLine { + fn write_str(&mut self, s: &str) -> fmt::Result { + for b in s.bytes() { + // 마지막 한 자리는 줄 끝을 위해 남겨 두어 긴 줄도 줄 끝으로 닫힘 + let room = if b == b'\n' { TASK_LINE_MAX } else { TASK_LINE_MAX - 1 }; + if self.logged && self.used < room { + log_push(b, false); + self.used = self.used.saturating_add(1); + TASK_LEN.store(TASK_LEN.load(Ordering::Relaxed).saturating_add(1), Ordering::Relaxed); + } + if b == b'\n' { + hw_put(b'\r'); + } + hw_put(b); + } + Ok(()) + } +} + /// 로그에는 남기지 않고 콘솔에만 쓰는 핸들입니다. 끝없이 반복되는 출력(주기 /// 틱)이 로그를 채워 뒤의 진단을 밀어내지 않게 하는 데 씁니다. 콘솔 드라이버가 /// 없는 빌드에는 쓸 곳이 없으므로 이 핸들도 없습니다. diff --git a/crates/k0-arch/src/irq.rs b/crates/k0-arch/src/irq.rs index e49befc..04c215e 100644 --- a/crates/k0-arch/src/irq.rs +++ b/crates/k0-arch/src/irq.rs @@ -259,10 +259,14 @@ pub mod gicv3 { let (mut frames, mut seen) = (0u32, 0u32); for &(base, size) in regions { - let end = base + size; + // 구간과 간격은 디바이스 트리가 준 값임. 호출자의 검증에 기대지 않고 + // 넘치는 덧셈은 구간의 끝으로 다룸 + let Some(end) = base.checked_add(size) else { + continue; + }; let mut frame = base; for _ in 0..MAX_FRAMES { - if frame + 2 * SGI_OFFSET > end { + if frame.checked_add(2 * SGI_OFFSET).is_none_or(|top| top > end) { break; } // 프레임마다 식별 레지스터를 확인함. 구간의 첫 프레임이 GICv3가 @@ -300,11 +304,15 @@ pub mod gicv3 { if lo & (1 << 4) != 0 { break; } - frame += match stride { + let step = match stride { 0 if lo & (1 << 1) != 0 => 4 * SGI_OFFSET, 0 => 2 * SGI_OFFSET, s => s, }; + let Some(next) = frame.checked_add(step) else { + break; + }; + frame = next; } } if found.is_none() { @@ -677,10 +685,11 @@ fn timer_tick() { let n = TICKS.load(Ordering::Relaxed) + 1; TICKS.store(n, Ordering::Relaxed); // 수신 인터럽트가 오지 않는 UART(수신 타임아웃이 없거나 번호가 조용히 - // 틀린 경우)에서도 입력이 늦게나마 도착하게 틱마다 한 번 들여다봄. 닫혀 - // 있는 동안에는 아무 일도 하지 않음 + // 틀린 경우)에서도 입력이 늦게나마 도착하게 틱마다 한 번 들여다봄. 오류 + // 문자를 버릴 만큼 버려 막아 둔 수신 인터럽트도 여기서 다시 열림. 닫혀 + // 있는 동안에는 장치를 건드리지 않음 #[cfg(feature = "console-input")] - crate::conin::poll(); + crate::conin::tick(); // 태스크가 콘솔 입력을 쓰기 시작한 뒤에는 틱 줄을 내지 않음(입력하는 줄 // 사이에 끼어들지 않게). 틱과 타임아웃은 그대로 동작함 #[cfg(feature = "console-input")] diff --git a/crates/k0-boot/src/platform.rs b/crates/k0-boot/src/platform.rs index 037de83..db7b763 100644 --- a/crates/k0-boot/src/platform.rs +++ b/crates/k0-boot/src/platform.rs @@ -23,6 +23,10 @@ use crate::fdt::{dtb_span, BootError, MemRegion}; /// 받아들이는 GICv3 리디스트리뷰터 구간 수의 상한 pub const MAX_REDIST_REGIONS: usize = 4; +/// 받아들이는 리디스트리뷰터 프레임 간격의 상한(이 값부터 거부). 커널이 쓰는 +/// 물리 주소는 48비트를 넘지 않으므로 넉넉한 값이고, 프레임을 걷는 덧셈이 넘치지 +/// 않게 하는 것이 목적임 +pub const MAX_REDIST_STRIDE: u64 = 1 << 52; /// PL011 드라이버가 건드리는 레지스터 범위(FR이 0x18에 있는 32비트 레지스터) const PL011_SPAN: u64 = 0x1C; @@ -494,7 +498,10 @@ fn read_intc(levels: &Levels<'_>, node: &Node<'_>, depth: usize) -> Result<(Intc None => 0, Some(v) if v.len() == 4 || v.len() == 8 => { let s = read_cells(v); - if s < 0x2_0000 || s % 0x1_0000 != 0 { + // 간격은 프레임 사이의 물리 주소 거리이므로 아키텍처의 물리 + // 주소 폭을 넘을 수 없음. 넘는 값은 프레임을 걷는 덧셈을 + // 넘치게 하려는 값으로 보고 거부함 + if s < 0x2_0000 || s % 0x1_0000 != 0 || s >= MAX_REDIST_STRIDE { return Err(DiscoverError::BadRedistributor); } s @@ -715,7 +722,8 @@ pub struct Layout<'a> { pub dtb: Range, /// 변환 그래뉼 크기 pub granule: u64, - /// RAM이 넘으면 안 되는 물리 주소 상한(선형 별칭의 한계) + /// RAM이 넘으면 안 되는 물리 주소 상한(선형 별칭의 한계와 이 코어의 물리 주소 + /// 폭 가운데 작은 쪽) pub ram_limit: u64, /// 디바이스가 넘으면 안 되는 물리 주소 상한(이 코어의 물리 주소 폭) pub device_limit: u64, diff --git a/crates/k0-boot/src/platform/tests.rs b/crates/k0-boot/src/platform/tests.rs index 89d42f4..a379de3 100644 --- a/crates/k0-boot/src/platform/tests.rs +++ b/crates/k0-boot/src/platform/tests.rs @@ -587,6 +587,16 @@ fn interrupt_controllers_are_validated() { Err(DiscoverError::BadRedistributor) ); } + // 물리 주소 폭을 넘는 간격은 프레임을 걷는 덧셈을 넘치게 하므로 거부. 폭 + // 안의 가장 큰 값까지는 받음(구간을 벗어나는 걸음은 커널이 끝으로 다룸) + for stride in [cells(&[0x0010_0000, 0]), cells(&[0xFFFF_FFFF, 0xFFFF_0000]), cells(&[0x8000_0000, 0])] { + assert_eq!( + edit(&|g| g.set("redistributor-stride", stride.clone())), + Err(DiscoverError::BadRedistributor) + ); + } + let d = edit(&|g| g.set("redistributor-stride", cells(&[0x000F_FFFF, 0xFFFF_0000]))).unwrap(); + assert!(d.platform.to_string().contains(" stride=0xfffffffff0000 ")); let d = edit(&|g| g.set("redistributor-stride", cells(&[0, 0x4_0000]))).unwrap(); assert!(d.platform.to_string().contains(" stride=0x40000 ")); diff --git a/crates/k0-cap/src/lib.rs b/crates/k0-cap/src/lib.rs index 237e471..52ce06e 100644 --- a/crates/k0-cap/src/lib.rs +++ b/crates/k0-cap/src/lib.rs @@ -91,6 +91,19 @@ impl PhysRegion { fn end(&self) -> u64 { self.base + self.size } + + /// 구간 안에 온전히 들어가는 그래뉼들의 범위(시작, 끝)를 주는 함수입니다. + /// + /// 하나도 없으면 `None`입니다. 주소 범위의 맨 끝에 걸쳐 올림이나 끝 주소가 + /// 넘치는 구간도 온전한 그래뉼이 없는 구간으로 다룹니다. + /// + /// # Arguments + /// `granule` - 그래뉼 크기(2의 거듭제곱) + pub fn whole(&self, granule: u64) -> Option<(u64, u64)> { + let lo = self.base.checked_next_multiple_of(granule)?; + let hi = self.base.checked_add(self.size)? / granule * granule; + (hi > lo).then_some((lo, hi)) + } } /// Frame / PageTable 케이퍼빌리티가 기억하는 매핑 위치 구조체입니다. diff --git a/crates/k0-cap/src/tests.rs b/crates/k0-cap/src/tests.rs index 688cbb2..61bfc04 100644 --- a/crates/k0-cap/src/tests.rs +++ b/crates/k0-cap/src/tests.rs @@ -309,6 +309,26 @@ fn reserved_outside_memory_is_ignored() { assert_eq!(untypeds(c, 64), vec![(0x10000, 0x1000, 0)]); } +#[test] +fn whole_granules_of_a_region() { + for g in [0x1000u64, 0x4000] { + // 그래뉼에 맞는 구간은 그대로, 걸친 구간은 안쪽의 온전한 그래뉼만 + assert_eq!(r(4 * g, 3 * g).whole(g), Some((4 * g, 7 * g))); + assert_eq!(r(4 * g + 8, 3 * g).whole(g), Some((5 * g, 7 * g))); + assert_eq!(r(4 * g + 8, 2 * g - 8).whole(g), Some((5 * g, 6 * g))); + // 온전한 그래뉼이 없는 구간: 그래뉼보다 작거나, 두 그래뉼에 걸쳐 있거나 + assert_eq!(r(4 * g, g - 1).whole(g), None); + assert_eq!(r(4 * g + 1, g).whole(g), None); + assert_eq!(r(4 * g + g / 2, g + g / 2 - 1).whole(g), None); + assert_eq!(r(4 * g, 0).whole(g), None); + // 주소 범위의 맨 끝: 올림이 넘치거나 끝 주소가 넘치면 없는 것으로 다룸 + assert_eq!(r(u64::MAX - 0xFF, 0x80).whole(g), None); + assert_eq!(r(u64::MAX - 0xFF, 0x1000).whole(g), None); + assert_eq!(r(u64::MAX - 2 * g + 1, 2 * g).whole(g), None); + assert_eq!(r(u64::MAX - 2 * g + 1, 2 * g - 1).whole(g), Some((u64::MAX - 2 * g + 1, u64::MAX - g + 1))); + } +} + #[test] fn bad_regions_are_rejected() { let cases: [(&[PhysRegion], &[PhysRegion]); 6] = [ @@ -1607,3 +1627,367 @@ fn revoking_every_untyped_empties_the_world() { } } } + +// 자기 참조, 순환, 깊은 중첩: 케이퍼빌리티가 자기를 담은 컨테이너나 자기가 +// 나온 untyped를 가리키는 모양에서도 삭제와 회수가 끝나고 불변식이 유지돼야 함 + +impl World { + fn with(granule: u64, frames: u64) -> Self { + let root = node(ROOT_N); + let memory = [r(0x4000_0000, granule * frames), r(0x5000_0000, granule * 4)]; + unsafe { bootstrap(&cref(root, ROOT_N), &BOOT, &memory, &[]) }.unwrap(); + let mut w = World { + granule, + containers: BTreeMap::new(), + graveyard: Vec::new(), + objs: BTreeSet::new(), + torn: BTreeSet::new(), + finalized: 0, + ever: BTreeSet::new(), + reused: 0, + }; + w.containers.insert(BOOT.cnode, (root, ROOT_N)); + w.containers.insert(BOOT.tcb, (node(TCB_N), TCB_N)); + for i in 1..ROOT_N { + if let Some(e) = get(root, i) { + w.objs.insert(ident(&e.cap)); + } + } + w + } + + fn root(&self) -> *mut Slot { + self.containers[&BOOT.cnode].0 + } + + /// `step`과 같은 장부로 retype하는 함수입니다. 새 오브젝트의 주소와, 컨테이너면 + /// 그 슬롯 배열(아니면 null)을 돌려줍니다. + fn make(&mut self, ut: *mut Slot, dest: *mut Slot, kind: ObjKind) -> (u64, *mut Slot) { + let g = self.granule; + let mut at = None; + unsafe { + retype(ut, dest, kind, g, |pa| { + at = Some(pa); + Some(7) + }) + } + .unwrap(); + let pa = at.unwrap(); + assert!(self.objs.insert((2, pa))); + self.ever.insert(pa); + let arr = match kind { + ObjKind::CNode => { + let n = (g / SLOT_SIZE as u64) as usize; + let a = node(n); + self.containers.insert(pa, (a, n)); + a + } + ObjKind::Tcb => { + let a = node(TCB_N); + self.containers.insert(pa, (a, TCB_N)); + a + } + _ => std::ptr::null_mut(), + }; + (pa, arr) + } +} + +/// 자기 원본을 자기 안에 든 CNode를 만드는 함수입니다. +/// +/// CNode C의 원본은 C의 3번 슬롯에, 사본 C'은 루트에 둡니다. 엔드포인트의 원본은 +/// C의 4번 슬롯에, 사본은 루트에 둡니다. TCB(원본은 루트)는 C'을 통해 C에 +/// 묶습니다. (모형, C의 배열, C'의 슬롯, 엔드포인트 사본의 슬롯, C의 주소, +/// 엔드포인트의 주소, TCB의 배열)을 돌려줍니다. +fn self_holding(granule: u64) -> (World, *mut Slot, *mut Slot, *mut Slot, u64, u64, *mut Slot) { + let mut w = World::with(granule, 16); + let root = w.root(); + unsafe { + let ut = root.add(5); + let (c_pa, c) = w.make(ut, root.add(10), ObjKind::CNode); + copy(root.add(10), root.add(11), rights::ALL, 0, false).unwrap(); + move_cap(root.add(10), c.add(3)).unwrap(); + let (e_pa, _) = w.make(ut, root.add(12), ObjKind::Endpoint); + copy(root.add(12), root.add(13), rights::ALL, 0, false).unwrap(); + move_cap(root.add(12), c.add(4)).unwrap(); + let (_, t) = w.make(ut, root.add(14), ObjKind::Tcb); + let (_, _) = w.make(ut, root.add(15), ObjKind::AddrSpace); + copy_pair_bound(root.add(11), t.add(1), root.add(15), t.add(2)).unwrap(); + w.check(); + (w, c, root.add(11), root.add(13), c_pa, e_pa, t) + } +} + +#[test] +fn a_cnode_holding_its_own_original_revoke_then_delete() { + for g in [4096u64, 16384] { + let (mut w, c, c_copy, e_copy, c_pa, e_pa, t) = self_holding(g); + unsafe { + // CNode 자신 안에 있는 슬롯으로 원본을 회수함 + revoke(c.add(3), &mut w).unwrap(); + w.check(); + assert!(read(c_copy).unwrap().is_none(), "the copy went away"); + assert!(read(t.add(1)).unwrap().is_none(), "the bound copy went away"); + assert!(w.torn.contains(&(t as u64)), "the bound TCB was told"); + assert!(w.objs.contains(&(2, c_pa)), "the CNode object itself survives a revoke"); + assert!(read(c.add(3)).unwrap().is_some()); + // 두 번째 회수는 아무 일도 하지 않음 + revoke(c.add(3), &mut w).unwrap(); + w.check(); + // 이제 안에서 원본을 삭제함 + delete(c.add(3), &mut w).unwrap(); + w.check(); + assert!(!w.objs.contains(&(2, c_pa))); + assert!(!w.objs.contains(&(2, e_pa)), "what the CNode held was finalized"); + assert!(read(e_copy).unwrap().is_none(), "copies of what it held are gone too"); + } + } +} + +#[test] +fn a_cnode_holding_its_own_original_delete_first_and_other_orders() { + for g in [4096u64, 16384] { + // 곧바로 삭제 + let (mut w, c, c_copy, e_copy, c_pa, e_pa, _t) = self_holding(g); + unsafe { + delete(c.add(3), &mut w).unwrap(); + w.check(); + assert!(!w.objs.contains(&(2, c_pa)) && !w.objs.contains(&(2, e_pa))); + assert!(read(c_copy).unwrap().is_none() && read(e_copy).unwrap().is_none()); + // 죽은 배열의 슬롯을 다시 삭제해도 아무 일도 없음(빈 슬롯) + delete(c.add(3), &mut w).unwrap(); + w.check(); + } + // 사본만 삭제: 오브젝트는 루트에서 닿지 않는 채로 남고, untyped를 회수하면 사라짐 + let (mut w, _c, c_copy, _e_copy, c_pa, e_pa, t) = self_holding(g); + unsafe { + delete(c_copy, &mut w).unwrap(); + w.check(); + assert!(w.objs.contains(&(2, c_pa)), "orphaned self-holding CNode is still alive"); + assert!(w.torn.contains(&(t as u64))); + let root = w.root(); + revoke(root.add(5), &mut w).unwrap(); + w.check(); + assert!(!w.objs.contains(&(2, c_pa)) && !w.objs.contains(&(2, e_pa))); + assert!(!has_descendants(root.add(5))); + } + // 모든 것이 살아 있는 채로 untyped를 바로 회수 + let (mut w, _c, _c_copy, _e_copy, c_pa, _e_pa, _t) = self_holding(g); + unsafe { + let root = w.root(); + revoke(root.add(5), &mut w).unwrap(); + w.check(); + assert!(!w.objs.contains(&(2, c_pa))); + // 그 메모리는 처음부터 다시 나감 + let (pa, _) = w.make(root.add(5), root.add(20), ObjKind::Frame); + assert_eq!(pa, 0x4000_0000); + w.check(); + } + // untyped를 회수가 아니라 삭제 + let (mut w, _c, _c_copy, _e_copy, c_pa, _e_pa, _t) = self_holding(g); + unsafe { + let root = w.root(); + delete(root.add(5), &mut w).unwrap(); + w.check(); + assert!(!w.objs.contains(&(2, c_pa))); + assert!(read(root.add(5)).unwrap().is_none()); + } + } +} + +#[test] +fn an_untyped_parked_inside_a_cnode_carved_from_it() { + for g in [4096u64, 16384] { + let mut w = World::with(g, 16); + let root = w.root(); + unsafe { + let (c_pa, c) = w.make(root.add(5), root.add(10), ObjKind::CNode); + let (f_pa, _) = w.make(root.add(5), root.add(11), ObjKind::Frame); + // untyped 자신을, 거기서 떼어 만든 CNode 안에 넣음 + move_cap(root.add(5), c.add(7)).unwrap(); + w.check(); + // 그 슬롯으로 회수: CNode가 죽고, 그 안을 비우면서 untyped 케이퍼빌리티도 삭제됨 + revoke(c.add(7), &mut w).unwrap(); + w.check(); + assert!(!w.objs.contains(&(2, c_pa)) && !w.objs.contains(&(2, f_pa))); + assert!(!w.objs.contains(&(0, 0x4000_0000)), "the untyped cap was destroyed with its holder"); + } + // 삭제로도 같고, CNode의 원본까지 자기 안에 있어도 같음 + let mut w = World::with(g, 16); + let root = w.root(); + unsafe { + let (c_pa, c) = w.make(root.add(5), root.add(10), ObjKind::CNode); + move_cap(root.add(5), c.add(7)).unwrap(); + move_cap(root.add(10), c.add(8)).unwrap(); + w.check(); + delete(c.add(7), &mut w).unwrap(); + w.check(); + assert!(!w.objs.contains(&(2, c_pa))); + } + } +} + +#[test] +fn two_cnodes_holding_each_others_original() { + for order in 0..4 { + let mut w = World::with(4096, 16); + let root = w.root(); + unsafe { + let (a_pa, a) = w.make(root.add(5), root.add(10), ObjKind::CNode); + let (b_pa, b) = w.make(root.add(5), root.add(11), ObjKind::CNode); + copy(root.add(10), root.add(12), rights::ALL, 0, false).unwrap(); + copy(root.add(11), root.add(13), rights::ALL, 0, false).unwrap(); + // A의 원본은 B에, B의 원본은 A에 둠 + move_cap(root.add(10), b.add(1)).unwrap(); + move_cap(root.add(11), a.add(1)).unwrap(); + w.check(); + match order { + // B를 통해 A를 삭제, A를 통해 B를 삭제 + 0 => delete(b.add(1), &mut w).unwrap(), + 1 => delete(a.add(1), &mut w).unwrap(), + 2 => { + revoke(b.add(1), &mut w).unwrap(); + w.check(); + revoke(a.add(1), &mut w).unwrap(); + w.check(); + // 둘 다 루트에서 닿지 않음. untyped로만 되찾을 수 있음 + assert!(w.objs.contains(&(2, a_pa)) && w.objs.contains(&(2, b_pa))); + revoke(root.add(5), &mut w).unwrap() + } + _ => { + delete(root.add(12), &mut w).unwrap(); + delete(root.add(13), &mut w).unwrap(); + w.check(); + revoke(root.add(5), &mut w).unwrap() + } + } + w.check(); + assert!(!w.objs.contains(&(2, a_pa)) && !w.objs.contains(&(2, b_pa)), "order {order}"); + } + } +} + +#[test] +fn cnodes_nested_through_cnodes_with_tcbs_bound_across_levels() { + on_small_stack(|| { + const DEPTH: usize = 400; + let mut w = World::with(4096, 3 * DEPTH as u64 + 8); + let root = w.root(); + unsafe { + let ut = root.add(5); + // i번째 층: CNode_i의 원본은 CNode_{i-1}의 1번 슬롯에 있음. CNode_i의 2번 + // 슬롯에는 TCB의 원본이 있고, 그 TCB의 묶인 슬롯에는 CNode_i와 CNode_i의 + // 3번 슬롯에 있는 주소 공간의 사본이 있음 + let mut holder = root.add(10); + let mut top = std::ptr::null_mut(); + for i in 0..DEPTH { + let (_, c) = w.make(ut, root.add(20), ObjKind::CNode); + let (_, t) = w.make(ut, c.add(2), ObjKind::Tcb); + let (_, _) = w.make(ut, c.add(3), ObjKind::AddrSpace); + copy_pair_bound(root.add(20), t.add(1), c.add(3), t.add(2)).unwrap(); + move_cap(root.add(20), holder).unwrap(); + if i == 0 { + top = holder; + } + holder = c.add(1); + } + w.check(); + let before = w.finalized; + delete(top, &mut w).unwrap(); + w.check(); + assert_eq!(w.finalized - before, 3 * DEPTH as u64); + assert_eq!(w.torn.len(), DEPTH); + assert!(!has_descendants(ut)); + } + }); +} + +/// 위의 무작위 모형 검사에 자기 참조를 노리는 연산 둘을 더한 것입니다. 컨테이너의 +/// 원본을 그 컨테이너 안에 넣는 것과, untyped를 CNode 안에 넣는 것입니다(그 +/// untyped에서 떼어 만든 CNode일 때가 많음). 씨앗과 회차도 다릅니다. +#[test] +fn random_sequences_with_self_reference_keep_every_invariant() { + let mut finalized = 0; + let mut selfs = 0; + for seed in [0x9E37_79B9_7F4A_7C15u64, 0xD1B5_4A32_D192_ED03, 0x1234_5678_9ABC_DEF1, 0x0F0F_1E1E_2D2D_3C3C] { + let mut rng = Rng(seed); + for round in 0..250 { + let granule = if round % 2 == 0 { 4096 } else { 16384 }; + let mut w = World::new(granule, &mut rng); + for _ in 0..300 { + if rng.below(9) == 0 { + // 컨테이너의 원본을 자기 안에 넣음(또는 untyped를 아무 CNode에나 넣음) + let mut cands = Vec::new(); + for &(base, n) in w.containers.values().filter(|c| c.1 != TCB_N) { + for i in 1..n { + let s = unsafe { base.add(i) }; + if let Some(e) = unsafe { read(s) }.unwrap() { + match e.cap { + Cap::CNode { base: pa, .. } if e.original => { + if let Some(&(arr, m)) = w.containers.get(&pa) { + cands.push((s, arr, m)); + } + } + Cap::Untyped { .. } => { + // 루트가 아닌 살아 있는 CNode 아무거나 + for (&pa, &(arr, m)) in w.containers.iter() { + if m != TCB_N && pa != BOOT.cnode { + cands.push((s, arr, m)); + break; + } + } + } + _ => {} + } + } + } + } + if !cands.is_empty() { + let (s, arr, m) = cands[rng.below(cands.len() as u64) as usize]; + let d = unsafe { arr.add(1 + rng.below(m as u64 - 1) as usize) }; + if unsafe { move_cap(s, d) }.is_ok() { + selfs += 1; + } + } + } else { + w.step(&mut rng); + } + w.check(); + } + finalized += w.finalized; + } + } + assert!(finalized > 5_000, "only {finalized} finalized"); + assert!(selfs > 300, "only {selfs} self-parking moves happened"); +} + +/// 온전한 그래뉼이 없는 untyped에서는 아무것도 만들 수 없고, 메모리를 준비하는 +/// 콜백에도 닿지 않습니다. 커널은 그런 틈을 untyped로 넘기지 않지만, 넘어왔다고 +/// 해도 이 층에서 막힙니다. +#[test] +fn an_untyped_without_a_whole_granule_never_yields_an_object() { + let mut rng = Rng(0x5DEE_CE66_D1CE_4E5B); + let mut tried = 0; + for g in [4096u64, 16384] { + for _ in 0..4000 { + // 구간 안에 그래뉼 경계에 맞는 그래뉼이 하나도 없게 시작과 크기를 고름 + let page = 0x4000_0000 + rng.below(1 << 20) * g; + let off = 1 + rng.below(g - 1); + let base = page + off; + let size = 1 + rng.below(2 * g - off - 1); + assert_eq!(r(base, size).whole(g), None); + tried += 1; + let c = node(8); + unsafe { + insert_root(c.add(1), Cap::Untyped { base, size, used: 0 }).unwrap(); + for kind in [ObjKind::Frame, ObjKind::PageTable, ObjKind::Tcb, ObjKind::Endpoint, ObjKind::CNode, ObjKind::AddrSpace] { + let r = retype(c.add(1), c.add(2), kind, g, |_| panic!("prep reached for a gap without a granule")); + assert_eq!(r, Err(CapError::Exhausted)); + } + assert_eq!(copy(c.add(1), c.add(2), rights::ALL, 0, false), Err(CapError::NotCopyable)); + assert_eq!(cap_at(c, 1), Cap::Untyped { base, size, used: 0 }); + } + } + } + assert!(tried > 4000, "only {tried} gaps without a granule were tried"); +} diff --git a/crates/k0-conin/src/lib.rs b/crates/k0-conin/src/lib.rs index 3241095..4409df5 100644 --- a/crates/k0-conin/src/lib.rs +++ b/crates/k0-conin/src/lib.rs @@ -12,8 +12,12 @@ //! - 바이트를 해석하지 않습니다. 옮기기만 합니다. //! - 인터럽트 한 번의 일은 링의 빈자리로 묶여 있습니다. 링이 가득 차면 UART의 //! 수신 인터럽트를 스스로 막고(게이트), 읽는 쪽이 자리를 비운 뒤에 다시 -//! 엽니다. 그래서 외부가 아무리 빨리 보내도 인터럽트는 읽는 쪽의 소비 -//! 속도만큼만 들어옵니다. +//! 엽니다. 그래서 외부가 아무리 빨리 보내도 받아들인 바이트의 인터럽트는 +//! 읽는 쪽의 소비 속도만큼만 들어옵니다. +//! - 오류가 난 문자(break, framing, parity)는 링의 자리를 쓰지 않고 버려지므로 +//! 따로 셉니다. 틱 하나 동안 [DROP_MAX]개를 버리면 수신 인터럽트를 막고 다음 +//! 틱에만 다시 엽니다. 그동안 온 바이트는 장치의 FIFO에서 기다리고, FIFO가 +//! 넘치면 유실로 표시됩니다. //! - 수신 원인은 지우지 않고 FIFO를 비워서 가라앉힙니다. FIFO에 남은 바이트를 //! 새 인터럽트가 알려 주리라고 기대하지 않고, 게이트를 열 때와 틱마다 직접 //! 들여다봅니다. @@ -81,11 +85,14 @@ pub trait Regs { pub const RING: usize = 256; /// 원인 없는 인터럽트가 이만큼 이어지면 입력 경로를 끔 pub const SPURIOUS_MAX: u8 = 8; -/// FIFO를 한 번 비울 때 데이터 레지스터를 읽는 횟수의 상한. 오류가 난 문자는 -/// 링의 자리를 쓰지 않고 버려지므로 링의 빈자리와 따로 묶어 둠 +/// FIFO를 한 번 비울 때 데이터 레지스터를 읽는 횟수의 상한. 링의 빈자리와 +/// [DROP_MAX]로도 묶이지만, 둘을 합친 것보다 작은 이 값이 먼저 걸릴 수 있음 const DRAIN_MAX: usize = RING + 64; /// 버릴 때 장치의 FIFO에서 꺼내는 횟수의 상한(PL011의 FIFO는 32칸) const FLUSH_MAX: usize = 64; +/// 틱 하나 동안 버리는 오류 문자의 상한. 오류가 난 문자는 링의 자리를 쓰지 +/// 않아서 링이 가득 차는 것으로는 묶이지 않으므로 따로 셈 +pub const DROP_MAX: u16 = RING as u16; const FR_RXFE: u32 = 1 << 4; const DR_FE: u32 = 1 << 8; @@ -130,12 +137,15 @@ pub struct Rx { open: bool, /// 입력 경로가 꺼졌는지(되돌리지 않음) off: bool, - /// 링이 가득 차 UART의 수신 인터럽트를 막아 둔 상태인지 + /// 링이 가득 찼거나 오류 문자를 버릴 만큼 버려 UART의 수신 인터럽트를 막아 + /// 둔 상태인지 gated: bool, /// 다음에 넣는 바이트에 유실 표시를 붙일지 gap: bool, /// 장치의 FIFO가 넘쳤고 그 FIFO를 아직 끝까지 비우지 못했는지 overrun: bool, + /// 지난 틱 뒤로 버린 오류 문자 수([DROP_MAX]에서 멈춤) + dropped: u16, spurious: u8, } @@ -155,6 +165,7 @@ impl Rx { gated: false, gap: false, overrun: false, + dropped: 0, spurious: 0, } } @@ -269,15 +280,25 @@ impl Rx { /// 인터럽트 없이 FIFO를 들여다보는 함수입니다. /// - /// 틱마다, 그리고 읽는 태스크가 잠들기 직전에 부릅니다. 수신 타임아웃 - /// 인터럽트가 없는 UART나 조용히 틀린 인터럽트 번호에서도 입력이 (늦게나마) - /// 도착하게 하는 보조 경로입니다. + /// 읽는 태스크가 잠들기 직전에 부르고, 틱마다 [Rx::tick]이 부릅니다. 수신 + /// 타임아웃 인터럽트가 없는 UART나 조용히 틀린 인터럽트 번호에서도 입력이 + /// (늦게나마) 도착하게 하는 보조 경로입니다. pub fn poll(&mut self, regs: &mut impl Regs) { if self.open && !self.off && self.service(regs) > 0 { self.spurious = 0; } } + /// 틱마다 한 번 부르는 함수입니다. + /// + /// 버린 오류 문자의 수를 다시 0부터 세고 [Rx::poll]처럼 FIFO를 + /// 들여다봅니다. 오류 문자 때문에 막아 둔 수신 인터럽트는 여기서만 다시 + /// 열립니다. + pub fn tick(&mut self, regs: &mut impl Regs) { + self.dropped = 0; + self.poll(regs); + } + /// 링에서 바이트 하나를 꺼내는 함수입니다. 둘째 값은 이 바이트 바로 앞에서 /// 입력이 유실됐는지입니다. pub fn pop(&mut self, regs: &mut impl Regs) -> Option<(u8, bool)> { @@ -301,6 +322,11 @@ impl Rx { let mut taken = 0; let mut empty = false; for _ in 0..DRAIN_MAX { + if self.dropped >= DROP_MAX { + // 이번 틱에 버릴 수 있는 만큼 버렸음. 장치를 건드리지 않고 + // 멈추며, FIFO가 비었는지 보지 않으므로 아래에서 게이트가 닫힘 + break; + } if regs.read(Reg::Fr) & FR_RXFE != 0 { empty = true; break; @@ -316,6 +342,7 @@ impl Rx { if d & (DR_FE | DR_PE | DR_BE) != 0 { // 오류가 난 문자는 버리고 다음 바이트에 표시함 self.gap = true; + self.dropped = self.dropped.saturating_add(1); continue; } let mark = if self.gap || self.overrun { GAP } else { 0 }; @@ -335,8 +362,9 @@ impl Rx { regs.write(Reg::Imsc, INT_OURS); } } else if !self.gated { - // FIFO에 남은 것이 있는데 받을 자리가 없음. 선이 내려가지 않으므로 - // UART 쪽에서 막고, 자리가 나면 pop이 다시 들여다봄 + // FIFO에 남은 것이 있는데 받을 자리가 없거나, 오류 문자를 버릴 만큼 + // 버렸음. 선이 내려가지 않으므로 UART 쪽에서 막고, 자리가 나면 + // pop이, 틱이 지나면 tick이 다시 들여다봄 self.gated = true; regs.write(Reg::Imsc, 0); } diff --git a/crates/k0-conin/src/tests.rs b/crates/k0-conin/src/tests.rs index 9f68350..8d0e9f6 100644 --- a/crates/k0-conin/src/tests.rs +++ b/crates/k0-conin/src/tests.rs @@ -9,6 +9,8 @@ use std::collections::VecDeque; use super::*; const BREAK: u32 = DR_BE | DR_FE; +/// 수신 로직이 버리는 문자에 붙어 있는 오류 비트 +const ERRORS: u32 = DR_FE | DR_PE | DR_BE; struct Fake { fifo: VecDeque, @@ -25,6 +27,8 @@ struct Fake { overrun: bool, accesses: usize, dr_reads: usize, + /// 데이터 레지스터에서 읽혀 나간 오류 문자 수 + err_reads: usize, cr_writes: usize, } @@ -42,6 +46,7 @@ impl Fake { overrun: false, accesses: 0, dr_reads: 0, + err_reads: 0, cr_writes: 0, } } @@ -81,6 +86,9 @@ impl Regs for Fake { Reg::Dr => { self.dr_reads += 1; let mut d = self.fifo.pop_front().unwrap_or(0); + if d & ERRORS != 0 { + self.err_reads += 1; + } if self.overrun { d |= DR_OE; self.overrun = false; @@ -154,6 +162,11 @@ struct Sim { sent: usize, got: Vec<(u8, bool)>, entries: usize, + /// 마지막으로 버린 뒤 처음 받을 문자의 순서 번호 + origin: usize, + /// 지난 틱 때의 err_reads와, 그 뒤로 읽는 쪽이 버린 횟수 + err_base: usize, + flushes: usize, } impl Sim { @@ -167,6 +180,9 @@ impl Sim { sent: 0, got: Vec::new(), entries: 0, + origin: 0, + err_base: 0, + flushes: 0, }; Rx::quiesce(&mut s.uart); s.rx.open(&mut s.uart); @@ -196,7 +212,7 @@ impl Sim { if self.uart.offer(e) { self.waiting.pop_front(); self.sent += 1; - if e & BREAK == 0 { + if e & ERRORS == 0 { self.accepted.push((index, e as u8)); } } else if self.uart.backpressure { @@ -209,6 +225,18 @@ impl Sim { } } self.irqs(); + self.audit(); + } + + /// 틱 하나 동안 꺼낸 오류 문자는 상한을 넘지 않고(읽는 쪽이 버리면서 직접 + /// 꺼낸 것은 따로 셈), 상한에 닿은 동안에는 수신 인터럽트가 막혀 있어야 함 + fn audit(&self) { + let errors = self.uart.err_reads - self.err_base; + let allowed = usize::from(DROP_MAX) + self.flushes * FLUSH_MAX; + assert!(errors <= allowed, "{errors} error characters taken in one tick"); + if self.rx.is_open() && self.rx.dropped >= DROP_MAX { + assert!(self.rx.gated && self.uart.imsc == 0, "the budget is spent and the line is still open"); + } } fn send(&mut self, bytes: &[u8]) { @@ -226,10 +254,34 @@ impl Sim { } fn tick(&mut self) { + self.err_base = self.uart.err_reads; + self.flushes = 0; + self.rx.tick(&mut self.uart); + self.pump(); + } + + /// 읽는 태스크가 잠들기 직전에 한 번 들여다봄 + fn presleep(&mut self) { self.rx.poll(&mut self.uart); self.pump(); } + /// 읽는 태스크가 받아 둔 입력을 버림. 그때까지 받은 것은 비교에서 빠짐 + fn flush(&mut self) { + self.rx.flush(&mut self.uart); + self.flushes += 1; + assert!(self.uart.fifo.is_empty()); + self.got.clear(); + self.accepted.clear(); + self.origin = self.sent; + self.pump(); + } + + fn noise(&mut self, kind: u32, n: usize) { + self.waiting.extend(std::iter::repeat(kind).take(n)); + self.pump(); + } + /// 더 올 것이 없을 때까지 읽는 쪽을 돌림(읽는 태스크는 잠들기 전에 한 번 /// 들여다보고, 틱마다 커널이 한 번 더 들여다봄) fn settle(&mut self) { @@ -256,7 +308,7 @@ impl Sim { let mut last = None; for (k, (index, _)) in self.accepted.iter().enumerate() { let hole = match last { - None => *index != 0, + None => *index != self.origin, Some(prev) => *index != prev + 1, }; if hole { @@ -599,3 +651,130 @@ fn turning_the_path_off_masks_the_uart_and_empties_the_ring() { assert!(sim.rx.is_off() && !sim.rx.has_data()); assert_eq!(sim.rx.pop(&mut sim.uart), None); } + +/// 세 가지 UART 모형입니다. QEMU의 PL011, 실제 PL011, SBSA UART 순서입니다. +fn models() -> [Fake; 3] { + let mut sbsa = Fake::new(32, 16, false); + sbsa.has_cr = false; + [Fake::new(16, 1, true), Fake::new(32, 16, false), sbsa] +} + +#[test] +fn a_stream_of_error_characters_is_held_to_the_budget_of_one_tick() { + // 오류가 난 문자는 링의 자리를 쓰지 않으므로 링이 가득 차는 것으로는 묶이지 + // 않음. 선로의 상대가 break나 framing 오류만 이어 보내도 틱 하나 동안 꺼내는 + // 문자와 인터럽트 진입은 상한을 넘지 않아야 함 + // 문서가 말하는 값: 틱 하나에 256개 + assert_eq!(DROP_MAX, 256); + let budget = usize::from(DROP_MAX); + for kind in [BREAK, DR_FE, DR_PE, DR_PE | 0x41] { + for uart in models() { + let mut sim = Sim::new(uart); + sim.noise(kind, 5000); + assert!(sim.uart.err_reads <= budget, "{} error characters taken", sim.uart.err_reads); + assert!(sim.entries <= budget, "{} entries", sim.entries); + assert_eq!(sim.uart.imsc, 0, "the gate is closed at the uart"); + assert!(!sim.uart.line()); + // 읽는 쪽이 꺼내 보거나 잠들기 전에 들여다봐도 다음 틱까지는 그대로임 + let quiet = (sim.uart.dr_reads, sim.entries, sim.uart.accesses); + for _ in 0..50 { + sim.noise(kind, 100); + assert!(!sim.pop()); + sim.presleep(); + } + assert_eq!((sim.uart.dr_reads, sim.entries, sim.uart.accesses), quiet); + assert_eq!(sim.rx.spurious, 0); + // 틱이 지나면 다시 상한만큼만 받음 + for tick in 2..=6 { + sim.tick(); + sim.noise(kind, 1000); + assert!(sim.uart.err_reads <= tick * budget); + assert!(sim.entries <= tick * budget + 1); + assert!(!sim.uart.line()); + } + assert!(sim.uart.err_reads > 2 * budget, "the tick must let the line in again"); + assert!(sim.enabled && !sim.rx.is_off(), "noise on the line is not a reason to cut it"); + assert!(!sim.rx.has_data()); + } + } +} + +#[test] +fn bytes_behind_the_noise_arrive_after_the_next_tick_with_a_mark() { + for uart in models() { + let mut sim = Sim::new(uart); + sim.noise(BREAK, usize::from(DROP_MAX)); + assert_eq!(sim.uart.imsc, 0); + sim.send(b"help\r"); + // 읽는 쪽만으로는 열리지 않음 + assert!(!sim.pop()); + sim.presleep(); + assert!(!sim.rx.has_data()); + sim.tick(); + assert!(sim.rx.has_data()); + sim.settle(); + assert_eq!(sim.got, [(b'h', true), (b'e', false), (b'l', false), (b'p', false), (b'\r', false)]); + sim.check(); + assert_eq!(sim.uart.imsc, INT_RX | INT_RT | INT_OE, "the gate is open again"); + } +} + +#[test] +fn a_spent_budget_is_no_excuse_for_a_line_that_stays_up() { + // 상한에 닿아 UART 쪽을 막은 뒤에도 선이 서 있으면 그것은 다른 장치의 선임 + let mut sim = Sim::new(Fake::new(16, 1, true)); + sim.noise(BREAK, usize::from(DROP_MAX)); + assert_eq!(sim.uart.imsc, 0); + for _ in 0..SPURIOUS_MAX - 1 { + assert_eq!(sim.rx.interrupt(&mut sim.uart), Irq::Spurious); + } + assert_eq!(sim.rx.interrupt(&mut sim.uart), Irq::CutOff); + assert!(sim.rx.is_off()); +} + +#[test] +fn random_noise_never_cuts_a_healthy_uart_and_every_hole_is_marked() { + let mut rng = Rng(0xA409_3822_299F_31D0); + let mut gated = 0; + for round in 0..600 { + let [emulator, hardware, sbsa] = models(); + let mut sim = Sim::new(match rng.below(3) { + 0 => emulator, + 1 => hardware, + _ => sbsa, + }); + let mut spent = false; + for _ in 0..rng.below(80) { + match rng.below(14) { + 0..=2 => { + let n = [1, 5, 40, 300][rng.below(4) as usize]; + let bytes: Vec = (0..n).map(|_| rng.next() as u8).collect(); + sim.send(&bytes); + } + 3..=5 => { + let kind = [BREAK, DR_FE, DR_PE, DR_PE | 0x41][rng.below(4) as usize]; + let n = [1, 30, 200, 600, 3000][rng.below(5) as usize]; + sim.noise(kind, n); + } + 6..=8 => { + for _ in 0..rng.below(300) { + sim.pop(); + } + } + 9 => sim.presleep(), + 10 => sim.flush(), + 11 => { + sim.uart.idle(); + sim.pump(); + } + _ => sim.tick(), + } + spent |= sim.rx.dropped >= DROP_MAX; + } + gated += usize::from(spent); + sim.settle(); + sim.check(); + assert!(sim.enabled && !sim.rx.is_off(), "round {round}: a healthy uart was cut off"); + } + assert!(gated > 100, "the schedules must actually spend the budget ({gated} rounds did)"); +} diff --git a/crates/k0-efi/src/prepare.rs b/crates/k0-efi/src/prepare.rs index 1176c04..d2a5291 100644 --- a/crates/k0-efi/src/prepare.rs +++ b/crates/k0-efi/src/prepare.rs @@ -75,7 +75,7 @@ pub struct Request<'a> { pub tail_size: u64, /// 내장한 커널의 변환 그래뉼 pub granule: u64, - /// 이 CPU의 물리 주소 폭이 정하는 디바이스 주소의 상한 + /// 이 CPU의 물리 주소 폭이 정하는 주소의 상한(디바이스, 그리고 RAM에도 적용) pub device_limit: u64, /// `rng-seed`에 더할 엔트로피, 없으면 빈 슬라이스 pub seed: &'a [u8], @@ -246,7 +246,8 @@ pub fn prepare(req: &Request<'_>, work: Work<'_>, out: &mut [u8]) -> Result = maps::QEMU_EDK2_512M.to_vec(); + high.push((CONV, 1 << 41, 256, WB)); + let mut bench = Bench::new(&high); + assert_eq!(bench.run(&virt3().blob()).err(), Some(PrepareError::Validate(ValidateError::MemoryAboveLimit))); + // 커널이 받는 2MiB를 넘는 DTB는 버퍼에 들어가더라도 거부 let mut big = virt3(); big.kids.push(N::new("blob").p("data", vec![0x5a; 2 * 1024 * 1024])); diff --git a/crates/k0-mm/Cargo.toml b/crates/k0-mm/Cargo.toml index e30d833..713418c 100644 --- a/crates/k0-mm/Cargo.toml +++ b/crates/k0-mm/Cargo.toml @@ -14,3 +14,6 @@ granule-16k = [] [dependencies] k0-abi = { path = "../k0-abi" } + +[dev-dependencies] +k0-cap = { path = "../k0-cap" } diff --git a/crates/k0-mm/src/paging.rs b/crates/k0-mm/src/paging.rs index 396d694..6e35b97 100644 --- a/crates/k0-mm/src/paging.rs +++ b/crates/k0-mm/src/paging.rs @@ -981,7 +981,7 @@ pub fn null_user_root() -> u64 { /// 이 코어가 구현한 물리 주소 폭(비트)을 주는 함수입니다. 커널의 변환 /// 설정에 맞춰 최대 48로 제한합니다. 디바이스 주소의 상한으로 쓰이고, RAM의 -/// 상한은 이보다 낮은 `PA_CEILING`입니다. +/// 상한은 이 값과 `PA_CEILING` 가운데 작은 쪽입니다. pub fn pa_bits() -> u32 { let mmfr0: u64; // SAFETY: ID 레지스터 읽기는 부작용 없음 diff --git a/crates/k0-mm/src/user/tests.rs b/crates/k0-mm/src/user/tests.rs index 92cf14a..fae98b4 100644 --- a/crates/k0-mm/src/user/tests.rs +++ b/crates/k0-mm/src/user/tests.rs @@ -450,3 +450,353 @@ fn the_top_level_covers_the_whole_48_bit_user_range() { assert_eq!(user_install_table(root, 1 << 48, table()), Err(MmuError::Misaligned)); } } + +/// 케이퍼빌리티(k0-cap), 주소 공간 등록부, 사용자 테이블 워커를 한데 묶어 무작위 +/// 연산열로 돌리는 테스트 모듈입니다. +/// +/// 정리 콜백은 커널의 것(kernel/src/object.rs의 Frame, PageTable, AddrSpace +/// 처리)을 본떴습니다. 커널이 정지로 처리하는 경우들이 태스크의 연산 순서로는 +/// 생기지 않는지를 봅니다. 어떤 워커도 BadTable을 내지 않고, 등록부 해제가 +/// 실패하지 않고, 살아 있는 AddrSpace 케이퍼빌리티는 등록부에서도 살아 있고, +/// 살아 있는 주소 공간은 살아 있는 오브젝트가 아닌 테이블이나 프레임에 닿지 +/// 않아야 합니다. +mod composed { + use super::*; + use k0_cap::{Cap, CapError, Entry, Mapping, ObjKind, Removed, Slot}; + use std::collections::BTreeSet; + + 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 + } + } + + struct Kern { + reg: AddrSpaces, + bad_table: u32, + release_failed: u32, + registry_mismatch: u32, + /// 살아 있는 슬롯 배열들의 (주소, 슬롯 수) + cnodes: Vec<(u64, usize)>, + unmapped: u64, + uninstalled: u64, + released: u64, + frame_maps: u64, + } + + impl k0_cap::Env for Kern { + fn removed(&mut self, r: &Removed) { + // SAFETY: 테이블은 이 테스트가 잡은 호스트 메모리임 + unsafe { + match r.cap { + Cap::Frame { base, map: Some(m), .. } => { + if let Some(root) = self.reg.resolve(m.asid, m.generation) { + match user_unmap_frame(root, m.va, base) { + Ok(true) => self.unmapped += 1, + Ok(false) => {} + Err(_) => self.bad_table += 1, + } + } + } + Cap::PageTable { base, map: Some(m) } => { + if let Some(root) = self.reg.resolve(m.asid, m.generation) { + match user_uninstall_table(root, m.va, u32::from(m.level), base) { + Ok(true) => self.uninstalled += 1, + Ok(false) => {} + Err(_) => self.bad_table += 1, + } + } + } + Cap::AddrSpace { root_pa, asid } if r.original => { + if self.reg.release(asid, root_pa) { + self.released += 1; + } else { + self.release_failed += 1; + } + } + _ => {} + } + } + } + + fn container(&mut self, cap: &Cap) -> Option<(*mut Slot, usize)> { + match *cap { + Cap::CNode { base, slots } => { + let before = self.cnodes.len(); + self.cnodes.retain(|c| c.0 != base); + assert_eq!(self.cnodes.len() + 1, before, "a CNode is finalized exactly once"); + Some((base as *mut Slot, slots as usize)) + } + _ => None, + } + } + } + + fn va_of(i: [u64; 4]) -> u64 { + let ps = GRANULE.trailing_zeros() as u64; + let bits = ps - 3; + (i[0] << (ps + 3 * bits)) | (i[1] << (ps + 2 * bits)) | (i[2] << (ps + bits)) | (i[3] << ps) + } + + fn slot_of(k: &Kern, rng: &mut Rng) -> *mut Slot { + let (base, n) = k.cnodes[rng.below(k.cnodes.len() as u64) as usize]; + (base + (1 + rng.below(n as u64 - 1)) * 64) as *mut Slot + } + + fn pick(k: &Kern, rng: &mut Rng, want: impl Fn(&Option) -> bool) -> *mut Slot { + for _ in 0..24 { + let s = slot_of(k, rng); + if want(&unsafe { k0_cap::read(s) }.unwrap()) { + return s; + } + } + slot_of(k, rng) + } + + /// kernel/src/syscall.rs의 sys_map을 본뜬 함수입니다. + unsafe fn op_map(k: &mut Kern, s: *mut Slot, va: u64, aspace: *mut Slot) { + unsafe { + let Some(Entry { cap: Cap::AddrSpace { root_pa, asid }, .. }) = k0_cap::read(aspace).unwrap() else { + return; + }; + let generation = match k.reg.get(asid) { + Some((root, generation)) if root == root_pa => generation, + _ => { + k.registry_mismatch += 1; + return; + } + }; + match k0_cap::read(s).unwrap() { + Some(Entry { cap: Cap::Frame { base, rights, map: None }, .. }) => { + match user_map_frame(root_pa, va, base, UserPerm::RwUser) { + Ok(()) => { + k.frame_maps += 1; + let map = Some(Mapping { asid, generation, va, level: 3 }); + k0_cap::update(s, Cap::Frame { base, rights, map }).unwrap(); + } + Err(MmuError::BadTable) => k.bad_table += 1, + Err(_) => {} + } + } + Some(Entry { cap: Cap::PageTable { base, map: None }, .. }) => { + match user_install_table(root_pa, va, base) { + Ok(level) => { + let map = Some(Mapping { asid, generation, va: va & !(G - 1), level: level as u8 }); + k0_cap::update(s, Cap::PageTable { base, map }).unwrap(); + } + Err(MmuError::BadTable) => k.bad_table += 1, + Err(_) => {} + } + } + _ => {} + } + } + } + + /// 같은 파일의 sys_unmap을 본뜬 함수입니다. + unsafe fn op_unmap(k: &mut Kern, s: *mut Slot) { + unsafe { + match k0_cap::read(s).unwrap() { + Some(Entry { cap: Cap::Frame { base, rights, map: Some(m) }, .. }) => { + if let Some(root) = k.reg.resolve(m.asid, m.generation) { + if user_unmap_frame(root, m.va, base).is_err() { + k.bad_table += 1; + } + } + k0_cap::update(s, Cap::Frame { base, rights, map: None }).unwrap(); + } + Some(Entry { cap: Cap::PageTable { base, map: Some(m) }, .. }) => { + if let Some(root) = k.reg.resolve(m.asid, m.generation) { + if user_uninstall_table(root, m.va, u32::from(m.level), base).is_err() { + k.bad_table += 1; + } + } + zero_table(base); + k0_cap::update(s, Cap::PageTable { base, map: None }).unwrap(); + } + _ => {} + } + } + } + + /// 살아 있는 주소 공간이 살아 있는 테이블(각각 한 번씩)과 살아 있는 프레임에만 + /// 닿는지 확인하는 함수입니다. + fn check(k: &Kern) { + assert_eq!((k.bad_table, k.release_failed, k.registry_mismatch), (0, 0, 0)); + let (mut frames, mut tables, mut roots) = (BTreeSet::new(), BTreeSet::new(), Vec::new()); + for &(base, n) in &k.cnodes { + for i in 1..n { + let s = (base + i as u64 * 64) as *mut Slot; + match unsafe { k0_cap::read(s) }.expect("slot decodes") { + Some(Entry { cap: Cap::Frame { base, .. }, .. }) => { + frames.insert(base); + } + Some(Entry { cap: Cap::PageTable { base, .. }, .. }) => { + assert!(tables.insert(base), "two capabilities name one page table"); + } + Some(Entry { cap: Cap::AddrSpace { root_pa, asid }, original, .. }) => { + assert_eq!(k.reg.get(asid).map(|x| x.0), Some(root_pa), "live cap, dead registry entry"); + if original { + roots.push(root_pa); + } + } + _ => {} + } + } + } + let mut seen = BTreeSet::new(); + for root in roots { + let mut stack = vec![(root, 0u32)]; + while let Some((t, level)) = stack.pop() { + for idx in 0..GRANULE / 8 { + // SAFETY: t는 아레나 안의 살아 있는 테이블임 + let e = unsafe { entry_ptr(t, idx).read() }; + if e == 0 { + continue; + } + assert_eq!(e & 0b11, 0b11, "an entry that is neither table nor page"); + let pa = e & ADDR_MASK; + if level < 3 { + assert!(tables.contains(&pa), "a live address space reaches a table that is not a live object"); + assert!(seen.insert(pa), "a table is reachable twice"); + stack.push((pa, level + 1)); + } else { + assert!(frames.contains(&pa), "a live address space maps a frame that is not a live object"); + } + } + } + } + } + + #[test] + fn caps_registry_and_walkers_survive_random_sequences() { + const N: u64 = 96; + let layout = std::alloc::Layout::from_size_align(GRANULE * N as usize, GRANULE).unwrap(); + let mut totals = (0u64, 0u64, 0u64, 0u64, 0u64); + for seed in [0x9E37_79B9_7F4A_7C15u64, 0xC2B2_AE3D_27D4_EB4F, 0x1656_67B1_9E37_79F9] { + let mut rng = Rng(seed); + for _round in 0..60 { + // SAFETY: 크기가 0이 아닌 배치임 + let arena = unsafe { std::alloc::alloc_zeroed(layout) } as u64; + assert!(arena != 0 && (arena + N * G) & !ADDR_MASK == 0); + let root: *mut Slot = Box::leak(vec![0u64; 8 * 64].into_boxed_slice()).as_mut_ptr().cast(); + let mut k = Kern { + reg: registry(arena, N), + bad_table: 0, + release_failed: 0, + registry_mismatch: 0, + cnodes: vec![(root as u64, 64)], + unmapped: 0, + uninstalled: 0, + released: 0, + frame_maps: 0, + }; + let ut = unsafe { root.add(1) }; + unsafe { k0_cap::insert_root(ut, Cap::Untyped { base: arena, size: N * G, used: 0 }) }.unwrap(); + let mut reuse = 0u64; + for _step in 0..1200 { + let filled = |e: &Option| e.is_some(); + let empty = |e: &Option| e.is_none(); + let mappable = |e: &Option| { + matches!(e, Some(Entry { cap: Cap::Frame { .. } | Cap::PageTable { .. }, .. })) + }; + let aspace = |e: &Option| matches!(e, Some(Entry { cap: Cap::AddrSpace { .. }, .. })); + let va = if rng.below(5) == 0 { + va_of([rng.below(2), rng.below(2), rng.below(2), 1 + rng.below(3)]) + } else { + va_of([0, 0, rng.below(2), 1 + rng.below(3)]) + }; + // SAFETY: 슬롯은 모두 살아 있는 슬롯 배열 안에 있고 아레나도 살아 있음 + unsafe { + match rng.below(100) { + 0..=27 => { + let dest = pick(&k, &mut rng, empty); + let kind = match rng.below(20) { + 0..=7 => ObjKind::Frame, + 8..=16 => ObjKind::PageTable, + 17..=18 => ObjKind::AddrSpace, + _ => ObjKind::CNode, + }; + let mut made = None; + let reg = &mut k.reg; + let r = k0_cap::retype(ut, dest, kind, G, |pa| { + std::ptr::write_bytes(pa as *mut u8, 0, GRANULE); + made = Some(pa); + if kind == ObjKind::AddrSpace { reg.register(pa) } else { Some(0) } + }); + match r { + Ok(()) => { + if kind == ObjKind::CNode { + k.cnodes.push((made.unwrap(), GRANULE / 64)); + } + if made == Some(arena) { + reuse += 1; + } + } + Err(CapError::PrepFailed) => panic!("the registry refused a granule of the untyped"), + Err(_) => {} + } + } + 28..=62 => { + let (s, a) = (pick(&k, &mut rng, mappable), pick(&k, &mut rng, aspace)); + op_map(&mut k, s, va, a); + } + 63..=70 => { + let s = pick(&k, &mut rng, mappable); + op_unmap(&mut k, s); + } + 71..=78 => { + let (s, d) = (pick(&k, &mut rng, filled), pick(&k, &mut rng, empty)); + let _ = k0_cap::copy(s, d, k0_cap::rights::ALL, 0, false); + } + 79..=83 => { + let (s, d) = (pick(&k, &mut rng, filled), pick(&k, &mut rng, empty)); + if s != ut { + let _ = k0_cap::move_cap(s, d); + } + } + 84..=88 => { + let s = pick(&k, &mut rng, filled); + if s != ut { + k0_cap::delete(s, &mut k).unwrap(); + } + } + 89..=90 => { + let s = pick(&k, &mut rng, filled); + if s != ut { + k0_cap::revoke(s, &mut k).unwrap(); + } + } + 91..=98 => { + let (s, a) = (pick(&k, &mut rng, mappable), pick(&k, &mut rng, aspace)); + op_map(&mut k, s, va, a); + } + _ => { + if rng.below(6) == 0 { + k0_cap::revoke(ut, &mut k).unwrap(); + assert_eq!(k.cnodes.len(), 1, "only the root slot array is left"); + } + } + } + } + check(&k); + } + totals.0 += k.unmapped; + totals.1 += k.uninstalled; + totals.2 += k.released; + totals.3 += reuse; + totals.4 += k.frame_maps; + // SAFETY: 이 회차가 끝난 뒤에는 아레나를 가리키는 것이 없음 + unsafe { std::alloc::dealloc(arena as *mut u8, layout) }; + } + } + assert!(totals.0 > 100 && totals.1 > 500 && totals.2 > 500 && totals.3 > 100 && totals.4 > 500, "{totals:?}"); + } +} diff --git a/design/en/boot.md b/design/en/boot.md index 37c8e50..6bd7fb9 100644 --- a/design/en/boot.md +++ b/design/en/boot.md @@ -26,7 +26,7 @@ UEFI firmware does not follow this protocol. So a separate UEFI loader (`loader/ - **Exception level**: the CPU is at EL1 or EL2. - **CPU count**: exactly one CPU is entered. The kernel runs on a single core. - **Interrupt controller and timer**: the interrupt controller is GICv2 or GICv3, and the CPU has the ARM generic timer. -- **RAM**: it lies below 2^47 (128 TiB). +- **RAM**: it lies below 2^47 (128 TiB) and inside the CPU's physical address width. > [!IMPORTANT] > The boot loader must enter exactly one CPU. The kernel no longer checks which CPU that is, so the boot loader must keep the others out. @@ -108,7 +108,7 @@ 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, 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: 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 and inside the CPU's physical address width, 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). | @@ -144,7 +144,7 @@ In the following table, each row gives a log line and the step it stands for, in - **Placement**: it takes that share from the top of the range. The tables become the table reserve (`k0_mm::reserve_tables`) and the entries become the address space registry for the range (`add_range`). The entry area is mapped into the kernel alias window and zeroed. Tables from the reserve are zeroed when they are handed out, not at boot. - **Result**: the range that remains, without its share, is handed out as one `Untyped` capability. After boot, `alias_object` takes its tables from the reserve, so a task cannot use them up. - **A range that cannot hold its share**: a range that is too small, or whose share cannot be mapped, is not handed out as `Untyped` at all. The kernel prints `k0: memory + not handed out ()` and continues. A range that does not fit in the buffer of ranges is skipped the same way (`too many ranges`). -- **A gap without a whole granule**: it is handed out unchanged, because no object can be made from it and it needs no share. +- **A gap without a whole granule**: it is not handed out either, because no object can be made from it. The kernel prints `k0: memory + not handed out (no whole page)`. This step **never refuses to boot**. The worst case is that memory is not handed out and a log line says so. The overhead is about 0.2 % of RAM with the 4 KiB granule and about 0.05 % with the 16 KiB granule. The root task's address space has its root table in the boot window and uses one dedicated registry entry. @@ -156,7 +156,7 @@ The root task starts with the boot seed in its registers `x0` to `x3` and the se ## The boot log -Every line the kernel prints also goes into a **16 KiB buffer** in kernel memory (`K0_BOOT_LOG`). Output printed before the console is known is replayed when the console attaches, so a generic image keeps the boot record in order. When there is no console, **the log is the only record**, and an image built without a console driver never has a console. Of the 16 KiB, user task output may use 6 KiB, and only the first 4 timer tick lines are logged. `tools/boot-log.py ` reads it out of guest memory. The log fills from the front and drops what does not fit. Output from user tasks through the Console capability is recorded only up to a quota, so it cannot push out kernel diagnostics. Neither the console nor the log marks which lines came from a task (see [hardening.md](hardening.md)). +Every line the kernel prints also goes into a **16 KiB buffer** in kernel memory (`K0_BOOT_LOG`). Output printed before the console is known is replayed when the console attaches, so a generic image keeps the boot record in order. When there is no console, **the log is the only record**, and an image built without a console driver never has a console. Of the 16 KiB, user task output may use 6 KiB, the lines the kernel prints when a task ends (a fault, an exit, an unknown system call) may use 4 KiB, and only the first 4 timer tick lines are logged. Both shares stop before the last 2 KiB, which stay for the kernel's own lines. A task-end line that no longer fits is left out of the log as a whole line and goes to the console only, and the kernel says so once with `k0: task lines over the log quota, later ones go to the console only`. `tools/boot-log.py ` reads it out of guest memory. The log fills from the front and drops what does not fit. Output from user tasks through the Console capability is recorded only up to a quota, so it cannot push out kernel diagnostics. Neither the console nor the log marks which lines came from a task (see [hardening.md](hardening.md)). ## Optional console output @@ -280,6 +280,7 @@ The following list shows what has been booted, by tier. - Four CPUs. - The 16 KiB image boots on `max` and is refused on `cortex-a72`. - One image loaded at three other physical addresses (the header `text_offset` patched), and a refusal for an address off the 16 KiB grid. + - Hostile boot input: a DTB pointer at the end of the address range or beyond the CPU's physical address width (`dtb-pointer-end`, `dtb-pointer-above-pa`), a redistributor stride that would overflow the walk and the largest stride that is accepted (`redist-stride`, `redist-stride-wide`), RAM declared beyond the CPU's physical address width (`ram-above-pa`), and a memory range without a whole page (`sub-page-memory`). The device trees are QEMU's own with one change made by `tools/fdt-patch.py`. - `xlnx-versal-virt`, which has RAM at address 0, GICv3 and PL011 elsewhere, entered at EL2. - A pinned image booting on its platform and refusing on another. - A static check that the image never touches the physical timer registers (the kernel uses the EL1 virtual timer, which also works in hypervisor guests). diff --git a/design/en/dtb.md b/design/en/dtb.md index 6485bba..11e5b1d 100644 --- a/design/en/dtb.md +++ b/design/en/dtb.md @@ -41,7 +41,7 @@ The following items apply this principle. - **Reserved ranges**: they only remove memory. A hostile reservation can at worst shrink the memory handed to user space. - **Entropy**: it is only one input among several. The bytes from `/chosen` are mixed with other sources through SHA-256, so hostile entropy cannot weaken the PAC keys. A missing seed does lower their quality, and the kernel says so in the boot log (see [hardening.md](hardening.md)). The parser also records where the seed values lie in the blob, so that the kernel can zero them before it enters the root task. -- **Memory nodes**: they grant memory, so they are checked hardest. Every memory region becomes untyped memory that user space can map. A region that claimed to be RAM but covered a device would hand EL0 direct access to that device. After parsing, the kernel compares every memory region with the device ranges it found in the same DTB (see below) and stops the boot on any overlap. It also stops the boot if a RAM region reaches 2^47 or a device range extends beyond the CPU's physical address width (`k0_mm::pa_bits`), because such a region could not be mapped. The CNode bootstrap also rejects memory regions that overlap each other, so no frame can be retyped twice. +- **Memory nodes**: they grant memory, so they are checked hardest. Every memory region becomes untyped memory that user space can map. A region that claimed to be RAM but covered a device would hand EL0 direct access to that device. After parsing, the kernel compares every memory region with the device ranges it found in the same DTB (see below) and stops the boot on any overlap. It also stops the boot if a RAM region reaches 2^47, or if a RAM region or a device range extends beyond the CPU's physical address width (`k0_mm::pa_bits`), because such a region could not be mapped. The CNode bootstrap also rejects memory regions that overlap each other, so no frame can be retyped twice. - **Device addresses**: they come from the DTB, so they are checked the hardest. A wrong DTB can point the console at another device. The kernel does not map a device page until the descriptor has passed the memory map check, it verifies the hardware identification registers where they exist, its console waits are bounded in time, and a pinned build can fix the expected platform (see "The platform descriptor"). ## Two stages @@ -99,7 +99,7 @@ Besides memory, the kernel finds exactly three devices in the DTB, plus the cons - **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 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 `redistributor-stride` must be a multiple of 64 KiB, at least 128 KiB and below 2^52. The kernel treats a step that leaves the range, or an addition that overflows, as the end of that range. 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. > [!IMPORTANT] @@ -109,7 +109,7 @@ Register addresses are translated through the `ranges` of the parent buses to CP 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. +- RAM must lie below 2^47 and inside the CPU's physical address width. - The kernel image and the DTB must lie inside declared memory. - No device range (widened to whole granules) may overlap memory or a reserved range. - The device ranges must not overlap each other. @@ -148,8 +148,8 @@ The loader's own logic (`crates/k0-efi`) has three more fuzzers of the same kind > Discovery is exercised on QEMU virt, `xlnx-versal-virt` and the host tests. No real board DTB has been run. - Under UEFI the memory map is no longer the DTB's own claim: the loader plans it from the UEFI memory map, and the firmware's own memory nodes are dropped. The gaps below that talk about the DTB's own memory map describe the case without the loader. The firmware that supplies the UEFI memory map is trusted to be wrong at worst, not hostile (see [uefi.md](uefi.md)). -- The memory parser itself does not know the CPU's physical address width. The check against it is in `Platform::validate`, with the limit passed in from `kernel/src/main.rs`. See advisory GHSA-hj3f-38h9-hrpj in [SECURITY.md](../../SECURITY.md) for the status of the earlier memory-map finding. A DTB controlled by an attacker can still stop the boot, which is the intended fail-secure result. -- The DTB pointer is used before anything can validate it. `map_dtb` in `kernel/src/main.rs` refuses a null or misaligned pointer, an address at or above 2^47 and a range that overlaps the kernel image, and nothing else, because the memory map comes from the blob itself. If a boot loader passes the address of a device, the kernel maps that page as read-only normal memory and reads the first eight bytes. Reading a device register can have side effects, and because the mapping is cacheable the processor may fetch more of the page than those eight bytes. The kernel reads further only if the bytes hold the DTB magic and a valid size, and the kernel writes through the mapping exactly once: it zeroes the recorded `rng-seed` and `kaslr-seed` bytes just before it enters the root task, after the DTB has been parsed and validated (see [hardening.md](hardening.md)). `Platform::validate` later checks that the DTB lies inside declared memory, but that memory map is the DTB's own claim. A pinned build could refuse a pointer outside its pinned RAM range before the first read. That check does not exist yet. +- The memory parser itself does not know the CPU's physical address width. The check against it is in `Platform::validate`, with the limit passed in from `kernel/src/main.rs`: the smaller of 2^47 and the address width. Before this check used the address width, RAM declared above it passed and the kernel stopped with a fault on the first access to it. See advisory GHSA-hj3f-38h9-hrpj in [SECURITY.md](../../SECURITY.md) for the status of the earlier memory-map finding. A DTB controlled by an attacker can still stop the boot, which is the intended fail-secure result. +- The DTB pointer is used before anything can validate it. `map_dtb` in `kernel/src/main.rs` refuses a null or misaligned pointer, an address at or above 2^47 or beyond the CPU's physical address width, and a range that overlaps the kernel image, and nothing else, because the memory map comes from the blob itself. If a boot loader passes the address of a device, the kernel maps that page as read-only normal memory and reads the first eight bytes. Reading a device register can have side effects, and because the mapping is cacheable the processor may fetch more of the page than those eight bytes. The kernel reads further only if the bytes hold the DTB magic and a valid size, and the kernel writes through the mapping exactly once: it zeroes the recorded `rng-seed` and `kaslr-seed` bytes just before it enters the root task, after the DTB has been parsed and validated (see [hardening.md](hardening.md)). `Platform::validate` later checks that the DTB lies inside declared memory, but that memory map is the DTB's own claim. A pinned build could refuse a pointer outside its pinned RAM range before the first read. That check does not exist yet. - The overlap checks know only the devices the kernel itself found. A DTB that describes some other device range as RAM is not caught, because the kernel has no independent list of devices. - A wrong DTB can still point the console at a different device that passes the checks. The 16550 family and the SBSA UART have no identification check, so nothing confirms that the hardware is one of them. An image without a console driver does not write to the device, but it does not read its identity either. Pinned mode narrows this but compares DTB-derived values. - Isolation covers confidentiality and integrity, not availability. A hostile DTB can always stop the boot. diff --git a/design/en/exceptions.md b/design/en/exceptions.md index 467d64e..4966d8f 100644 --- a/design/en/exceptions.md +++ b/design/en/exceptions.md @@ -149,7 +149,7 @@ Once a tick has been counted, the handler also drains the console receive ring ( 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. +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. A character with a break, framing or parity error uses no place in the ring, so it is counted by itself: after 256 of them in one tick the kernel masks the receive interrupt until the next tick. 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`. diff --git a/design/en/hardening.md b/design/en/hardening.md index 9b86d73..7393ae1 100644 --- a/design/en/hardening.md +++ b/design/en/hardening.md @@ -111,7 +111,7 @@ The EL0 thread pointer registers `TPIDR_EL0` and `TPIDRRO_EL0` are part of each 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. +> 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, and it masks it until the next tick after 256 characters with a line error, which use no place in the ring. 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 c4a3fa4..a4d0d92 100644 --- a/design/en/ipc.md +++ b/design/en/ipc.md @@ -260,7 +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 on a one-second tick. A task that got the CPU between two ticks keeps it through the next tick, so a woken task can wait one tick period longer than it did before. With k tasks to run before it, a task starts within k + 1 tick periods. These numbers describe this version of the scheduler and are not an interface (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. 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. +- **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 for bytes and by 256 per tick for characters with a line error), 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, plus one more tick when the running task got the CPU between two ticks. - **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/memory.md b/design/en/memory.md index 35a44fa..5623d17 100644 --- a/design/en/memory.md +++ b/design/en/memory.md @@ -64,7 +64,7 @@ The tables for the kernel alias of retyped objects do not come from the static p - A table from a reserve is **zeroed when it is handed out**, not at boot. - If a walk fails, the rollback gives back the tables from both places. -After boot, `alias_object` takes its tables from the reserves. It cannot fail for lack of tables for any address inside an `Untyped` that the kernel handed out. A range that cannot host its share, or whose share cannot be mapped, is **not handed out** as `Untyped`. The kernel prints `k0: memory + not handed out ()` and goes on booting. A gap that holds no whole granule is handed out unchanged, because no object can be made from it. +After boot, `alias_object` takes its tables from the reserves. It cannot fail for lack of tables for any address inside an `Untyped` that the kernel handed out. A range that cannot host its share, or whose share cannot be mapped, is **not handed out** as `Untyped`. The kernel prints `k0: memory + not handed out ()` and goes on booting. A gap that holds no whole granule is not handed out either, because no object can be made from it. > [!NOTE] > The reserve costs one table per 2 MiB of memory with the 4 KiB granule (about 0.2 % of RAM), and one per 32 MiB with the 16 KiB granule (about 0.05 %). diff --git a/design/en/terminal.md b/design/en/terminal.md index f1ac481..d7c3d53 100644 --- a/design/en/terminal.md +++ b/design/en/terminal.md @@ -51,7 +51,7 @@ QEMU shows the serial port on your terminal. Under `cargo run`, QEMU's own escap 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. +- **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 character with a break, framing or parity error is dropped and uses no place in the ring, so a full ring cannot bound it. The kernel counts these characters, and after 256 in one tick it masks the receive interrupt until the next tick (`DROP_MAX` in `crates/k0-conin`). Only the tick reopens it. Bytes that arrive in between wait in the device FIFO, up to a tick, and are marked as lost if it overruns. - **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. @@ -137,11 +137,11 @@ The vault side changed with this feature. There are four roles by endpoint badge ## 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 363 tests on an ARM host and 277 on other hosts (`k0-slice` adds 9). +**Host tests** (`tools/host-test.sh`): `k0-conin` has 19 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 377 tests on an ARM host and 289 on other hosts (`k0-slice` adds 9). -**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. +**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 82 rows on a Mac with HVF and 71 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`. +**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, a serial break and a flood of 2000 breaks. The flood step checks that the input path is not cut off and that the terminal answers again; the bound itself is shown by the host tests. The step runs on QEMU 8.0 or later, so not in CI: an older QEMU puts a break into its PL011 receive FIFO without checking the depth, and breaks pile up there while the kernel keeps the interrupt masked. `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). @@ -152,7 +152,7 @@ The vault side changed with this feature. There are four roles by endpoint badge - **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. +- **A timing channel that is not analysed**: an outside party can now cause interrupts while tasks run, bounded by the reader for bytes and by 256 per tick for characters with a line error. 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, plus one more tick when the running task got the CPU between two ticks (see [scheduling.md](scheduling.md)). - **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. diff --git a/design/en/uefi.md b/design/en/uefi.md index 869ffdc..59f2ad7 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 363 tests on an ARM host (`k0-abi` 15, `k0-cap` 44, `k0-boot` 85, `k0-efi` 33, `k0-conin` 15, `k0-slice` 9, `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 277 on other hosts, where the `k0-mm` tests are skipped. +- **Host test script**: `tools/host-test.sh` now runs 377 tests on an ARM host (`k0-abi` 15, `k0-cap` 52, `k0-boot` 85, `k0-efi` 33, `k0-conin` 19, `k0-slice` 9, `k0-vault` 20 with Ed25519 and 11 without, `k0-term` 24 with the vault feature and 21 without, and `k0-mm` 44 for each of the two granules) and 289 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. diff --git a/design/en/vault.md b/design/en/vault.md index 3e2b74a..6d6ec0b 100644 --- a/design/en/vault.md +++ b/design/en/vault.md @@ -156,7 +156,7 @@ $ cargo build -p k0-kernel --features console,vault-ed25519 - 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 363 tests on an ARM host and 277 on other hosts (without `k0-mm`), and `k0-slice` adds 9 of them. +With the other crates, the host suite has 377 tests on an ARM host and 289 on other hosts (without `k0-mm`), and `k0-slice` adds 9 of them. **Root task self-test** (`test_oracle` in `userspace/root-task/src/oracle.rs`, only in images built with `vault`). It checks the following: @@ -173,7 +173,7 @@ With the other crates, the host suite has 363 tests on an ARM host and 277 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 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 ...`. +**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 82 rows on a Mac with HVF and 71 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 diff --git a/design/kr/boot_KR.md b/design/kr/boot_KR.md index 4511bf9..84bd70d 100644 --- a/design/kr/boot_KR.md +++ b/design/kr/boot_KR.md @@ -22,7 +22,7 @@ UEFI 펌웨어는 이 프로토콜을 따르지 않습니다. 그래서 별도 - **예외 레벨**: CPU는 EL1 또는 EL2에 있습니다. - **CPU 수**: 정확히 하나만 진입시킵니다. 커널은 싱글 코어로 실행됩니다. - **인터럽트 컨트롤러와 타이머**: 인터럽트 컨트롤러는 GICv2 또는 GICv3이고, CPU에 ARM generic timer가 있습니다. -- **RAM**: 2^47(128 TiB) 아래에 있습니다. +- **RAM**: 2^47(128 TiB) 아래이면서 CPU의 물리 주소 폭 안에 있습니다. > [!IMPORTANT] > 부트로더는 CPU를 정확히 하나만 진입시켜야 합니다. 커널은 더 이상 어느 CPU인지 확인하지 않으므로, 나머지 CPU는 부트로더가 들어오지 못하게 해야 합니다. @@ -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: platform con=pl011@0x9000000,irq33 ...`). 고정 모드에서는 이어서 이 줄을 기대값과 비교하므로, 이 필드가 생기기 전에 만든 고정 문자열은 더 이상 맞지 않아 다시 만들어야 합니다. 그 뒤에야 콘솔을 연결합니다. 이 종류의 콘솔 드라이버가 있는 이미지는 콘솔을 매핑하고 연결하며, 이때 버퍼에 쌓인 로그가 재생됩니다. 드라이버가 없는 이미지는 아무것도 매핑하지 않고 `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 아래이면서 CPU의 물리 주소 폭 안에 있어야 하고, 커널 이미지와 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의 마스크를 해제합니다. | @@ -138,7 +138,7 @@ $ cargo build -p k0-kernel --offline --no-default-features --features granule-16 - **배치**: 그 몫을 범위의 윗부분에서 가져옵니다. 테이블은 테이블 예비분이 되고(`k0_mm::reserve_tables`), 항목은 그 범위의 주소 공간 등록부가 됩니다(`add_range`). 항목 영역은 커널 별칭 윈도우에 매핑하고 0으로 지웁니다. 예비분의 테이블은 부팅 때가 아니라 넘겨줄 때 0으로 지웁니다. - **결과**: 몫을 뺀 나머지 범위가 `Untyped` 케이퍼빌리티 하나로 넘어갑니다. 부팅 후 `alias_object`는 이 예비분에서 테이블을 가져오므로 태스크가 이를 소진할 수 없습니다. - **몫을 담지 못하는 범위**: 너무 작거나 몫을 매핑할 수 없는 범위는 `Untyped`로 넘기지 않습니다. 커널은 `k0: memory + not handed out ()`을 출력하고 계속합니다. 범위 버퍼에 들어가지 않는 범위도 같은 방식으로 건너뜁니다(`too many ranges`). -- **온전한 그래뉼이 없는 틈**: 오브젝트를 만들 수 없고 몫도 필요 없으므로 그대로 넘깁니다. +- **온전한 그래뉼이 없는 틈**: 오브젝트를 만들 수 없으므로 이것도 넘기지 않습니다. 커널은 `k0: memory + not handed out (no whole page)`를 출력합니다. 이 단계는 **부팅을 거부하지 않습니다**. 최악의 경우 메모리가 넘겨지지 않고 로그 한 줄이 그 사실을 알립니다. 오버헤드는 4 KiB 그래뉼에서 RAM의 약 0.2 %, 16 KiB 그래뉼에서 약 0.05 %입니다. 루트 태스크의 주소 공간은 루트 테이블이 부트 윈도우에 있으며 전용 등록부 항목 하나를 사용합니다. @@ -150,7 +150,7 @@ $ cargo build -p k0-kernel --offline --no-default-features --features granule-16 ## 부트 로그 -커널이 출력하는 모든 줄은 커널 메모리의 **16 KiB 버퍼**(`K0_BOOT_LOG`)에도 들어갑니다. 콘솔을 알기 전의 출력은 콘솔이 붙을 때 재생되므로, 범용 이미지에서도 부팅 순서대로의 기록이 남습니다. 콘솔이 없으면 **이 로그가 유일한 기록**이며, 콘솔 드라이버 없이 빌드한 이미지에는 콘솔이 없습니다. 16 KiB 중 사용자 태스크 출력이 사용할 수 있는 것은 6 KiB입니다. 타이머 tick 줄은 처음 4개만 기록합니다. `tools/boot-log.py <커널 ELF> <적재 주소> `이 게스트 메모리에서 이 로그를 읽습니다. 로그는 앞에서부터 채우고 넘치는 것은 버립니다. 사용자 태스크가 Console 케이퍼빌리티로 내는 출력은 정해진 몫까지만 기록하므로 커널 진단을 밀어내지 못합니다. 콘솔과 로그 어느 쪽에도 태스크가 쓴 줄이라는 표시는 없습니다([hardening_KR.md](hardening_KR.md) 참고). +커널이 출력하는 모든 줄은 커널 메모리의 **16 KiB 버퍼**(`K0_BOOT_LOG`)에도 들어갑니다. 콘솔을 알기 전의 출력은 콘솔이 붙을 때 재생되므로, 범용 이미지에서도 부팅 순서대로의 기록이 남습니다. 콘솔이 없으면 **이 로그가 유일한 기록**이며, 콘솔 드라이버 없이 빌드한 이미지에는 콘솔이 없습니다. 16 KiB 중 사용자 태스크 출력이 사용할 수 있는 것은 6 KiB이고, 태스크가 끝날 때 커널이 내는 줄(폴트, 종료, 알 수 없는 시스템 콜)이 사용할 수 있는 것은 4 KiB입니다. 두 몫 모두 커널 자신의 줄을 위해 남겨 둔 마지막 2 KiB 앞에서 멈춥니다. 더 들어가지 않는 태스크 종료 줄은 줄 단위로 로그에서 빠지고 콘솔에만 나가며, 커널은 이 사실을 `k0: task lines over the log quota, later ones go to the console only`로 한 번 알립니다. 타이머 tick 줄은 처음 4개만 기록합니다. `tools/boot-log.py <커널 ELF> <적재 주소> `이 게스트 메모리에서 이 로그를 읽습니다. 로그는 앞에서부터 채우고 넘치는 것은 버립니다. 사용자 태스크가 Console 케이퍼빌리티로 내는 출력은 정해진 몫까지만 기록하므로 커널 진단을 밀어내지 못합니다. 콘솔과 로그 어느 쪽에도 태스크가 쓴 줄이라는 표시는 없습니다([hardening_KR.md](hardening_KR.md) 참고). ## 선택적 콘솔 출력 @@ -274,6 +274,7 @@ SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU에서 - CPU는 4개입니다. - `max`에서는 16 KiB 이미지가 부팅하고, `cortex-a72`에서는 거부됩니다. - 하나의 이미지를 다른 세 물리 주소에 적재하고(헤더의 `text_offset`을 고쳐서), 16 KiB 격자에 맞지 않는 주소는 거부합니다. + - 적대적인 부팅 입력: 주소 범위의 맨 끝이나 CPU의 물리 주소 폭 밖을 가리키는 DTB 포인터(`dtb-pointer-end`, `dtb-pointer-above-pa`), 프레임을 걷는 덧셈을 넘치게 하는 리디스트리뷰터 간격과 받아들이는 가장 큰 간격(`redist-stride`, `redist-stride-wide`), CPU의 물리 주소 폭 밖에 선언된 RAM(`ram-above-pa`), 온전한 페이지가 없는 메모리 범위(`sub-page-memory`). 디바이스 트리는 QEMU의 것을 `tools/fdt-patch.py`로 한 군데만 바꿔 씁니다. - RAM이 주소 0에 있고 GICv3와 PL011이 다른 곳에 있는 `xlnx-versal-virt`를 EL2로 진입시킵니다. - 고정 이미지가 자기 플랫폼에서는 부팅하고 다른 플랫폼에서는 거부합니다. - 이미지가 물리 타이머 레지스터에 접근하지 않음을 정적 검사로 확인합니다(커널은 하이퍼바이저 게스트에서도 동작하는 EL1 가상 타이머를 사용합니다). diff --git a/design/kr/dtb_KR.md b/design/kr/dtb_KR.md index 6381254..e8b3982 100644 --- a/design/kr/dtb_KR.md +++ b/design/kr/dtb_KR.md @@ -41,7 +41,7 @@ UEFI에는 구체적인 사례가 있습니다. EDK2를 사용하는 QEMU에서 - **예약 구간**: 메모리를 제거할 뿐입니다. 적대적인 예약이 할 수 있는 일은 사용자 공간에 넘기는 메모리를 줄이는 것이 최대입니다. - **엔트로피**: 여러 입력 중 하나일 뿐입니다. `/chosen`의 바이트는 SHA-256을 통해 다른 소스와 섞이므로, 적대적인 엔트로피로 PAC 키를 약화할 수 없습니다. 시드가 없으면 키의 품질이 낮아지며, 커널은 부팅 로그에 이를 알립니다([hardening_KR.md](hardening_KR.md) 참고). 파서는 시드 값이 블롭 안의 어디에 있는지도 기록하여, 커널이 루트 태스크에 진입하기 전에 그 값을 0으로 지울 수 있게 합니다. -- **메모리 노드**: 메모리를 부여하므로 가장 엄격하게 검사합니다. 모든 메모리 리전은 사용자 공간이 매핑할 수 있는 untyped 메모리가 됩니다. RAM이라고 주장하지만 실제로는 디바이스를 덮는 리전은 EL0에 그 디바이스 직접 접근을 넘기게 됩니다. 파싱 후 커널은 모든 메모리 리전을 같은 DTB에서 찾은 디바이스 구간(뒤의 "플랫폼 기술서" 절 참고)과 비교하고, 겹치면 부팅을 중단합니다. RAM 리전이 2^47에 닿거나 디바이스 구간이 CPU의 물리 주소 폭(`k0_mm::pa_bits`)을 넘어서도 부팅을 중단합니다. 그런 구간은 매핑할 수 없기 때문입니다. CNode bootstrap도 서로 겹치는 메모리 리전을 거부하므로 어떤 프레임도 두 번 retype될 수 없습니다. +- **메모리 노드**: 메모리를 부여하므로 가장 엄격하게 검사합니다. 모든 메모리 리전은 사용자 공간이 매핑할 수 있는 untyped 메모리가 됩니다. RAM이라고 주장하지만 실제로는 디바이스를 덮는 리전은 EL0에 그 디바이스 직접 접근을 넘기게 됩니다. 파싱 후 커널은 모든 메모리 리전을 같은 DTB에서 찾은 디바이스 구간(뒤의 "플랫폼 기술서" 절 참고)과 비교하고, 겹치면 부팅을 중단합니다. RAM 리전이 2^47에 닿거나, RAM 리전이나 디바이스 구간이 CPU의 물리 주소 폭(`k0_mm::pa_bits`)을 넘어서도 부팅을 중단합니다. 그런 구간은 매핑할 수 없기 때문입니다. CNode bootstrap도 서로 겹치는 메모리 리전을 거부하므로 어떤 프레임도 두 번 retype될 수 없습니다. - **디바이스 주소**: DTB에서 오므로 가장 엄격하게 검사합니다. 잘못된 DTB는 콘솔을 다른 디바이스로 향하게 할 수 있습니다. 커널은 기술서가 메모리 맵 대조를 통과하기 전에는 디바이스 페이지를 매핑하지 않고, 하드웨어 식별 레지스터가 있는 곳에서는 이를 확인하며, 콘솔 대기에 시간 상한을 두고, 고정 빌드로 기대 플랫폼을 못 박을 수 있습니다("플랫폼 기술서" 참고). ## 두 단계 @@ -99,7 +99,7 @@ MMU가 켜진 상태에서 커널이 블롭을 읽으려면 먼저 매핑해야 - **콘솔**: `/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`)는 거부합니다. +- **인터럽트 컨트롤러**: 타이머 노드(`arm,armv8-timer` 또는 `arm,armv7-timer`, 사용 가능한 노드는 정확히 하나)의 인터럽트 부모가 가리키는 노드입니다. 기대하는 셀 수와 프레임 정렬을 갖춘 GICv3(`arm,gic-v3`) 또는 GICv2(`arm,gic-400`, `arm,cortex-a15-gic`, `arm,cortex-a7-gic`)여야 합니다. GICv3 리디스트리뷰터 구간은 최대 4개까지 받습니다. `redistributor-stride`는 64 KiB의 배수이고 128 KiB 이상이며 2^52보다 작아야 합니다. 구간을 벗어나는 걸음이나 넘치는 덧셈은 커널이 그 구간의 끝으로 다룹니다. 중복된 phandle, 비활성 노드, `interrupt-map`, CPU별 뱅크가 없는 GICv2(`cpu-offset`)는 거부합니다. - **EL1 가상 타이머의 인터럽트 번호**: 타이머 노드의 `interrupts`에서 가져오며(`interrupt-names`가 있으면 `virt` 항목, 없으면 세 번째 항목) PPI 번호에 16을 더한 값입니다. 타이머 정오표를 선언한 타이머 노드(`fsl,erratum-a008585`, `hisilicon,erratum-161010101`, `allwinner,erratum-unknown1`)는 우회 코드가 없으므로 거부합니다. > [!IMPORTANT] @@ -109,7 +109,7 @@ MMU가 켜진 상태에서 커널이 블롭을 읽으려면 먼저 매핑해야 결과는 불변인 `Platform` 값 하나입니다. 커널은 이를 정해진 형식의 한 줄 `k0: platform con=... gic=... tmr=...`로 출력합니다. 콘솔 필드에는 인터럽트가 있을 때 그 번호가 들어갑니다(예: `con=pl011@0x9000000,irq33`). 디바이스 페이지를 매핑하기 전에 `Platform::validate`가 기술서를 메모리 맵과 대조합니다. 대조 항목은 다음과 같습니다. -- RAM은 2^47 아래여야 합니다. +- RAM은 2^47 아래이면서 CPU의 물리 주소 폭 안에 있어야 합니다. - 커널 이미지와 DTB는 선언된 메모리 안에 있어야 합니다. - 그래뉼 단위로 넓힌 디바이스 구간은 메모리나 예약 구간과 겹치면 안 됩니다. - 디바이스 구간끼리도 겹치면 안 됩니다. @@ -148,8 +148,8 @@ MMU가 켜진 상태에서 커널이 블롭을 읽으려면 먼저 매핑해야 > 발견은 QEMU virt, `xlnx-versal-virt`, 호스트 테스트에서만 실행해 보았습니다. 실제 보드의 DTB로 실행한 적은 없습니다. - UEFI에서는 메모리 맵이 더 이상 DTB 자신의 주장이 아닙니다. 로더가 UEFI 메모리 맵으로 계획하고 펌웨어 자신의 메모리 노드는 버립니다. 다음 공백 중 DTB 자신의 메모리 맵을 말하는 것은 로더가 없는 경우를 설명합니다. UEFI 메모리 맵을 주는 펌웨어는 잘못될 수는 있어도 적대적이지는 않다고 가정합니다([uefi_KR.md](uefi_KR.md) 참고). -- 메모리 파서 자체는 CPU의 물리 주소 폭을 모릅니다. 그에 대한 검사는 `Platform::validate`에 있고 한계값은 `kernel/src/main.rs`에서 넘겨줍니다. 이전 메모리 맵 발견 사항의 상태는 [SECURITY_KR.md](../../SECURITY_KR.md)의 어드바이저리 GHSA-hj3f-38h9-hrpj를 참고하세요. 공격자가 제어하는 DTB는 여전히 부팅을 멈출 수 있으며, 이것이 의도한 fail-secure 결과입니다. -- DTB 포인터는 무엇으로도 검증할 수 없는 시점에 쓰입니다. `kernel/src/main.rs`의 `map_dtb`는 널이거나 정렬이 맞지 않는 포인터, 2^47 이상인 주소, 커널 이미지와 겹치는 구간만 거부합니다. 메모리 맵이 바로 그 블롭에서 나오기 때문입니다. 부트로더가 디바이스의 주소를 넘기면 커널은 그 페이지를 읽기 전용 일반 메모리로 매핑하고 처음 8바이트를 읽습니다. 디바이스 레지스터는 읽기만 해도 부작용이 있을 수 있고, 매핑이 캐시 가능하므로 프로세서가 그 8바이트보다 페이지를 더 많이 가져올 수 있습니다. 커널은 그 바이트에 DTB 매직과 올바른 크기가 있을 때만 더 읽으며, 이 매핑으로 쓰기는 정확히 한 번만 합니다. DTB를 파싱하고 검증한 뒤 루트 태스크에 진입하기 직전에, 기록해 둔 `rng-seed`와 `kaslr-seed` 바이트를 0으로 지웁니다([hardening_KR.md](hardening_KR.md) 참고). 나중에 `Platform::validate`가 DTB가 선언된 메모리 안에 있는지 검사하지만, 그 메모리 맵은 DTB 자신의 주장입니다. 고정 빌드라면 처음 읽기 전에 고정된 RAM 범위 밖의 포인터를 거부할 수 있습니다. 이 검사는 아직 없습니다. +- 메모리 파서 자체는 CPU의 물리 주소 폭을 모릅니다. 그에 대한 검사는 `Platform::validate`에 있고 한계값은 `kernel/src/main.rs`에서 넘겨줍니다. 한계값은 2^47과 주소 폭 가운데 작은 쪽입니다. 이 검사가 주소 폭을 쓰기 전에는 그 위에 선언된 RAM이 통과했고, 커널은 그 주소를 처음 건드릴 때 폴트로 멈췄습니다. 이전 메모리 맵 발견 사항의 상태는 [SECURITY_KR.md](../../SECURITY_KR.md)의 어드바이저리 GHSA-hj3f-38h9-hrpj를 참고하세요. 공격자가 제어하는 DTB는 여전히 부팅을 멈출 수 있으며, 이것이 의도한 fail-secure 결과입니다. +- DTB 포인터는 무엇으로도 검증할 수 없는 시점에 쓰입니다. `kernel/src/main.rs`의 `map_dtb`는 널이거나 정렬이 맞지 않는 포인터, 2^47 이상이거나 CPU의 물리 주소 폭을 넘는 주소, 커널 이미지와 겹치는 구간만 거부합니다. 메모리 맵이 바로 그 블롭에서 나오기 때문입니다. 부트로더가 디바이스의 주소를 넘기면 커널은 그 페이지를 읽기 전용 일반 메모리로 매핑하고 처음 8바이트를 읽습니다. 디바이스 레지스터는 읽기만 해도 부작용이 있을 수 있고, 매핑이 캐시 가능하므로 프로세서가 그 8바이트보다 페이지를 더 많이 가져올 수 있습니다. 커널은 그 바이트에 DTB 매직과 올바른 크기가 있을 때만 더 읽으며, 이 매핑으로 쓰기는 정확히 한 번만 합니다. DTB를 파싱하고 검증한 뒤 루트 태스크에 진입하기 직전에, 기록해 둔 `rng-seed`와 `kaslr-seed` 바이트를 0으로 지웁니다([hardening_KR.md](hardening_KR.md) 참고). 나중에 `Platform::validate`가 DTB가 선언된 메모리 안에 있는지 검사하지만, 그 메모리 맵은 DTB 자신의 주장입니다. 고정 빌드라면 처음 읽기 전에 고정된 RAM 범위 밖의 포인터를 거부할 수 있습니다. 이 검사는 아직 없습니다. - 겹침 검사는 커널이 스스로 찾은 디바이스만 압니다. 다른 디바이스 구간을 RAM으로 기술하는 DTB는 잡아내지 못합니다. 커널에 독립적인 디바이스 목록이 없기 때문입니다. - 잘못된 DTB가 검사를 통과하는 다른 디바이스로 콘솔을 향하게 할 수 있습니다. 16550 계열과 SBSA UART는 식별 확인이 없어 하드웨어가 그것들인지 확인하는 것이 없습니다. 콘솔 드라이버 없이 빌드한 이미지는 그 디바이스에 쓰지 않지만 정체를 읽지도 않습니다. 고정 모드는 이를 좁히지만 DTB에서 나온 값을 비교합니다. - 격리는 기밀성과 무결성을 다루며 가용성은 다루지 않습니다. 적대적인 DTB는 언제나 부팅을 멈출 수 있습니다. diff --git a/design/kr/exceptions_KR.md b/design/kr/exceptions_KR.md index 2560d44..f77fead 100644 --- a/design/kr/exceptions_KR.md +++ b/design/kr/exceptions_KR.md @@ -149,7 +149,7 @@ EL0에서 받은 IRQ는 시스템 콜과 같은 방식으로 저장됩니다. `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)`와 함께 꺼집니다. 이 차단은 호스트 테스트로만 확인했습니다. 수신 인터럽트는 태스크가 읽기 권리로 콘솔 입력을 처음 읽을 때까지 꺼져 있습니다. +인터럽트는 읽는 쪽이 한도를 정합니다. 링이 차면 커널이 UART의 수신 인터럽트를 스스로 가리고, 읽는 쪽이 링의 절반을 가져가면 다시 엽니다. 브레이크, 프레이밍 오류, 패리티 오류가 난 문자는 링의 자리를 쓰지 않으므로 따로 셉니다. 한 틱 동안 256개가 들어오면 커널은 다음 틱까지 수신 인터럽트를 가립니다. 같은 비우기가 틱마다 한 번 더 실행되므로, 인터럽트가 오지 않아도 입력은 (최대 한 틱 늦게) 도착합니다. 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`로 즉시 깨어납니다. diff --git a/design/kr/hardening_KR.md b/design/kr/hardening_KR.md index 47727e5..2f373ad 100644 --- a/design/kr/hardening_KR.md +++ b/design/kr/hardening_KR.md @@ -111,7 +111,7 @@ EL0 스레드 포인터 레지스터 `TPIDR_EL0`와 `TPIDRRO_EL0`는 각 태스 이 필터는 줄을 누가 썼는지 표시하지 않습니다. 커널 출력과 태스크 출력이 부트 로그를 함께 사용하고 (콘솔 드라이버를 포함해 빌드한 이미지에서는) 콘솔도 함께 사용합니다. 터미널은 추가로 자신의 현재 줄 안에서 지울 수 있습니다. 읽기 권리(R)가 있는 `Console` 케이퍼빌리티(터미널의 것)만 백스페이스(0x08)도 출력할 수 있습니다. > [!NOTE] -> `console-input` 이미지에서는 외부가 태스크 실행 중에 인터럽트를 일으킬 수 있습니다. 링이 차면 커널이 수신 인터럽트를 스스로 가리므로 빈도는 읽는 쪽이 한도를 정합니다. 그래도 읽는 쪽은 틱보다 세밀한 도착 시각을 알게 되고 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널은 분석하지 않았습니다. 커널의 수신 코드는 EL1에서 실행되며 바이트를 해석하지 않지만 외부가 구동하는 커널 코드이고, 사용자 공간 드라이버에는 K0에 없는 장치·인터럽트 위임이 필요합니다. +> `console-input` 이미지에서는 외부가 태스크 실행 중에 인터럽트를 일으킬 수 있습니다. 링이 차면 커널이 수신 인터럽트를 스스로 가리므로 빈도는 읽는 쪽이 한도를 정합니다. 선로 오류가 난 문자는 링의 자리를 쓰지 않으므로, 한 틱 동안 256개가 들어오면 다음 틱까지 가립니다. 그래도 읽는 쪽은 틱보다 세밀한 도착 시각을 알게 되고 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널은 분석하지 않았습니다. 커널의 수신 코드는 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 d20e3df..320fac5 100644 --- a/design/kr/ipc_KR.md +++ b/design/kr/ipc_KR.md @@ -260,7 +260,7 @@ IPC와 해체는 부팅으로 테스트합니다. 루트 태스크는 서버 태 - **타임아웃은 태스크가 준비되는 시점이지 실행되는 시점이 아님**: 우선순위도 CPU 예산도 없으며, 스케줄러는 1초 틱 기준의 라운드 로빈입니다. 두 틱 사이에 CPU를 받은 태스크는 다음 틱까지 CPU를 유지하므로, 깨어난 태스크는 이전보다 한 틱 주기 더 기다릴 수 있습니다. 앞에 실행할 태스크가 k개이면 k + 1 틱 주기 안에 시작합니다. 이 수치는 이 버전의 스케줄러를 설명할 뿐 인터페이스가 아닙니다([scheduling_KR.md](scheduling_KR.md) 참고). - **긴 시스템 콜**: 커널은 선점되지 않으므로, 객체가 많은 untyped에 대한 `CAP_REVOKE` 같은 긴 호출은 다른 모든 태스크와 모든 타임아웃을 지연시킵니다. - **치명적 정지**: `k0_arch::fatal`이나 커널 패닉은 여전히 머신을 정지시킵니다. -- **EL0의 시간 소스**: 틱에 맞춰 깨어나는 성질을 타이밍 공격에 쓸 수 있는지는 분석하지 않았습니다. 콘솔 입력이 있는 이미지에서는 외부의 누군가가 태스크가 실행되는 동안 인터럽트를 일으킬 수 있고(읽는 쪽이 속도를 정함), 읽는 태스크는 틱보다 세밀한 도착 시각을 압니다. 다른 태스크도 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널도 분석하지 않았습니다. +- **EL0의 시간 소스**: 틱에 맞춰 깨어나는 성질을 타이밍 공격에 쓸 수 있는지는 분석하지 않았습니다. 콘솔 입력이 있는 이미지에서는 외부의 누군가가 태스크가 실행되는 동안 인터럽트를 일으킬 수 있고(바이트는 읽는 쪽이, 선로 오류가 난 문자는 틱당 256개가 속도를 정함), 읽는 태스크는 틱보다 세밀한 도착 시각을 압니다. 다른 태스크도 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널도 분석하지 않았습니다. - **입력 지연**: `CONSOLE_READ` 대기자는 실행 중인 태스크 뒤에서 깨어나므로 바이트는 준비된 태스크마다 최대 한 틱을 기다릴 수 있고, 실행 중인 태스크가 두 틱 사이에 CPU를 받았다면 한 틱을 더 기다립니다. - **큐에 있던 송신자**: 회수 뒤에도 메시지를 한 번 전달합니다. 엔드포인트에서 이미 기다리는 송신자는 자신을 큐에 세운 송신의 배지를 유지합니다. 기다리는 동안 그 케이퍼빌리티가 회수되어도 메시지는 다음 수신자에게 한 번 전달됩니다. - **메시지당 워드 네 개**: 더 큰 데이터는 공유 메모리가 필요합니다. 태스크가 서로 다른 주소 공간에서 실행될 수 있으므로, 공유 메모리는 그 태스크의 `AddrSpace` 케이퍼빌리티를 가진 쪽이 해당 주소 공간에 매핑해 주어야 합니다. diff --git a/design/kr/memory_KR.md b/design/kr/memory_KR.md index 4d8953f..78bdae9 100644 --- a/design/kr/memory_KR.md +++ b/design/kr/memory_KR.md @@ -64,7 +64,7 @@ retype된 오브젝트의 커널 별칭에 드는 테이블은 정적 풀에서 - 예약 구간의 테이블은 부팅 때가 아니라 **내줄 때 소거**합니다. - 워크가 실패하면 롤백이 두 곳의 테이블을 모두 돌려줍니다. -부팅 뒤 `alias_object`는 예약 구간에서 테이블을 가져옵니다. 커널이 `Untyped`으로 넘긴 구간 안의 어떤 주소에 대해서도 테이블이 모자라 실패하는 일은 없습니다. 자기 몫을 둘 수 없거나 몫을 매핑할 수 없는 구간은 `Untyped`으로 **넘기지 않습니다**. 커널은 `k0: memory + not handed out ()`를 출력하고 부팅을 계속합니다. 온전한 그래뉼이 하나도 없는 틈은 오브젝트를 만들 수 없으므로 그대로 넘깁니다. +부팅 뒤 `alias_object`는 예약 구간에서 테이블을 가져옵니다. 커널이 `Untyped`으로 넘긴 구간 안의 어떤 주소에 대해서도 테이블이 모자라 실패하는 일은 없습니다. 자기 몫을 둘 수 없거나 몫을 매핑할 수 없는 구간은 `Untyped`으로 **넘기지 않습니다**. 커널은 `k0: memory + not handed out ()`를 출력하고 부팅을 계속합니다. 온전한 그래뉼이 하나도 없는 틈도 오브젝트를 만들 수 없으므로 넘기지 않습니다. > [!NOTE] > 예약 구간의 비용은 4 KiB 그래뉼에서 메모리 2 MiB당 테이블 하나(RAM의 약 0.2 %), 16 KiB 그래뉼에서 32 MiB당 하나(약 0.05 %)입니다. diff --git a/design/kr/terminal_KR.md b/design/kr/terminal_KR.md index f8c6fa6..a8bd829 100644 --- a/design/kr/terminal_KR.md +++ b/design/kr/terminal_KR.md @@ -51,7 +51,7 @@ QEMU는 시리얼 포트를 사용자의 터미널에 연결합니다. `cargo ru 커널의 UART 드라이버는 받은 바이트를 모두 256바이트 링에 넣습니다. 수신 로직은 별도 크레이트 `crates/k0-conin`이며, 작은 레지스터 트레이트에 맞춰 작성해 호스트 테스트가 가짜 UART로 구동할 수 있습니다. - **수신 인터럽트는 꺼진 채로 둡니다**: 태스크가 읽기 권한으로 콘솔 입력을 처음 읽을 때까지입니다. 그 첫 읽기는 장치가 쥐고 있던 바이트를 버립니다. 또한 `k0: tick lines off (console input in use)` 한 줄 뒤로 주기적인 `k0: tick N` 줄을 멈춥니다. 틱, 선점, 타임아웃은 계속 동작합니다. -- **커널 작업량의 한계**: 링이 가득 차면 커널이 UART의 수신 인터럽트를 스스로 마스크합니다. 읽는 쪽이 링의 절반을 가져간 뒤에 다시 엽니다. 그래서 폭주 상황에서 인터럽트 빈도는 보내는 쪽이 아니라 읽는 쪽이 정한 한계 안에 있습니다. +- **커널 작업량의 한계**: 링이 가득 차면 커널이 UART의 수신 인터럽트를 스스로 마스크합니다. 읽는 쪽이 링의 절반을 가져간 뒤에 다시 엽니다. 그래서 폭주 상황에서 인터럽트 빈도는 보내는 쪽이 아니라 읽는 쪽이 정한 한계 안에 있습니다. 브레이크, 프레이밍 오류, 패리티 오류가 난 문자는 버려지고 링의 자리를 쓰지 않으므로 링이 차는 것으로는 묶이지 않습니다. 커널은 이런 문자를 세어, 한 틱 동안 256개가 되면 다음 틱까지 수신 인터럽트를 마스크합니다(`crates/k0-conin`의 `DROP_MAX`). 다시 여는 것은 틱뿐입니다. 그 사이에 온 바이트는 장치의 FIFO에서 최대 한 틱을 기다리고, FIFO가 넘치면 유실로 표시됩니다. - **틱마다 비우기**: 같은 비우기를 틱마다 한 번 더 실행하므로, 인터럽트가 오지 않아도 입력은 (최대 한 틱 늦게) 도착합니다. - **유실 표시**: FIFO 오버런, 브레이크, 프레이밍 오류, 패리티 오류는 구멍 뒤의 바이트에 표시됩니다. `CONSOLE_READ`가 이 표시를 읽는 쪽에 돌려줍니다. - **인터럽트 번호**는 디바이스 트리(콘솔 노드의 `interrupts` 속성: 발견한 GIC의 SPI 하나, 레벨, active high)에서 가져오고, UEFI 로더를 거치면 ACPI SPCR 테이블에서 가져옵니다. 플랫폼 줄에 출력되며(예: `k0: platform con=pl011@0x9000000,irq33 ...`) 그래서 `K0_PIN`으로 고정됩니다. 이 변경 이전에 만든 핀 문자열은 더 이상 일치하지 않으므로 다시 만들어야 합니다. 사용할 수 있는 인터럽트가 없는 콘솔 노드는 부팅 거부 사유가 아닙니다. 입력만 꺼집니다. @@ -137,11 +137,11 @@ QEMU는 시리얼 포트를 사용자의 터미널에 연결합니다. `cargo ru ## 테스트 방법 -**호스트 테스트**(`tools/host-test.sh`): `k0-conin`은 가짜 UART로 15개, `k0-term`은 vault feature가 있으면 24개, 없으면 21개, `k0-vault`는 Ed25519가 있으면 20개, 없으면 11개입니다. 전체는 ARM 호스트에서 363개, 다른 호스트에서 277개입니다(`k0-slice`가 9개를 더합니다). +**호스트 테스트**(`tools/host-test.sh`): `k0-conin`은 가짜 UART로 19개, `k0-term`은 vault feature가 있으면 24개, 없으면 21개, `k0-vault`는 Ed25519가 있으면 20개, 없으면 11개입니다. 전체는 ARM 호스트에서 377개, 다른 호스트에서 289개입니다(`k0-slice`가 9개를 더합니다). -**부팅 매트릭스**: 새 행은 `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행입니다. +**부팅 매트릭스**: 새 행은 `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에서 82행, CI에서 71행입니다. -**스크립트 세션**: `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`를 읽습니다. +**스크립트 세션**: `tools/term-test.py `는 QEMU의 시리얼 포트를 파이프에 연결해 이미지를 부팅하고 세션을 실행합니다. 모든 명령과 모든 오류, 지우기와 취소, CR LF, ESC 시퀀스, 너무 긴 줄, 키 생성, 공개 키 형식, zeroize, 줄 끝이 없는 200 kB, 연속 2000줄, 시리얼 브레이크, 브레이크 2000번의 폭주를 다룹니다. 폭주 단계는 입력 경로가 끊기지 않고 터미널이 다시 답하는지만 확인하며, 상한 자체는 호스트 테스트가 보입니다. 이 단계는 QEMU 8.0부터만 실행하므로 CI에서는 실행되지 않습니다. 그 전의 QEMU는 브레이크를 PL011 수신 FIFO에 넣을 때 깊이를 확인하지 않는데, 커널이 인터럽트를 마스크해 둔 동안 브레이크가 거기에 쌓이기 때문입니다. `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줄). @@ -152,7 +152,7 @@ QEMU는 시리얼 포트를 사용자의 터미널에 연결합니다. `cargo ru - **인증 없음**: 시리얼 선은 그 선에 닿을 수 있는 사람만큼만 신뢰할 수 있습니다. 운영자는 키를 지울 수 있지만(설계상의 서비스 거부) 서명을 얻지 못하고 정책을 바꿀 수 없습니다. - **외부가 구동하는 커널 코드**: 수신 코드는 EL1에서 실행됩니다. -- **분석하지 않은 타이밍 채널**: 외부 당사자가 이제 태스크가 실행되는 동안 인터럽트를 일으킬 수 있습니다(읽는 쪽이 정한 한계 안에서). 읽는 쪽은 틱보다 세밀한 도착 시각을 알게 되고, 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다. +- **분석하지 않은 타이밍 채널**: 외부 당사자가 이제 태스크가 실행되는 동안 인터럽트를 일으킬 수 있습니다(바이트는 읽는 쪽이 정한 한계 안에서, 선로 오류가 난 문자는 틱당 256개 안에서). 읽는 쪽은 틱보다 세밀한 도착 시각을 알게 되고, 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다. - **지연**: 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 준비된 태스크마다 최대 한 틱씩 지연되며, 실행 중인 태스크가 두 틱 사이에 CPU를 받았다면 한 틱이 더해집니다([scheduling_KR.md](scheduling_KR.md) 참고). - **16550 콘솔에는 입력 없음**: 16550 콘솔에는 출력만 있고 입력은 없습니다. - **폭주 중 측정 없음**: 어떤 테스트도 머신에서 폭주 중 커널 시간을 측정하지 않습니다. 한계는 게이트로 논증하고 호스트 테스트로 보였습니다. diff --git a/design/kr/uefi_KR.md b/design/kr/uefi_KR.md index 3c4b128..19d875c 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 호스트에서 363개(`k0-abi` 15, `k0-cap` 44, `k0-boot` 85, `k0-efi` 33, `k0-conin` 15, `k0-slice` 9, Ed25519 포함 20개와 제외 11개의 `k0-vault`, 볼트 feature 포함 24개와 제외 21개의 `k0-term`, 두 그래뉼 각각에 `k0-mm` 43)를, `k0-mm` 테스트를 건너뛰는 그 밖의 호스트에서 277개를 실행합니다. +- **호스트 테스트 스크립트**: `tools/host-test.sh`는 이제 ARM 호스트에서 377개(`k0-abi` 15, `k0-cap` 52, `k0-boot` 85, `k0-efi` 33, `k0-conin` 19, `k0-slice` 9, Ed25519 포함 20개와 제외 11개의 `k0-vault`, 볼트 feature 포함 24개와 제외 21개의 `k0-term`, 두 그래뉼 각각에 `k0-mm` 44)를, `k0-mm` 테스트를 건너뛰는 그 밖의 호스트에서 289개를 실행합니다. - **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)에 있습니다. diff --git a/design/kr/vault_KR.md b/design/kr/vault_KR.md index 15431ce..8f3f1dc 100644 --- a/design/kr/vault_KR.md +++ b/design/kr/vault_KR.md @@ -156,7 +156,7 @@ $ cargo build -p k0-kernel --features console,vault-ed25519 - 항상: `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 호스트에서 363개, 그 외 호스트에서 277개입니다(`k0-mm` 제외). 이 가운데 9개는 `k0-slice`의 테스트입니다. +다른 크레이트와 합치면 호스트 테스트는 ARM 호스트에서 377개, 그 외 호스트에서 289개입니다(`k0-mm` 제외). 이 가운데 9개는 `k0-slice`의 테스트입니다. **루트 태스크 자가 테스트**(`userspace/root-task/src/oracle.rs`의 `test_oracle`, `vault`로 빌드한 이미지에만 있음). 다음을 검사합니다. @@ -173,7 +173,7 @@ $ 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에서 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 ...`도 출력합니다. +**부팅 매트릭스 행**: `vault`, `vault-max`(RNDR), `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`, 그리고 정적 행 `vault-symbols`(기본 이미지에는 볼트나 암호 코드가 없고, 볼트 이미지에는 그 코드에서 온 쓰기 가능한 정적 변수가 없음)입니다. 매트릭스는 HVF가 있는 Mac에서 82행, CI에서 71행입니다. 터미널용 행은 `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 ...`도 출력합니다. ## 알려진 공백 diff --git a/kernel/src/main.rs b/kernel/src/main.rs index c378640..63b455a 100644 --- a/kernel/src/main.rs +++ b/kernel/src/main.rs @@ -583,8 +583,8 @@ fn scrub_boot_stack() { /// 수 없는 구간(너무 작거나 매핑에 실패한 구간)은 untyped로 넘기지 않고 한 /// 줄을 남깁니다. 부팅을 거부하지는 않습니다(UEFI 로더의 사전 검사가 이 /// 단계를 알지 못하므로 로더가 예측할 수 없는 거부를 만들지 않음). 온전한 -/// 그래뉼이 하나도 없는 틈은 오브젝트를 만들 수 없어 커널 몫도 필요 없으므로 -/// 그대로 넘깁니다. +/// 그래뉼이 하나도 없는 틈도 오브젝트를 만들 수 없으므로 넘기지 않고 한 줄을 +/// 남깁니다. /// /// # Arguments /// `memory` - DTB가 보고한 물리 메모리 구간들 @@ -608,7 +608,15 @@ fn reserve_kernel_share( let mut count = 0; for m in memory { let _ = k0_cap::for_each_gap(*m, reserved, |gap| -> Result<(), ()> { - if count < out.len() { + if gap.whole(g).is_none() { + // 온전한 그래뉼이 없는 틈으로는 오브젝트를 만들 수 없음. 넘기면 + // 쓸 수 없는 케이퍼빌리티가 되고 버퍼의 자리만 차지함 + let _ = writeln!( + con, + "k0: memory {:#x} + {:#x} not handed out (no whole page)", + gap.base, gap.size + ); + } else if count < out.len() { out[count] = gap; count += 1; } else { @@ -636,15 +644,11 @@ fn reserve_kernel_share( done[i] = true; let (base, size) = (out[i].base, out[i].size); - // 주소 범위의 맨 끝에 걸친 틈은 올림이 넘치므로 온전한 그래뉼이 없는 - // 틈과 같이 다룸(끝 주소는 check_regions가 넘치지 않음을 확인함) - let Some(lo) = base.checked_next_multiple_of(g) else { + // 온전한 그래뉼이 없는 틈은 위에서 걸렀음. 그래도 남아 있으면 넘기지 않음 + let Some((lo, hi)) = out[i].whole(g) else { + out[i].size = 0; continue; }; - let hi = (base + size) / g * g; - if hi <= lo { - continue; - } let pages = (hi - lo) / g; let table_count = k0_mm::alias_tables_for(&(lo..hi)); let entry_pages = (pages * 8).div_ceil(g); @@ -833,9 +837,10 @@ fn enable_mmu(con: &mut EarlyCon) -> u64 { /// DTB를 TTBR1 별칭에 읽기 전용으로 매핑하는 함수입니다. /// /// 크기를 알려면 헤더를 읽어야 하므로 첫 그래뉼을 먼저 열고, 헤더가 말하는 -/// 크기(상한 2MiB)만큼 다시 엽니다. 포인터가 RAM이 아닌 곳을 가리키면 여기서의 -/// 읽기가 폴트로 정지합니다. 그 주소가 선언된 메모리 안인지는 메모리 맵을 -/// 읽은 뒤에 확인합니다. +/// 크기(상한 2MiB)만큼 다시 엽니다. 주소 범위의 끝이나 이 코어의 물리 주소 폭을 +/// 넘는 포인터는 읽기 전에 거부합니다. 그 안에서 RAM이 아닌 곳을 가리키면 +/// 여기서의 읽기가 폴트로 정지할 수 있습니다. 그 주소가 선언된 메모리 안인지는 +/// 메모리 맵을 읽은 뒤에 확인합니다. fn map_dtb(con: &mut EarlyCon, dtb_phys: usize) { let fail = |con: &mut EarlyCon, what: &str| -> ! { let _ = writeln!(con, "k0: dtb rejected: {what}"); @@ -845,7 +850,13 @@ fn map_dtb(con: &mut EarlyCon, dtb_phys: usize) { fail(con, "bad pointer"); } let start = dtb_phys as u64; - if k0_mm::map_dtb(start..start + 8).is_err() { + // 포인터는 부트로더가 준 값이라 주소 범위의 맨 끝일 수도, 이 코어의 물리 주소 + // 폭 밖일 수도 있음. 폭 밖의 주소는 매핑은 되지만 읽는 순간 폴트가 남 + let limit = 1u64 << k0_mm::pa_bits(); + let Some(head) = start.checked_add(8).filter(|end| *end <= limit) else { + fail(con, "bad pointer"); + }; + if k0_mm::map_dtb(start..head).is_err() { fail(con, "header not mappable"); } let span = match k0_boot::dtb_span(dtb_phys + k0_mm::KERNEL_VA_OFFSET as usize) { @@ -855,7 +866,8 @@ fn map_dtb(con: &mut EarlyCon, dtb_phys: usize) { park() } }; - if k0_mm::map_dtb(start..start + (span.end - span.start) as u64).is_err() { + let whole = start.checked_add((span.end - span.start) as u64).filter(|end| *end <= limit); + if whole.is_none_or(|end| k0_mm::map_dtb(start..end).is_err()) { fail(con, "not mappable"); } } @@ -1055,14 +1067,17 @@ fn bring_up_platform( // 거부로 끝나는 부팅에서도 어떤 이미지인지 로그에 남도록 맨 먼저 출력함 let _ = writeln!(con, "{}", k0_arch::earlycon::DRIVERS_LINE); let off = k0_mm::KERNEL_VA_OFFSET as usize; + let device_limit = 1u64 << k0_mm::pa_bits(); let layout = k0_boot::Layout { memory: bootinfo.memory(), reserved: bootinfo.reserved(), image: image.clone(), dtb: bootinfo.dtb.start as u64..bootinfo.dtb.end as u64, granule: k0_mm::GRANULE as u64, - ram_limit: k0_mm::PA_CEILING, - device_limit: 1u64 << k0_mm::pa_bits(), + // RAM은 선형 별칭의 한계와 이 코어의 물리 주소 폭을 모두 넘지 않아야 함. + // 폭을 넘는 RAM을 받아들이면 그 주소를 처음 건드릴 때 커널이 폴트로 멈춤 + ram_limit: k0_mm::PA_CEILING.min(device_limit), + device_limit, }; let found = match k0_boot::discover(dtb_phys, off) { diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index f28bdb6..ee620d3 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -35,7 +35,7 @@ use core::fmt::Write; use core::sync::atomic::{AtomicBool, Ordering}; use k0_abi::err; -use k0_arch::earlycon::EarlyCon; +use k0_arch::earlycon::{EarlyCon, TaskLine}; use k0_arch::usermode::Context; use k0_cap::{Cap, CapError, CNodeRef, Entry, Mapping, Slot}; use k0_task::{TaskState, Tcb}; @@ -64,7 +64,6 @@ const _: () = { extern "C" fn k0_syscall(ctx: &mut Context) { use k0_abi::syscall as nr; - let mut con = EarlyCon; let a = [ctx.x[0], ctx.x[1], ctx.x[2], ctx.x[3], ctx.x[4], ctx.x[5]]; // Some(v)는 x0에 쓸 반환값, None은 핸들러가 컨텍스트 기록을 이미 끝낸 경우 let ret: Option = match ctx.x[8] { @@ -76,7 +75,8 @@ extern "C" fn k0_syscall(ctx: &mut Context) { None } nr::EXIT => { - let _ = writeln!(con, "k0: task exited (code {})", a[0]); + // 태스크가 끝날 때마다 나오는 줄은 로그의 정해진 몫까지만 남김 + let _ = writeln!(TaskLine::begin(), "k0: task exited (code {})", a[0]); kill_current(); None } @@ -115,7 +115,7 @@ extern "C" fn k0_syscall(ctx: &mut Context) { ipc_or_idle(ctx, switched) } other => { - let _ = writeln!(con, "k0: unknown syscall {other}, killing task"); + let _ = writeln!(TaskLine::begin(), "k0: unknown syscall {other}, killing task"); kill_current(); None } @@ -135,10 +135,9 @@ extern "C" fn k0_syscall(ctx: &mut Context) { /// `far` - FAR_EL1(어보트 계열에서만 의미 있음) #[unsafe(no_mangle)] extern "C" fn k0_fault(ctx: &mut Context, esr: u64, far: u64) { - let mut con = EarlyCon; let ec = k0_arch::vectors::ec_name((esr >> 26) & 0x3F); let _ = writeln!( - con, + TaskLine::begin(), "k0: task fault {ec} (esr {esr:#x} elr {:#x} far {far:#x}), killing task", ctx.elr ); diff --git a/tools/boot-matrix.sh b/tools/boot-matrix.sh index 2dab174..e1f4b07 100755 --- a/tools/boot-matrix.sh +++ b/tools/boot-matrix.sh @@ -420,6 +420,41 @@ pass load-default "$img4" K0_IMAGE_TEXT_OFFSET=0x0 K0_BOOT_REUSE=skip # 그래뉼 경계에 맞지 않는 적재 주소는 거부 (16K 이미지를 4K만 맞는 주소에) refuse load-misaligned "$img16" 0x40081000 "k0: mmu enable failed" K0_IMAGE_TEXT_OFFSET=0x81000 K0_QEMU_CPU=max +# 적대적인 부팅 입력: 부트로더나 디바이스 트리가 엉뚱한 값을 주면 커널은 계산이 +# 넘치거나 폴트로 멈추는 대신 사유를 남기고 거부해야 함. 디바이스 트리는 QEMU +# virt의 것을 떠서 한 군데만 바꿈(tools/fdt-patch.py). memory 노드를 더한 트리는 +# -dtb로 주면 QEMU가 그 노드를 자기 것으로 되돌리므로, 메모리에 따로 싣고 커널이 +# 받는 포인터를 그리로 돌림 +refuse dtb-pointer-end "$img4" 0x40080000 "k0: dtb rejected: bad pointer" K0_IMAGE_DTB_POINTER=end +# 2^47 아래이지만 이 코어의 물리 주소 폭(cortex-a72는 44비트) 밖인 포인터 +refuse dtb-pointer-above-pa "$img4" 0x40080000 "k0: dtb rejected: bad pointer" K0_IMAGE_DTB_POINTER=0x200000000000 +if want redist-stride $only || want redist-stride-wide $only || want ram-above-pa $only || want sub-page-memory $only; then + vdt="$root/target/matrix-virt.dtb" + hdt="$root/target/matrix-hostile" + if qemu-system-aarch64 -machine "virt,gic-version=3,dumpdtb=$vdt" -cpu cortex-a72 -m 512M -smp 1 -nographic > target/matrix-hostile.dump 2>&1 < /dev/null \ + && tools/fdt-patch.py "$vdt" "$hdt-stride.dtb" prop:intc@8000000:redistributor-stride:ffffffff,ffff0000 >> target/matrix-hostile.dump 2>&1 \ + && tools/fdt-patch.py "$vdt" "$hdt-wide.dtb" prop:intc@8000000:redistributor-stride:000fffff,ffff0000 >> target/matrix-hostile.dump 2>&1 \ + && tools/fdt-patch.py "$vdt" "$hdt-ram.dtb" memory:100000000000:200000 >> target/matrix-hostile.dump 2>&1 \ + && tools/fdt-patch.py "$vdt" "$hdt-sub.dtb" memory:8000000000:800 >> target/matrix-hostile.dump 2>&1 + then + at="-device loader,addr=0x4a000000,force-raw=on,file=$hdt" + # 프레임을 걷는 덧셈을 넘치게 하는 간격. 코어가 둘이면 첫 프레임이 마지막이 + # 아니라서 한 걸음을 더 걷게 됨 + refuse redist-stride "$img4" 0x40080000 "k0: platform rejected: BadRedistributor" K0_QEMU_SMP=2 K0_QEMU_EXTRA="-dtb $hdt-stride.dtb" + # 받아들이는 가장 큰 간격: 구간을 벗어나는 걸음은 구간의 끝으로 다루고 부팅함 + pass redist-stride-wide "$img4" K0_QEMU_SMP=2 K0_QEMU_EXTRA="-dtb $hdt-wide.dtb" K0_BOOT_REQUIRE="stride=0xfffffffff0000 " + # 이 코어의 물리 주소 폭(cortex-a72는 44비트) 밖에 선언된 RAM + refuse ram-above-pa "$img4" 0x40080000 "k0: platform rejected: MemoryAboveLimit" K0_IMAGE_DTB_POINTER=0x4a000000 K0_QEMU_EXTRA="$at-ram.dtb" + # 온전한 페이지가 하나도 없는 메모리 구간은 untyped로 넘기지 않음 + pass sub-page-memory "$img4" K0_IMAGE_DTB_POINTER=0x4a000000 K0_QEMU_EXTRA="$at-sub.dtb" K0_BOOT_REQUIRE="k0: memory 0x8000000000 + 0x800 not handed out (no whole page)|, 3 untyped," + else + ran=$((ran + 1)) + echo "matrix: hostile boot input FAIL (could not prepare the device trees)" + show target/matrix-hostile.dump + failed="$failed hostile-dtb" + fi +fi + # 다른 보드 모양: RAM이 0에서 시작, GICv3와 PL011이 다른 주소, EL2 진입 pass versal "$img4" K0_QEMU_MACHINE=xlnx-versal-virt K0_QEMU_CPU= K0_QEMU_SMP= K0_QEMU_MEM=2G diff --git a/tools/fdt-patch.py b/tools/fdt-patch.py new file mode 100755 index 0000000..b78f92a --- /dev/null +++ b/tools/fdt-patch.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +"""디바이스 트리 블롭을 고쳐 적대적인 부팅 입력을 만듭니다. + +사용법: tools/fdt-patch.py <입력.dtb> <출력.dtb> <편집> [<편집> ...] + +편집 + prop:<노드 이름>:<속성 이름>:<셀>[,<셀>...] + 그 이름의 노드에 32비트 셀들로 된 속성을 더함(셀은 16진수) + memory:<시작>:<크기> + 루트 아래에 memory 노드를 하나 더함(주소와 크기는 셀 둘씩, 16진수) + +부팅 매트릭스가 QEMU의 디바이스 트리를 떠서 한 군데만 바꾼 것으로 부팅할 때 +씁니다. dtc 없이 돌도록 구조 블록을 직접 고칩니다. QEMU는 -dtb로 받은 파일의 +크기를 두 배로 늘려 싣기 때문에, 커널의 DTB 크기 상한을 넘지 않게 쓰인 데까지만 +남깁니다. 표준 라이브러리만 씁니다. +""" +import struct +import sys + +MAGIC = 0xD00DFEED +BEGIN_NODE, END_NODE, PROP, NOP, END = 1, 2, 3, 4, 9 + + +def pad(data): + return data + b"\0" * (-len(data) % 4) + + +class Tree: + def __init__(self, blob): + if len(blob) < 40 or struct.unpack(">I", blob[:4])[0] != MAGIC: + sys.exit("fdt-patch: not a device tree blob") + head = struct.unpack(">10I", blob[:40]) + _, total, off_struct, off_strings, off_rsv, self.version, self.last, self.cpu, size_strings, size_struct = head + ends = (off_struct + size_struct, off_strings + size_strings) + if total > len(blob) or max(ends) > total or not 40 <= off_rsv <= off_struct: + sys.exit("fdt-patch: the header points outside the blob") + self.rsv = blob[off_rsv:off_struct] + self.struct = bytearray(blob[off_struct:off_struct + size_struct]) + self.strings = bytearray(blob[off_strings:off_strings + size_strings]) + + def name_offset(self, name): + key = name.encode() + b"\0" + at = 0 + while True: + at = self.strings.find(key, at) + if at < 0: + break + if at == 0 or self.strings[at - 1] == 0: + return at + at += 1 + self.strings += key + return len(self.strings) - len(key) + + def prop(self, name, value): + return struct.pack(">3I", PROP, len(value), self.name_offset(name)) + pad(value) + + def walk(self): + """(토큰의 위치, 토큰, 깊이, 노드 이름, 토큰 다음 위치)를 차례로 줍니다.""" + at, depth = 0, 0 + while at < len(self.struct): + token, = struct.unpack_from(">I", self.struct, at) + if token == BEGIN_NODE: + end = self.struct.index(b"\0", at + 4) + name = self.struct[at + 4:end].decode() + after = at + 4 + len(pad(bytes(self.struct[at + 4:end + 1]))) + yield at, token, depth, name, after + depth += 1 + elif token == END_NODE: + depth -= 1 + yield at, token, depth, None, at + 4 + after = at + 4 + elif token == PROP: + size, = struct.unpack_from(">I", self.struct, at + 4) + after = at + 12 + len(pad(b"\0" * size)) + yield at, token, depth, None, after + elif token == NOP: + after = at + 4 + elif token == END: + return + else: + sys.exit("fdt-patch: unknown token %#x at %#x" % (token, at)) + at = after + + def add_prop(self, node, name, value): + hits = [after for _, token, _, n, after in self.walk() if token == BEGIN_NODE and n == node] + if len(hits) != 1: + sys.exit("fdt-patch: expected exactly one node named %r, found %d" % (node, len(hits))) + at = hits[0] + # 같은 이름의 속성이 이미 있으면 둘이 되므로 거부함. 노드 자신의 속성은 자식 + # 노드보다 앞에 오므로 속성이 아닌 것이 나오면 멈춤 + key = name.encode() + b"\0" + for pos, token, _, _, _ in self.walk(): + if pos < at: + continue + if token != PROP: + break + offset, = struct.unpack_from(">I", self.struct, pos + 8) + if self.strings[offset:offset + len(key)] == key: + sys.exit("fdt-patch: node %r already has a property %r" % (node, name)) + self.struct[at:at] = self.prop(name, value) + + def add_memory(self, base, size): + # 루트의 속성 뒤, 첫 자식 노드 앞에 넣음(속성은 자식보다 앞에 와야 함) + # (자식의 시작은 깊이 1로, 자식이 없는 루트의 끝은 깊이 0으로 나옴) + spots = [pos for pos, token, depth, _, _ in self.walk() if (depth, token) in ((1, BEGIN_NODE), (0, END_NODE))] + if not spots: + sys.exit("fdt-patch: the tree has no root node") + at = spots[0] + name = b"memory@%x\0" % base + node = struct.pack(">I", BEGIN_NODE) + pad(name) + node += self.prop("device_type", b"memory\0") + node += self.prop("reg", struct.pack(">QQ", base, size)) + node += struct.pack(">I", END_NODE) + self.struct[at:at] = node + + def blob(self): + off_rsv = 40 + off_struct = off_rsv + len(self.rsv) + off_strings = off_struct + len(self.struct) + total = (off_strings + len(self.strings) + 7) & ~7 + head = struct.pack( + ">10I", MAGIC, total, off_struct, off_strings, off_rsv, self.version, self.last, self.cpu, + len(self.strings), len(self.struct), + ) + body = head + self.rsv + bytes(self.struct) + bytes(self.strings) + return body + b"\0" * (total - len(body)) + + +def main(): + if len(sys.argv) < 4: + sys.exit(__doc__.strip()) + with open(sys.argv[1], "rb") as f: + tree = Tree(f.read()) + for edit in sys.argv[3:]: + kind, _, rest = edit.partition(":") + if kind == "prop": + node, name, cells = rest.split(":") + tree.add_prop(node, name, b"".join(struct.pack(">I", int(c, 16)) for c in cells.split(","))) + elif kind == "memory": + base, size = (int(v, 16) for v in rest.split(":")) + tree.add_memory(base, size) + else: + sys.exit("fdt-patch: unknown edit %r" % edit) + with open(sys.argv[2], "wb") as f: + f.write(tree.blob()) + + +if __name__ == "__main__": + main() diff --git a/tools/qemu-virt-runner.sh b/tools/qemu-virt-runner.sh index 34ceac1..204621e 100755 --- a/tools/qemu-virt-runner.sh +++ b/tools/qemu-virt-runner.sh @@ -13,6 +13,12 @@ # K0_QEMU_EXTRA QEMU에 더 넘길 인자(공백으로 나눔) # K0_IMAGE_TEXT_OFFSET Image 헤더의 text_offset을 이 값으로 바꾼 사본을 부팅 # (같은 이미지를 다른 물리 주소에 적재시키는 시험) +# K0_IMAGE_DTB_POINTER 커널이 받는 DTB 포인터(x0)를 바꾼 사본을 부팅. end면 +# 주소 범위의 맨 끝(0xFFFFFFFFFFFFFFF8)이고, 아니면 그 +# 주소(16비트 조각 하나로 적을 수 있는 값). QEMU가 손대지 +# 않은 디바이스 트리를 -device loader로 그 주소에 실어 +# 부팅할 때도 씀(-dtb로 준 트리는 QEMU가 memory 노드를 +# 자기 것으로 바꿈) # # 인자가 .efi로 끝나면(tools/build-loader.sh가 만든 UEFI 로더) 펌웨어를 거쳐 # 부팅합니다. 이때 머신 기본값은 virt,gic-version=3,acpi=off 입니다(EDK2는 @@ -69,12 +75,31 @@ case "$elf" in echo "runner: this kernel has no console driver and prints nothing here (build with --features console to see output)" >&2 fi - if [ -n "${K0_IMAGE_TEXT_OFFSET:-}" ]; then - patched="${elf}.${K0_IMAGE_TEXT_OFFSET}.bin" - python3 - "$img" "$patched" "$K0_IMAGE_TEXT_OFFSET" <<'PATCH' + if [ -n "${K0_IMAGE_TEXT_OFFSET:-}" ] || [ -n "${K0_IMAGE_DTB_POINTER:-}" ]; then + tag="${K0_IMAGE_TEXT_OFFSET:-}" + [ -z "${K0_IMAGE_DTB_POINTER:-}" ] || tag="${tag:+$tag.}dtb-${K0_IMAGE_DTB_POINTER}" + patched="${elf}.${tag}.bin" + python3 - "$img" "$patched" "${K0_IMAGE_TEXT_OFFSET:-}" "${K0_IMAGE_DTB_POINTER:-}" <<'PATCH' import struct, sys data = bytearray(open(sys.argv[1], "rb").read()) -data[8:16] = struct.pack("> (16 * hw)) & 0xFFFF) for hw in range(4)] + used = [c for c in chunks if c[1]] + if value >> 64 or len(used) != 1: + sys.exit("runner: K0_IMAGE_DTB_POINTER must be 'end' or a value with one 16-bit chunk set") + set_x0 = 0xD2800000 | used[0][0] << 21 | used[0][1] << 5 # movz x0, #chunk, lsl #(16 * hw) + code0, code1 = struct.unpack("> 26 != 0b000101 or code1 != 0: + sys.exit("runner: the image header does not start with a branch and an empty word") + data[:8] = struct.pack(" deadline: + raise Failure("the monitor did not finish %d breaks, last reply %r" % (count, bytes(seen[-80:]))) + drain() + except OSError as e: + raise Failure("monitor socket during the break flood: %s" % e) + finally: + s.close() + def send(self, data): self.proc.stdin.write(data) self.proc.stdin.flush() @@ -158,6 +200,16 @@ def run(self, line, reply, typed=None, echo=None, timeout=20): self.expect(shown + reply.encode() + PROMPT, timeout, what=repr(line)) +def qemu_version(): + """QEMU의 (주, 부) 버전을 줍니다. 알 수 없으면 None입니다.""" + try: + out = subprocess.run(["qemu-system-aarch64", "--version"], capture_output=True, timeout=20).stdout + except (OSError, subprocess.TimeoutExpired): + return None + m = re.search(rb"version (\d+)\.(\d+)", out) + return (int(m.group(1)), int(m.group(2))) if m else None + + def boot_judge(root, image, log_path, boot, vault): """프롬프트 전의 출력을 부팅 시험의 판정 전용 모드로 넘깁니다.""" path = log_path + ".boot" @@ -268,6 +320,19 @@ def session(s, vault, seed): s.monitor("chardev-send-break serial0") s.send(b"firm\r") s.expect(b"\nerr input-lost\n" + PROMPT, what="break") + # break의 홍수: 오류가 난 문자는 링의 자리를 쓰지 않으므로 커널이 틱마다 + # 정해진 수까지만 받음. 입력 경로는 끊기지 않고, 홍수 뒤의 첫 줄은 유실로 + # 알려지며 그다음 줄부터 정상임. 커널이 받지 않는 동안 break는 QEMU의 UART에 + # 쌓이는데, 8.0 전의 QEMU는 break를 수신 FIFO에 넣을 때 깊이를 확인하지 않아 + # 자기 상태를 덮어쓰므로 이 단계는 8.0부터만 돌림 + version = qemu_version() + if version is not None and version >= (8, 0): + s.breaks(2000) + s.send(b"help\r") + s.expect(b"\nerr input-lost\n" + PROMPT, timeout=60, what="break flood") + s.run("help", full_help) + else: + print("term-test: break flood skipped (needs QEMU 8.0 or later, found %s)" % (version,)) if vault == "ed25519": s.run("vault status", ready) s.run("vault zeroize confirm", "state=zeroized\nok\n")