diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 387df6a..118fd2c 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -68,9 +68,9 @@ $ tools/build-loader.sh # put the built kernel into the UEFI loader, prints th
Input and output are optional in K0. You can select them with Cargo features of the kernel crate.
> [!NOTE]
-> A feature for input or for a terminal does not exist yet. Console output is the only thing you can select today.
+> Console input and the operator terminal are features too (`console-input`, `terminal`), and they are off by default.
-Console output exists only in an image built with a console feature (`console-pl011`, `console-16550`, `console`). No image has input. `cargo virt` is an alias for `cargo run -p k0-kernel --features console`. [USAGE.md](USAGE.md#console-features) explains the features.
+Console output exists only in an image built with a console feature (`console-pl011`, `console-16550`, `console`). An image has input only if it was built with `console-input` or `terminal`. `cargo virt` is an alias for `cargo run -p k0-kernel --features console`. [USAGE.md](USAGE.md#console-features) explains the features.
The kernel never exits. Once the root task finishes its self-tests, it yields forever and a kernel with console prints `k0: tick N` once a second. Stop QEMU with `Ctrl-A X`.
@@ -92,11 +92,11 @@ $ cargo build -p k0-kernel --features console --offline
$ tools/qemu-boot-test.sh # boot under QEMU and check the self-tests
```
-`tools/host-test.sh` runs the tests of `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi` and `k0-vault` on any host (276 tests on an AArch64 host, 190 elsewhere). It runs `k0-vault` twice, with and without the algorithm feature `vault-ed25519`, which gives 13 and 7 tests. The tests of `k0-mm` contain AArch64 inline assembly, so they only run on an AArch64 host (Apple Silicon or Linux arm64). The script runs them for both the 4 KiB and the 16 KiB granule.
+`tools/host-test.sh` runs the tests of `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-conin`, `k0-vault` and `k0-term` on any host (354 tests on an AArch64 host, 268 elsewhere). It runs `k0-vault` twice, with and without the algorithm feature `vault-ed25519`, which gives 20 and 11 tests. It runs `k0-term` with and without the vault feature, which gives 24 and 21 tests. The tests of `k0-mm` contain AArch64 inline assembly, so they only run on an AArch64 host (Apple Silicon or Linux arm64). The script runs them for both the 4 KiB and the 16 KiB granule.
`tools/qemu-boot-test.sh` boots the debug kernel, checks the boot log line by line in a fixed order, fails on any error marker, and stops QEMU as soon as the root task reports `root: sched tests pass`. Besides the pass lines, it expects `k0: kernel reserve ` before the `k0: untyped ` lines, `k0: idle (waiting for a timeout)` and `root: timeout tests pass` after `root: teardown tests pass`, and `root: kernel reserve tests pass` after `root: revocation tests pass`. Any line that starts with `k0: all tasks` is a failure. It also counts the timer tick lines between `root: teardown tests pass` and `root: timeout tests pass` and wants at least 4, because EL0 has no clock and this is how the lower bound of a timeout is checked. The timeout tests wait for real ticks, so a boot takes about 4 seconds longer than it did before. Set `K0_BOOT_TIMEOUT` (seconds) on slow machines. It reads the serial port, so it needs an image with a console driver. To test an image without console, use `K0_BOOT_MEMLOG`, `K0_BOOT_SERIAL=empty` and `K0_BOOT_CONSOLE_PAGE`, which are described in "Testing an image without console" in [USAGE.md](USAGE.md#testing-an-image-without-console).
-An image with the signing oracle (`vault` or `vault-ed25519`) has two more intended faults, so it prints 8 `k0: task fault` lines instead of 6. Run the test with `K0_BOOT_FAULTS=8` and require `root: oracle tests pass` with `K0_BOOT_REQUIRE`. The boot matrix has the rows `vault`, `vault-max`, `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault` and the static check `vault-symbols` for it, and 61 rows in total on a Mac with HVF and 51 in CI. [USAGE.md](USAGE.md) describes the rows.
+An image with the signing oracle (`vault` or `vault-ed25519`) has two more intended faults, so it prints 8 `k0: task fault` lines instead of 6. Run the test with `K0_BOOT_FAULTS=8` and require `root: oracle tests pass` with `K0_BOOT_REQUIRE`. The boot matrix has the rows `vault`, `vault-max`, `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault` and the static check `vault-symbols` for it, and 76 rows in total on a Mac with HVF and 65 in CI. The rows `input-*` and `term-*` cover console input and the terminal. A terminal image prints two more `k0: task fault` lines (8 without the vault, 10 with it), and `tools/term-test.py ` runs its scripted serial session. [USAGE.md](USAGE.md) describes the rows.
The default QEMU CPU model (`cortex-a72`) has no PAC, PAN or RNDR. To exercise those paths as well, boot on QEMU's `max` model and require the matching log lines. Any arguments after the kernel path are passed to QEMU. You can enter it as follows:
diff --git a/CONTRIBUTING_KR.md b/CONTRIBUTING_KR.md
index 0f8268e..f6dbb2f 100644
--- a/CONTRIBUTING_KR.md
+++ b/CONTRIBUTING_KR.md
@@ -70,9 +70,9 @@ $ tools/build-loader.sh # 빌드한 커널을 UEFI 로더에 포함하고 .efi
K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Cargo features로 선택할 수 있습니다.
> [!NOTE]
-> 입력 또는 터미널용 feature는 아직 없습니다. 지금 선택할 수 있는 것은 콘솔 출력뿐입니다.
+> 콘솔 입력과 운영자 터미널도 feature(`console-input`, `terminal`)이며 기본으로는 꺼져 있습니다.
-콘솔 출력은 콘솔 feature(`console-pl011`, `console-16550`, `console`)를 포함해 빌드한 이미지에만 있습니다. 입력은 어떤 이미지에도 없습니다. `cargo virt`는 `cargo run -p k0-kernel --features console`의 별칭입니다. feature의 설명은 [USAGE_KR.md](USAGE_KR.md#콘솔-feature)에 있습니다.
+콘솔 출력은 콘솔 feature(`console-pl011`, `console-16550`, `console`)를 포함해 빌드한 이미지에만 있습니다. 입력은 `console-input` 또는 `terminal`을 포함해 빌드한 이미지에만 있습니다. `cargo virt`는 `cargo run -p k0-kernel --features console`의 별칭입니다. feature의 설명은 [USAGE_KR.md](USAGE_KR.md#콘솔-feature)에 있습니다.
커널은 종료하지 않습니다. 루트 태스크가 자가 테스트를 마치면 계속 양보하고, 콘솔이 있는 커널은 1초마다 `k0: tick N`을 출력합니다. QEMU는 `Ctrl-A X`로 끕니다.
@@ -94,11 +94,11 @@ $ cargo build -p k0-kernel --features console --offline
$ tools/qemu-boot-test.sh # QEMU 부팅과 자가 테스트 확인
```
-`tools/host-test.sh`는 `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-vault`의 테스트를 어느 호스트에서나 실행합니다(AArch64 호스트에서 276개, 그 밖에서 190개). `k0-vault`는 알고리즘 feature `vault-ed25519`를 포함한 경우와 포함하지 않은 경우로 두 번 실행하며, 각각 13개와 7개입니다. `k0-mm` 테스트는 AArch64 인라인 어셈블리를 포함하기 때문에 AArch64 호스트(Apple Silicon 또는 Linux arm64)에서만 실행되며, 스크립트가 4 KiB와 16 KiB 그래뉼 두 구성으로 모두 돌립니다.
+`tools/host-test.sh`는 `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-conin`, `k0-vault`, `k0-term`의 테스트를 어느 호스트에서나 실행합니다(AArch64 호스트에서 354개, 그 밖에서 268개). `k0-vault`는 알고리즘 feature `vault-ed25519`를 포함한 경우와 포함하지 않은 경우로 두 번 실행하며, 각각 20개와 11개입니다. `k0-term`도 `vault` feature를 포함한 경우와 포함하지 않은 경우로 실행하며, 각각 24개와 21개입니다. `k0-mm` 테스트는 AArch64 인라인 어셈블리를 포함하기 때문에 AArch64 호스트(Apple Silicon 또는 Linux arm64)에서만 실행되며, 스크립트가 4 KiB와 16 KiB 그래뉼 두 구성으로 모두 돌립니다.
`tools/qemu-boot-test.sh`는 디버그 커널을 부팅하고 부팅 로그를 정해진 순서대로 한 줄씩 확인합니다. 에러 표식이 하나라도 나오면 실패하고, 루트 태스크가 `root: sched tests pass`를 출력하면 곧바로 QEMU를 종료합니다. 통과 줄 외에도 `k0: untyped ` 줄보다 앞의 `k0: kernel reserve `, `root: teardown tests pass` 뒤의 `k0: idle (waiting for a timeout)`와 `root: timeout tests pass`, `root: revocation tests pass` 뒤의 `root: kernel reserve tests pass`를 기대합니다. `k0: all tasks`로 시작하는 줄은 모두 실패입니다. `root: teardown tests pass`와 `root: timeout tests pass` 사이의 타이머 틱 줄도 세어 4개 이상을 요구하는데, EL0에는 시계가 없어서 이것이 타임아웃의 하한을 확인하는 방법이기 때문입니다. 타임아웃 테스트는 실제 틱을 기다리므로 부팅 한 번이 이전보다 약 4초 더 걸립니다. 느린 환경에서는 `K0_BOOT_TIMEOUT`(초)을 늘려 주세요. 직렬 포트를 읽기 때문에 콘솔 드라이버가 있는 이미지가 필요합니다. 콘솔 없는 이미지를 시험하려면 [USAGE_KR.md](USAGE_KR.md#콘솔-없는-이미지-시험)의 "콘솔 없는 이미지 시험"에 설명된 `K0_BOOT_MEMLOG`, `K0_BOOT_SERIAL=empty`, `K0_BOOT_CONSOLE_PAGE`를 사용하세요.
-서명 오라클이 있는 이미지(`vault` 또는 `vault-ed25519`)는 일부러 일으키는 폴트가 두 번 더 있어 `k0: task fault` 줄이 6개가 아니라 8개이므로 `K0_BOOT_FAULTS=8`이 필요하고, `root: oracle tests pass`를 `K0_BOOT_REQUIRE`로 요구하세요. 부팅 매트릭스에는 이를 위한 행 `vault`, `vault-max`, `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`와 정적 검사 `vault-symbols`가 있으며, 행렬은 HVF가 있는 Mac에서 61행, CI에서 51행입니다. 행의 내용은 [USAGE_KR.md](USAGE_KR.md)에 있습니다.
+서명 오라클이 있는 이미지(`vault` 또는 `vault-ed25519`)는 일부러 일으키는 폴트가 두 번 더 있어 `k0: task fault` 줄이 6개가 아니라 8개이므로 `K0_BOOT_FAULTS=8`이 필요하고, `root: oracle tests pass`를 `K0_BOOT_REQUIRE`로 요구하세요. 부팅 매트릭스에는 이를 위한 행 `vault`, `vault-max`, `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`와 정적 검사 `vault-symbols`가 있으며, 행렬은 HVF가 있는 Mac에서 76행, CI에서 65행입니다. 행 `input-*`와 `term-*`는 콘솔 입력과 터미널을 다룹니다. 터미널 이미지는 `k0: task fault` 줄이 두 개 더 나오며(볼트 없이 8개, 볼트와 함께 10개), `tools/term-test.py <이미지>`가 정해진 직렬 세션을 실행합니다. 행의 내용은 [USAGE_KR.md](USAGE_KR.md)에 있습니다.
기본 QEMU CPU 모델(`cortex-a72`)에는 PAC, PAN, RNDR이 없습니다. 이 경로까지 검증하려면 QEMU의 `max` 모델로 부팅하고 해당 로그 줄을 필수로 지정하세요. 커널 경로 뒤의 인자는 그대로 QEMU에 전달됩니다. 다음과 같이 입력할 수 있습니다.
diff --git a/Cargo.lock b/Cargo.lock
index ad657a8..3d65e9b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -120,6 +120,7 @@ name = "k0-arch"
version = "0.1.0"
dependencies = [
"k0-abi",
+ "k0-conin",
]
[[package]]
@@ -133,6 +134,10 @@ dependencies = [
name = "k0-cap"
version = "0.1.0"
+[[package]]
+name = "k0-conin"
+version = "0.1.0"
+
[[package]]
name = "k0-efi"
version = "0.1.0"
@@ -202,6 +207,13 @@ dependencies = [
"k0-mm",
]
+[[package]]
+name = "k0-term"
+version = "0.1.0"
+dependencies = [
+ "k0-vault",
+]
+
[[package]]
name = "k0-vault"
version = "0.1.0"
@@ -240,6 +252,7 @@ name = "root-task"
version = "0.1.0"
dependencies = [
"k0-abi",
+ "k0-term",
"k0-vault",
]
diff --git a/Cargo.toml b/Cargo.toml
index 4de7ed5..01efbac 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -11,8 +11,10 @@ members = [
"crates/k0-boot",
"crates/k0-abi",
"crates/k0-efi",
+ "crates/k0-conin",
"userspace/root-task",
"userspace/k0-vault",
+ "userspace/k0-term",
"loader",
]
# UEFI 로더는 타겟이 달라(aarch64-unknown-uefi) 기본 빌드 대상에서 뺌.
@@ -28,6 +30,7 @@ default-members = [
"crates/k0-boot",
"crates/k0-abi",
"crates/k0-efi",
+ "crates/k0-conin",
"userspace/root-task",
]
diff --git a/INTRODUCTION.md b/INTRODUCTION.md
index 97fdd82..c8499ce 100644
--- a/INTRODUCTION.md
+++ b/INTRODUCTION.md
@@ -35,6 +35,7 @@ In the following table, you can find the words used in this document.
| **Endpoint** | A mailbox through which tasks exchange messages (IPC) |
| **System call** | A request that a program makes to the kernel |
| **Interrupt** | A signal from the hardware, such as a timer, that makes the processor stop and run the kernel |
+| **Terminal** | A screen on the serial line where a person types commands and reads the answers. In K0 one ordinary task provides it |
## Goals
@@ -46,7 +47,7 @@ K0 is meant to become the isolation core of high-security systems. The targets a
- **Research base**: formal verification and certification research
> [!NOTE]
-> Only a first small step exists: the optional signing oracle described under "What works today". The rest does not work yet. Today K0 is a research platform: it boots and checks its own security properties, but by default it does no useful work of its own yet.
+> Only a first small step exists: the optional signing oracle and the operator terminal that drives it over the serial line, both described under "What works today". The rest does not work yet. Today K0 is a research platform: it boots and checks its own security properties, but by default it does no useful work of its own yet.
## What works today
@@ -76,39 +77,40 @@ K0 is meant to become the isolation core of high-security systems. The targets a
- **Finding devices**: from the device tree the kernel takes only three things.
- - **Console**: the node named by `stdout-path` in `/chosen` (PL011, SBSA UART or 16550 family).
+ - **Console**: the node named by `stdout-path` in `/chosen` (PL011, SBSA UART or 16550 family). If the node has `interrupts`, its interrupt number is read as well, and it is used for input only. Through the UEFI loader it comes from the ACPI SPCR table.
- **Interrupt controller**: the interrupt parent of the timer node (GICv2 or GICv3).
- **Timer interrupt**: the interrupt number of the EL1 virtual timer.
- They go into one platform descriptor that never changes, printed as a `k0: platform ...` line. It is checked against the memory map before any device page is mapped. The hardware must agree with the device tree (the identification registers of the GIC and the PL011), otherwise the kernel refuses to boot. With any other UART, or without `stdout-path`, there is no console. Every image finds and checks the console node this way, even an image that never drives the console (see the next item). A device tree whose console fails the checks is therefore refused by every image.
+ They go into one platform descriptor that never changes, printed as a `k0: platform ...` line. It is checked against the memory map before any device page is mapped. The hardware must agree with the device tree (the identification registers of the GIC and the PL011), otherwise the kernel refuses to boot. With any other UART, or without `stdout-path`, there is no console. Every image finds and checks the console node this way, even an image that never drives the console (see the next item). A device tree whose console fails the checks is therefore refused by every image. A console node without a usable interrupt is not a reason to refuse: only input is switched off.
-- **Console output is optional**: input and output are optional in K0. You can select them with Cargo features of the kernel crate.
+- **Console input and output are optional**: input and output are optional in K0. You can select them with Cargo features of the kernel crate. Console output exists only in an image built with a console feature, and console input exists only in an image built with `console-input` or `terminal`. In the following table, you can find the Cargo features.
-> [!NOTE]
-> A feature for input or for a terminal does not exist yet. Console output is the only thing you can select today.
-
-Console output exists only in an image built with a console feature. No image has input. In the following table, you can find the Cargo features that add a transmit driver.
-
-| Feature | Transmit driver it adds |
+| Feature | What it adds |
| --- | --- |
-| `console-pl011` | PL011 and SBSA UART |
-| `console-16550` | The 16550 family |
-| `console` | Both of the above |
+| `console-pl011` | The transmit driver for PL011 and SBSA UART |
+| `console-16550` | The transmit driver for the 16550 family |
+| `console` | Both transmit drivers above |
+| `console-input` | The receive path for the console UART and the system call `CONSOLE_READ`. It needs a console driver feature to do anything |
+| `terminal` | The operator terminal task in the root task image. It turns `console-input` on |
+
+> [!NOTE]
+> Input exists only for the PL011 and the SBSA UART. A 16550 console has output and no input.
These features only add and are not in `default`, so **every build command must name the features**, for example `cargo build -p k0-kernel --features console --offline`. An image built without them has the following properties:
- It contains no UART driver code.
- It never maps the console device page.
- It writes nothing to a UART.
+- It has no receive code and no `CONSOLE_READ`.
- It prints `k0: no console (driver not built in)`.
- All its output goes only to the boot log.
-`DEBUG_PUTC`, the `Console` capability and the boot log stay in every image, and so does the check of the console node. `grep -a 'k0: console drivers' ` tells which drivers an image has (a label, not proof), and `k0: device pages [...]` lists every device page the kernel keeps mapped. The UEFI loader still prints through the firmware console. See [design/en/boot.md](design/en/boot.md) and the section "Optional console output" in [SECURITY.md](SECURITY.md).
+`DEBUG_PUTC`, the `Console` capability and the boot log stay in every image, and so does the check of the console node. The `Console` capability carries the rights R (read input) and W (write output). A copy can only lose them, and the root task's capability has W, and R only in images with `console-input`. `grep -a 'k0: console drivers' ` tells which drivers an image has (a label, not proof), and `k0: device pages [...]` lists every device page the kernel keeps mapped. The UEFI loader still prints through the firmware console. See [design/en/boot.md](design/en/boot.md) and the section "Optional console output" in [SECURITY.md](SECURITY.md).
- **Boot log**: every line the kernel prints also goes into a 16 KiB buffer in kernel memory. Lines printed before the console is attached are replayed once it is. With no console, this buffer is the only record. `tools/boot-log.py` reads it from the memory of a QEMU guest. Output of user tasks is recorded only up to a quota (6 KiB of the 16 KiB), and only the first 4 timer tick lines are logged.
- **Timer**: only the EL1 virtual timer is used, so it works inside hypervisor guests. The image never touches the physical timer, and the boot matrix checks that.
- **Granule**: the page size is 4 KiB by default. A 16 KiB build is a build option (see [USAGE.md](USAGE.md)). It is not selected at run time, and on a processor without 16 KiB support the 16 KiB image refuses to boot.
-- **Pinned build**: an image built with `K0_PIN` set to the platform line of a boot log refuses to boot when the discovered platform, the entry level or the RAM range differs. This catches a wrong board or a swapped device tree. It is not a defence against a hostile boot chain, because the comparison uses values that come from the device tree.
+- **Pinned build**: an image built with `K0_PIN` set to the platform line of a boot log refuses to boot when the discovered platform, the entry level or the RAM range differs. The platform line now also carries the console interrupt number (`con=pl011@0x9000000,irq33`), so pin strings made earlier must be made again. This catches a wrong board or a swapped device tree. It is not a defence against a hostile boot chain, because the comparison uses values that come from the device tree.
- **Protecting its own memory**: the kernel keeps the following.
- No page of kernel memory is both writable and executable (W^X).
- An empty guard page sits below the kernel's boot stack, so running off the end of the stack stops the kernel instead of damaging other memory.
@@ -132,7 +134,7 @@ These features only add and are not in `default`, so **every build command must
- **Running tasks**: a task is tied to one key ring and one address space when it is set up (TCB_CONFIGURE) and then started (TCB_RESUME). Tasks take turns, and a timer interrupts a task that runs too long (round-robin scheduling with timer preemption). A task can give up its turn (YIELD) or finish (EXIT).
- **Messages**: tasks exchange short messages that travel in processor registers. The sender waits until the receiver takes the message (synchronous IPC: SEND, RECV, CALL, REPLY_RECV). Sending needs the write right on the mailbox key and receiving needs the read right. The receiver learns the tag of the sender's key, and the right to reply can be used only once.
- **Timeouts**: every one of these calls can carry a time limit, counted in timer ticks (one tick is one second). If no partner arrives in time, the call returns an error (`TIMEOUT`, or `REPLY_TIMEOUT` when a `CALL` was delivered but no reply came). Without a limit a task waits as long as it takes. The wait lasts at least the given number of ticks and may be a little longer. The limit says when the task becomes ready again, not when it runs.
-- **Idle**: when no task can run, the kernel no longer stops. It waits for the next interrupt, wakes tasks whose time limit has passed and carries on. If nothing can ever wake a task, the machine stays idle and the boot log says `k0: all tasks stopped (none ready, no timeout pending)`.
+- **Idle**: when no task can run, the kernel no longer stops. It waits for the next interrupt, wakes tasks whose time limit has passed and carries on. If nothing can ever wake a task, the machine stays idle and the boot log says `k0: all tasks stopped (none ready, no timeout pending)`. That line appears only when there is neither a timed waiter nor a task waiting for console input. A terminal image prints nothing there, because waiting for input is its normal state.
- **Kernel tables sized at boot**: the kernel sets aside the memory for its own page tables and address space entries at boot, in proportion to the memory it hands out (about 0.4 % of RAM). So a task cannot use these tables up, and the number of address spaces is limited only by memory.
- **Crash containment**: when a task crashes, makes a system call the kernel does not know, or exits, only that task is stopped (fault isolation).
- **Task isolation and taking keys back**: tasks tied to different key rings and address spaces cannot reach each other's memory or keys. Every key remembers which key it was copied from (derivation list). Taking a key back (CAP_REVOKE) or deleting it (CAP_DELETE) has the following effects.
@@ -147,11 +149,28 @@ These features only add and are not in `default`, so **every build command must
- **Signing oracle (optional)**: this is the first service that does a job for other programs. A digital signature is a short value that proves a message was approved by whoever holds a secret key, and anyone with the matching public key can check it. A signing oracle is a program that signs messages for others and never shows its secret key. In K0 a vault task holds one key. Client tasks send it messages through a mailbox (IPC) and get back a signature or the public key, but never the key. The vault runs in its own address space, so no task other than the root task can map its memory.
- **Off by default**: two Cargo features of the kernel crate add it. `vault` adds the service, with no signing algorithm: every signing request answers "unsupported". `vault-ed25519` adds the algorithm. For example: `cargo build -p k0-kernel --features console,vault-ed25519`. The vault's code is part of the root task image, which is checked at boot like before, and nothing is loaded after boot. The default image has no vault code and no crypto code.
- **Algorithm**: Ed25519 (PureEdDSA with SHA-512, as in FIPS 186-5 and RFC 8032). The implementation is the vendored crate `ed25519-dalek` 2.2.0 and has no validation of any kind. The key does not come from an approved random bit generator.
- - **Who may do what**: the rules are fixed at build time and depend on the tag (badge) that the kernel puts on each message, so a client cannot forge it. The root task is the admin: it can ask for the status, create the key once (INIT) and wipe it (ZEROIZE), but it cannot sign. A signer can ask for the status and the public key and can sign. A reader can ask for the status and the public key only. A call without a known tag is refused. All signers share the one key, so a signature does not tell which client asked.
- - **The key**: the vault makes the key only if the boot seed holds enough randomness (at least 32 bytes from the device tree `rng-seed` or 256 bits from the processor's random number instruction RNDR). Otherwise it refuses. Before the kernel starts the root task, it zeroes the seed bytes in the device tree it received, and the boot log says `k0: dtb seeds wiped B`. The seed is as good as its inputs and no better. Copies that the firmware or the UEFI loader keep are not wiped.
- - **Self-test**: every image built with `vault` runs a test in the root task, which plays the admin and several clients. It shows that an unbadged call is refused, that the key is made once, that the admin cannot sign, that a signer gets a signature that checks and fails for a changed message, that a reader cannot sign, that a client that writes its read-only reply memory or reads another client's request is stopped by a fault, and that signing is refused after ZEROIZE. It ends with `root: oracle tests pass`. The test clients run one after another in one address space, so it shows the isolation between the vault and a client, not between clients.
+ - **Who may do what**: the rules are fixed at build time and depend on the tag (badge) that the kernel puts on each message, so a client cannot forge it. There are four roles. The root task is the admin: it can ask for the status, deliver the seed once (INIT), create the key (KEYGEN) and wipe it (ZEROIZE), but it cannot sign. The operator (the terminal) can ask for the status and the public key, create the key and wipe it, but it can neither sign nor deliver a seed. A signer can ask for the status and the public key and can sign. A reader can ask for the status and the public key only. A call without a known tag is refused. All signers share the one key, so a signature does not tell which client asked.
+ - **The key**: INIT only delivers the boot seed. The vault takes and holds the seed (`seeded`) only if it has enough randomness (at least 32 bytes from the device tree `rng-seed` or 256 bits from the processor's random number instruction RNDR), and otherwise refuses. KEYGEN then makes the key of the chosen algorithm from the held seed and wipes the seed (`ready`). There is one key per boot: a second KEYGEN is refused, and after ZEROIZE a reboot is needed. Before the kernel starts the root task, it zeroes the seed bytes in the device tree it received, and the boot log says `k0: dtb seeds wiped B`. The seed is as good as its inputs and no better. Copies that the firmware or the UEFI loader keep are not wiped.
+ - **Self-test**: every image built with `vault` runs a test in the root task, which plays the admin and several clients. Its vault makes its key from the public RFC 8032 test seed, and the entropy rule still runs. The test shows that an unbadged call is refused, that the key is made once, that the admin cannot sign, that a signer gets a signature that checks and fails for a changed message, that a reader cannot sign, that a client that writes its read-only reply memory or reads another client's request is stopped by a fault, and that signing is refused after ZEROIZE. It ends with `root: oracle tests pass`. The test clients run one after another in one address space, so it shows the isolation between the vault and a client, not between clients.
+
+- **Operator terminal (optional)**: a task that lets a person type commands on the serial line to work with the signing oracle's vault. It can make the key, read the public key and erase the key, but it cannot sign.
+ - **How to turn it on**: it is off by default and is added by the Cargo feature `terminal` of the kernel crate. The vault also needs `vault-ed25519` to make a key. You can build it and run it in QEMU as follows:
+
+ ```sh
+ $ cargo build -p k0-kernel --features console,terminal,vault-ed25519
+ $ cargo run -p k0-kernel --features console,terminal,vault-ed25519
+ ```
+
+ Under `cargo run`, QEMU's own escape key is Ctrl-A (Ctrl-A, then X quits QEMU), so Ctrl-A never reaches K0.
+ - **Start-up order**: a terminal image runs all self-tests first. Then the root task starts a new vault and hands it the boot seed (`root: vault seeded`), checks that two hostile tasks wired exactly like the terminal are refused and end in a fault (`root: terminal wiring holds`), drops its own admin capability and starts the terminal (`root: service started`). After that the banner `K0 operator console, type 'help'` and the prompt `k0> ` appear. On a machine without an input path, `root: no console input, terminal not started` appears and the terminal does not start.
+ - **Commands**: they are `help`, `vault status` (the vault's state), `vault pubkey` (the public key), `vault keygen ed25519` (make the key) and `vault zeroize confirm` (erase the key). `vault zeroize` alone erases nothing and answers `err confirm-required`. Every command ends with one line, `ok` or `err `. `vault status` always prints `validated=no`, because the implementation has no validation of any kind. [USAGE.md](USAGE.md) has the details and an example screen.
+ - **Input rules**: a line ends with Enter (CR or LF), has at most 64 characters and takes printable ASCII only. Backspace and DEL erase one character, Ctrl-C and Ctrl-U cancel the line, and escape sequences such as the arrow keys are ignored. Bytes that reached the UART before the prompt are dropped. If input was lost, everything up to the next line end is dropped and `err input-lost` is printed.
+ - **What the kernel does**: the kernel only collects the bytes received by the UART in a ring of 256 bytes and never interprets them. A task takes them one byte at a time with the system call `CONSOLE_READ`, and only one task can wait at a time. The receive interrupt stays off until a task first reads console input. At that moment one line `k0: tick lines off (console input in use)` is printed and the periodic `k0: tick N` lines stop, while the timer, preemption and timeouts keep working. When the ring is full, the kernel masks the receive interrupt itself and reopens it after the task has taken half of the ring, so a flood of input costs the kernel no more work than the reader allows. At boot the log says `k0: console input on (pl011 irq 33)` or `k0: console input off ()`. A wrong interrupt number switches off input only and does not stop the boot.
+ - **There is no authentication**: whoever holds the serial line is the operator and can do all four of the operator's jobs (status, public key, make the key, erase the key). That includes erasing the key and so stopping the service, which is by design. The operator cannot get a signature and cannot change policy.
+ - **Do not trust the screen**: if a kernel line appears while someone is typing, the line on the screen is split but the input buffer is whole, and Enter runs the whole buffer. Any task with console output can print lines that look like kernel or root task lines, so a line prefix proves nothing. The terminal can also erase within its own line (it prints backspace).
+ - **Known limits**: the terminal and the vault are not restarted if they die (the root task is trusted). In service mode no client asks for signatures yet, so the key is made and shown but not used by another task (the self-test shows client signing). Terminal output counts against the user share of the boot log, and once that share is full, later task output is not recorded there.
-The root task tests every item above with self-tests on every boot. The signing oracle is tested in the images built with it.
+The root task tests every item above with self-tests on every boot. The signing oracle and the terminal are tested in the images built with them.
## Where it has run
@@ -164,7 +183,7 @@ The following picture summarizes what each evidence tier means.
> [!NOTE]
> Only the first two tiers may be called supported.
-- **Tier 1**: checked by `tools/boot-matrix.sh` (CI runs it on QEMU 7.2).
+- **Tier 1**: checked by `tools/boot-matrix.sh` (CI runs it on QEMU 7.2). It has 76 rows locally with HVF and 65 in CI.
- **Direct boot rows**
- QEMU virt with GICv3 and with GICv2, each entered at EL1 and at EL2
- The CPU models cortex-a72, cortex-a53 and max
@@ -186,6 +205,8 @@ The following picture summarizes what each evidence tier means.
- A static check of the loader's PE file form and of the order of its cache and MMU instructions (`tools/pe-check.py`)
- **ACPI rows**: the rows `uefi-acpi-gic3-el1`, `uefi-acpi-gic3-el2`, `uefi-acpi-gic2-el1`, `uefi-acpi-smp4`, `uefi-acpi-16k` and `uefi-acpi-rng` boot the default QEMU machine with ACPI on, without a device tree, through the tables.
- **Signing oracle rows**: `vault`, `vault-max` (with RNDR), `vault-el2`, `vault-16k`, `vault-no-alg` (no signing algorithm) and `hvf-vault` (only on a Mac with HVF) boot images with the oracle and judge its self-test. The static row `vault-symbols` checks that the default image has no vault or crypto code.
+ - **Input rows**: `input-only`, `input-gicv2`, `input-16550` and `input-bad-irq` boot images with the input path on and judge whether input came on (or went off where it must) and the self-test. The static row `input-symbols` checks that an image built without an input feature has no receive code, no `CONSOLE_READ` and none of the new log lines.
+ - **Terminal rows**: `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi` and `hvf-term` (only on a Mac with HVF) boot terminal images. `tools/term-test.py ` connects QEMU's serial port to pipes and runs a scripted session: every command and error, erase and cancel, a line that is too long, key generation and the public key format, zeroize, 200 kB without a line end, 2000 lines in a row and a serial break.
- **Refusal checks**: two refusals are read from the serial log.
- The 16 KiB image on a CPU without 16 KiB pages
- A loader whose embedded kernel has one flipped byte
@@ -216,6 +237,7 @@ The rows also ran locally on QEMU 11.1.3.
- Any real board, KVM, Firecracker, Cloud Hypervisor, crosvm
- The 16550 console driver: no machine in the matrix has one, so no test has ever executed it. It was checked by review only.
- The SBSA UART: it uses the PL011 driver without an identity check.
+ - Parts of input: a 16550 console has no input. The receive path of the SBSA UART, FIFO overruns and the receive timeout interrupt are not exercised by QEMU and are covered only by host tests with a fake UART. So is the cut-off of an interrupt line that fires without a UART cause. No test has measured kernel time under a flood of input on a machine. The bound is argued from the design and shown in host tests.
- Release (LTO) images of the feature sets without console: the matrix builds and boots only debug images, and the symbol check runs on them.
- Any image without console booted through UEFI
- GICs with real security extensions on hardware
@@ -253,6 +275,9 @@ What it does not stop:
- A fatal error inside the kernel, or an error from the hardware that the kernel cannot attribute to one task, still stops the whole machine.
- The kernel part of the boot log can be filled up by crash and exit lines.
- The signing oracle is no exception: clients share one mailbox to the vault and must give a timeout on every call, or a stuck vault holds them up.
+ - In an image with input, an outside party can cause interrupts while tasks run. Their number is bounded by the reader, but the reader learns arrival times finer than a timer tick, and other tasks can notice the stolen time. This timing channel has not been analysed.
+ - Input waits behind the running tasks. There are no priorities, so the delay is up to one tick for each ready task.
+ - The receive code runs in the kernel (EL1). It is small and never interprets a byte, but it is kernel code driven by an outside party. Moving it to a user-space driver needs delegation of devices and interrupts, which K0 does not have yet.
- **Tasks that share a key ring and an address space**: such tasks are not isolated from each other. They behave like threads, parts of one program that share everything.
- **Control of a task**: whoever holds the key to a task, to its key ring or to its address space controls that task.
- **The root task**: it builds every task, key ring and address space, so it is trusted and is outside the isolation. It could read the memory of the signing oracle and with it the key. "No task other than the root task can map the vault's memory" is all that holds.
@@ -264,7 +289,7 @@ What it does not stop:
Missing features:
-- **Input**: input of any kind does not exist yet. No code reads from a UART or from any other device, and no feature for input or for a terminal exists.
+- **The rest of input**: only input from the console UART exists (PL011 and SBSA UART, optional). Input from a 16550 console or from any other device does not exist yet, and neither does handling input in a user-space driver.
- **Capability transfer**: a key cannot be handed to another task inside a message (capability transfer over IPC).
- **Hardware interrupt notification**: a program cannot be told about hardware interrupts (Notification objects).
- **Crash reports**: a crashed task is only stopped. It is not reported to a handler task.
@@ -276,9 +301,9 @@ Missing features:
- No persistence: the key lives only in memory and is gone after a reboot or ZEROIZE.
- One key only, and no way to import or export a key.
- No post-quantum (PQC) algorithm yet.
- - No operator input: nobody can type a command to it, because no input of any kind exists.
+ - No authentication of the operator: the terminal reads the serial line, and whoever holds the line is the operator. In service mode no signing client uses the key yet.
- No validation of the implementation, no analysis of timing or cache side channels of the crypto crate on this kernel, and no random bit generator beyond the boot seed.
- - It has been run only in QEMU (TCG and HVF).
+ - It has been run only in QEMU (TCG and HVF), never on real hardware.
- **Signature checking**: checking a digital signature (Ed25519) once the root task ships separately from the kernel. The signing oracle makes signatures but does not use them to check the root task.
- **Real boards and other virtualization**: K0 has not been booted on real boards, or on KVM, Firecracker, Cloud Hypervisor or crosvm (tier 3 above).
- **Entry from EL3 and ACPI beyond the static tables**: these two are missing.
@@ -316,6 +341,7 @@ In the following table, you can find the contents of each path in the repository
| `kernel/` | The kernel program: startup assembly, the order of initialization, system call handling (`syscall.rs`), cleanup when a key is removed (`object.rs`), files that describe the memory layout of the kernel image (linker scripts) |
| `crates/k0-abi` | System call numbers, error codes and the boot information layout that programs share with the kernel |
| `crates/k0-arch` | Handling of errors, system calls and interrupts (exceptions), entering and leaving user mode, interrupt controller and timer, PAC and PAN, the boot log and the optional console drivers |
+| `crates/k0-conin` | The receive logic of console input (the ring and the loss mark), tested on the host with a fake UART |
| `crates/k0-boot` | Device tree parser, the built-in root task image and its integrity check, PAC key derivation, the search for the boot memory window (shared with the loader) |
| `crates/k0-efi` | The loader's logic without `unsafe` code: planning RAM from the UEFI memory map, rewriting the firmware device tree, an independent re-check of the result, and the check of the kernel image header. It runs the kernel's own device tree code on the result before the jump |
| `crates/k0-cap` | Keys and their rights, key rings, the derivation list, untyped memory, retype, revoke and delete |
@@ -324,8 +350,9 @@ In the following table, you can find the contents of each path in the repository
| `crates/k0-sched` | Round-robin scheduler |
| `crates/k0-ipc` | Synchronous messages |
| `loader/` | The UEFI application (`k0-loader`, target `aarch64-unknown-uefi`) that embeds a built kernel image and starts it: UEFI calls, the flow, and the final cache flush, MMU off and jump |
-| `userspace/root-task` | The first program and its self-tests, and the wiring and self-test of the signing oracle (`oracle.rs`) |
+| `userspace/root-task` | The first program and its self-tests, and the wiring and self-test of the signing oracle (`oracle.rs`), and the start of the terminal service (`service.rs`) |
+| `userspace/k0-term` | The operator terminal: line editing, command parsing and the requests to the vault |
| `userspace/k0-vault` | The signing oracle service: protocol and fixed policy, the request handling, and the boundary around the crypto crate |
-| `tools/` | QEMU runner (also for `.efi` files), boot test, boot matrix, boot log reader, host test, loader build (`build-loader.sh`), PE and instruction order check (`pe-check.py`) |
+| `tools/` | QEMU runner (also for `.efi` files), boot test, boot matrix, terminal session test (`term-test.py`), boot log reader, host test, loader build (`build-loader.sh`), PE and instruction order check (`pe-check.py`) |
| `ci/` | The CI build and test image (`Dockerfile`) and the threat model (`threat_model.md`) |
| `vendor/` | Third-party crates kept in the repository (`sha2`, `ed25519-dalek` and their dependencies) |
diff --git a/INTRODUCTION_KR.md b/INTRODUCTION_KR.md
index dc8420d..f675685 100644
--- a/INTRODUCTION_KR.md
+++ b/INTRODUCTION_KR.md
@@ -35,6 +35,7 @@
| **엔드포인트** | 태스크끼리 메시지를 주고받는 우편함(IPC)입니다 |
| **시스템 콜** | 프로그램이 커널에 하는 요청입니다 |
| **인터럽트** | 타이머 같은 하드웨어가 보내는 신호입니다. 프로세서가 하던 일을 멈추고 커널을 실행하게 합니다 |
+| **터미널** | 시리얼 줄로 사람이 명령을 입력하고 답을 읽는 화면입니다. K0에서는 일반 태스크 하나가 맡습니다 |
## 목표
@@ -46,7 +47,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
- **연구용 기반**: 정형 검증과 인증 연구
> [!NOTE]
-> 첫 작은 걸음만 있습니다. "지금 동작하는 것"에 적은 선택 사항인 서명 오라클입니다. 나머지는 아직 동작하지 않습니다. 지금의 K0는 연구용 플랫폼으로, 부팅해서 자신의 보안 성질을 스스로 확인하지만 기본값으로는 아직 그 자체로 쓸모 있는 일을 하지는 않습니다.
+> 첫 작은 걸음만 있습니다. "지금 동작하는 것"에 적은 선택 사항인 서명 오라클과, 그것을 시리얼 줄로 다루는 운영자 터미널입니다. 나머지는 아직 동작하지 않습니다. 지금의 K0는 연구용 플랫폼으로, 부팅해서 자신의 보안 성질을 스스로 확인하지만 기본값으로는 아직 그 자체로 쓸모 있는 일을 하지는 않습니다.
## 지금 동작하는 것
@@ -76,39 +77,40 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
- **장치 찾기**: 커널은 디바이스 트리에서 세 가지만 가져옵니다.
- - **콘솔**: `/chosen`의 `stdout-path`가 가리키는 노드입니다(PL011·SBSA UART·16550 계열).
+ - **콘솔**: `/chosen`의 `stdout-path`가 가리키는 노드입니다(PL011·SBSA UART·16550 계열). 노드에 `interrupts`가 있으면 인터럽트 번호도 가져오며, 이 번호는 입력에만 사용합니다. UEFI 로더를 거치면 ACPI SPCR 표에서 가져옵니다.
- **인터럽트 컨트롤러**: 타이머 노드의 인터럽트 부모입니다(GICv2 또는 GICv3).
- **타이머 인터럽트**: EL1 가상 타이머의 인터럽트 번호입니다.
- 이 값들은 바뀌지 않는 플랫폼 기술자 하나에 담겨 `k0: platform ...` 줄로 출력됩니다. 장치 페이지를 하나라도 매핑하기 전에 메모리 맵과 대조합니다. 하드웨어가 디바이스 트리와 일치해야 하며(GIC와 PL011의 식별 레지스터), 맞지 않으면 커널은 부팅을 거부합니다. 다른 UART이거나 `stdout-path`가 없으면 콘솔이 없습니다. 모든 이미지가 콘솔 노드를 이렇게 찾고 검사합니다. 콘솔을 전혀 구동하지 않는 이미지도 마찬가지입니다(다음 항목 참고). 그래서 콘솔이 검사를 통과하지 못하는 디바이스 트리는 모든 이미지가 거부합니다.
+ 이 값들은 바뀌지 않는 플랫폼 기술자 하나에 담겨 `k0: platform ...` 줄로 출력됩니다. 장치 페이지를 하나라도 매핑하기 전에 메모리 맵과 대조합니다. 하드웨어가 디바이스 트리와 일치해야 하며(GIC와 PL011의 식별 레지스터), 맞지 않으면 커널은 부팅을 거부합니다. 다른 UART이거나 `stdout-path`가 없으면 콘솔이 없습니다. 모든 이미지가 콘솔 노드를 이렇게 찾고 검사합니다. 콘솔을 전혀 구동하지 않는 이미지도 마찬가지입니다(다음 항목 참고). 그래서 콘솔이 검사를 통과하지 못하는 디바이스 트리는 모든 이미지가 거부합니다. 콘솔 노드에 쓸 수 있는 인터럽트가 없는 것은 거부 사유가 아닙니다. 그 경우에는 입력만 꺼집니다.
-- **콘솔 출력은 선택 사항**: K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Cargo features로 선택할 수 있습니다.
+- **콘솔 입출력은 선택 사항**: K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Cargo features로 선택할 수 있습니다. 콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있고, 콘솔 입력은 `console-input` 또는 `terminal`을 포함해 빌드한 이미지에만 있습니다. 다음 표는 Cargo feature를 정리한 것입니다.
-> [!NOTE]
-> 입력 또는 터미널용 feature는 아직 없습니다. 지금 선택할 수 있는 것은 콘솔 출력뿐입니다.
-
-콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다. 입력은 어떤 이미지에도 없습니다. 다음 표는 송신 드라이버를 더하는 Cargo feature를 정리한 것입니다.
-
-| feature | 더하는 송신 드라이버 |
+| feature | 더하는 것 |
| --- | --- |
-| `console-pl011` | PL011과 SBSA UART |
-| `console-16550` | 16550 계열 |
-| `console` | 위의 둘 모두 |
+| `console-pl011` | PL011과 SBSA UART의 송신 드라이버 |
+| `console-16550` | 16550 계열의 송신 드라이버 |
+| `console` | 위의 두 송신 드라이버 모두 |
+| `console-input` | 콘솔 UART의 수신 경로와 시스템 콜 `CONSOLE_READ`. 콘솔 드라이버 feature와 함께 써야 동작합니다 |
+| `terminal` | 루트 태스크 이미지 안의 운영자 터미널 태스크. `console-input`을 함께 켭니다 |
+
+> [!NOTE]
+> 입력 받기는 PL011과 SBSA UART에만 있습니다. 16550 콘솔은 출력만 있고 입력이 없습니다.
이 feature는 더하기만 하며 `default`에 없습니다. 따라서 **모든 빌드 명령이 feature 이름을 직접 적어야 합니다**. 예를 들어 `cargo build -p k0-kernel --features console --offline`입니다. feature 없이 빌드한 이미지는 다음과 같습니다.
- UART 드라이버 코드가 아예 없습니다.
- 콘솔 장치 페이지를 매핑하지 않습니다.
- UART에 아무것도 쓰지 않습니다.
+- 수신 코드와 `CONSOLE_READ`도 없습니다.
- `k0: no console (driver not built in)`을 출력합니다.
- 출력은 모두 부트 로그로만 갑니다.
-`DEBUG_PUTC`, `Console` 케이퍼빌리티, 부트 로그는 모든 이미지에 남고, 콘솔 노드의 검사도 그대로입니다. `grep -a 'k0: console drivers' <이미지 파일>`로 이미지에 어떤 드라이버가 있는지 알 수 있습니다(증거가 아니라 표지입니다). `k0: device pages [...]`는 커널이 매핑한 채로 두는 모든 장치 페이지를 나열합니다. UEFI 로더는 여전히 펌웨어 콘솔로 출력합니다. [design/kr/boot_KR.md](design/kr/boot_KR.md)와 [SECURITY_KR.md](SECURITY_KR.md)의 "선택적 콘솔 출력" 절을 참고하세요.
+`DEBUG_PUTC`, `Console` 케이퍼빌리티, 부트 로그는 모든 이미지에 남고, 콘솔 노드의 검사도 그대로입니다. `Console` 케이퍼빌리티에는 읽기(R, 입력)와 쓰기(W, 출력) 권한이 있습니다. 복사할 때 줄일 수만 있고, 루트 태스크의 케이퍼빌리티는 W를 가지며 `console-input` 이미지에서만 R도 가집니다. `grep -a 'k0: console drivers' <이미지 파일>`로 이미지에 어떤 드라이버가 있는지 알 수 있습니다(증거가 아니라 표지입니다). `k0: device pages [...]`는 커널이 매핑한 채로 두는 모든 장치 페이지를 나열합니다. UEFI 로더는 여전히 펌웨어 콘솔로 출력합니다. [design/kr/boot_KR.md](design/kr/boot_KR.md)와 [SECURITY_KR.md](SECURITY_KR.md)의 "선택적 콘솔 출력" 절을 참고하세요.
- **부트 로그**: 커널이 출력하는 모든 줄은 커널 메모리의 16 KiB 버퍼에도 들어갑니다. 콘솔이 붙기 전에 출력한 줄은 콘솔이 붙을 때 다시 출력합니다. 콘솔이 없으면 이 버퍼가 유일한 기록입니다. `tools/boot-log.py`가 QEMU 게스트의 메모리에서 이를 읽습니다. 사용자 태스크의 출력은 할당량(16 KiB 중 6 KiB)까지만 기록하고, 타이머 tick 줄은 처음 4개만 기록합니다.
- **타이머**: EL1 가상 타이머만 사용하므로 하이퍼바이저 게스트 안에서도 동작합니다. 이미지는 물리 타이머를 건드리지 않으며, 부팅 매트릭스가 이를 확인합니다.
- **그래뉼**: 페이지 크기는 기본 4 KiB입니다. 16 KiB 빌드는 빌드 옵션입니다([USAGE_KR.md](USAGE_KR.md) 참고). 실행 중에 선택하는 것이 아니며, 16 KiB 지원이 없는 프로세서에서는 16 KiB 이미지가 부팅을 거부합니다.
-- **고정 빌드**: 부트 로그의 플랫폼 줄을 `K0_PIN`에 설정해 빌드한 이미지는 찾아낸 플랫폼, 진입 단계, RAM 범위가 다르면 부팅을 거부합니다. 보드를 잘못 선택했거나 디바이스 트리를 바꿔치기한 경우를 잡아냅니다. 비교에 사용하는 값이 디바이스 트리에서 나오므로, 악의적인 부트 체인을 막는 방어는 아닙니다.
+- **고정 빌드**: 부트 로그의 플랫폼 줄을 `K0_PIN`에 설정해 빌드한 이미지는 찾아낸 플랫폼, 진입 단계, RAM 범위가 다르면 부팅을 거부합니다. 플랫폼 줄에는 이제 콘솔 인터럽트 번호도 들어가므로(`con=pl011@0x9000000,irq33`) 이전에 만든 고정 문자열은 다시 만들어야 합니다. 보드를 잘못 선택했거나 디바이스 트리를 바꿔치기한 경우를 잡아냅니다. 비교에 사용하는 값이 디바이스 트리에서 나오므로, 악의적인 부트 체인을 막는 방어는 아닙니다.
- **커널 자신의 메모리 보호**: 다음을 지킵니다.
- 커널 메모리의 어떤 페이지도 쓰기와 실행이 동시에 되지 않습니다(W^X).
- 커널의 부트 스택 아래에는 빈 경계 페이지를 두어서, 스택 끝을 넘어가면 다른 메모리를 망가뜨리지 않고 커널이 멈춥니다.
@@ -132,7 +134,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
- **태스크 실행**: 태스크는 준비할 때 열쇠고리 하나와 주소 공간 하나에 묶이고(TCB_CONFIGURE) 그다음 시작됩니다(TCB_RESUME). 태스크는 차례를 돌아가며 실행되고, 너무 오래 도는 태스크는 타이머가 끊습니다(타이머 선점이 있는 라운드 로빈 스케줄링). 태스크는 자기 차례를 양보하거나(YIELD) 끝낼 수 있습니다(EXIT).
- **메시지**: 태스크는 프로세서 레지스터에 담긴 짧은 메시지를 주고받습니다. 보내는 쪽은 받는 쪽이 메시지를 가져갈 때까지 기다립니다(동기 IPC: SEND, RECV, CALL, REPLY_RECV). 보내려면 우편함 열쇠에 쓰기 권한이, 받으려면 읽기 권한이 있어야 합니다. 받는 쪽은 보낸 쪽 열쇠의 표식을 알게 되고, 답장할 권리는 한 번만 사용할 수 있습니다.
- **타임아웃**: 이 호출들은 모두 제한 시간을 줄 수 있습니다. 단위는 타이머 틱입니다(1틱은 1초). 제한 시간 안에 상대가 오지 않으면 호출이 오류(`TIMEOUT`, 또는 `CALL`이 전달됐지만 답이 오지 않은 경우 `REPLY_TIMEOUT`)로 돌아옵니다. 제한 시간을 주지 않으면 태스크는 필요한 만큼 계속 기다립니다. 기다리는 시간은 준 틱 수 이상이며 조금 더 길 수 있습니다. 제한 시간은 태스크가 다시 준비 상태가 되는 때를 정할 뿐, 실행되는 때를 정하지는 않습니다.
-- **대기 상태**: 실행할 수 있는 태스크가 없어도 커널은 더 이상 멈추지 않습니다. 다음 인터럽트를 기다리다가, 제한 시간이 지난 태스크를 깨우고 계속 진행합니다. 태스크를 깨울 수 있는 것이 아무것도 없으면 기계는 대기 상태로 남고, 부트 로그에 `k0: all tasks stopped (none ready, no timeout pending)`이 찍힙니다.
+- **대기 상태**: 실행할 수 있는 태스크가 없어도 커널은 더 이상 멈추지 않습니다. 다음 인터럽트를 기다리다가, 제한 시간이 지난 태스크를 깨우고 계속 진행합니다. 태스크를 깨울 수 있는 것이 아무것도 없으면 기계는 대기 상태로 남고, 부트 로그에 `k0: all tasks stopped (none ready, no timeout pending)`이 찍힙니다. 시간 제한이 걸린 대기도, 콘솔 입력을 기다리는 태스크도 없을 때만 이 줄이 찍힙니다. 터미널 이미지는 입력을 기다리는 것이 정상이라 아무것도 출력하지 않습니다.
- **부팅 때 크기를 정하는 커널 표**: 커널은 자신이 쓸 페이지 테이블과 주소 공간 항목의 메모리를 부팅할 때 따로 떼어 둡니다. 크기는 커널이 내어 주는 메모리에 비례합니다(RAM의 약 0.4 %). 그래서 태스크가 이 표들을 다 사용해 버릴 수 없고, 주소 공간의 수는 메모리로만 제한됩니다.
- **충돌 격리**: 태스크가 죽거나, 커널이 모르는 시스템 콜을 부르거나, 끝나면 그 태스크만 멈춥니다(폴트 격리).
- **태스크 격리와 열쇠 회수**: 서로 다른 열쇠고리와 주소 공간에 묶인 태스크는 서로의 메모리와 열쇠에 닿을 수 없습니다. 모든 열쇠는 어느 열쇠에서 복사됐는지 기억합니다(파생 목록). 열쇠를 회수하거나(CAP_REVOKE) 지우면(CAP_DELETE) 다음 일이 일어납니다.
@@ -148,11 +150,28 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
- **서명 오라클(선택 사항)**: 다른 프로그램을 위해 일하는 첫 번째 서비스입니다. 디지털 서명은 어떤 메시지를 비밀 키를 가진 쪽이 승인했음을 보여 주는 짧은 값이고, 짝이 되는 공개 키가 있으면 누구나 검증할 수 있습니다. 서명 오라클은 다른 프로그램의 메시지에 서명해 주면서 비밀 키는 절대 보여 주지 않는 프로그램입니다. K0에서는 볼트 태스크가 키 하나를 가집니다. 클라이언트 태스크는 우편함(IPC)으로 메시지를 보내 서명 또는 공개 키를 받지만 키는 받지 못합니다. 볼트는 자기만의 주소 공간에서 실행되므로 루트 태스크 이외의 어떤 태스크도 볼트의 메모리를 매핑할 수 없습니다.
- **기본값은 꺼짐**: 커널 크레이트의 Cargo features 두 개로 추가합니다. `vault`는 서명 알고리즘 없이 서비스만 추가하며, 모든 서명 요청에 "unsupported"로 답합니다. `vault-ed25519`는 알고리즘을 추가합니다. 예를 들어 `cargo build -p k0-kernel --features console,vault-ed25519`입니다. 볼트의 코드는 루트 태스크 이미지의 일부이고 이전과 같이 부팅 때 검사하며, 부팅 뒤에는 아무것도 적재하지 않습니다. 기본 이미지에는 볼트 코드도 암호 코드도 없습니다.
- **알고리즘**: Ed25519(FIPS 186-5와 RFC 8032의 SHA-512를 쓰는 PureEdDSA)입니다. 구현은 vendor에 둔 크레이트 `ed25519-dalek` 2.2.0이며 어떤 종류의 검증도 받지 않았습니다. 키는 승인된 난수 비트 생성기에서 나오지 않습니다.
- - **누가 무엇을 할 수 있나**: 규칙은 빌드 때 고정되며, 커널이 각 메시지에 붙이는 표식(배지)에 따라 정해집니다. 클라이언트는 이 표식을 위조할 수 없습니다. 루트 태스크는 관리자로서 상태 조회, 키 생성(INIT, 한 번만), 키 소거(ZEROIZE)를 할 수 있지만 서명은 할 수 없습니다. 서명자는 상태와 공개 키를 조회하고 서명할 수 있습니다. 읽기 전용 역할은 상태와 공개 키만 조회할 수 있습니다. 알려진 표식이 없는 호출은 거부합니다. 서명자는 모두 키 하나를 공유하므로 서명만으로는 어느 클라이언트가 요청했는지 알 수 없습니다.
- - **키**: 볼트는 부팅 시드에 충분한 무작위성(디바이스 트리 `rng-seed` 32바이트 이상 또는 프로세서의 난수 명령 RNDR에서 256비트)이 있을 때만 키를 만들고, 그렇지 않으면 거부합니다. 커널은 루트 태스크를 시작하기 직전에 받은 디바이스 트리 안의 시드 바이트를 0으로 지우며, 부트 로그에 `k0: dtb seeds wiped B`가 찍힙니다. 시드는 입력만큼만 좋습니다. 펌웨어나 UEFI 로더가 따로 가진 사본은 지우지 못합니다.
- - **자가 테스트**: `vault`를 포함해 빌드한 이미지는 모두 루트 태스크에서 테스트를 실행합니다. 루트 태스크가 관리자와 여러 클라이언트를 연기합니다. 이 테스트는 배지 없는 호출의 거부, 키가 한 번만 만들어짐, 관리자가 서명하지 못함, 서명자가 받은 서명이 검증되고 바뀐 메시지에서는 실패함, 읽기 전용 역할이 서명하지 못함, 읽기 전용 응답 메모리에 쓰거나 다른 클라이언트의 요청을 읽는 클라이언트가 폴트로 멈춤, ZEROIZE 뒤 서명 거부를 확인하고 `root: oracle tests pass`로 끝납니다. 테스트 클라이언트는 한 주소 공간에서 차례로 실행되므로, 이 테스트가 보여 주는 것은 볼트와 클라이언트 사이의 격리이며 클라이언트끼리의 격리가 아닙니다.
+ - **누가 무엇을 할 수 있나**: 규칙은 빌드 때 고정되며, 커널이 각 메시지에 붙이는 표식(배지)에 따라 정해집니다. 클라이언트는 이 표식을 위조할 수 없습니다. 역할은 네 가지입니다. 루트 태스크는 관리자로서 상태 조회, 시드 전달(INIT, 한 번만), 키 생성(KEYGEN), 키 소거(ZEROIZE)를 할 수 있지만 서명은 할 수 없습니다. 운영자(터미널)는 상태 조회, 공개 키 조회, 키 생성, 키 소거만 할 수 있고 서명도 시드 전달도 할 수 없습니다. 서명자는 상태와 공개 키를 조회하고 서명할 수 있습니다. 읽기 전용 역할은 상태와 공개 키만 조회할 수 있습니다. 알려진 표식이 없는 호출은 거부합니다. 서명자는 모두 키 하나를 공유하므로 서명만으로는 어느 클라이언트가 요청했는지 알 수 없습니다.
+ - **키**: INIT은 부팅 시드를 전달할 뿐입니다. 볼트는 시드에 충분한 무작위성(디바이스 트리 `rng-seed` 32바이트 이상 또는 프로세서의 난수 명령 RNDR에서 256비트)이 있을 때만 시드를 받아 두고(`seeded`), 그렇지 않으면 거부합니다. KEYGEN이 받아 둔 시드로 고른 알고리즘의 키를 만들고 시드를 지웁니다(`ready`). 키는 부팅마다 하나뿐이어서 두 번째 KEYGEN은 거부되고, ZEROIZE 뒤에는 재부팅이 필요합니다. 커널은 루트 태스크를 시작하기 직전에 받은 디바이스 트리 안의 시드 바이트를 0으로 지우며, 부트 로그에 `k0: dtb seeds wiped B`가 찍힙니다. 시드는 입력만큼만 좋습니다. 펌웨어나 UEFI 로더가 따로 가진 사본은 지우지 못합니다.
+ - **자가 테스트**: `vault`를 포함해 빌드한 이미지는 모두 루트 태스크에서 테스트를 실행합니다. 루트 태스크가 관리자와 여러 클라이언트를 연기합니다. 이 테스트의 볼트는 공개된 RFC 8032 시험 시드로 키를 만들며, 엔트로피 규칙은 그대로 실행합니다. 테스트는 배지 없는 호출의 거부, 키가 한 번만 만들어짐, 관리자가 서명하지 못함, 서명자가 받은 서명이 검증되고 바뀐 메시지에서는 실패함, 읽기 전용 역할이 서명하지 못함, 읽기 전용 응답 메모리에 쓰거나 다른 클라이언트의 요청을 읽는 클라이언트가 폴트로 멈춤, ZEROIZE 뒤 서명 거부를 확인하고 `root: oracle tests pass`로 끝납니다. 테스트 클라이언트는 한 주소 공간에서 차례로 실행되므로, 이 테스트가 보여 주는 것은 볼트와 클라이언트 사이의 격리이며 클라이언트끼리의 격리가 아닙니다.
+
+- **운영자 터미널(선택 사항)**: 사람이 시리얼 줄로 명령을 입력해 서명 오라클의 볼트를 다루게 해 주는 태스크입니다. 서명 오라클에 키를 만들게 하고 공개 키를 읽고 키를 지울 수 있지만, 서명은 할 수 없습니다.
+ - **켜는 법**: 기본값은 꺼짐이고, 커널 크레이트의 Cargo feature `terminal`로 추가합니다. 볼트가 키를 만들려면 `vault-ed25519`도 필요합니다. 다음과 같이 빌드하고 QEMU에서 실행할 수 있습니다.
+
+ ```sh
+ $ cargo build -p k0-kernel --features console,terminal,vault-ed25519
+ $ cargo run -p k0-kernel --features console,terminal,vault-ed25519
+ ```
+
+ `cargo run` 아래에서는 QEMU 자신의 탈출 키가 Ctrl-A라서(Ctrl-A 다음 X로 QEMU 종료) Ctrl-A는 K0에 닿지 않습니다.
+ - **시작 순서**: 터미널 이미지는 자가 테스트를 모두 실행한 다음, 루트 태스크가 새 볼트를 시작해 부팅 시드를 건네고(`root: vault seeded`), 터미널과 똑같이 연결한 적대 태스크 둘이 거부되고 폴트로 끝나는지 확인한 뒤(`root: terminal wiring holds`), 자기 관리자 열쇠를 버리고 터미널을 시작합니다(`root: service started`). 그 뒤 배너 `K0 operator console, type 'help'`와 프롬프트 `k0> `가 나옵니다. 입력 경로가 없는 기계에서는 `root: no console input, terminal not started`가 나오고 터미널은 시작하지 않습니다.
+ - **명령**: `help`, `vault status`(볼트 상태), `vault pubkey`(공개 키), `vault keygen ed25519`(키 만들기), `vault zeroize confirm`(키 지우기)이 있습니다. `vault zeroize`만 입력하면 지우지 않고 `err confirm-required`가 나옵니다. 모든 명령은 `ok` 또는 `err <이유>` 한 줄로 끝납니다. `vault status`는 항상 `validated=no`를 출력합니다. 구현이 어떤 검증도 받지 않았기 때문입니다. 자세한 사용법과 예시 화면은 [USAGE_KR.md](USAGE_KR.md)에 있습니다.
+ - **입력 규칙**: 줄은 Enter(CR 또는 LF)로 끝나고 64자까지이며 출력할 수 있는 ASCII만 받습니다. Backspace와 DEL은 한 글자를 지우고, Ctrl-C와 Ctrl-U는 줄을 취소하며, 방향키 같은 ESC 열은 무시합니다. 프롬프트가 나오기 전에 UART에 도착한 바이트는 버립니다. 입력이 유실되면 다음 줄 끝까지 모두 버리고 `err input-lost`를 출력합니다.
+ - **커널이 하는 일**: 커널은 UART에서 받은 바이트를 256바이트 링에 쌓기만 하고 해석하지 않습니다. 태스크는 시스템 콜 `CONSOLE_READ`로 한 번에 한 바이트씩 가져가며, 한 번에 한 태스크만 기다릴 수 있습니다. 수신 인터럽트는 어떤 태스크가 처음 입력을 읽을 때까지 꺼져 있습니다. 그때 `k0: tick lines off (console input in use)` 한 줄을 남기고 주기적인 `k0: tick N` 줄이 멈추지만 타이머, 선점, 제한 시간은 계속 동작합니다. 링이 차면 커널이 수신 인터럽트를 스스로 막았다가 태스크가 절반을 가져간 뒤 다시 열어서, 입력이 몰려도 커널의 일은 읽는 쪽 속도로 제한됩니다. 부팅 때 `k0: console input on (pl011 irq 33)` 또는 `k0: console input off (<이유>)`가 출력됩니다. 틀린 인터럽트 번호는 입력만 끄고 부팅은 막지 않습니다.
+ - **인증이 없습니다**: 시리얼 줄을 쥔 사람이 곧 운영자이고, 운영자의 네 가지 일(상태, 공개 키, 키 만들기, 키 지우기)을 모두 할 수 있습니다. 키를 지워 서비스를 멈추게 하는 것까지 포함하며, 이것은 설계에 따른 것입니다. 서명을 받거나 정책을 바꾸지는 못합니다.
+ - **화면을 믿으면 안 됩니다**: 커널 줄이 입력 도중에 끼어들면 화면의 줄은 갈라져 보이지만 입력 버퍼는 온전하고, Enter를 치면 버퍼 전체가 실행됩니다. 콘솔 출력을 가진 태스크는 커널이나 루트 태스크 줄처럼 보이는 줄을 아무거나 출력할 수 있어서 줄 머리말은 아무것도 증명하지 않습니다. 터미널은 거기에 더해 자기 줄 안에서 글자를 지울 수 있습니다(백스페이스 출력).
+ - **알려진 한계**: 터미널과 볼트는 죽어도 다시 시작하지 않습니다(루트 태스크는 신뢰합니다). 서비스 모드에는 서명을 요청하는 클라이언트가 아직 없어서 키는 만들고 보여 줄 뿐 다른 태스크가 쓰지 못합니다(클라이언트의 서명은 자가 테스트가 보여 줍니다). 터미널 출력은 부트 로그의 사용자 몫을 차지하므로, 그 몫이 차면 이후 태스크 출력은 기록되지 않습니다.
-위 항목은 전부 루트 태스크가 부팅할 때마다 자가 테스트로 확인합니다. 서명 오라클은 그것을 포함해 빌드한 이미지에서 테스트합니다.
+위 항목은 전부 루트 태스크가 부팅할 때마다 자가 테스트로 확인합니다. 서명 오라클과 터미널은 그것을 포함해 빌드한 이미지에서 테스트합니다.
## 어디서 돌려 봤나
@@ -165,7 +184,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
> [!NOTE]
> 앞의 두 단계만 지원한다고 말할 수 있습니다.
-- **1단계**: `tools/boot-matrix.sh`가 확인합니다(CI가 QEMU 7.2로 실행).
+- **1단계**: `tools/boot-matrix.sh`가 확인합니다(CI가 QEMU 7.2로 실행). 행은 HVF가 있는 로컬에서 76개, CI에서 65개입니다.
- **직접 부팅 행**
- GICv3와 GICv2의 QEMU virt를 각각 EL1과 EL2로 진입
- CPU 모델 cortex-a72, cortex-a53, max
@@ -187,6 +206,8 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
- 로더 PE 파일의 형식과 캐시·MMU 명령의 순서에 대한 정적 검사(`tools/pe-check.py`)
- **ACPI 행**: `uefi-acpi-gic3-el1`, `uefi-acpi-gic3-el2`, `uefi-acpi-gic2-el1`, `uefi-acpi-smp4`, `uefi-acpi-16k`, `uefi-acpi-rng` 행은 ACPI를 켠 기본 QEMU 머신을 디바이스 트리 없이 테이블만으로 부팅합니다.
- **서명 오라클 행**: `vault`, `vault-max`(RNDR 포함), `vault-el2`, `vault-16k`, `vault-no-alg`(서명 알고리즘 없음), `hvf-vault`(HVF가 있는 Mac에서만)는 오라클을 포함한 이미지를 부팅해 그 자가 테스트를 판정합니다. 정적 행 `vault-symbols`는 기본 이미지에 볼트 코드와 암호 코드가 없는지 확인합니다.
+ - **입력 행**: `input-only`, `input-gicv2`, `input-16550`, `input-bad-irq`는 입력 경로를 켠 이미지를 부팅해 입력이 켜졌는지(또는 꺼져야 하는 곳에서 꺼졌는지)와 그 자가 테스트를 판정합니다. 정적 행 `input-symbols`는 입력 feature 없이 빌드한 이미지에 수신 코드, `CONSOLE_READ`, 새 로그 줄이 없는지 확인합니다.
+ - **터미널 행**: `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k`, `term-no-vault`, `term-no-alg`, `term-uefi`, `term-uefi-acpi`, `hvf-term`(HVF가 있는 Mac에서만)은 터미널 이미지를 부팅합니다. `tools/term-test.py <이미지>`는 QEMU의 시리얼 포트를 파이프로 이어 모든 명령과 오류, 지우기와 취소, 너무 긴 줄, 키 생성과 공개 키 형식, 키 소거, 줄 끝 없는 200 kB, 연속 2000줄, 시리얼 break까지 정해 둔 대화를 그대로 실행합니다.
- **거부 확인**: 시리얼 로그로 확인하는 거부는 두 가지입니다.
- 16 KiB 페이지가 없는 CPU에서의 16 KiB 이미지
- 내장 커널의 한 바이트를 뒤집은 로더
@@ -217,6 +238,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
- 모든 실제 보드, KVM, Firecracker, Cloud Hypervisor, crosvm
- **16550 콘솔 드라이버**: 매트릭스의 어떤 머신에도 없어서 어떤 테스트도 실행한 적이 없고, 리뷰로만 확인했습니다.
- **SBSA UART**: 식별 검사 없이 PL011 드라이버를 사용합니다.
+ - **입력의 일부**: 16550 콘솔에는 입력이 없습니다. SBSA UART의 수신 경로, FIFO 넘침, 수신 시간 초과 인터럽트는 QEMU가 실행하지 않아서 가짜 UART를 쓰는 호스트 테스트로만 확인했습니다. 설명 없이 계속 울리는 인터럽트 선을 끊는 장치도 호스트 테스트로만 확인했습니다. 입력이 몰릴 때 커널이 쓰는 시간을 실제 기계에서 잰 테스트는 없고, 상한은 설계에서 따져 보고 호스트 테스트로 보인 것입니다.
- **콘솔 없는 feature 조합의 릴리즈(LTO) 이미지**: 매트릭스는 디버그 이미지만 빌드하고 부팅하며 심볼 검사도 거기서 합니다.
- UEFI로 부팅한 콘솔 없는 이미지
- 실제 하드웨어의 보안 확장이 있는 GIC
@@ -254,6 +276,9 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
- 커널 안의 치명적 오류, 또는 커널이 한 태스크의 탓으로 돌릴 수 없는 하드웨어 오류는 여전히 기계 전체를 멈춥니다.
- 부트 로그의 커널 부분은 충돌과 종료 줄로 가득 찰 수 있습니다.
- 서명 오라클도 예외가 아닙니다. 클라이언트는 볼트로 가는 우편함 하나를 함께 사용하므로 모든 호출에 타임아웃을 줘야 하며, 그렇지 않으면 멈춘 볼트가 클라이언트를 붙잡습니다.
+ - 입력을 켠 이미지에서는 바깥 쪽이 태스크가 실행되는 동안에도 인터럽트를 일으킬 수 있습니다. 그 횟수는 읽는 쪽 속도로 제한되지만, 읽는 태스크는 타이머 틱보다 더 잘게 도착 시각을 알 수 있고 다른 태스크도 빼앗긴 시간을 눈치챌 수 있습니다. 이 시간 채널은 분석하지 않았습니다.
+ - 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없어서 지연은 준비된 태스크마다 최대 한 틱입니다.
+ - 입력 수신 코드는 커널(EL1)에서 실행됩니다. 작고 바이트를 해석하지 않지만, 바깥 쪽이 움직이는 커널 코드입니다. 이것을 사용자 공간 드라이버로 옮기려면 장치와 인터럽트를 넘겨 주는 기능이 필요한데, K0에는 아직 없습니다.
- **열쇠고리와 주소 공간을 함께 사용하는 태스크**: 이런 태스크끼리는 격리되지 않습니다. 모든 것을 함께 사용하는 한 프로그램의 일부, 즉 스레드처럼 동작합니다.
- **태스크 통제**: 어떤 태스크나 그 태스크의 열쇠고리, 주소 공간의 열쇠를 가진 쪽이 그 태스크를 통제합니다.
- **루트 태스크**: 모든 태스크, 열쇠고리, 주소 공간을 만들기 때문에 신뢰해야 하며 격리 바깥에 있습니다. 서명 오라클의 메모리와 그 안의 키를 읽을 수 있습니다. "루트 태스크 이외의 어떤 태스크도 볼트의 메모리를 매핑할 수 없다"만 성립합니다.
@@ -265,7 +290,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
없는 기능:
-- **입력**: 어떤 종류의 입력도 아직 없습니다. UART든 다른 장치든 읽는 코드가 없고, 입력 또는 터미널용 feature도 없습니다.
+- **입력의 나머지**: 콘솔 UART의 입력만 있습니다(PL011과 SBSA UART, 선택 사항). 16550 콘솔과 다른 장치의 입력은 아직 없습니다. 입력을 사용자 공간 드라이버로 처리하는 것도 아직 없습니다.
- **케이퍼빌리티 전송**: 메시지에 열쇠를 담아 다른 태스크에 넘기는 기능입니다(IPC를 통한 케이퍼빌리티 전송).
- **하드웨어 인터럽트 알림**: 하드웨어 인터럽트를 프로그램에 알려 주는 기능입니다(Notification 오브젝트).
- **죽은 태스크 통지**: 죽은 태스크를 멈추기만 하지 않고 처리 담당 태스크에 알려 주는 기능입니다.
@@ -277,9 +302,9 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
- 영속성이 없습니다. 키는 메모리에만 있고 재부팅이나 ZEROIZE 뒤에는 사라집니다.
- 키는 하나뿐이며, 키를 가져오거나 내보내는 방법이 없습니다.
- 양자내성(PQC) 알고리즘은 아직 없습니다.
- - 운영자 입력이 없습니다. 어떤 종류의 입력도 없으므로 아무도 명령을 입력할 수 없습니다.
+ - 운영자의 인증이 없습니다. 시리얼 줄에서 입력하는 터미널은 있지만 줄을 쥔 사람이 곧 운영자입니다. 서비스 모드에서 키를 쓰는 서명 클라이언트도 아직 없습니다.
- 구현은 검증받지 않았고, 이 커널에서 암호 크레이트의 타이밍·캐시 사이드 채널을 분석하지 않았으며, 부팅 시드 이외의 난수 비트 생성기도 없습니다.
- - QEMU(TCG와 HVF)에서만 실행했습니다.
+ - QEMU(TCG와 HVF)에서만 실행했고, 실제 하드웨어에서는 실행한 적이 없습니다.
- **서명 검증**: 루트 태스크를 커널과 따로 배포할 때의 디지털 서명(Ed25519) 검증입니다. 서명 오라클은 서명을 만들지만, 그 서명으로 루트 태스크를 검증하지는 않습니다.
- **실제 보드와 가상화 환경 부팅**: 실제 보드, 그리고 KVM·Firecracker·Cloud Hypervisor·crosvm에서의 부팅입니다(위 3단계).
- **EL3 진입과 정적 테이블 너머의 ACPI**: 이 둘은 없습니다.
@@ -317,6 +342,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
| `kernel/` | 커널 프로그램. 시작 어셈블리, 초기화 순서, 시스템 콜 처리(`syscall.rs`), 열쇠가 지워질 때의 정리(`object.rs`), 커널 이미지의 메모리 배치를 정하는 파일(링커 스크립트) |
| `crates/k0-abi` | 프로그램과 커널이 함께 사용하는 시스템 콜 번호, 에러 코드, 부팅 정보 레이아웃 |
| `crates/k0-arch` | 에러, 시스템 콜, 인터럽트 처리(예외), 사용자 모드 진입과 복귀, 인터럽트 컨트롤러와 타이머, PAC과 PAN, 부트 로그와 선택적 콘솔 드라이버 |
+| `crates/k0-conin` | 콘솔 입력의 수신 논리(링과 유실 표시). 가짜 UART로 호스트에서 테스트합니다 |
| `crates/k0-boot` | 디바이스 트리 파서, 내장된 루트 태스크 이미지와 무결성 검사, PAC 키 파생, 부트 메모리 창 탐색(로더와 공유) |
| `crates/k0-efi` | `unsafe` 없는 로더의 논리. UEFI 메모리 맵에서 RAM 계획, 펌웨어 디바이스 트리 고쳐 쓰기, 결과의 독립적인 재검사, 커널 이미지 헤더 검사. 점프 전에 결과에 커널 자신의 디바이스 트리 코드를 돌려 봅니다 |
| `crates/k0-cap` | 열쇠와 권한, 열쇠고리, 파생 목록, untyped 메모리, retype, revoke와 delete |
@@ -325,8 +351,9 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
| `crates/k0-sched` | 라운드 로빈 스케줄러 |
| `crates/k0-ipc` | 동기 메시지 |
| `loader/` | 빌드된 커널 이미지를 품고 시작시키는 UEFI 응용 프로그램(`k0-loader`, 타겟 `aarch64-unknown-uefi`). UEFI 호출, 흐름, 마지막의 캐시 비우기·MMU 끄기·점프 |
-| `userspace/root-task` | 첫 프로그램과 자가 테스트, 서명 오라클의 연결과 자가 테스트(`oracle.rs`) |
+| `userspace/root-task` | 첫 프로그램과 자가 테스트, 서명 오라클의 연결과 자가 테스트(`oracle.rs`), 터미널 서비스의 시작(`service.rs`) |
+| `userspace/k0-term` | 운영자 터미널. 줄 편집, 명령 해석, 볼트로 보내는 요청 |
| `userspace/k0-vault` | 서명 오라클 서비스. 프로토콜과 고정 정책, 요청 처리, 암호 크레이트를 감싸는 경계 |
-| `tools/` | QEMU 러너(`.efi`도 지원), 부팅 테스트, 부팅 매트릭스, 부트 로그 읽기, 호스트 테스트, 로더 빌드(`build-loader.sh`), PE와 명령 순서 검사(`pe-check.py`) |
+| `tools/` | QEMU 러너(`.efi`도 지원), 부팅 테스트, 부팅 매트릭스, 터미널 대화 테스트(`term-test.py`), 부트 로그 읽기, 호스트 테스트, 로더 빌드(`build-loader.sh`), PE와 명령 순서 검사(`pe-check.py`) |
| `ci/` | CI 빌드·테스트 이미지(`Dockerfile`)와 위협 모델(`threat_model.md`) |
| `vendor/` | 저장소 안에 함께 넣어 둔 서드파티 크레이트(`sha2`, `ed25519-dalek`과 그 의존성) |
diff --git a/README.md b/README.md
index ceae4f0..48112e4 100644
--- a/README.md
+++ b/README.md
@@ -34,6 +34,10 @@ K0 is a small operating system kernel for 64-bit ARM (AArch64) computers. It is
- **Write or run, never both**: no memory is writable and executable at the same time. The flip side is that no new code can become executable after boot, so programs cannot load new code.
- **Distrust of boot input**: the hardware description handed over at boot is checked as if an attacker wrote it.
- **Optional signing oracle**: a build option adds a task that signs messages for other tasks and never gives out its key. It is off by default, the Ed25519 implementation is unvalidated, and it keeps one key in memory only. See [INTRODUCTION.md](INTRODUCTION.md).
+- **Optional operator terminal**: a build option adds a screen on the serial line where a person types commands. It can make the signing oracle's key, read the public key and erase the key, but it cannot sign. It is off by default.
+
+> [!NOTE]
+> The terminal has no authentication, so whoever holds the serial line is the operator. Input exists only for the PL011 and the SBSA UART, and it has never been run on real hardware.
The first program checks these properties with self-tests on every boot.
@@ -48,6 +52,12 @@ $ cd k0
$ cargo virt
```
+To build an image with the terminal and run it in QEMU, you can enter the following. Under `cargo run`, Ctrl-A is QEMU's own escape key, so it never reaches K0.
+
+```sh
+$ cargo run -p k0-kernel --features console,terminal,vault-ed25519
+```
+
[USAGE.md](USAGE.md) explains what you need, how to read the output and how to run the automatic tests.
## Documents
diff --git a/README_KR.md b/README_KR.md
index 555bbfd..ac1bd08 100644
--- a/README_KR.md
+++ b/README_KR.md
@@ -34,6 +34,10 @@ K0는 64비트 ARM(AArch64) 컴퓨터용 작은 운영체제 커널입니다. Ru
- **쓰기와 실행은 동시에 불가**: 어떤 메모리도 쓰기와 실행이 동시에 되지 않습니다. 그 대가로 부팅 뒤에는 새 코드를 실행 가능하게 만들 수 없어서, 프로그램이 새 코드를 불러올 수 없습니다.
- **부팅 입력 불신**: 부팅 때 넘겨받는 하드웨어 설명은 공격자가 작성한 것처럼 검사합니다.
- **선택 사항인 서명 오라클**: 빌드 옵션으로 다른 태스크를 위해 메시지에 서명하고 키는 절대 내주지 않는 태스크를 추가합니다. 기본값은 꺼짐이고, Ed25519 구현은 검증받지 않았으며, 키는 하나를 메모리에만 둡니다. [INTRODUCTION_KR.md](INTRODUCTION_KR.md)를 참고하세요.
+- **선택 사항인 운영자 터미널**: 빌드 옵션으로 시리얼 줄에서 사람이 명령을 입력하는 화면을 추가합니다. 서명 오라클의 키를 만들고, 공개 키를 읽고, 키를 지울 수 있지만 서명은 할 수 없습니다. 기본값은 꺼짐입니다.
+
+> [!NOTE]
+> 터미널에는 인증이 없어서 시리얼 줄을 쥔 사람이 곧 운영자입니다. 입력은 PL011과 SBSA UART에만 있고, 실제 하드웨어에서는 실행해 본 적이 없습니다.
첫 프로그램이 부팅할 때마다 자가 테스트로 위 성질들을 확인합니다.
@@ -48,6 +52,12 @@ $ cd k0
$ cargo virt
```
+터미널을 켠 이미지를 빌드해 QEMU에서 실행하려면 다음과 같이 입력할 수 있습니다. `cargo run` 아래에서는 Ctrl-A가 QEMU의 탈출 키라서 K0에 닿지 않습니다.
+
+```sh
+$ cargo run -p k0-kernel --features console,terminal,vault-ed25519
+```
+
필요한 도구, 출력 읽는 법 및 자동 테스트 실행 방법은 [USAGE_KR.md](USAGE_KR.md)에 있습니다.
## 문서
diff --git a/SECURITY.md b/SECURITY.md
index e6f23e3..edd1d86 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -47,7 +47,7 @@ Treat every task as fully trusted in those versions.
### The current `main` branch (unreleased)
-The current `main` branch contains task isolation. No release or tag contains it yet, and its system call ABI is incompatible with `v0.1.0` (bootinfo layout version 3).
+The current `main` branch contains task isolation. No release or tag contains it yet, and its system call ABI is incompatible with `v0.1.0` (bootinfo layout version 4).
A confined task has the following properties:
@@ -55,7 +55,7 @@ A confined task has the following properties:
- **Address space**: every task runs in the address space named by an `AddrSpace` capability. A task reaches exactly the memory that the holder of its `AddrSpace` capability mapped into that address space.
- **Bindings**: both bindings are held as capabilities inside the task's TCB. If either capability is revoked or deleted, the task is torn down.
- **Scope of isolation**: isolation holds between tasks bound to different CNodes and address spaces. Tasks that share them, as the root task's helper threads do, are threads of one another. Whoever holds a task's TCB, CNode or AddrSpace capability controls that task.
-- **Rights**: capabilities carry rights (R, W, X). Rights can only be removed by `CAP_COPY`, never added. `Endpoint` capabilities can carry a badge, set once by `CAP_COPY`, which the receiver sees. Retyped frames never gain X, and X exists only on the root task's text frames, so no physical frame is writable in one place and executable in another.
+- **Rights**: capabilities carry rights (R, W, X). Rights can only be removed by `CAP_COPY`, never added. `Endpoint` capabilities can carry a badge, set once by `CAP_COPY`, which the receiver sees. The `Console` capability carries R (read input) and W (write output) in the same way. Retyped frames never gain X, and X exists only on the root task's text frames, so no physical frame is writable in one place and executable in another.
- **Derivation and teardown**: capabilities form a derivation list. `CAP_REVOKE` removes everything derived from a capability, `CAP_DELETE` also removes the slot, an object is finalized when its original capability is removed, and the underlying `Untyped` memory can then be retyped again. Retyped objects are zeroed before a capability to them exists.
- **Fault isolation**: a fault, an exit, or an unknown system call in a confined task terminates only that task.
@@ -71,15 +71,16 @@ What is still NOT provided on `main`:
- **Missing features**: no fault delivery to a handler task, no notifications, and no capability transfer over IPC.
- **Time visible to EL0**: EL0 still cannot read any hardware counter or timer. IPC timeouts give a task a clock as coarse as the scheduler tick (1 second) and a wake-up aligned to the timer interrupt. Whether that can be amplified into a usable timing source for cache or speculation attacks has not been analysed.
- **Sender after revoke**: a sender already queued on an endpoint still delivers once after its capability is revoked.
+- **Serial line**: in an image built with the features `console-input` or `terminal`, an outside party can reach the kernel through the serial line. The operator terminal has no authentication, an outside party can cause interrupts while tasks run, and input waits behind running tasks. See "Serial input and the operator terminal".
- **Cores**: one core only.
- **Executable code**: new executable code cannot be loaded after boot, so a confined task runs code from the root task image.
- **Supported scope**: only the evidence tiers in [INTRODUCTION.md](INTRODUCTION.md) count as supported. Real boards, KVM and other hypervisors, the 16550 console driver, and processors with `HCR_EL2.E2H` fixed to 1 have never been booted.
- **Device tree**: the device tree is not trusted, but it now supplies device addresses. A wrong or hostile device tree can point the console at another device. The kernel limits this: it checks the platform descriptor against the memory map, checks the identification registers of the GIC and the PL011 (the PL011 through a temporary probe mapping, so a device that fails the check is not left mapped; no such register exists for a 16550 or an SBSA UART, so those have no such check), maps a device page only after validation, bounds every console wait, and offers a pinned build (`K0_PIN`) that refuses a different platform. The pinned build compares values that come from the device tree, so it does not stop a hostile boot chain.
- **Device tree address**: the address of the device tree cannot be checked before the first read. The boot loader passes it in `x0`, and the kernel has no memory map until it has read that blob. The kernel refuses a null or misaligned address, an address at or above 2^47 and a range that overlaps the kernel image. It then maps the address as read-only normal memory and reads eight bytes. It reads further, up to 2 MiB, only if those bytes look like a device tree header. A boot loader that passes the address of a device therefore makes the kernel read device registers as if they were memory, and reading some registers has side effects. The mapping is cacheable, so the processor may fetch more of that page than the eight bytes the kernel asks for. The later check that the device tree lies inside declared memory uses the memory map from the same blob. The only write through this mapping happens once, after the blob was parsed and validated: right before the kernel enters the root task, it zeroes the `rng-seed` and `kaslr-seed` values (see "Boot seed and seed wipe" under "The signing oracle"). A second `/chosen` node is refused.
-- **Source of output**: kernel output and task output share one boot log, and in an image built with a console driver also one console. A line does not say who wrote it. A task that holds a `Console` capability can print a line that starts with `k0:`. The kernel replaces control bytes and limits how much of the boot log task output may use, but nothing that reads the console or the log, including `tools/qemu-boot-test.sh`, can treat a `k0:` line printed after `k0: entering root task (el0)` as written by the kernel. This includes the `k0: console drivers [...]` line (see "Optional console output").
+- **Source of output**: kernel output and task output share one boot log, and in an image built with a console driver also one console. A line does not say who wrote it. A task that holds a `Console` capability with the write right can print a line that starts with `k0:`. The kernel replaces control bytes and limits how much of the boot log task output may use, but nothing that reads the console or the log, including `tools/qemu-boot-test.sh`, can treat a `k0:` line printed after `k0: entering root task (el0)` as written by the kernel. This includes the `k0: console drivers [...]` line (see "Optional console output").
- **Trap to EL2**: isolation covers confidentiality and integrity, not availability. A trap to EL2 after the kernel has stepped down to EL1 parks the whole machine by design.
- **Entry at EL2**: entry at EL2 relies on the firmware contract that Linux also uses: an EL3 firmware must enable the fine-grained-trap and HCRX controls when those features exist.
-- **Root task**: the root task is still trusted and holds the initial `Untyped` capabilities, and `write_bootinfo` still exposes their physical addresses to it. In an image with the signing oracle it also builds the vault and could read the vault's memory (see "The signing oracle").
+- **Root task**: the root task is still trusted and holds the initial `Untyped` capabilities, and `write_bootinfo` still exposes their physical addresses to it. In an image with the signing oracle it also builds the vault and could read the vault's memory (see "The signing oracle"). In an image with the feature `terminal` it also starts the terminal task and is not restarted if the terminal or the vault dies.
> [!WARNING]
> Even on `main`, treat running untrusted code as experimental. The availability limits above still apply.
@@ -120,9 +121,9 @@ Limits and residual risks of the loader:
Input and output are optional in K0. You can select them with Cargo features of the kernel crate.
> [!NOTE]
-> A feature for input or for a terminal does not exist yet. Console output is the only thing you can select today.
+> Input exists only in an image built with the feature `console-input`, and only for the PL011 and the SBSA UART. A 16550 console has output and no input. See "Serial input and the operator terminal".
-Console output exists only in an image built with a console feature. No image has input. The following table lists the console features of `k0-kernel`.
+Console output exists only in an image built with a console feature. An image built without `console-input` has no input code at all. The following table lists the console features of `k0-kernel`.
| Feature | Drivers it includes |
| --- | --- |
@@ -130,7 +131,7 @@ Console output exists only in an image built with a console feature. No image ha
| `console-16550` | A transmit driver for the 16550 family |
| `console` | Both drivers above |
-These features only add console output and are never in `default`, so every build command names them. The following commands build the 4 KiB image with console and an image without console:
+These features only add console output and are never in `default`, like every feature of `k0-kernel`, so every build command names them. The following commands build the 4 KiB image with console and an image without console:
```sh
$ cargo build -p k0-kernel --features console --offline
@@ -148,7 +149,7 @@ What **an image without a console feature** removes:
What stays in **every image**:
- The kernel still finds and checks the console node of the device tree, with the same judgement, the same `K0_PIN` line and the same self-check in the UEFI loader. A device tree whose console fails the checks is refused even by an image that would never use the console.
-- The `DEBUG_PUTC` system call and the `Console` capability stay, and what a task prints still reaches the boot log.
+- The `DEBUG_PUTC` system call and the `Console` capability stay, and what a task prints still reaches the boot log. `DEBUG_PUTC` needs the write right (W) of the `Console` capability.
- The boot log stays.
- The UEFI loader prints its own lines through the firmware console before it exits boot services, whatever its embedded kernel was built with.
@@ -169,10 +170,58 @@ The limits are as follows:
1. The empty serial log of the `quiet` rows shows only that no byte reached the serial port of QEMU virt, which is a PL011. It says nothing about register reads. Those are covered by the symbol check and by the device page list, which is the kernel's own report.
2. The symbol check runs on debug images. Release (LTO) images of the feature sets without console are not built or booted by the matrix, and no image without console is booted through UEFI.
-3. The 16550 driver has never been executed by any test, because QEMU virt has no such UART. Its code was checked by review only. The SBSA UART uses the PL011 driver without an identity check. Nothing has run on real hardware.
+3. The 16550 driver has never been executed by any test, because QEMU virt has no such UART, and it has no input path. Its code was checked by review only. The SBSA UART uses the PL011 driver without an identity check. Nothing has run on real hardware.
4. An image without console reduces the output path, not what the kernel holds in memory. The boot log is plain kernel memory, and anyone who can read RAM or attach a debugger sees it.
5. A task that holds a `Console` capability can print lines that look like kernel lines, and that includes `k0: console drivers [...]`. Only the first occurrence of that line in the log, or the image file, identifies a build. The line is a label, not proof.
+## Serial input and the operator terminal
+
+Input is a second path for outside data into the kernel, so it is off by default and gets its own features. In the following table, both features of `k0-kernel` only add code and are never in `default`.
+
+| Feature | Adds |
+| --- | --- |
+| `console-input` | The kernel's receive path for the console UART and the system call `CONSOLE_READ`. It needs a console driver feature to do anything. Receive exists for the PL011 and the SBSA UART only. |
+| `terminal` | The operator terminal task in the root task image, started as a service after the self-tests. It turns `console-input` on. With `vault` the terminal is the vault's operator, and with `vault-ed25519` it can make an Ed25519 key. |
+
+> [!WARNING]
+> There is no authentication on the serial line. Whoever holds the line is the operator and can do exactly the operator's four operations (`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`), including erasing the key. The operator cannot get a signature, cannot deliver a seed and cannot change the policy.
+
+An image without `console-input` contains no receive code, no `CONSOLE_READ` and none of the new log lines (a static boot matrix row, `input-symbols`, checks this). An image without `terminal` has no terminal code.
+
+What the kernel does with input:
+
+- **Receive path**: the kernel's UART driver puts received bytes into a ring of 256 bytes. The kernel never interprets a byte. Loss (a FIFO overrun, a break, a framing or parity error) is marked on the byte after the hole.
+- **Reading input**: `CONSOLE_READ` (system call 16). The caller names a `Console` slot and flags (`NONBLOCK`, `FLUSH`, a timeout in ticks in bits 63..32, other bits refused with `BAD_FLAGS`). It returns one byte per call. Only one task can wait at a time, and a second reader gets `BUSY`. It returns `NO_DEVICE` when there is no input path or it was turned off. A waiter whose capability is deleted, revoked or moved wakes at once with `REVOKED`. A woken reader goes to the end of the ready queue, so input does not preempt.
+- **Console capability rights**: R (read input) and W (write output). `CAP_COPY` can only remove them. The root task's capability has W, and R only in images with `console-input`. `bootinfo::VERSION` is 4.
+- **Output filter**: unchanged, except that a `Console` capability with R (the terminal's) may also emit backspace (0x08). Every other control byte is still printed as `?`.
+- **Receive interrupts stay off** until a task first reads console input with the right. That first read discards what the device holds, and the periodic `k0: tick N` lines stop after one line `k0: tick lines off (console input in use)`. Ticks, preemption and timeouts keep working.
+- **Bound on interrupt work**: when the ring is full, the kernel masks the UART's receive interrupt itself and reopens it after the reader has taken half of the ring. Under a flood the interrupt rate is therefore bounded by the reader. The same drain also runs once per tick, so input still arrives, up to a tick late, when the interrupt does not.
+- **Interrupt number**: it comes from the device tree (`interrupts` of the console node: one SPI, level, active high, of the discovered GIC) or, through the UEFI loader, from the ACPI SPCR table. It is printed in the platform line (`k0: platform con=pl011@0x9000000,irq33 ...`) and is therefore pinned by `K0_PIN`. Pin strings made before this change no longer match and must be made again.
+- **A wrong interrupt number costs only the input path**: out of range or not available gives `k0: console input off (...)` at boot, and a line that keeps firing without a UART cause is switched off after 8 entries with `k0: console input off (interrupt N fired without a uart cause)`. A console node without a usable interrupt is not a boot refusal, and input is just off.
+- **Boot log**: `k0: console input on (pl011 irq 33)` or `k0: console input off ()`.
+
+What the terminal is:
+
+- **Isolation**: the terminal is a task in its own address space with two capabilities: a `Console` copy with R and W, and the vault endpoint with the send right and the operator badge. The vault's response frame is mapped read-only for it.
+- **Start**: after the self-tests, the root task starts a new vault, hands it the boot seed, runs two hostile tasks wired exactly like the terminal (they must be refused and end in a fault), drops its admin capability, starts the terminal and blocks for ever. The lines `root: terminal wiring holds` and `root: service started` report this. On a machine without an input path the root task prints `root: no console input, terminal not started`.
+- **Input rules**: a line is at most 64 printable ASCII characters. The terminal drops what reached the UART before the prompt, and a reported loss discards everything up to the next line end (`err input-lost`).
+
+The limits are as follows:
+
+1. The serial line is as trusted as whoever can reach it. The operator can erase the key, which is a denial of service by design.
+2. The kernel's receive code runs at EL1. It is small and never interprets bytes, but it is kernel code driven by an outside party. A user-space driver needs device and interrupt delegation, which K0 does not have.
+3. An outside party can now cause interrupts while tasks run, bounded by the reader. The reader learns arrival times finer than the tick, and other tasks can notice the stolen time. This is a timing channel that has not been analysed.
+4. Input waits behind running tasks. There are no priorities, so the latency is up to a tick per ready task.
+5. A 16550 console has no input. The SBSA UART path, FIFO overruns and the receive timeout interrupt are not exercised by QEMU, and host tests with a fake UART (`crates/k0-conin`) are their only coverage. The cut-off for an interrupt line that fires without a UART cause is covered by host tests only.
+6. No test measures kernel time under a flood on a machine. The bound is argued from the gate and shown in host tests.
+7. "Dropped before the prompt" counts bytes that reached the UART. An emulator or adapter that holds bytes back delivers them later, and QEMU does.
+8. If a kernel line appears while the operator is typing, the screen line is split but the buffer is whole, and Enter runs the whole buffer.
+9. Any task with `Console` output can still print lines that look like kernel or root task lines, and nothing authenticates the prefix. The terminal can additionally erase within its current line.
+10. No signing client exists in service mode. The vault's key is made and shown but not used by another task. Client signing is shown by the self-test.
+11. The terminal and the vault are not restarted if they die. The root task is trusted.
+12. Terminal output counts against the user share of the in-memory boot log. Once that share is full, later task output is not recorded there.
+13. The vault limits under "The signing oracle" all stay. Nothing ran on real hardware.
+
## The signing oracle
The signing oracle is the first service on top of the isolation core. A vault task holds one Ed25519 key. Client tasks get signatures and the public key over IPC and never the key. It is optional and off by default.
@@ -183,28 +232,30 @@ The signing oracle is the first service on top of the isolation core. A vault ta
What the oracle claims:
- **Key separation**: the key lives in the vault's own address space and stack. The root task builds the vault, and no other task can map the vault's memory. A client's CNode holds only a send-only, badged copy of the vault endpoint.
-- **Frame rights**: per caller there is a request frame (caller read-write, vault read-only) and a response frame (vault read-write, caller read-only), enforced by reduced-rights copies of the frame capabilities.
-- **Fixed policy**: the policy is fixed at build time and keyed by the endpoint badge, which the kernel delivers and a client cannot forge. Roles: admin (the root task: STATUS, INIT, ZEROIZE, not SIGN), signer (STATUS, PUBLIC_KEY, SIGN) and reader (STATUS, PUBLIC_KEY). A call without a badge or with an unknown badge is refused. No operation changes the policy.
+- **Frame rights**: per caller there is a request frame (caller read-write, vault read-only) and a response frame (vault read-write, caller read-only), enforced by reduced-rights copies of the frame capabilities. The operator has a response frame and no request frame. The vault decides from the badge and the operation alone which frame it reads or writes, and a request that claims a body its role cannot have is refused without touching memory.
+- **Fixed policy**: the policy is fixed at build time and keyed by the endpoint badge, which the kernel delivers and a client cannot forge. Four roles are fixed at build time: admin (the root task: STATUS, INIT, KEYGEN, ZEROIZE, not SIGN), operator (the terminal: STATUS, PUBLIC_KEY, KEYGEN, ZEROIZE, not SIGN and not INIT), signer (STATUS, PUBLIC_KEY, SIGN) and reader (STATUS, PUBLIC_KEY). A call without a badge or with an unknown badge is refused. No operation changes the policy.
- **Fixed image**: the vault code is part of the root task image, which is checked by SHA-256 at boot like before. Nothing is loaded after boot.
- **Single read of the request**: the vault reads the request body once into a private buffer, with the length fixed first, and uses only that copy. A reply always sets four registers: status, length, indicator bits and the caller's nonce. A client must trust the response frame only after an OK reply that carries its own nonce.
-- **Failure state**: a failed known-answer self-test (two RFC 8032 vectors) or a failed pairwise consistency test after key generation puts the vault into a failed state that refuses everything but STATUS. Verification is strict (`verify_strict`). There is no key export, and ZEROIZE drops the key and ends SIGN and PUBLIC_KEY.
+- **Failure state**: a failed known-answer self-test (two RFC 8032 vectors) or a failed pairwise consistency test after key generation puts the vault into a failed state that refuses everything but STATUS. Every way into the failed state wipes seed and key. Verification is strict (`verify_strict`). There is no key export, and ZEROIZE drops the key and ends SIGN and PUBLIC_KEY.
What the oracle does not claim:
1. The algorithm is Ed25519 (PureEdDSA with SHA-512, as in FIPS 186-5 and RFC 8032). The implementation is the vendored crate `ed25519-dalek` 2.2.0 and has no validation of any kind. The key does not come from an approved random bit generator.
2. There is no side-channel analysis of the crate on this kernel.
-3. There is one key, no persistence, no key import or export, no DRBG and no operator input. No post-quantum algorithm exists yet.
+3. There is one key per boot (a second KEYGEN is refused with `key-exists`, and after ZEROIZE a reboot is needed), no persistence, no key import or export and no DRBG. The only operator input is the serial terminal, which has no authentication (see "Serial input and the operator terminal"). No post-quantum algorithm exists yet.
4. All signers share the one key, so a signature carries no client identity.
-5. Availability of the vault is not protected. Clients share one endpoint and must use timeouts.
+5. Availability of the vault is not protected. Clients share one endpoint and must use timeouts, and the operator can erase the key.
6. The root task is trusted and could read the vault.
7. The oracle was only run in QEMU (TCG and HVF). The scrubs of stack copies (kernel boot stack, vault stack after signing) are best effort.
-8. The self-test runs its clients one after another in one client address space, so it shows isolation between the vault and a client, not between clients.
+8. The self-test runs its clients one after another in one client address space, so it shows isolation between the vault and a client, not between clients. It makes its key from the public RFC 8032 test seed, with the real seed information, so the entropy rule is still exercised.
+
+Seed and key: the vault has the states `fresh`, `seeded`, `ready`, `zeroized` and `failed`. INIT (admin only, once) only delivers the seed. The vault checks the entropy rule and holds the seed (`seeded`). KEYGEN (admin and operator) makes the key from the held seed with the chosen algorithm and wipes the seed (`ready`). A vault in an image without an algorithm refuses the seed and stays `fresh`, and an all-zero seed is refused.
-Entropy rule: the vault refuses to make a key (status `NO_ENTROPY`) unless the boot seed contains at least 32 bytes of `rng-seed` or 256 bits from RNDR. QEMU virt provides a 32-byte `rng-seed`. Every reply carries indicator bits: the algorithm is in FIPS 186-5, the self-tests passed, at least 32 `rng-seed` bytes went into the key seed, and RNDR went into the key seed. These bits report what happened. They are not a validation claim.
+Entropy rule: the vault refuses the boot seed (status `NO_ENTROPY`) unless the boot seed contains at least 32 bytes of `rng-seed` or 256 bits from RNDR. QEMU virt provides a 32-byte `rng-seed`. Every reply carries indicator bits: the algorithm is in FIPS 186-5, the self-tests passed, at least 32 `rng-seed` bytes went into the key seed, and RNDR went into the key seed. These bits report what happened. They are not a validation claim. The STATUS reply packs the state, the key's algorithm and the algorithms in the image into one word.
### Boot seed and seed wipe
-The kernel derives 32 bytes for the root task with SHA-256 under its own domain string from the device tree entropy, the counter and, when the CPU has RNDR, four fresh RNDR words. It is independent of the PAC keys by domain separation. The seed is as good as its inputs and no better. It reaches the root task in the entry registers `x0` to `x3`, and `x4` tells how many `rng-seed` bytes were used and whether RNDR contributed. It is not in the bootinfo page, and the root task prints only the source, never the seed.
+The kernel derives 32 bytes for the root task with SHA-256 under its own domain string from the device tree entropy, the counter and, when the CPU has RNDR, four fresh RNDR words. It is independent of the PAC keys by domain separation. The seed is as good as its inputs and no better. It reaches the root task in the entry registers `x0` to `x3`, and `x4` tells how many `rng-seed` bytes were used and whether RNDR contributed. It is not in the bootinfo page, and the root task prints only the source, never the seed. The real boot seed is used exactly once, by the service vault in images with `terminal` and `vault`. In every other image the root task wipes it at entry.
Right before the kernel enters the root task it zeroes the `rng-seed` and `kaslr-seed` bytes in the device tree: it switches the read-only alias entry of that page to read-write in place, writes zeros, cleans and invalidates the cache lines, switches it back and reads the bytes back. It then wipes its own copy in `BootInfo`, prints `k0: dtb seeds wiped B` and zeroes the boot stack below the live frames. Copies that the firmware or the UEFI loader keep, and anything in the live frames of the boot stack, are not wiped.
@@ -233,7 +284,7 @@ You can report a problem in the following ways:
- **Preferred**: open a draft security advisory at .
- **Alternative**: email the maintainer at . Include the affected commit hash, the platform (QEMU machine and CPU model, hypervisor, or board), the entry level (EL1 or EL2), the page size (4 KiB or 16 KiB), the `k0: platform ...` line from the boot log, and a reproduction if you have one.
-Isolation gaps in `v0.1.0` and earlier commits, and the availability and resource limits listed under "What is still NOT provided on `main`", are already known and **do not need to be filed again**. Isolation bypasses on the current `main` branch are welcome, for example a task reaching another task's memory or capabilities, a revoked capability that keeps working, or a stale mapping that survives unmap, revoke or address space destruction. Reports about the signing oracle are welcome, for example a key disclosure to a client, a policy bypass, or a reply that reaches the wrong caller. Reports about the UEFI loader are welcome too, for example a memory map or device tree that makes it hand the kernel memory that firmware still uses, or a refusal that does not happen. Reports about anything else, including boot-time memory map validation, exception handling, scheduler policy, and IPC state machines, are welcome.
+Isolation gaps in `v0.1.0` and earlier commits, and the availability and resource limits listed under "What is still NOT provided on `main`", are already known and **do not need to be filed again**. Isolation bypasses on the current `main` branch are welcome, for example a task reaching another task's memory or capabilities, a revoked capability that keeps working, or a stale mapping that survives unmap, revoke or address space destruction. Reports about the signing oracle are welcome, for example a key disclosure to a client, a policy bypass, or a reply that reaches the wrong caller. Reports about the serial input path and the operator terminal are welcome too, for example a byte stream that makes the kernel misbehave, a wake-up of the wrong task, or an operator operation beyond the four listed. Reports about the UEFI loader are welcome too, for example a memory map or device tree that makes it hand the kernel memory that firmware still uses, or a refusal that does not happen. Reports about anything else, including boot-time memory map validation, exception handling, scheduler policy, and IPC state machines, are welcome.
## Scope
@@ -243,7 +294,7 @@ The following picture shows how this document divides what is in scope, what is
-**In scope**: everything under `kernel/`, `crates/` (including `crates/k0-efi`), `loader/`, `userspace/root-task/` and `userspace/k0-vault` with its wiring in the root task. The UEFI loader is part of the boot chain, but it is code of this repository, so its handling of the memory map, the device tree and the kernel image is in scope.
+**In scope**: everything under `kernel/`, `crates/` (including `crates/k0-efi`), `loader/`, `userspace/root-task/` and `userspace/k0-vault` and `userspace/k0-term` with their wiring in the root task. The UEFI loader is part of the boot chain, but it is code of this repository, so its handling of the memory map, the device tree and the kernel image is in scope.
**Out of scope**: the rest of the boot chain before the kernel entry point (for example firmware, any other boot loader and the hypervisor), and the integrity of the kernel image itself. Kernel image signing is the boot chain's responsibility. Under UEFI that means Secure Boot in the firmware, because the loader's SHA-256 check is not a signature (see "The UEFI loader").
diff --git a/SECURITY_KR.md b/SECURITY_KR.md
index 84ff69f..29a5b96 100644
--- a/SECURITY_KR.md
+++ b/SECURITY_KR.md
@@ -47,7 +47,7 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다.
### 현재 `main` 브랜치(릴리즈 전)
-현재 `main` 브랜치에는 태스크 격리가 들어 있습니다. 아직 어떤 릴리즈나 태그에도 포함되지 않았고, 시스템 콜 ABI가 `v0.1.0`과 호환되지 않습니다(bootinfo 레이아웃 버전 3).
+현재 `main` 브랜치에는 태스크 격리가 들어 있습니다. 아직 어떤 릴리즈나 태그에도 포함되지 않았고, 시스템 콜 ABI가 `v0.1.0`과 호환되지 않습니다(bootinfo 레이아웃 버전 4).
격리된 태스크의 성질은 다음과 같습니다.
@@ -55,7 +55,7 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다.
- **주소 공간**: 태스크는 `AddrSpace` 케이퍼빌리티가 가리키는 주소 공간에서 실행됩니다. 태스크는 그 `AddrSpace` 케이퍼빌리티를 가진 쪽이 해당 주소 공간에 매핑해 준 메모리에만 접근합니다.
- **바인딩**: 두 바인딩은 모두 태스크의 TCB 안에 케이퍼빌리티로 보관됩니다. 둘 중 하나가 revoke되거나 삭제되면 그 태스크는 해체됩니다.
- **격리의 범위**: 격리는 서로 다른 CNode와 주소 공간에 묶인 태스크 사이에서 성립합니다. 루트 태스크의 보조 스레드처럼 같은 것을 함께 사용하는 태스크끼리는 서로의 스레드입니다. 태스크의 TCB, CNode, AddrSpace 케이퍼빌리티를 가진 쪽이 그 태스크를 통제합니다.
-- **권한**: 케이퍼빌리티는 권한(R, W, X)을 가집니다. 권한은 `CAP_COPY`로 줄이기만 할 수 있고 늘릴 수는 없습니다. `Endpoint` 케이퍼빌리티는 `CAP_COPY`로 한 번 설정하는 배지를 가질 수 있고, 수신자가 이 배지를 받습니다. retype된 프레임은 X를 얻을 수 없고 X는 루트 태스크의 text 프레임에만 있으므로, 어떤 물리 프레임도 한 곳에서 쓰기 가능하면서 다른 곳에서 실행 가능하지 않습니다.
+- **권한**: 케이퍼빌리티는 권한(R, W, X)을 가집니다. 권한은 `CAP_COPY`로 줄이기만 할 수 있고 늘릴 수는 없습니다. `Endpoint` 케이퍼빌리티는 `CAP_COPY`로 한 번 설정하는 배지를 가질 수 있고, 수신자가 이 배지를 받습니다. `Console` 케이퍼빌리티도 같은 방식으로 R(입력 읽기)과 W(출력 쓰기) 권한을 가집니다. retype된 프레임은 X를 얻을 수 없고 X는 루트 태스크의 text 프레임에만 있으므로, 어떤 물리 프레임도 한 곳에서 쓰기 가능하면서 다른 곳에서 실행 가능하지 않습니다.
- **파생과 해체**: 케이퍼빌리티는 파생 목록을 이룹니다. `CAP_REVOKE`는 파생된 모든 케이퍼빌리티를 제거하고, `CAP_DELETE`는 슬롯까지 제거합니다. 오브젝트는 원본 케이퍼빌리티가 제거될 때 finalize되며, 그 뒤 해당 `Untyped` 메모리를 다시 retype할 수 있습니다. retype된 오브젝트는 케이퍼빌리티가 만들어지기 전에 0으로 지워집니다.
- **폴트 격리**: 격리된 태스크의 폴트, 종료, 알 수 없는 시스템 콜은 그 태스크만 종료시킵니다.
@@ -71,15 +71,16 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다.
- **미구현 기능**: 핸들러 태스크로의 폴트 전달, 알림(notification), IPC를 통한 케이퍼빌리티 전송이 아직 없습니다.
- **EL0에서 보이는 시간**: EL0는 여전히 하드웨어 카운터나 타이머를 읽을 수 없습니다. IPC 타임아웃은 태스크에 스케줄러 틱(1초)만큼 거친 시계와 타이머 인터럽트에 맞춰진 깨어남을 제공합니다. 이것이 캐시나 추측 실행 공격에 쓸 만한 시간 원천으로 증폭될 수 있는지는 분석하지 않았습니다.
- **revoke 뒤의 송신자**: 엔드포인트에 이미 대기 중인 송신자는 케이퍼빌리티가 revoke된 뒤에도 한 번 전달됩니다.
+- **직렬 회선**: feature `console-input` 또는 `terminal`을 포함해 빌드한 이미지에서는 외부 당사자가 직렬 회선으로 커널에 닿을 수 있습니다. 운영자 터미널에는 인증이 없고, 외부 당사자가 태스크 실행 중에 인터럽트를 일으킬 수 있으며, 입력은 실행 중인 태스크 뒤에서 기다립니다("직렬 입력과 운영자 터미널" 참고).
- **코어 수**: 단일 코어만 지원합니다.
- **실행 코드**: 부팅 후에는 새 실행 코드를 로드할 수 없으므로, 격리된 태스크는 루트 태스크 이미지의 코드를 실행합니다.
- **지원 범위**: [INTRODUCTION_KR.md](INTRODUCTION_KR.md)의 증거 단계에 든 것만 지원한다고 봅니다. 실제 보드, KVM 등 다른 하이퍼바이저, 16550 콘솔 드라이버, `HCR_EL2.E2H`가 1로 고정된 프로세서는 한 번도 부팅한 적이 없습니다.
- **디바이스 트리**: 디바이스 트리는 신뢰하지 않지만, 이제 장치 주소를 여기서 가져옵니다. 잘못되었거나 악의적인 디바이스 트리가 콘솔을 다른 장치로 향하게 할 수 있습니다. 커널은 이를 다음과 같이 제한합니다. 플랫폼 기술자를 메모리 맵과 대조합니다. GIC와 PL011의 식별 레지스터를 확인합니다(PL011은 임시 프로브 매핑으로 확인하므로 확인에 실패한 장치는 매핑된 채 남지 않습니다. 16550과 SBSA UART에는 그런 레지스터가 없어서 이 확인이 없습니다). 검증이 끝난 뒤에만 장치 페이지를 매핑합니다. 콘솔 대기는 모두 시간 제한으로 묶습니다. 다른 플랫폼을 거부하는 고정 빌드(`K0_PIN`)도 제공합니다. 고정 빌드는 디바이스 트리에서 나온 값을 비교하므로 악의적인 부트 체인은 막지 못합니다.
- **디바이스 트리의 주소**: 디바이스 트리의 주소는 처음 읽기 전에 검사할 방법이 없습니다. 부트로더가 이 주소를 `x0`로 넘기는데, 커널은 그 블롭을 읽기 전에는 메모리 맵을 모릅니다. 커널은 널이거나 정렬이 맞지 않는 주소, 2^47 이상인 주소, 커널 이미지와 겹치는 구간을 거부합니다. 그런 다음 그 주소를 읽기 전용 일반 메모리로 매핑하고 8바이트를 읽습니다. 그 바이트가 디바이스 트리 헤더처럼 보일 때만 더 읽습니다(최대 2 MiB). 따라서 부트로더가 장치의 주소를 넘기면 커널은 장치 레지스터를 메모리처럼 읽게 되고, 일부 레지스터는 읽기만 해도 부작용이 생깁니다. 이 매핑은 캐시 가능한 메모리라서 프로세서가 커널이 요청한 8바이트보다 그 페이지를 더 많이 가져올 수 있습니다. 디바이스 트리가 선언된 메모리 안에 있는지 보는 나중의 검사는 같은 블롭에서 나온 메모리 맵을 사용합니다. 이 매핑으로 쓰기를 하는 것은 단 한 번뿐이며, 블롭을 파싱하고 검증한 뒤에 일어납니다. 커널은 루트 태스크에 진입하기 직전에 `rng-seed`와 `kaslr-seed` 값을 0으로 지웁니다("서명 오라클" 절의 "부트 시드와 시드 삭제" 참고). 두 번째 `/chosen` 노드는 거부합니다.
-- **출력의 출처**: 커널 출력과 태스크 출력은 부트 로그 하나를 함께 사용합니다. 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔 하나도 함께 사용합니다. 줄에는 누가 썼는지 표시가 없습니다. `Console` 케이퍼빌리티를 가진 태스크는 `k0:`로 시작하는 줄을 출력할 수 있습니다. 커널은 제어 바이트를 바꾸고 태스크 출력이 부트 로그에서 차지할 수 있는 양을 제한합니다. 그래도 콘솔이나 로그를 읽는 쪽은 `tools/qemu-boot-test.sh`를 포함해 누구도 `k0: entering root task (el0)` 뒤에 나온 `k0:` 줄을 커널이 쓴 것으로 믿을 수 없습니다. `k0: console drivers [...]` 줄도 여기에 포함됩니다("선택적 콘솔 출력" 참고).
+- **출력의 출처**: 커널 출력과 태스크 출력은 부트 로그 하나를 함께 사용합니다. 콘솔 드라이버를 포함해 빌드한 이미지에서는 콘솔 하나도 함께 사용합니다. 줄에는 누가 썼는지 표시가 없습니다. 쓰기 권한이 있는 `Console` 케이퍼빌리티를 가진 태스크는 `k0:`로 시작하는 줄을 출력할 수 있습니다. 커널은 제어 바이트를 바꾸고 태스크 출력이 부트 로그에서 차지할 수 있는 양을 제한합니다. 그래도 콘솔이나 로그를 읽는 쪽은 `tools/qemu-boot-test.sh`를 포함해 누구도 `k0: entering root task (el0)` 뒤에 나온 `k0:` 줄을 커널이 쓴 것으로 믿을 수 없습니다. `k0: console drivers [...]` 줄도 여기에 포함됩니다("선택적 콘솔 출력" 참고).
- **EL2 트랩**: 격리는 기밀성과 무결성을 다루고 가용성은 다루지 않습니다. 커널이 EL1로 내려온 뒤 EL2로 트랩이 오면 설계상 기계 전체를 멈춥니다.
- **EL2 진입**: EL2 진입은 Linux와 같은 펌웨어 약속을 전제로 합니다. EL3 펌웨어는 세분화된 트랩과 HCRX 제어 기능이 있으면 이를 켜 주어야 합니다.
-- **루트 태스크**: 루트 태스크는 여전히 신뢰 대상이며 최초의 `Untyped` 케이퍼빌리티를 가지고, `write_bootinfo`는 그 물리 주소를 루트 태스크에 계속 노출합니다. 서명 오라클이 있는 이미지에서는 루트 태스크가 볼트도 만들며 볼트의 메모리를 읽을 수 있습니다("서명 오라클" 참고).
+- **루트 태스크**: 루트 태스크는 여전히 신뢰 대상이며 최초의 `Untyped` 케이퍼빌리티를 가지고, `write_bootinfo`는 그 물리 주소를 루트 태스크에 계속 노출합니다. 서명 오라클이 있는 이미지에서는 루트 태스크가 볼트도 만들며 볼트의 메모리를 읽을 수 있습니다("서명 오라클" 참고). feature `terminal`이 있는 이미지에서는 터미널 태스크도 시작하며, 터미널이나 볼트가 죽어도 다시 시작하지 않습니다.
> [!WARNING]
> `main`에서도 신뢰하지 않는 코드의 실행은 실험적인 것으로 취급하세요. 위의 가용성 한계는 그대로 적용됩니다.
@@ -120,9 +121,9 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다.
K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Cargo features로 선택할 수 있습니다.
> [!NOTE]
-> 입력 또는 터미널용 feature는 아직 없습니다. 지금 선택할 수 있는 것은 콘솔 출력뿐입니다.
+> 입력은 feature `console-input`을 포함해 빌드한 이미지에만 있고, PL011과 SBSA UART에만 있습니다. 16550 콘솔에는 출력만 있고 입력이 없습니다("직렬 입력과 운영자 터미널" 참고).
-콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다. 입력은 어떤 이미지에도 없습니다. `k0-kernel`의 콘솔 feature는 다음과 같습니다.
+콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다. `console-input` 없이 빌드한 이미지에는 입력 코드가 전혀 없습니다. `k0-kernel`의 콘솔 feature는 다음과 같습니다.
| feature | 포함하는 드라이버 |
| --- | --- |
@@ -130,7 +131,7 @@ K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Car
| `console-16550` | 16550 계열의 송신 드라이버 |
| `console` | 위의 두 드라이버 모두 |
-이 feature는 콘솔 출력을 더하기만 하며 `default`에는 절대 추가하지 않습니다. 따라서 모든 빌드 명령이 이름을 직접 적습니다. 다음 명령은 각각 콘솔이 있는 4 KiB 이미지와 콘솔이 없는 이미지를 만듭니다.
+이 feature는 콘솔 출력을 더하기만 하며 `k0-kernel`의 모든 feature와 마찬가지로 `default`에는 절대 추가하지 않습니다. 따라서 모든 빌드 명령이 이름을 직접 적습니다. 다음 명령은 각각 콘솔이 있는 4 KiB 이미지와 콘솔이 없는 이미지를 만듭니다.
```sh
$ cargo build -p k0-kernel --features console --offline
@@ -148,7 +149,7 @@ $ cargo build -p k0-kernel --offline
**모든 이미지**에는 다음이 남습니다.
- 커널은 여전히 디바이스 트리의 콘솔 노드를 찾아 검사합니다. 판단 기준, `K0_PIN` 줄, UEFI 로더의 자가 검사가 모두 같습니다. 콘솔이 검사를 통과하지 못하는 디바이스 트리는 콘솔을 전혀 쓰지 않을 이미지도 거부합니다.
-- `DEBUG_PUTC` 시스템 콜과 `Console` 케이퍼빌리티가 남고, 태스크가 출력한 것은 여전히 부트 로그에 닿습니다.
+- `DEBUG_PUTC` 시스템 콜과 `Console` 케이퍼빌리티가 남고, 태스크가 출력한 것은 여전히 부트 로그에 닿습니다. `DEBUG_PUTC`에는 `Console` 케이퍼빌리티의 쓰기 권한(W)이 필요합니다.
- 부트 로그가 남습니다.
- UEFI 로더는 내장한 커널을 어떻게 빌드했든, 부트 서비스를 종료하기 전에는 자기 줄을 펌웨어 콘솔로 출력합니다.
@@ -169,10 +170,58 @@ $ grep -a 'k0: console drivers' <이미지 파일>
1. `quiet` 행의 비어 있는 직렬 로그는 PL011인 QEMU virt의 직렬 포트로 한 바이트도 나오지 않았다는 것만 보여 줍니다. 레지스터 읽기에 대해서는 아무것도 말하지 않습니다. 그것은 심볼 검사와, 커널 자신의 보고인 장치 페이지 목록이 다룹니다.
2. 심볼 검사는 디버그 이미지에서 실행합니다. 콘솔 없는 feature 조합의 릴리즈(LTO) 이미지는 매트릭스가 빌드하거나 부팅하지 않으며, 콘솔 없는 이미지를 UEFI로 부팅해 본 적도 없습니다.
-3. 16550 드라이버는 어떤 테스트로도 실행된 적이 없습니다. QEMU virt에 그런 UART가 없기 때문입니다. 코드는 리뷰로만 확인했습니다. SBSA UART는 식별 확인 없이 PL011 드라이버를 사용합니다. 실제 하드웨어에서 실행한 것은 없습니다.
+3. 16550 드라이버는 어떤 테스트로도 실행된 적이 없습니다. QEMU virt에 그런 UART가 없기 때문이며, 입력 경로도 없습니다. 코드는 리뷰로만 확인했습니다. SBSA UART는 식별 확인 없이 PL011 드라이버를 사용합니다. 실제 하드웨어에서 실행한 것은 없습니다.
4. 콘솔 없는 이미지가 줄이는 것은 출력 경로이지 커널이 메모리에 가진 내용이 아닙니다. 부트 로그는 평범한 커널 메모리이며, RAM을 읽거나 디버거를 붙일 수 있는 사람은 누구나 봅니다.
5. `Console` 케이퍼빌리티를 가진 태스크는 커널 줄처럼 보이는 줄을 출력할 수 있으며, `k0: console drivers [...]`도 여기에 포함됩니다. 로그에서 그 줄의 첫 번째 등장 또는 이미지 파일만이 빌드를 식별합니다. 이 줄은 증거가 아니라 표지입니다.
+## 직렬 입력과 운영자 터미널
+
+입력은 외부 데이터가 커널로 들어오는 두 번째 경로이므로 기본으로 꺼져 있고 자체 feature를 가집니다. 다음 표의 두 feature는 `k0-kernel`에서 코드를 더하기만 하며 `default`에는 절대 추가하지 않습니다.
+
+| feature | 추가하는 것 |
+| --- | --- |
+| `console-input` | 콘솔 UART용 커널 수신 경로와 시스템 콜 `CONSOLE_READ`입니다. 콘솔 드라이버 feature가 있어야 동작합니다. 수신은 PL011과 SBSA UART에만 있습니다. |
+| `terminal` | 루트 태스크 이미지 안의 운영자 터미널 태스크이며, 자가 시험 뒤에 서비스로 시작합니다. `console-input`을 켭니다. `vault`와 함께면 터미널이 볼트의 운영자가 되고, `vault-ed25519`와 함께면 Ed25519 키를 만들 수 있습니다. |
+
+> [!WARNING]
+> 직렬 회선에는 인증이 없습니다. 회선을 쥔 쪽이 운영자이며, 키를 지우는 것을 포함해 운영자의 네 연산(`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`)을 정확히 할 수 있습니다. 운영자는 서명을 받을 수 없고, 시드를 전달할 수 없으며, 정책을 바꿀 수 없습니다.
+
+`console-input` 없이 빌드한 이미지에는 수신 코드, `CONSOLE_READ`, 새 로그 줄이 전혀 없습니다(정적 부팅 매트릭스 행 `input-symbols`가 확인합니다). `terminal` 없이 빌드한 이미지에는 터미널 코드가 없습니다.
+
+커널이 입력으로 하는 일은 다음과 같습니다.
+
+- **수신 경로**: 커널의 UART 드라이버가 받은 바이트를 256바이트 링에 넣습니다. 커널은 바이트를 해석하지 않습니다. 손실(FIFO 오버런, 브레이크, 프레이밍 또는 패리티 오류)은 구멍 뒤의 바이트에 표시합니다.
+- **입력 읽기**: `CONSOLE_READ`(시스템 콜 16번). 호출자가 `Console` 슬롯과 플래그(`NONBLOCK`, `FLUSH`, 63..32비트의 틱 단위 타임아웃, 그 밖의 비트는 `BAD_FLAGS`로 거부)를 지정합니다. 호출마다 한 바이트를 돌려줍니다. 한 번에 한 태스크만 기다릴 수 있고 두 번째 읽는 쪽은 `BUSY`를 받습니다. 입력 경로가 없거나 꺼져 있으면 `NO_DEVICE`를 돌려줍니다. 기다리던 태스크의 케이퍼빌리티가 삭제, revoke 또는 이동되면 즉시 `REVOKED`로 깨어납니다. 깨어난 읽는 쪽은 준비 큐의 맨 뒤로 가므로 입력은 선점하지 않습니다.
+- **Console 케이퍼빌리티의 권한**: R(입력 읽기)과 W(출력 쓰기)입니다. `CAP_COPY`는 이를 줄이기만 할 수 있습니다. 루트 태스크의 케이퍼빌리티는 W를 가지며, R은 `console-input`이 있는 이미지에서만 가집니다. `bootinfo::VERSION`은 4입니다.
+- **출력 필터**: 바뀌지 않았습니다. 다만 R이 있는 `Console` 케이퍼빌리티(터미널의 것)는 백스페이스(0x08)도 내보낼 수 있습니다. 다른 제어 바이트는 여전히 `?`로 출력됩니다.
+- **수신 인터럽트는 꺼진 채로 둡니다**: 어떤 태스크가 권한을 가지고 처음 콘솔 입력을 읽을 때까지입니다. 그 첫 읽기가 장치에 있던 것을 버리고, 주기적인 `k0: tick N` 줄은 `k0: tick lines off (console input in use)` 한 줄을 남기고 멈춥니다. 틱, 선점, 타임아웃은 계속 동작합니다.
+- **인터럽트 작업의 상한**: 링이 가득 차면 커널이 UART의 수신 인터럽트를 스스로 마스크하고, 읽는 쪽이 링의 절반을 가져간 뒤 다시 엽니다. 따라서 폭주 중에도 인터럽트 빈도는 읽는 쪽이 정하는 만큼으로 제한됩니다. 같은 비우기가 틱마다 한 번 더 실행되므로, 인터럽트가 오지 않아도 입력은 최대 한 틱 늦게 도착합니다.
+- **인터럽트 번호**: 디바이스 트리(콘솔 노드의 `interrupts`: 찾아낸 GIC의 SPI 하나, 레벨, active high)에서, UEFI 로더를 거치면 ACPI SPCR 테이블에서 가져옵니다. 플랫폼 줄(`k0: platform con=pl011@0x9000000,irq33 ...`)에 출력되므로 `K0_PIN`이 고정합니다. 이 변경 이전에 만든 고정 문자열은 더 이상 맞지 않으므로 다시 만들어야 합니다.
+- **잘못된 인터럽트 번호가 치르는 비용은 입력 경로뿐입니다**: 범위를 벗어나거나 쓸 수 없으면 부팅 때 `k0: console input off (...)`가 나오고, UART 원인 없이 계속 발생하는 회선은 8번 진입한 뒤 `k0: console input off (interrupt N fired without a uart cause)`와 함께 꺼집니다. 쓸 수 있는 인터럽트가 없는 콘솔 노드는 부팅 거부 사유가 아니며 입력만 꺼집니다.
+- **부트 로그**: `k0: console input on (pl011 irq 33)` 또는 `k0: console input off ()`입니다.
+
+터미널의 정체는 다음과 같습니다.
+
+- **격리**: 터미널은 자기 주소 공간을 가진 태스크이며 케이퍼빌리티를 두 개 가집니다. R과 W가 있는 `Console` 사본, 그리고 송신 권한과 운영자 배지가 있는 볼트 엔드포인트입니다. 볼트의 응답 프레임은 터미널에 읽기 전용으로 매핑됩니다.
+- **시작**: 자가 시험이 끝나면 루트 태스크가 새 볼트를 시작하고 부트 시드를 넘기며, 터미널과 똑같이 연결한 적대적 태스크 둘을 실행하고(거부되어 폴트로 끝나야 합니다), 자신의 admin 케이퍼빌리티를 버리고, 터미널을 시작한 뒤 영원히 블록됩니다. `root: terminal wiring holds`와 `root: service started` 줄이 이를 보고합니다. 입력 경로가 없는 기계에서는 루트 태스크가 `root: no console input, terminal not started`를 출력합니다.
+- **입력 규칙**: 한 줄은 출력 가능한 ASCII 최대 64자입니다. 터미널은 프롬프트 전에 UART에 닿은 것을 버리고, 보고된 손실은 다음 줄 끝까지의 모든 것을 버립니다(`err input-lost`).
+
+한계는 다음과 같습니다.
+
+1. 직렬 회선은 그 회선에 닿을 수 있는 쪽만큼만 신뢰할 수 있습니다. 운영자는 키를 지울 수 있으며, 이는 설계상의 서비스 거부입니다.
+2. 커널의 수신 코드는 EL1에서 실행됩니다. 작고 바이트를 해석하지 않지만, 외부 당사자가 구동하는 커널 코드입니다. 사용자 공간 드라이버에는 장치와 인터럽트의 위임이 필요한데, K0에는 이것이 없습니다.
+3. 외부 당사자가 이제 태스크 실행 중에 인터럽트를 일으킬 수 있으며, 그 빈도는 읽는 쪽이 제한합니다. 읽는 쪽은 틱보다 정밀한 도착 시각을 알게 되고, 다른 태스크는 빼앗긴 시간을 알아챌 수 있습니다. 이것은 분석하지 않은 타이밍 채널입니다.
+4. 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 지연은 준비된 태스크마다 최대 한 틱입니다.
+5. 16550 콘솔에는 입력이 없습니다. SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU에서 실행되지 않으며, 가짜 UART를 쓰는 호스트 테스트(`crates/k0-conin`)가 유일한 검증입니다. UART 원인 없이 발생하는 인터럽트 회선을 끊는 동작도 호스트 테스트로만 검증합니다.
+6. 기계에서 폭주 중의 커널 시간을 측정한 테스트는 없습니다. 상한은 게이트에서 논증하고 호스트 테스트로 보입니다.
+7. "프롬프트 전에 버림"은 UART에 닿은 바이트를 센 것입니다. 바이트를 붙잡아 두는 에뮬레이터나 어댑터는 나중에 전달하며, QEMU가 그렇게 합니다.
+8. 운영자가 입력하는 동안 커널 줄이 나타나면 화면의 줄은 쪼개지지만 버퍼는 온전하며, Enter는 버퍼 전체를 실행합니다.
+9. `Console` 출력이 있는 모든 태스크는 여전히 커널 줄이나 루트 태스크 줄처럼 보이는 줄을 출력할 수 있으며, 접두어를 인증하는 것은 없습니다. 터미널은 추가로 자기 현재 줄 안에서 지울 수 있습니다.
+10. 서비스 모드에는 서명 클라이언트가 없습니다. 볼트의 키는 만들어지고 표시되지만 다른 태스크가 사용하지 않습니다. 클라이언트의 서명은 자가 시험이 보여 줍니다.
+11. 터미널과 볼트는 죽어도 다시 시작하지 않습니다. 루트 태스크는 신뢰 대상입니다.
+12. 터미널 출력은 메모리 안 부트 로그의 사용자 몫에 포함됩니다. 그 몫이 차면 이후 태스크 출력은 거기에 기록되지 않습니다.
+13. "서명 오라클"의 볼트 한계는 모두 그대로입니다. 실제 하드웨어에서 실행한 것은 없습니다.
+
## 서명 오라클
서명 오라클은 격리 코어 위에 올라가는 첫 번째 서비스입니다. 볼트 태스크 하나가 Ed25519 키 하나를 보관합니다. 클라이언트 태스크는 IPC로 서명과 공개 키를 받으며 키 자체는 받지 못합니다. 이 기능은 선택 사항이며 기본으로 꺼져 있습니다.
@@ -183,28 +232,30 @@ $ grep -a 'k0: console drivers' <이미지 파일>
오라클이 주장하는 것은 다음과 같습니다.
- **키 분리**: 키는 볼트 자신의 주소 공간과 스택에 있습니다. 루트 태스크가 볼트를 만들며, 루트 태스크 외의 어떤 태스크도 볼트의 메모리를 매핑할 수 없습니다. 클라이언트의 CNode에는 볼트 엔드포인트의 송신 전용 배지 사본만 들어 있습니다.
-- **프레임 권한**: 호출자마다 요청 프레임(호출자 읽기·쓰기, 볼트 읽기 전용)과 응답 프레임(볼트 읽기·쓰기, 호출자 읽기 전용)이 있으며, 권한을 줄인 프레임 케이퍼빌리티 사본으로 강제합니다.
-- **고정 정책**: 정책은 빌드 시점에 고정되고 엔드포인트 배지를 키로 삼습니다. 배지는 커널이 전달하므로 클라이언트가 위조할 수 없습니다. 역할은 admin(루트 태스크: STATUS, INIT, ZEROIZE, SIGN은 불가), signer(STATUS, PUBLIC_KEY, SIGN), reader(STATUS, PUBLIC_KEY)입니다. 배지가 없거나 알 수 없는 배지로 한 호출은 거부합니다. 정책을 바꾸는 연산은 없습니다.
+- **프레임 권한**: 호출자마다 요청 프레임(호출자 읽기·쓰기, 볼트 읽기 전용)과 응답 프레임(볼트 읽기·쓰기, 호출자 읽기 전용)이 있으며, 권한을 줄인 프레임 케이퍼빌리티 사본으로 강제합니다. operator에게는 응답 프레임만 있고 요청 프레임은 없습니다. 볼트는 배지와 연산만으로 어느 프레임을 읽고 쓸지 정하며, 역할이 가질 수 없는 본문이 있다고 주장하는 요청은 메모리를 건드리지 않고 거부합니다.
+- **고정 정책**: 정책은 빌드 시점에 고정되고 엔드포인트 배지를 키로 삼습니다. 배지는 커널이 전달하므로 클라이언트가 위조할 수 없습니다. 역할 넷이 빌드 시점에 고정됩니다. admin(루트 태스크: STATUS, INIT, KEYGEN, ZEROIZE, SIGN은 불가), operator(터미널: STATUS, PUBLIC_KEY, KEYGEN, ZEROIZE, SIGN과 INIT은 불가), signer(STATUS, PUBLIC_KEY, SIGN), reader(STATUS, PUBLIC_KEY)입니다. 배지가 없거나 알 수 없는 배지로 한 호출은 거부합니다. 정책을 바꾸는 연산은 없습니다.
- **고정 이미지**: 볼트 코드는 루트 태스크 이미지의 일부이며 이전처럼 부팅할 때 SHA-256으로 검사합니다. 부팅 후에는 아무것도 로드하지 않습니다.
- **요청을 한 번만 읽음**: 볼트는 길이를 먼저 확정한 뒤 요청 본문을 비공개 버퍼로 한 번만 읽고 그 사본만 사용합니다. 응답은 항상 레지스터 네 개(상태, 길이, 표시 비트, 호출자의 nonce)를 채웁니다. 클라이언트는 자신의 nonce가 담긴 OK 응답을 받은 뒤에만 응답 프레임을 신뢰해야 합니다.
-- **실패 상태**: 알려진 답 자가 시험(RFC 8032 벡터 두 개)이나 키 생성 뒤의 쌍 일관성 시험이 실패하면 볼트는 STATUS 외의 모든 것을 거부하는 실패 상태가 됩니다. 검증은 엄격 모드(`verify_strict`)입니다. 키를 내보내는 기능은 없고, ZEROIZE는 키를 버려 SIGN과 PUBLIC_KEY를 끝냅니다.
+- **실패 상태**: 알려진 답 자가 시험(RFC 8032 벡터 두 개)이나 키 생성 뒤의 쌍 일관성 시험이 실패하면 볼트는 STATUS 외의 모든 것을 거부하는 실패 상태가 됩니다. 실패 상태로 들어가는 모든 경로는 시드와 키를 지웁니다. 검증은 엄격 모드(`verify_strict`)입니다. 키를 내보내는 기능은 없고, ZEROIZE는 키를 버려 SIGN과 PUBLIC_KEY를 끝냅니다.
오라클이 주장하지 않는 것은 다음과 같습니다.
1. 알고리즘은 Ed25519(SHA-512를 쓰는 PureEdDSA, FIPS 186-5와 RFC 8032에 있음)입니다. 구현은 벤더링한 크레이트 `ed25519-dalek` 2.2.0이며 어떤 종류의 검증도 받지 않았습니다. 키는 승인된 난수 비트 생성기에서 나오지 않습니다.
2. 이 커널 위에서 크레이트의 부채널 분석은 하지 않았습니다.
-3. 키는 하나이고, 영속성, 키 가져오기·내보내기, DRBG, 운영자 입력이 없습니다. 양자 내성 알고리즘은 아직 없습니다.
+3. 키는 부팅마다 하나이고(두 번째 KEYGEN은 `key-exists`로 거부하며, ZEROIZE 뒤에는 재부팅이 필요합니다), 영속성, 키 가져오기·내보내기, DRBG가 없습니다. 운영자 입력은 인증이 없는 직렬 터미널뿐입니다("직렬 입력과 운영자 터미널" 참고). 양자 내성 알고리즘은 아직 없습니다.
4. 모든 signer가 키 하나를 공유하므로 서명에는 클라이언트 신원이 담기지 않습니다.
-5. 볼트의 가용성은 보호하지 않습니다. 클라이언트는 엔드포인트 하나를 공유하며 타임아웃을 사용해야 합니다.
+5. 볼트의 가용성은 보호하지 않습니다. 클라이언트는 엔드포인트 하나를 공유하며 타임아웃을 사용해야 하고, 운영자는 키를 지울 수 있습니다.
6. 루트 태스크는 신뢰 대상이며 볼트를 읽을 수 있습니다.
7. 오라클은 QEMU(TCG와 HVF)에서만 실행했습니다. 스택 사본(커널 부트 스택, 서명 뒤의 볼트 스택)의 삭제는 최선을 다하는 수준입니다.
-8. 자가 시험은 클라이언트를 하나의 클라이언트 주소 공간에서 차례로 실행하므로, 클라이언트 사이가 아니라 볼트와 클라이언트 사이의 격리를 보여 줍니다.
+8. 자가 시험은 클라이언트를 하나의 클라이언트 주소 공간에서 차례로 실행하므로, 클라이언트 사이가 아니라 볼트와 클라이언트 사이의 격리를 보여 줍니다. 자가 시험은 공개된 RFC 8032 테스트 시드로 키를 만들며, 실제 시드 정보를 함께 넘기므로 엔트로피 규칙은 여전히 시험됩니다.
+
+시드와 키는 다음과 같습니다. 볼트의 상태는 `fresh`, `seeded`, `ready`, `zeroized`, `failed`입니다. INIT(admin 전용, 한 번)은 시드를 전달하기만 합니다. 볼트는 엔트로피 규칙을 확인하고 시드를 보관합니다(`seeded`). KEYGEN(admin과 operator)은 보관한 시드에서 선택한 알고리즘으로 키를 만들고 시드를 지웁니다(`ready`). 알고리즘이 없는 이미지의 볼트는 시드를 거부하고 `fresh`에 머물며, 모두 0인 시드도 거부합니다.
-엔트로피 규칙은 다음과 같습니다. 볼트는 부트 시드에 `rng-seed` 바이트가 32바이트 이상 있거나 RNDR에서 온 256비트가 있지 않으면 키 생성을 거부합니다(상태 `NO_ENTROPY`). QEMU virt는 32바이트 `rng-seed`를 제공합니다. 모든 응답에는 표시 비트가 담깁니다. 알고리즘이 FIPS 186-5에 있는지, 자가 시험이 통과했는지, `rng-seed`가 32바이트 이상 키 시드에 들어갔는지, RNDR이 키 시드에 들어갔는지입니다. 이 비트는 일어난 일을 보고할 뿐 검증 주장이 아닙니다.
+엔트로피 규칙은 다음과 같습니다. 볼트는 부트 시드에 `rng-seed` 바이트가 32바이트 이상 있거나 RNDR에서 온 256비트가 있지 않으면 부트 시드를 거부합니다(상태 `NO_ENTROPY`). QEMU virt는 32바이트 `rng-seed`를 제공합니다. 모든 응답에는 표시 비트가 담깁니다. 알고리즘이 FIPS 186-5에 있는지, 자가 시험이 통과했는지, `rng-seed`가 32바이트 이상 키 시드에 들어갔는지, RNDR이 키 시드에 들어갔는지입니다. 이 비트는 일어난 일을 보고할 뿐 검증 주장이 아닙니다. STATUS 응답은 상태, 키의 알고리즘, 이미지에 있는 알고리즘을 한 워드에 담습니다.
### 부트 시드와 시드 삭제
-커널은 루트 태스크용 32바이트를 디바이스 트리 엔트로피, 카운터, CPU에 RNDR이 있으면 새 RNDR 워드 네 개로부터 자기만의 도메인 문자열을 붙인 SHA-256으로 유도합니다. 도메인 분리 덕분에 PAC 키와는 독립입니다. 시드는 입력만큼만 좋고 그 이상은 아닙니다. 시드는 진입 레지스터 `x0`~`x3`로 루트 태스크에 전달되며, `x4`가 사용한 `rng-seed` 바이트 수와 RNDR 기여 여부를 알려 줍니다. bootinfo 페이지에는 없고, 루트 태스크는 시드가 아니라 출처만 출력합니다.
+커널은 루트 태스크용 32바이트를 디바이스 트리 엔트로피, 카운터, CPU에 RNDR이 있으면 새 RNDR 워드 네 개로부터 자기만의 도메인 문자열을 붙인 SHA-256으로 유도합니다. 도메인 분리 덕분에 PAC 키와는 독립입니다. 시드는 입력만큼만 좋고 그 이상은 아닙니다. 시드는 진입 레지스터 `x0`~`x3`로 루트 태스크에 전달되며, `x4`가 사용한 `rng-seed` 바이트 수와 RNDR 기여 여부를 알려 줍니다. bootinfo 페이지에는 없고, 루트 태스크는 시드가 아니라 출처만 출력합니다. 실제 부트 시드는 `terminal`과 `vault`가 있는 이미지의 서비스 볼트가 정확히 한 번 사용합니다. 그 밖의 모든 이미지에서는 루트 태스크가 진입할 때 지웁니다.
커널은 루트 태스크에 진입하기 직전에 디바이스 트리의 `rng-seed`와 `kaslr-seed` 바이트를 0으로 지웁니다. 그 페이지의 읽기 전용 별칭 항목을 제자리에서 읽기·쓰기로 바꾸고, 0을 쓰고, 캐시 줄을 비우고 무효화한 뒤, 다시 되돌리고 바이트를 읽어 확인합니다. 그런 다음 `BootInfo` 안의 자기 사본을 지우고, `k0: dtb seeds wiped B`를 출력하고, 활성 프레임 아래의 부트 스택을 0으로 지웁니다. 펌웨어나 UEFI 로더가 보관한 사본과 부트 스택의 활성 프레임에 있는 것은 지우지 않습니다.
@@ -233,7 +284,7 @@ $ grep -a 'k0: console drivers' <이미지 파일>
- **권장**: 에서 draft advisory를 작성하세요.
- **대안**: 메인테이너 에게 메일을 보내세요. 영향을 받는 커밋 해시, 플랫폼(QEMU 머신과 CPU 모델, 하이퍼바이저 또는 보드), 진입 단계(EL1 또는 EL2), 페이지 크기(4 KiB 또는 16 KiB), 부트 로그의 `k0: platform ...` 줄, 재현 방법이 있으면 포함해 주세요.
-`v0.1.0` 이하의 격리 공백과, "`main`에서도 여전히 제공하지 않는 것"에 적은 가용성·자원 한계는 이미 알려진 문제이기 때문에 **다시 신고하실 필요는 없습니다**. 현재 `main` 브랜치의 격리 우회는 환영합니다. 예를 들어 한 태스크가 다른 태스크의 메모리나 케이퍼빌리티에 닿는 경우, revoke된 케이퍼빌리티가 계속 동작하는 경우, unmap·revoke·주소 공간 파괴 뒤에도 낡은 매핑이 남는 경우입니다. 서명 오라클에 관한 신고도 환영합니다. 예를 들어 클라이언트에 키가 노출되는 경우, 정책 우회, 엉뚱한 호출자에게 응답이 가는 경우입니다. UEFI 로더에 관한 신고도 환영합니다. 예를 들어 펌웨어가 아직 쓰는 메모리를 커널에 넘기게 만드는 메모리 맵이나 디바이스 트리, 일어나야 할 거부가 일어나지 않는 경우입니다. 그 외의 문제, 예를 들어 부팅 시 메모리 맵 검증, 예외 처리, 스케줄러 정책, IPC 상태 기계에 관한 신고는 언제든 환영합니다.
+`v0.1.0` 이하의 격리 공백과, "`main`에서도 여전히 제공하지 않는 것"에 적은 가용성·자원 한계는 이미 알려진 문제이기 때문에 **다시 신고하실 필요는 없습니다**. 현재 `main` 브랜치의 격리 우회는 환영합니다. 예를 들어 한 태스크가 다른 태스크의 메모리나 케이퍼빌리티에 닿는 경우, revoke된 케이퍼빌리티가 계속 동작하는 경우, unmap·revoke·주소 공간 파괴 뒤에도 낡은 매핑이 남는 경우입니다. 서명 오라클에 관한 신고도 환영합니다. 예를 들어 클라이언트에 키가 노출되는 경우, 정책 우회, 엉뚱한 호출자에게 응답이 가는 경우입니다. 직렬 입력 경로와 운영자 터미널에 관한 신고도 환영합니다. 예를 들어 커널을 오동작하게 만드는 바이트 열, 엉뚱한 태스크를 깨우는 경우, 나열한 네 가지를 넘는 운영자 연산입니다. UEFI 로더에 관한 신고도 환영합니다. 예를 들어 펌웨어가 아직 쓰는 메모리를 커널에 넘기게 만드는 메모리 맵이나 디바이스 트리, 일어나야 할 거부가 일어나지 않는 경우입니다. 그 외의 문제, 예를 들어 부팅 시 메모리 맵 검증, 예외 처리, 스케줄러 정책, IPC 상태 기계에 관한 신고는 언제든 환영합니다.
## 범위
@@ -243,7 +294,7 @@ $ grep -a 'k0: console drivers' <이미지 파일>
-**범위 안**: `kernel/`, `crates/`(`crates/k0-efi` 포함), `loader/`, `userspace/root-task/`, `userspace/k0-vault`(루트 태스크 안의 연결 코드 포함) 하위의 모든 코드입니다. UEFI 로더는 부트 체인의 일부이지만 이 저장소의 코드이므로, 메모리 맵과 디바이스 트리와 커널 이미지를 다루는 부분은 범위 안입니다.
+**범위 안**: `kernel/`, `crates/`(`crates/k0-efi` 포함), `loader/`, `userspace/root-task/`, `userspace/k0-vault`와 `userspace/k0-term`(루트 태스크 안의 연결 코드 포함) 하위의 모든 코드입니다. UEFI 로더는 부트 체인의 일부이지만 이 저장소의 코드이므로, 메모리 맵과 디바이스 트리와 커널 이미지를 다루는 부분은 범위 안입니다.
**범위 밖**: 커널 진입점 이전의 나머지 부트 체인(예: 펌웨어, 다른 부트로더, 하이퍼바이저)과 커널 이미지 자체의 무결성입니다(커널 이미지 서명은 부트 체인의 책임입니다). UEFI에서는 이것이 펌웨어의 Secure Boot를 뜻합니다. 로더의 SHA-256 검사는 서명이 아니기 때문입니다("UEFI 로더" 절 참고).
diff --git a/USAGE.md b/USAGE.md
index 7e8e692..87135b6 100644
--- a/USAGE.md
+++ b/USAGE.md
@@ -33,9 +33,9 @@ This builds the kernel with a console driver and starts it in QEMU. The boot mes
Input and output are optional in K0. You can select them with Cargo features of the kernel crate.
> [!NOTE]
-> A feature for input or for a terminal does not exist yet. Console output is the only thing you can select today.
+> Console input and the operator terminal are features too, but they are off by default. They are described in "Operator terminal" below.
-Console output exists only in an image built with a console feature. No image has input. `cargo virt` is an alias for `cargo run -p k0-kernel --features console`, so it always includes the console. The following picture shows where the output goes, depending on the features in the build.
+Console output exists only in an image built with a console feature. An image has input only if it was built with `console-input` or `terminal`. `cargo virt` is an alias for `cargo run -p k0-kernel --features console`, so it always includes the console. The following picture shows where the output goes, depending on the features in the build.
@@ -189,12 +189,112 @@ In the boot log you should see these lines, in addition to the lines in "Reading
- `k0: dtb seeds wiped 40B` and `root: boot seed from rng-seed bytes 0x0000000000000020 without rndr` (with `K0_QEMU_CPU=max` the second line ends with `and rndr`). QEMU virt provides a 32-byte `rng-seed`, which is `0x20`.
- Two more `k0: task fault` lines, 8 in total. They come from two clients that the self-test lets break the memory rules on purpose.
-- `root: oracle tests pass` before `root: sched tests pass`. This line means that all the checks of the oracle passed: the vault made its key from the boot seed, a signer got a signature that verifies, a changed message or signature does not verify, the admin and a reader were refused when they asked to sign, and signing was refused after the key was erased.
+- `root: oracle tests pass` before `root: sched tests pass`. This line means that all the checks of the oracle passed: the vault made its key from the public RFC 8032 test seed, a signer got a signature that verifies, a changed message or signature does not verify, the admin and a reader were refused when they asked to sign, and signing was refused after the key was erased.
The vault makes a key only if the boot seed holds at least 32 `rng-seed` bytes or 256 bits from RNDR. If it does not, for example on a machine whose device tree has no `rng-seed` and whose CPU has no RNDR, the vault answers `NO_ENTROPY` and makes no key. The root task then prints `root: oracle made no key (boot seed has no entropy)` and stops the oracle test there. `root: oracle tests pass` does not appear, so a boot test that requires it fails, which is the intended result.
> [!NOTE]
-> The implementation of Ed25519 is the vendored crate `ed25519-dalek` 2.2.0 and has no validation of any kind, and the key does not come from an approved random bit generator. There is one key, no persistence, no key import or export and no input from an operator. The availability of the vault is not protected, because all clients share one endpoint and must use timeouts. The root task is trusted and could read the vault. The oracle was only run in QEMU (TCG and HVF). The details and the limits are in [SECURITY.md](SECURITY.md).
+> The implementation of Ed25519 is the vendored crate `ed25519-dalek` 2.2.0 and has no validation of any kind, and the key does not come from an approved random bit generator. There is one key, no persistence, no key import or export and no authentication of the operator. The availability of the vault is not protected, because all clients share one endpoint and must use timeouts. The root task is trusted and could read the vault. The oracle was only run in QEMU (TCG and HVF). The details and the limits are in [SECURITY.md](SECURITY.md).
+
+### Operator terminal
+
+The operator terminal is a small task that lets you type commands on the serial line and talk to the vault. It is optional and off by default. Two features of `k0-kernel` select it, and features only add.
+
+| Feature | Adds |
+| --- | --- |
+| `console-input` | The kernel's receive path for the console UART and the system call `CONSOLE_READ`. It needs a console driver feature to do anything. Receive exists for PL011 and SBSA UART only, so a 16550 console has output and no input |
+| `terminal` | The terminal task in the root task image, started as a service after the self-tests. It turns `console-input` on. With `vault` the terminal is the vault's operator. With `vault-ed25519` it can make an Ed25519 key |
+
+An image without `console-input` has no receive code, no `CONSOLE_READ` and none of the new log lines. An image without `terminal` has no terminal code. You can build and run it as follows:
+
+```sh
+$ cargo build -p k0-kernel --features console,terminal,vault-ed25519
+$ cargo run -p k0-kernel --features console,terminal,vault-ed25519
+```
+
+`cargo run` starts QEMU with the serial port on your terminal. QEMU's own escape key is `Ctrl-A` there (`Ctrl-A`, then `X` quits QEMU), so `Ctrl-A` never reaches K0.
+
+After the self-tests, the root task starts the vault, hands it the boot seed, runs two hostile tasks wired like the terminal (they must be refused and end in a fault), drops its admin capability and starts the terminal. The boot log shows `root: vault seeded`, `root: terminal console filter [...]`, `root: terminal wiring holds`, two `k0: task fault` lines, `root: service started` and then the banner. On a machine without an input path it shows `root: no console input, terminal not started`. After the first read, the periodic `k0: tick N` lines stop, and one line `k0: tick lines off (console input in use)` marks that. In the following session, every command ends with exactly one line, `ok` or `err `:
+
+```
+K0 operator console, type 'help'
+k0> vault status
+state=seeded
+alg=none
+selftest=passed
+seed=rng-seed
+validated=no
+ok
+k0> vault keygen ed25519
+state=ready
+alg=ed25519
+ok
+k0> vault pubkey
+pubkey=<32 hex characters>
+ <32 hex characters>
+ok
+k0> vault zeroize
+hint=type 'vault zeroize confirm' to erase the key
+err confirm-required
+k0>
+```
+
+Values are printed as `name=value`. The screen prompt is `k0> `. In the following table, the first column is what you type:
+
+| Command | Argument | What it does |
+| --- | --- | --- |
+| `help` | | Lists the commands |
+| `vault status` | | Prints the vault state (see below) |
+| `vault pubkey` | | Prints the public key |
+| `vault keygen ` | `ed25519` | Makes the key from the held seed with the chosen algorithm and wipes the seed |
+| `vault zeroize confirm` | | Erases the key. `vault zeroize` alone prints `hint=type 'vault zeroize confirm' to erase the key` and `err confirm-required` |
+
+`vault status` prints `state=fresh|seeded|ready|zeroized|failed`, `alg=none|ed25519`, `selftest=passed|failed`, `seed=none|rng-seed|rndr|rng-seed+rndr` and `validated=no`. `seed=rng-seed` means that the bytes were present, not that they were unpredictable. `validated=no` is always printed, because the implementation has no validation of any kind. `vault pubkey` prints `pubkey=` and 32 hex characters, then a second line indented by 7 spaces with the other 32. A vault makes one key per boot: a second `vault keygen` gives `err key-exists`, and after `vault zeroize confirm` you have to reboot. Without the `vault` feature, `help` lists only `help` and `vault ...` answers `err no-vault`.
+
+In the following table, the keys work on the line you are typing:
+
+| Key | Effect |
+| --- | --- |
+| Enter (CR or LF) | Runs the line. A line has at most 64 characters, printable ASCII only |
+| Backspace or DEL | Erases one character |
+| `Ctrl-C` or `Ctrl-U` | Cancels the line (shown as `^C` or `^U`) |
+| ESC sequences (arrow keys) | Ignored |
+
+Bytes that reached the UART before the prompt are dropped. If the input was lost (a FIFO overrun, a break, a framing or parity error), everything up to the next line end is discarded and the command answers `err input-lost`. A keygen or zeroize that was delivered but not answered in time adds `hint=run 'vault status' to see whether it took effect`. In the following table, the error names are what comes after `err `:
+
+| Error | Meaning |
+| --- | --- |
+| `unknown-command` | The command is not known |
+| `bad-argument` | An argument is wrong or missing |
+| `line-too-long` | The line is longer than 64 characters |
+| `input-lost` | Input was lost before the line end |
+| `confirm-required` | `vault zeroize` without `confirm` |
+| `denied` | The operation is not allowed for the operator |
+| `no-vault` | The image has no vault |
+| `no-key` | The vault has no key |
+| `key-exists` | The vault already made its key this boot |
+| `no-entropy` | The boot seed has no entropy |
+| `unsupported-algorithm` | The algorithm is not in this image |
+| `zeroized` | The key was erased; a reboot is needed |
+| `vault-failed` | The vault failed and wiped seed and key |
+| `vault-timeout` | The vault did not answer in time |
+
+> [!WARNING]
+> There is no authentication on the serial line. Whoever holds the line is the operator and can do exactly the operator's four operations (`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`), including erasing the key. The operator cannot get a signature, cannot deliver a seed and cannot change policy.
+
+What stays true, and what is not covered:
+
+- **Kernel code**: the receive code runs at EL1. It is small and never interprets a byte, but it is kernel code driven by an outside party. A user-space driver needs device and interrupt delegation, which K0 does not have.
+- **Timing**: an outside party can now cause interrupts while tasks run (bounded by the reader), and the reader learns arrival times finer than the tick. Other tasks can notice the stolen time. This timing channel is not analysed.
+- **Latency**: input waits behind running tasks. There are no priorities, so the latency is up to a tick per ready task.
+- **Hardware**: a 16550 console has no input. The SBSA UART path, FIFO overruns and the receive timeout interrupt are not exercised by QEMU, only by host tests with a fake UART. The cut-off for an interrupt line that fires without a UART cause is also covered only by host tests. No test measures kernel time under a flood on a machine. Nothing ran on real hardware.
+- **Screen**: if a kernel line appears while you are typing, the screen line is split but the buffer is whole, and Enter runs the whole buffer. Any task with `Console` output can still print lines that look like kernel or root task lines, and nothing authenticates the prefix. The terminal can additionally erase within its current line.
+- **Bytes held back**: "dropped before the prompt" counts bytes that reached the UART. An emulator or adapter that holds bytes back delivers them later (QEMU does).
+- **Service**: no signing client exists in service mode yet. The key is made and shown but not used by another task. The terminal and the vault are not restarted if they die. The root task is trusted.
+- **Boot log**: terminal output counts against the user share of the in-memory boot log. Once that share is full, later task output is not recorded there.
+- **Vault**: all earlier limits stay. The implementation is unvalidated, there is no side-channel analysis, the key does not come from an approved random bit generator, there is no persistence and there is no PQC. The availability of the vault and of the terminal is not protected.
+
+If the console interrupt number is wrong, only the input path is lost: the boot log shows `k0: console input off (...)`. The reasons are `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range` and `interrupt not available`. A line that keeps firing without a UART cause is switched off after 8 entries with `k0: console input off (interrupt N fired without a uart cause)`. With input on, the boot log shows `k0: console input on (pl011 irq 33)`. The interrupt number is part of the platform line (`k0: platform con=pl011@0x9000000,irq33 ...`), so a `K0_PIN` made before this change no longer matches and must be made again.
## Booting through UEFI
@@ -307,9 +407,9 @@ $ tools/qemu-boot-test.sh # boot in QEMU and che
$ tools/boot-matrix.sh # boot every supported configuration (builds the 16 KiB, pinned and UEFI loader images too)
```
-- `tools/host-test.sh` runs the 276 host tests (190 on an x86-64 computer): small tests of single parts of the kernel (unit tests) as ordinary programs on your computer. It also does **fuzzing**: it feeds the device tree parser and the UEFI loader's planning code random, broken input to find crashes. The 276 are 14 (`k0-abi`), 42 (`k0-cap`), 82 (`k0-boot`), 32 (`k0-efi`), 20 (`k0-vault`, which is 13 with Ed25519 and 7 without) and 43 for each of the two page sizes (`k0-mm`). The memory management tests use ARM instructions, so they run only on an ARM computer (an Apple Silicon Mac or Linux arm64), and the x86-64 count leaves out those 86.
+- `tools/host-test.sh` runs the 354 host tests (268 on other hosts): small tests of single parts of the kernel (unit tests) as ordinary programs on your computer. It also does **fuzzing**: it feeds the device tree parser and the UEFI loader's planning code random, broken input to find crashes. The 354 are 15 (`k0-abi`), 44 (`k0-cap`), 85 (`k0-boot`), 33 (`k0-efi`), 15 (`k0-conin`), 31 (`k0-vault`, which is 20 with Ed25519 and 11 without), 45 (`k0-term`, which is 24 with the vault feature and 21 without) and 43 for each of the two page sizes (`k0-mm`). The memory management tests use ARM instructions, so they run only on an ARM computer (an Apple Silicon Mac or Linux arm64), and the count on other hosts leaves out those 86.
- `tools/qemu-boot-test.sh` boots the kernel and reads the log line by line in a fixed order. It fails on any error line, checks the exact number of intentional fault lines, and stops QEMU when it is done. The root task's timeout tests wait for real timer ticks, so a boot takes about 4 seconds longer than it did before they existed. The test also counts the tick lines between `root: teardown tests pass` and `root: timeout tests pass` and wants at least 4, which is how it checks that a timeout does not end early. It prints `boot-test: pass` on success and saves the full log in `target/qemu-boot-test.log`. It takes the machine from the `K0_QEMU_*` variables above. It accepts `K0_BOOT_REUSE=skip` for memory layouts that have no untyped region of the right size, where the root task skips its reuse test. It reads the kernel lines from the **serial port**, so it needs an image with a console driver. For an image without one, see "Testing an image without console" below. If the serial log has no kernel line, it prints a hint about a kernel built without a console feature.
-- `tools/boot-matrix.sh` boots the kernel in **each** configuration that K0 calls supported and checks the result. It boots QEMU virt with GICv3 and GICv2 at EL1 and EL2, and also three CPU models, 4 cores, the 16 KiB image, other load addresses, `xlnx-versal-virt`, a pinned image and the images with the signing oracle. It also checks statically that the image does not touch the physical timer. The matrix has 61 rows on a Mac with HVF and 51 in CI. You can name single rows as arguments. CI runs it.
+- `tools/boot-matrix.sh` boots the kernel in **each** configuration that K0 calls supported and checks the result. It boots QEMU virt with GICv3 and GICv2 at EL1 and EL2, and also three CPU models, 4 cores, the 16 KiB image, other load addresses, `xlnx-versal-virt`, a pinned image and the images with the signing oracle. It also checks statically that the image does not touch the physical timer. The matrix has 76 rows on a Mac with HVF and 65 in CI. You can name single rows as arguments. CI runs it.
The console rows check the console features. The following table lists the console rows and what they check.
@@ -336,7 +436,24 @@ The `uefi-*` rows boot the kernel through the UEFI loader on EDK2: GICv3 and GIC
For configurations that must be refused, it reads the reason from the boot log in memory, or for the loader from the serial log. These are a 16 KiB kernel on `cortex-a72` and a kernel with one changed byte.
-On an Apple Silicon Mac, `K0_MATRIX_HVF=1 tools/boot-matrix.sh` adds rows that run the kernel, also through the UEFI loader, on the real CPU cores through QEMU's HVF accelerator. Among them are `hvf-quiet` for the image without console and `hvf-vault` for the image with the oracle.
+On an Apple Silicon Mac, `K0_MATRIX_HVF=1 tools/boot-matrix.sh` adds rows that run the kernel, also through the UEFI loader, on the real CPU cores through QEMU's HVF accelerator. Among them are `hvf-quiet` for the image without console, `hvf-vault` for the image with the oracle and `hvf-term` for the terminal image.
+
+The input and terminal rows check the receive path and the terminal. In the following table, the rows `input-only`, `input-gicv2`, `input-16550` and `input-bad-irq` boot images with `console-input` and no terminal:
+
+| Row | What it checks |
+| --- | --- |
+| `input-only` | An image with `console-input` and no terminal |
+| `input-gicv2` | The same on GICv2 |
+| `input-16550` | An image with only the 16550 driver: input is off (`console not attached`) and the log says so |
+| `input-bad-irq` | A device tree with an interrupt number out of range costs only the input path (`interrupt number out of range`) |
+| `input-symbols` | Static check. An image without `console-input` contains no receive code, no `CONSOLE_READ` and none of the new log lines |
+| `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k` | The terminal image, run through `tools/term-test.py` on the default CPU, on the `max` CPU, at EL2, on GICv2 and with a 16 KiB image |
+| `term-no-vault` | A terminal without the vault: `help` lists only `help` |
+| `term-no-alg` | A terminal with `vault` but no algorithm |
+| `term-uefi`, `term-uefi-acpi` | The terminal image through the UEFI loader (device tree path and ACPI path) |
+| `hvf-term` | The terminal image under HVF (Mac only) |
+
+`tools/term-test.py ` boots the image with QEMU's serial port on pipes and runs a scripted session. It covers every command and error, erase and cancel, CR LF, an ESC sequence, a line that is too long, key generation, the public key format, zeroize, 200 kB without a line end, 2000 lines in a row and a serial break. `tools/qemu-boot-test.sh` also knows `K0_BOOT_INPUT=on|off` and `K0_BOOT_SERVICE=vault|plain|none` to say what the image should show, and a judge-only mode `K0_BOOT_JUDGE`. A terminal image prints two more `k0: task fault` lines than the same image without the terminal (8 without the vault, 10 with it), so use `K0_BOOT_FAULTS` for it.
### Testing an image without console
@@ -397,3 +514,7 @@ The following table lists what to do for each problem.
| `build-loader: kernel ELF not found` | Build the kernel first with `cargo build -p k0-kernel --features console --offline` |
| `build-loader: embedding a kernel with: k0: console drivers [none]` | The loader will carry a kernel without console. It still prints its own lines, and the kernel prints nothing after them. Build the kernel with `--features console` and run `tools/build-loader.sh` again if you want output |
| The screen shows only firmware messages, or the firmware menu | The firmware could not start the loader, or the loader refused and the firmware went on. Look for `k0-loader:` lines. With none, check that the `.efi` file exists and, with `K0_QEMU_ESP`, that the drive is found |
+| The terminal shows no `k0> ` prompt | Either the image was built without `terminal` (and `console-input`), or the log shows `k0: console input off (...)` or `root: no console input, terminal not started`. Build with `--features console,terminal,vault-ed25519` and read the reason in the boot log |
+| Nothing happens when I type, or `Ctrl-A` does not arrive | Under `cargo run` QEMU keeps `Ctrl-A` for itself. A 16550 console has no input at all |
+| `boot-test` fails on the number of `k0: task fault` lines for a terminal image | That image prints 2 more than without the terminal (8 or 10). Use `K0_BOOT_FAULTS` |
+| A `K0_PIN` made earlier no longer matches | The platform line now contains the console interrupt (`irq33`). Make the pin again |
diff --git a/USAGE_KR.md b/USAGE_KR.md
index 9ca5f66..ccae298 100644
--- a/USAGE_KR.md
+++ b/USAGE_KR.md
@@ -33,9 +33,9 @@ $ cargo virt
K0에서 입력 및 출력은 선택 사항입니다. 커널 크레이트의 Cargo features로 선택할 수 있습니다.
> [!NOTE]
-> 입력 또는 터미널용 feature는 아직 없습니다. 지금 선택할 수 있는 것은 콘솔 출력뿐입니다.
+> 콘솔 입력과 운영자 터미널도 feature이지만 기본으로는 꺼져 있습니다. 뒤의 "운영자 터미널"에서 설명합니다.
-콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다. 입력은 어떤 이미지에도 없습니다. `cargo virt`는 `cargo run -p k0-kernel --features console`의 별칭이므로 항상 콘솔을 포함합니다. 다음 그림은 빌드에 포함한 feature에 따라 출력이 어디에 닿는지 보여 줍니다.
+콘솔 출력은 콘솔 feature를 포함해 빌드한 이미지에만 있습니다. 입력은 `console-input` 또는 `terminal`을 포함해 빌드한 이미지에만 있습니다. `cargo virt`는 `cargo run -p k0-kernel --features console`의 별칭이므로 항상 콘솔을 포함합니다. 다음 그림은 빌드에 포함한 feature에 따라 출력이 어디에 닿는지 보여 줍니다.
@@ -189,12 +189,112 @@ $ K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE='k0: dtb seeds wiped 40B|root: oracle tests p
- `k0: dtb seeds wiped 40B`와 `root: boot seed from rng-seed bytes 0x0000000000000020 without rndr`입니다(`K0_QEMU_CPU=max`에서는 두 번째 줄이 `and rndr`로 끝납니다). QEMU virt는 32바이트 `rng-seed`를 제공하며, 이것이 `0x20`입니다.
- `k0: task fault` 줄이 두 개 더 나와 모두 8개입니다. 자가 테스트가 일부러 메모리 규칙을 어기게 하는 클라이언트 둘에서 나온 줄입니다.
-- `root: sched tests pass` 앞의 `root: oracle tests pass`입니다. 이 줄은 오라클의 검사가 모두 통과했다는 뜻입니다. 볼트가 부트 시드로 키를 만들었고, 서명자가 검증되는 서명을 받았으며, 메시지나 서명을 바꾸면 검증되지 않고, 관리자와 읽기 전용 클라이언트는 서명을 요청했을 때 거부되었으며, 키를 지운 뒤에는 서명이 거부되었습니다.
+- `root: sched tests pass` 앞의 `root: oracle tests pass`입니다. 이 줄은 오라클의 검사가 모두 통과했다는 뜻입니다. 볼트가 공개 RFC 8032 테스트 시드로 키를 만들었고, 서명자가 검증되는 서명을 받았으며, 메시지나 서명을 바꾸면 검증되지 않고, 관리자와 읽기 전용 클라이언트는 서명을 요청했을 때 거부되었으며, 키를 지운 뒤에는 서명이 거부되었습니다.
볼트는 부트 시드에 `rng-seed` 바이트가 32개 이상 있거나 RNDR에서 온 256비트가 있을 때만 키를 만듭니다. 그렇지 않으면, 예를 들어 디바이스 트리에 `rng-seed`가 없고 CPU에 RNDR도 없는 머신에서는 볼트가 `NO_ENTROPY`로 답하고 키를 만들지 않습니다. 그러면 루트 태스크가 `root: oracle made no key (boot seed has no entropy)`를 출력하고 오라클 테스트를 거기서 멈춥니다. `root: oracle tests pass`는 나오지 않으므로 이 줄을 요구하는 부팅 테스트는 실패하며, 이것이 의도한 결과입니다.
> [!NOTE]
-> Ed25519 구현은 vendor에 넣은 `ed25519-dalek` 2.2.0 크레이트이며 어떤 종류의 검증도 받지 않았고, 키는 승인된 난수 비트 생성기에서 나오지 않습니다. 키는 하나뿐이고, 영속성도 키의 가져오기나 내보내기도 운영자 입력도 아직 없습니다. 클라이언트가 엔드포인트 하나를 함께 사용하므로 볼트의 가용성은 보호되지 않으며 타임아웃을 써야 합니다. 루트 태스크는 신뢰 대상이며 볼트를 읽을 수 있습니다. 오라클은 QEMU(TCG와 HVF)에서만 실행해 보았습니다. 자세한 내용과 한계는 [SECURITY_KR.md](SECURITY_KR.md)에 있습니다.
+> Ed25519 구현은 vendor에 넣은 `ed25519-dalek` 2.2.0 크레이트이며 어떤 종류의 검증도 받지 않았고, 키는 승인된 난수 비트 생성기에서 나오지 않습니다. 키는 하나뿐이고, 영속성도 키의 가져오기나 내보내기도 운영자 인증도 아직 없습니다. 클라이언트가 엔드포인트 하나를 함께 사용하므로 볼트의 가용성은 보호되지 않으며 타임아웃을 써야 합니다. 루트 태스크는 신뢰 대상이며 볼트를 읽을 수 있습니다. 오라클은 QEMU(TCG와 HVF)에서만 실행해 보았습니다. 자세한 내용과 한계는 [SECURITY_KR.md](SECURITY_KR.md)에 있습니다.
+
+### 운영자 터미널
+
+운영자 터미널은 직렬 포트에서 명령을 입력해 볼트와 대화하는 작은 태스크입니다. 선택 사항이며 기본으로는 꺼져 있습니다. 커널 크레이트의 feature 두 개로 선택하며, feature는 더하기만 합니다.
+
+| Feature | 추가하는 것 |
+| --- | --- |
+| `console-input` | 콘솔 UART용 커널 수신 경로와 시스템 콜 `CONSOLE_READ`. 동작하려면 콘솔 드라이버 feature가 필요함. 수신은 PL011과 SBSA UART에만 있으므로 16550 콘솔에는 출력만 있고 입력은 없음 |
+| `terminal` | 루트 태스크 이미지 안의 터미널 태스크로, 자가 테스트 뒤에 서비스로 시작함. `console-input`을 켬. `vault`를 포함하면 터미널이 볼트의 운영자가 되고, `vault-ed25519`를 포함하면 Ed25519 키를 만들 수 있음 |
+
+`console-input` 없이 빌드한 이미지에는 수신 코드도 `CONSOLE_READ`도 새 로그 줄도 없습니다. `terminal` 없이 빌드한 이미지에는 터미널 코드가 없습니다. 다음과 같이 빌드하고 실행할 수 있습니다.
+
+```sh
+$ cargo build -p k0-kernel --features console,terminal,vault-ed25519
+$ cargo run -p k0-kernel --features console,terminal,vault-ed25519
+```
+
+`cargo run`은 직렬 포트를 내 터미널에 연결해 QEMU를 시작합니다. 이때 QEMU 자신의 이스케이프 키는 `Ctrl-A`입니다(`Ctrl-A`를 누른 다음 `X`로 QEMU 종료). 따라서 `Ctrl-A`는 K0에 전달되지 않습니다.
+
+자가 테스트가 끝나면 루트 태스크가 볼트를 시작해 부트 시드를 넘기고, 터미널과 똑같이 연결한 적대적 태스크 둘을 돌리고(둘 다 거부되어 폴트로 끝나야 함), 관리자 케이퍼빌리티를 버린 뒤 터미널을 시작합니다. 부트 로그에는 `root: vault seeded`, `root: terminal console filter [...]`, `root: terminal wiring holds`, `k0: task fault` 두 줄, `root: service started`, 그다음 배너가 나옵니다. 입력 경로가 없는 머신에서는 `root: no console input, terminal not started`가 나옵니다. 처음 읽은 뒤에는 주기적인 `k0: tick N` 줄이 멈추고, `k0: tick lines off (console input in use)` 한 줄이 그 사실을 알립니다. 다음 세션에서 모든 명령은 `ok` 또는 `err ` 중 정확히 한 줄로 끝납니다.
+
+```
+K0 operator console, type 'help'
+k0> vault status
+state=seeded
+alg=none
+selftest=passed
+seed=rng-seed
+validated=no
+ok
+k0> vault keygen ed25519
+state=ready
+alg=ed25519
+ok
+k0> vault pubkey
+pubkey=<32 hex characters>
+ <32 hex characters>
+ok
+k0> vault zeroize
+hint=type 'vault zeroize confirm' to erase the key
+err confirm-required
+k0>
+```
+
+값은 `name=value` 형태로 출력됩니다. 화면 프롬프트는 `k0> `입니다. 다음 표의 첫 열이 입력하는 명령입니다.
+
+| 명령 | 인자 | 하는 일 |
+| --- | --- | --- |
+| `help` | | 명령 목록을 출력함 |
+| `vault status` | | 볼트 상태를 출력함(아래 참고) |
+| `vault pubkey` | | 공개 키를 출력함 |
+| `vault keygen ` | `ed25519` | 보관 중인 시드로 고른 알고리즘의 키를 만들고 시드를 지움 |
+| `vault zeroize confirm` | | 키를 지움. `vault zeroize`만 입력하면 `hint=type 'vault zeroize confirm' to erase the key`와 `err confirm-required`를 출력함 |
+
+`vault status`는 `state=fresh|seeded|ready|zeroized|failed`, `alg=none|ed25519`, `selftest=passed|failed`, `seed=none|rng-seed|rndr|rng-seed+rndr`, `validated=no`를 출력합니다. `seed=rng-seed`는 바이트가 있었다는 뜻이지 예측할 수 없다는 뜻이 아닙니다. 구현이 어떤 종류의 검증도 받지 않았으므로 `validated=no`는 항상 출력됩니다. `vault pubkey`는 `pubkey=`와 16진수 32자를 출력하고, 7칸 들여쓴 둘째 줄에 나머지 32자를 출력합니다. 볼트는 부팅 한 번에 키를 하나만 만듭니다. `vault keygen`을 한 번 더 하면 `err key-exists`가 나오고, `vault zeroize confirm` 뒤에는 재부팅해야 합니다. `vault` feature가 없으면 `help`는 `help`만 나열하고 `vault ...`는 `err no-vault`로 답합니다.
+
+다음 표의 키는 입력 중인 줄에 작용합니다.
+
+| 키 | 효과 |
+| --- | --- |
+| Enter(CR 또는 LF) | 줄을 실행함. 한 줄은 최대 64자이며 출력 가능한 ASCII만 허용함 |
+| Backspace 또는 DEL | 한 글자를 지움 |
+| `Ctrl-C` 또는 `Ctrl-U` | 줄을 취소함(`^C` 또는 `^U`로 표시) |
+| ESC 시퀀스(방향키) | 무시함 |
+
+프롬프트가 나오기 전에 UART에 도착한 바이트는 버려집니다. 입력이 유실되면(FIFO 오버런, 브레이크, 프레이밍 또는 패리티 오류) 다음 줄 끝까지 모두 버리고 명령은 `err input-lost`로 답합니다. 전달은 됐지만 제때 응답받지 못한 keygen 또는 zeroize는 `hint=run 'vault status' to see whether it took effect`를 덧붙입니다. 다음 표의 오류 이름은 `err ` 뒤에 나오는 것입니다.
+
+| 오류 | 뜻 |
+| --- | --- |
+| `unknown-command` | 모르는 명령 |
+| `bad-argument` | 인자가 틀렸거나 빠짐 |
+| `line-too-long` | 한 줄이 64자를 넘음 |
+| `input-lost` | 줄이 끝나기 전에 입력이 유실됨 |
+| `confirm-required` | `confirm` 없는 `vault zeroize` |
+| `denied` | 운영자에게 허용되지 않은 동작 |
+| `no-vault` | 이미지에 볼트가 없음 |
+| `no-key` | 볼트에 키가 없음 |
+| `key-exists` | 볼트가 이번 부팅에서 이미 키를 만듦 |
+| `no-entropy` | 부트 시드에 엔트로피가 없음 |
+| `unsupported-algorithm` | 이 이미지에 없는 알고리즘 |
+| `zeroized` | 키가 지워짐. 재부팅이 필요함 |
+| `vault-failed` | 볼트가 실패해 시드와 키를 지움 |
+| `vault-timeout` | 볼트가 제때 응답하지 않음 |
+
+> [!WARNING]
+> 직렬 포트에는 인증이 없습니다. 포트를 쥔 사람이 곧 운영자이며, 키 삭제를 포함해 운영자의 네 가지 동작(`STATUS`, `PUBLIC_KEY`, `KEYGEN`, `ZEROIZE`)을 그대로 할 수 있습니다. 운영자는 서명을 받을 수 없고, 시드를 넘길 수 없으며, 정책을 바꿀 수 없습니다.
+
+계속 유효한 한계와 다루지 않는 부분은 다음과 같습니다.
+
+- **커널 코드**: 수신 코드는 EL1에서 실행됩니다. 작고 바이트를 해석하지 않지만, 외부 당사자가 구동하는 커널 코드입니다. 사용자 공간 드라이버에는 장치 및 인터럽트 위임이 필요한데, K0에는 그것이 없습니다.
+- **타이밍**: 외부 당사자가 이제 태스크가 도는 동안 인터럽트를 일으킬 수 있고(읽는 쪽이 상한을 정함), 읽는 쪽은 틱보다 정밀한 도착 시각을 알게 됩니다. 다른 태스크가 빼앗긴 시간을 알아챌 수 있습니다. 이 타이밍 채널은 분석하지 않았습니다.
+- **지연**: 입력은 실행 중인 태스크 뒤에서 기다립니다. 우선순위가 없으므로 지연은 준비된 태스크마다 최대 한 틱입니다.
+- **하드웨어**: 16550 콘솔에는 입력이 없습니다. SBSA UART 경로, FIFO 오버런, 수신 타임아웃 인터럽트는 QEMU로 실행되지 않고 가짜 UART를 쓰는 호스트 테스트로만 다룹니다. UART 원인 없이 발생하는 인터럽트 선을 끊는 동작도 호스트 테스트로만 다룹니다. 플러드 상황에서 커널이 쓰는 시간을 머신에서 측정하는 테스트는 없습니다. 실제 하드웨어에서는 아무것도 돌려 보지 않았습니다.
+- **화면**: 입력 중에 커널 줄이 나타나면 화면의 줄은 갈라지지만 버퍼는 온전하며, Enter는 버퍼 전체를 실행합니다. `Console` 출력이 있는 태스크는 여전히 커널이나 루트 태스크 줄처럼 보이는 줄을 출력할 수 있고, 접두어를 인증하는 것은 없습니다. 터미널은 추가로 자기 현재 줄 안을 지울 수 있습니다.
+- **붙잡힌 바이트**: "프롬프트 전에 버림"은 UART에 도착한 바이트를 말합니다. 바이트를 붙잡아 두는 에뮬레이터나 어댑터는 나중에 전달합니다(QEMU가 그렇습니다).
+- **서비스**: 서비스 모드에는 서명 클라이언트가 아직 없습니다. 키는 만들어지고 보이지만 다른 태스크가 사용하지 않습니다. 터미널과 볼트는 죽어도 다시 시작되지 않습니다. 루트 태스크는 신뢰 대상입니다.
+- **부트 로그**: 터미널 출력은 메모리 부트 로그의 사용자 몫을 소모합니다. 그 몫이 차면 이후 태스크 출력은 거기에 기록되지 않습니다.
+- **볼트**: 이전의 한계는 모두 유지됩니다. 구현은 검증을 받지 않았고, 부채널 분석이 없으며, 키는 승인된 난수 비트 생성기에서 나오지 않고, 영속성도 PQC도 없습니다. 볼트와 터미널의 가용성은 보호되지 않습니다.
+
+콘솔 인터럽트 번호가 틀려도 잃는 것은 입력 경로뿐이며, 부트 로그에 `k0: console input off (...)`가 나옵니다. 이유는 `no console`, `no receive driver for this uart`, `no usable interrupt in the device tree`, `register frame too small`, `console not attached`, `interrupt number out of range`, `interrupt not available`입니다. UART 원인 없이 계속 발생하는 인터럽트 선은 8번 진입한 뒤 `k0: console input off (interrupt N fired without a uart cause)`와 함께 꺼집니다. 입력이 켜지면 부트 로그에 `k0: console input on (pl011 irq 33)`이 나옵니다. 인터럽트 번호는 플랫폼 줄(`k0: platform con=pl011@0x9000000,irq33 ...`)에 들어 있으므로, 이번 변경 이전에 만든 `K0_PIN`은 더 이상 맞지 않아 다시 만들어야 합니다.
## UEFI로 부팅
@@ -307,9 +407,9 @@ $ tools/qemu-boot-test.sh # QEMU에서 부팅하
$ tools/boot-matrix.sh # 지원하는 구성을 전부 부팅(16 KiB 이미지, 고정 이미지, UEFI 로더 이미지도 빌드함)
```
-- `tools/host-test.sh`는 호스트 테스트 276개를 실행합니다(x86-64 컴퓨터에서는 190개). 커널의 부분 하나하나를 내 컴퓨터에서 일반 프로그램처럼 돌리는 작은 테스트(단위 테스트)입니다. **퍼징**도 합니다. 디바이스 트리 파서와 UEFI 로더의 계획 코드에 무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법입니다. 276개는 `k0-abi` 14개, `k0-cap` 42개, `k0-boot` 82개, `k0-efi` 32개, `k0-vault` 20개(Ed25519를 포함하면 13개, 없으면 7개), `k0-mm` 43개씩 두 페이지 크기분입니다. 메모리 관리 테스트는 ARM 명령을 사용하므로 ARM 컴퓨터(Apple Silicon Mac이나 Linux arm64)에서만 돌고, x86-64의 개수는 그 86개를 뺀 것입니다.
+- `tools/host-test.sh`는 호스트 테스트 354개를 실행합니다(그 밖의 호스트에서는 268개). 커널의 부분 하나하나를 내 컴퓨터에서 일반 프로그램처럼 돌리는 작은 테스트(단위 테스트)입니다. **퍼징**도 합니다. 디바이스 트리 파서와 UEFI 로더의 계획 코드에 무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법입니다. 354개는 `k0-abi` 15개, `k0-cap` 44개, `k0-boot` 85개, `k0-efi` 33개, `k0-conin` 15개, `k0-vault` 31개(Ed25519를 포함하면 20개, 없으면 11개), `k0-term` 45개(`vault` feature를 포함하면 24개, 없으면 21개), `k0-mm` 43개씩 두 페이지 크기분입니다. 메모리 관리 테스트는 ARM 명령을 사용하므로 ARM 컴퓨터(Apple Silicon Mac이나 Linux arm64)에서만 돌고, 그 밖의 호스트의 개수는 그 86개를 뺀 것입니다.
- `tools/qemu-boot-test.sh`는 커널을 부팅하고, 로그를 정해진 순서대로 한 줄씩 확인합니다. 에러 줄이 하나라도 나오면 실패하고, 일부러 일으킨 폴트 줄의 개수를 정확히 맞춘 뒤 QEMU를 끕니다. 루트 태스크의 타임아웃 테스트는 실제 타이머 틱을 기다리므로, 부팅 한 번이 그 테스트가 생기기 전보다 약 4초 더 걸립니다. `root: teardown tests pass`와 `root: timeout tests pass` 사이의 틱 줄도 세어 4개 이상을 요구하는데, 이것이 타임아웃이 일찍 끝나지 않는지 확인하는 방법입니다. 성공하면 `boot-test: pass`를 출력하고 전체 로그를 `target/qemu-boot-test.log`에 남깁니다. 머신은 앞의 `K0_QEMU_*` 변수에서 가져옵니다. 맞는 크기의 untyped 영역이 없는 메모리 배치에서는 루트 태스크가 재사용 시험을 건너뛰므로, 그때는 `K0_BOOT_REUSE=skip`을 받습니다. 커널 줄을 **직렬 포트**에서 읽으므로 콘솔 드라이버가 있는 이미지가 필요합니다. 콘솔 없는 이미지는 뒤의 "콘솔 없는 이미지 시험"을 보세요. 직렬 로그에 커널 줄이 하나도 없으면 콘솔 feature 없이 빌드한 커널이 아닌지 알려 주는 힌트를 출력합니다.
-- `tools/boot-matrix.sh`는 K0가 지원한다고 말하는 **구성마다** 커널을 부팅해서 결과를 확인합니다. GICv3와 GICv2의 QEMU virt를 EL1과 EL2에서 부팅하고, CPU 모델 세 가지, 코어 4개, 16 KiB 이미지, 다른 적재 주소, `xlnx-versal-virt`, 고정 이미지, 서명 오라클이 있는 이미지도 부팅합니다. 이미지가 물리 타이머를 건드리지 않는지는 정적으로 검사합니다. 행렬은 HVF가 있는 Mac에서 61행, CI에서 51행입니다. 행 이름을 인자로 주면 그 행만 돌립니다. CI가 이것을 실행합니다.
+- `tools/boot-matrix.sh`는 K0가 지원한다고 말하는 **구성마다** 커널을 부팅해서 결과를 확인합니다. GICv3와 GICv2의 QEMU virt를 EL1과 EL2에서 부팅하고, CPU 모델 세 가지, 코어 4개, 16 KiB 이미지, 다른 적재 주소, `xlnx-versal-virt`, 고정 이미지, 서명 오라클이 있는 이미지도 부팅합니다. 이미지가 물리 타이머를 건드리지 않는지는 정적으로 검사합니다. 행렬은 HVF가 있는 Mac에서 76행, CI에서 65행입니다. 행 이름을 인자로 주면 그 행만 돌립니다. CI가 이것을 실행합니다.
콘솔 행은 콘솔 feature를 확인합니다. 다음 표는 콘솔 행과 확인하는 내용입니다.
@@ -336,7 +436,24 @@ $ tools/boot-matrix.sh # 지원하는 구성
거부해야 하는 구성에서는 커널의 사유를 메모리에 남은 부트 로그에서 읽고, 로더의 사유는 직렬 로그에서 읽습니다. 이런 구성으로 `cortex-a72`에서의 16 KiB 커널과 한 바이트를 바꾼 커널이 있습니다.
-Apple Silicon Mac에서는 `K0_MATRIX_HVF=1 tools/boot-matrix.sh`로 QEMU의 HVF 가속기를 통해 실제 CPU 코어에서 커널을 (UEFI 로더를 거치는 경우도 포함해) 돌리는 행을 더할 수 있습니다. 콘솔 없는 이미지용으로는 `hvf-quiet`이, 오라클이 있는 이미지용으로는 `hvf-vault`가 있습니다.
+Apple Silicon Mac에서는 `K0_MATRIX_HVF=1 tools/boot-matrix.sh`로 QEMU의 HVF 가속기를 통해 실제 CPU 코어에서 커널을 (UEFI 로더를 거치는 경우도 포함해) 돌리는 행을 더할 수 있습니다. 콘솔 없는 이미지용으로는 `hvf-quiet`이, 오라클이 있는 이미지용으로는 `hvf-vault`가, 터미널 이미지용으로는 `hvf-term`이 있습니다.
+
+입력 및 터미널 행은 수신 경로와 터미널을 확인합니다. 다음 표에서 `input-only`, `input-gicv2`, `input-16550`, `input-bad-irq` 행은 `console-input`을 포함하고 터미널은 없는 이미지를 부팅합니다.
+
+| 행 | 확인하는 것 |
+| --- | --- |
+| `input-only` | `console-input`을 포함하고 터미널이 없는 이미지 |
+| `input-gicv2` | GICv2에서 같은 이미지 |
+| `input-16550` | 16550 드라이버만 있는 이미지. 입력이 꺼지고(`console not attached`) 로그에 그렇게 남음 |
+| `input-bad-irq` | 디바이스 트리의 인터럽트 번호가 범위를 벗어나도 입력 경로만 잃는지(`interrupt number out of range`) |
+| `input-symbols` | 정적 검사. `console-input` 없는 이미지에 수신 코드도 `CONSOLE_READ`도 새 로그 줄도 없음 |
+| `term`, `term-max`, `term-el2`, `term-gicv2`, `term-16k` | 터미널 이미지를 `tools/term-test.py`로 실행. 기본 CPU, `max` CPU, EL2, GICv2, 16 KiB 이미지 |
+| `term-no-vault` | 볼트가 없는 터미널. `help`가 `help`만 나열함 |
+| `term-no-alg` | `vault`는 있고 알고리즘은 없는 터미널 |
+| `term-uefi`, `term-uefi-acpi` | UEFI 로더를 거치는 터미널 이미지(디바이스 트리 경로와 ACPI 경로) |
+| `hvf-term` | HVF에서의 터미널 이미지(Mac 전용) |
+
+`tools/term-test.py <이미지>`는 QEMU의 직렬 포트를 파이프에 연결해 이미지를 부팅하고 정해진 세션을 실행합니다. 모든 명령과 오류, 지우기와 취소, CR LF, ESC 시퀀스, 너무 긴 줄, 키 생성, 공개 키 형식, zeroize, 줄 끝 없는 200 kB, 연속 2000줄, 직렬 브레이크를 다룹니다. `tools/qemu-boot-test.sh`는 이미지가 보여야 할 것을 알려 주는 `K0_BOOT_INPUT=on|off`와 `K0_BOOT_SERVICE=vault|plain|none`, 그리고 판정만 하는 모드 `K0_BOOT_JUDGE`도 이해합니다. 터미널 이미지는 터미널 없는 같은 이미지보다 `k0: task fault` 줄이 두 개 더 나오므로(볼트 없이 8개, 볼트와 함께 10개) `K0_BOOT_FAULTS`를 사용하세요.
### 콘솔 없는 이미지 시험
@@ -397,3 +514,7 @@ GitHub도 풀 리퀘스트와 `main` 푸시가 있을 때마다 이 테스트를
| `build-loader: kernel ELF not found` | 먼저 `cargo build -p k0-kernel --features console --offline`로 커널을 빌드하세요 |
| `build-loader: embedding a kernel with: k0: console drivers [none]` | 로더가 콘솔 없는 커널을 품게 됩니다. 로더는 자기 줄을 계속 출력하고, 그 뒤로 커널은 아무것도 출력하지 않습니다. 출력이 필요하면 `--features console`로 커널을 빌드하고 `tools/build-loader.sh`를 다시 실행하세요 |
| 화면에 펌웨어 메시지나 펌웨어 메뉴만 나옴 | 펌웨어가 로더를 시작하지 못했거나, 로더가 거부해서 펌웨어가 다음으로 넘어간 것입니다. `k0-loader:` 줄이 있는지 보세요. 없다면 `.efi` 파일이 있는지, `K0_QEMU_ESP`를 사용했다면 드라이브가 보이는지 확인하세요 |
+| 터미널에 `k0> ` 프롬프트가 나오지 않음 | 이미지를 `terminal`(과 `console-input`) 없이 빌드했거나, 로그에 `k0: console input off (...)` 또는 `root: no console input, terminal not started`가 있습니다. `--features console,terminal,vault-ed25519`로 빌드하고 부트 로그에서 이유를 읽으세요 |
+| 입력해도 반응이 없거나 `Ctrl-A`가 전달되지 않음 | `cargo run`에서는 QEMU가 `Ctrl-A`를 자기 몫으로 씁니다. 16550 콘솔에는 입력이 전혀 없습니다 |
+| 터미널 이미지에서 `boot-test`가 `k0: task fault` 줄 수 때문에 실패 | 그 이미지는 터미널 없는 이미지보다 2개 더 출력합니다(8개 또는 10개). `K0_BOOT_FAULTS`를 사용하세요 |
+| 이전에 만든 `K0_PIN`이 더 이상 맞지 않음 | 플랫폼 줄에 이제 콘솔 인터럽트(`irq33`)가 들어 있습니다. 핀을 다시 만드세요 |
diff --git a/assets/terminal-flow.svg b/assets/terminal-flow.svg
new file mode 100644
index 0000000..44e9405
--- /dev/null
+++ b/assets/terminal-flow.svg
@@ -0,0 +1,60 @@
+
diff --git a/assets/terminal-flow_KR.svg b/assets/terminal-flow_KR.svg
new file mode 100644
index 0000000..5e542aa
--- /dev/null
+++ b/assets/terminal-flow_KR.svg
@@ -0,0 +1,60 @@
+
diff --git a/ci/threat_model.md b/ci/threat_model.md
index f9df62f..767a6a4 100644
--- a/ci/threat_model.md
+++ b/ci/threat_model.md
@@ -1,6 +1,6 @@
# Threat model: K0
-K0 is a capability-based microkernel for AArch64, written in Rust `no_std` in the style of seL4 and licensed under PolyForm Noncommercial 1.0.0. The kernel runs at EL1. The only user-space code today is the root task, which runs at EL0 and doubles as the self-test harness. Console output is optional: it exists only in an image built with a console feature (see "Optional console output" in `SECURITY.md`). One generic image finds the console, the interrupt controller (GICv2 or GICv3) and the timer in the device tree at boot, and it may be entered at EL1 or at EL2. The 4 KiB granule is the default and the 16 KiB granule is a build option. It can also be started by a UEFI loader (`loader/`) that embeds the kernel. Only QEMU machines can be exercised in this image, with the EDK2 firmware package installed for the loader.
+K0 is a capability-based microkernel for AArch64, written in Rust `no_std` in the style of seL4 and licensed under PolyForm Noncommercial 1.0.0. The kernel runs at EL1. The user-space code is the root task, which runs at EL0 and doubles as the self-test harness, and the vault and terminal tasks that it starts in images built with those features. Console output is optional: it exists only in an image built with a console feature (see "Optional console output" in `SECURITY.md`). Serial input and the operator terminal are optional too: they exist only in an image built with the feature `console-input` or `terminal`, and an image without them has no input code at all (see "Serial input and the operator terminal" in `SECURITY.md`). One generic image finds the console, the interrupt controller (GICv2 or GICv3) and the timer in the device tree at boot, and it may be entered at EL1 or at EL2. The 4 KiB granule is the default and the 16 KiB granule is a build option. It can also be started by a UEFI loader (`loader/`) that embeds the kernel. Only QEMU machines can be exercised in this image, with the EDK2 firmware package installed for the loader.
Read `SECURITY.md` at the repository root first. It describes the isolation model of the released version 0.1.0, the unreleased isolation work on the current `main` branch, and the issues that are already known. This model describes the current `main` branch.
@@ -15,7 +15,8 @@ Trust boundaries, from least to most trusted:
5. **The root task image** is embedded in the kernel at build time together with its SHA-256 (`crates/k0-boot/build.rs`, `verify_root_task`). It is part of the trusted computing base today. The hash detects corruption, not a malicious image; signature verification is a documented TODO.
6. **The UEFI loader** (`loader/`, `crates/k0-efi`) sits between the firmware and the kernel, and it is in scope. Its inputs come from firmware and are treated as wrong or hostile data: the UEFI memory map, the firmware device tree or, without one, the ACPI static tables (RSDP, XSDT, MADT, GTDT, SPCR) from the configuration table, the random number protocol and the embedded kernel image. It decides which memory the kernel sees as RAM, so a mistake there hands firmware memory to user space without any kernel bug. Entry path: `loader/src/load.rs` (flow) -> `crates/k0-efi/src/prepare.rs` (plan, rewrite, self-check with the kernel's own parser, discovery, `Platform::validate` and `boot_window`) -> `loader/src/handoff.rs` (cache flush, MMU off, jump). The pure logic is in `memmap.rs`, `fdtw.rs`, `verify.rs` and `image.rs` of `k0-efi`, none of it `unsafe`. The loader does not verify a signature: its SHA-256 over the embedded kernel is a corruption check, and authenticity is the firmware's Secure Boot job.
-7. **The vault task and its clients** (optional, features `vault` and `vault-ed25519` of `k0-kernel`). The vault holds one Ed25519 key in its own address space. Clients send requests over one endpoint with a badge that the kernel delivers; the badge selects the role (admin, signer, reader) in a policy fixed at build time. Everything in a request (operation, algorithm, length, message, nonce) is attacker controlled, and the vault reads the body once into a private buffer. The root task builds the vault and is trusted, so a root task that reads the vault is not a finding. Entry path: `userspace/k0-vault` (`server`, `proto`, `provider`) and the wiring and self-test in `userspace/root-task/src/oracle.rs`. The Ed25519 code is the vendored crate `ed25519-dalek` 2.2.0, which has no validation of any kind.
+7. **The vault task and its clients** (optional, features `vault` and `vault-ed25519` of `k0-kernel`). The vault holds one Ed25519 key in its own address space. Clients send requests over one endpoint with a badge that the kernel delivers; the badge selects the role (admin, operator, signer, reader) in a policy fixed at build time. The operator is the terminal of boundary 8. Everything in a request (operation, algorithm, length, message, nonce) is attacker controlled, and the vault reads the body once into a private buffer. The root task builds the vault and is trusted, so a root task that reads the vault is not a finding. Entry path: `userspace/k0-vault` (`server`, `proto`, `provider`) and the wiring and self-test in `userspace/root-task/src/oracle.rs`. The Ed25519 code is the vendored crate `ed25519-dalek` 2.2.0, which has no validation of any kind.
+8. **The serial line and the operator terminal** (optional, features `console-input` and `terminal` of `k0-kernel`). Every byte that arrives on the console UART is attacker controlled, and so is its timing. The kernel's receive path runs at EL1 in interrupt context: it puts bytes into a ring of 256 bytes and never interprets them, and the console interrupt is the second interrupt source after the timer. `CONSOLE_READ` hands one byte at a time to the one task that holds a `Console` capability with the read right (R). The terminal task (`userspace/k0-term`) parses lines in its own address space and, when the vault is built in, acts as the vault's operator: it can ask for `STATUS`, `PUBLIC_KEY`, `KEYGEN` and `ZEROIZE`, nothing else. There is no authentication on the serial line, so whoever reaches it is the operator, and erasing the key is a denial of service by design. Entry path: `crates/k0-arch/src/conin.rs` and `crates/k0-conin` (receive logic), `crates/k0-ipc/src/console.rs` and `kernel/src/syscall.rs` (`CONSOLE_READ`, the rights of `Console`), `userspace/k0-term` (`lib.rs`, `wire.rs`) and its wiring in `userspace/root-task/src/oracle.rs`. The interrupt number comes from the device tree or the ACPI SPCR table, which are inputs of boundary 4 and 6.
Out of the kernel's control and therefore trusted: the rest of the boot chain (firmware, any other boot loader, the hypervisor), the integrity of the kernel image itself, and the hardware. Under UEFI the firmware is trusted to run honestly, but the loader must still not trust what it describes.
@@ -36,6 +37,8 @@ Highest value, all in scope:
- `userspace/k0-vault` and `userspace/root-task/src/oracle.rs`: the request state machine (`Vault::handle`), the badge policy, the provider boundary around the crypto crate, the entropy rule (`NO_ENTROPY`), the rights of the request and response frames, and the nonce handshake. Reports that are welcome: a key disclosed to a client, a policy bypass (an operation a role must not have), and a reply that reaches the wrong caller.
+- The input path: `crates/k0-conin` (ring, drain, gate and loss marking), `crates/k0-arch/src/conin.rs` and the PL011 and SBSA receive code in `earlycon/uart.rs`, the receive interrupt handling in `irq.rs`, the `Console` rights (R and W) and the output filter, `CONSOLE_READ` and its waiter (`crates/k0-ipc/src/console.rs`), and `userspace/k0-term` with its wiring check in `oracle.rs`. Reports that are welcome: a byte stream that makes the kernel misbehave, interrupt work that is not bounded by the reader, a wake-up of the wrong task, a `Console` right that is gained instead of removed, and an operator operation beyond the four listed.
+
Lower value:
- `userspace/root-task` (other than `oracle.rs`): the trusted root task and test harness. Bugs here are not kernel vulnerabilities, but it is the right place to write reproducers.
@@ -45,12 +48,12 @@ Lower value:
## How to exercise it
-- Build: `cargo build -p k0-kernel --features console --offline` (generic 4 KiB image with console, dev profile with debug info; `panic = "abort"` in every profile). Input and output are Cargo features that only add and are never in `default`, so every command names them. `cargo build -p k0-kernel --offline` builds an image without console: it has no UART driver, never maps the console page and prints nothing on the serial port, and `tools/qemu-boot-test.sh` cannot judge it from the serial log (it prints a hint). All feature sets write the same ELF path, so give an image without console its own directory, for example `--target-dir target/quiet`. The 16 KiB image is `cargo build -p k0-kernel --offline --no-default-features --features granule-16k,console --target-dir target/g16`. It boots only on a CPU model with 16 KiB pages: `K0_QEMU_CPU=max tools/qemu-boot-test.sh target/g16/aarch64-unknown-none-softfloat/debug/k0-kernel`. `grep -a 'k0: console drivers' ` tells which I/O an image was built with.
+- Build: `cargo build -p k0-kernel --features console --offline` (generic 4 KiB image with console, dev profile with debug info; `panic = "abort"` in every profile). Input and output are Cargo features that only add and are never in `default`, so every command names them. The operator terminal image is `cargo build -p k0-kernel --features console,terminal,vault-ed25519`, and `cargo run -p k0-kernel --features console,terminal,vault-ed25519` boots it under QEMU with the serial port on the terminal (QEMU's own escape key is Ctrl-A, so it never reaches K0 there). `tools/term-test.py ` boots an image with QEMU's serial port on pipes and runs a scripted session (every command and error, a line that is too long, 200 kB without a line end, 2000 lines in a row, a serial break), and `tools/qemu-boot-test.sh` takes `K0_BOOT_INPUT=on|off` and `K0_BOOT_SERVICE=vault|plain|none`. `cargo build -p k0-kernel --offline` builds an image without console: it has no UART driver, never maps the console page and prints nothing on the serial port, and `tools/qemu-boot-test.sh` cannot judge it from the serial log (it prints a hint). All feature sets write the same ELF path, so give an image without console its own directory, for example `--target-dir target/quiet`. The 16 KiB image is `cargo build -p k0-kernel --offline --no-default-features --features granule-16k,console --target-dir target/g16`. It boots only on a CPU model with 16 KiB pages: `K0_QEMU_CPU=max tools/qemu-boot-test.sh target/g16/aarch64-unknown-none-softfloat/debug/k0-kernel`. `grep -a 'k0: console drivers' ` tells which I/O an image was built with.
- Run: `tools/qemu-virt-runner.sh target/aarch64-unknown-none-softfloat/debug/k0-kernel`, which is what `cargo virt` (alias of `cargo run -p k0-kernel --features console`) does. A plain `cargo run -p k0-kernel` boots the image without console, and the runner then prints `runner: this kernel has no console driver and prints nothing here (build with --features console to see output)`. It converts the ELF to a raw image with `llvm-objcopy` and boots `qemu-system-aarch64 -machine virt,gic-version=3 -cpu cortex-a72 -smp 1 -m 512M -nographic`. `K0_QEMU_MACHINE`, `K0_QEMU_CPU`, `K0_QEMU_SMP` and `K0_QEMU_MEM` change the machine, for example `K0_QEMU_MACHINE=virt,gic-version=2` or `K0_QEMU_MACHINE=virt,gic-version=3,virtualization=on` (entry at EL2). `tools/boot-matrix.sh` runs every configuration that K0 calls supported. The kernel never exits: once the root task finishes its self-tests it yields forever and an image with a console driver prints `k0: tick N` on the console once a second (every image logs only the first 4 tick lines in the boot log). Wrap every run in `timeout`, or use `tools/qemu-boot-test.sh`, which checks the expected log lines in order, requires an exact number of `k0: task fault` lines and exactly one `k0: unknown syscall` line, and stops QEMU once they appear.
-- A healthy boot log is in `/src/bootcheck.log`, captured when this image was built. The lines that matter are `k0: w^x checks pass`, `k0: user w^x checks pass`, `root: retype/map tests pass`, `root: child exit test pass`, `root: ipc tests pass`, `root: fault isolation tests pass`, `root: preempt test pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: timeout tests pass`, `root: revocation tests pass`, `root: kernel reserve tests pass` and `root: sched tests pass`. Every image also prints `k0: dtb seeds wiped B` (40B on QEMU virt) and `root: boot seed from rng-seed bytes ...`. An image built with the feature `vault` also prints `root: oracle tests pass` and two more `k0: task fault` lines (8 instead of 6).
+- A healthy boot log is in `/src/bootcheck.log`, captured when this image was built. The lines that matter are `k0: w^x checks pass`, `k0: user w^x checks pass`, `root: retype/map tests pass`, `root: child exit test pass`, `root: ipc tests pass`, `root: fault isolation tests pass`, `root: preempt test pass`, `root: isolation tests pass`, `root: violation tests pass`, `root: teardown tests pass`, `root: timeout tests pass`, `root: revocation tests pass`, `root: kernel reserve tests pass` and `root: sched tests pass`. Every image also prints `k0: dtb seeds wiped B` (40B on QEMU virt) and `root: boot seed from rng-seed bytes ...`. An image built with the feature `vault` also prints `root: oracle tests pass` and two more `k0: task fault` lines (8 instead of 6). An image built with the feature `terminal` shows two more `k0: task fault` lines than the same image without it (the hostile wiring checks: 8 in total without `vault`, 10 with it), `root: terminal wiring holds` and `root: service started`. An image with `console-input` prints `k0: console input on (pl011 irq 33)` or `k0: console input off ()` and `root: console input tests pass`. When a task first reads console input the `k0: tick N` lines stop after `k0: tick lines off (console input in use)`.
- Reproducers: the root task (`userspace/root-task/src/main.rs`) is the only EL0 image and already contains the test harness and thin `sys*` wrappers around `svc`. Add a test there; when the reproducer needs its own thread, build a task with its own CNode and address space (`RETYPE`, `TCB_CONFIGURE`, `TCB_RESUME`), which then runs code from the root task image, rebuild and run. `crates/k0-boot/build.rs` rebuilds and re-embeds the root task automatically.
- UEFI loader: `cargo build -p k0-kernel --features console --offline`, then `tools/build-loader.sh`, which embeds that kernel into the loader, prints `build-loader: embedding a kernel with: k0: console drivers [...]` so that nobody embeds a silent kernel unknowingly, and prints the path (`.efi`). `tools/qemu-virt-runner.sh .efi` boots it through EDK2 with `-machine virt,gic-version=3,acpi=off` (firmware from `K0_QEMU_FIRMWARE`, else Homebrew's `edk2-aarch64-code.fd`, else `/usr/share/AAVMF/AAVMF_CODE.fd`, which is the Debian package in this image). `K0_QEMU_ESP=1` boots it from a FAT drive instead of `-kernel`, and `K0_QEMU_EXTRA` passes extra QEMU arguments. `tools/qemu-boot-test.sh .efi` judges the run from the loader's first line, `k0-loader: start`, so firmware messages before it do not count. The loader prints `k0-loader: ...` lines before the kernel's, and a refusal reads `k0-loader: refused: `. `K0_QEMU_MACHINE=virt,gic-version=3` (ACPI on, no device tree) boots through the static tables. `tools/pe-check.py .efi` checks the PE form and the order of the cache and MMU instructions. `K0_LOADER_FEATURES=refuse-halt tools/build-loader.sh` builds a loader that parks instead of returning to the firmware. The UEFI rows of `tools/boot-matrix.sh` (`uefi-*`) cover GICv2 and GICv3 at EL1 and EL2, the max CPU, 4 cores, the 16 KiB image, a firmware RNG, the FAT drive, the ACPI rows (`uefi-acpi-*`) and the refusals.
-- Host tests: `tools/host-test.sh` runs the unit tests of `k0-abi`, `k0-cap`, `k0-boot` and `k0-efi` on any host and those of `k0-mm` on AArch64 hosts. `k0-cap` includes a model test over random retype, copy, move, delete and revoke sequences, and `k0-mm` runs the real user page table walkers and the address space registry. The DTB parser has a deterministic mutation fuzzer: `K0_FUZZ_ITERS=5000000 cargo test --release --offline --target "$(rustc -vV | sed -n 's/^host: //p')" -p k0-boot fuzz -- --nocapture`. A failing case prints `K0_FUZZ_CASE=0x...`, which replays it and dumps the input. The fuzzer's DTB builder in `crates/k0-boot/src/fdt/builder.rs` is a convenient way to write a crafted DTB for a reproducer. `k0-efi` has three more deterministic fuzzers (`fuzz_plan_with_random_maps`, `fuzz_rewrite_with_mutated_trees`, `fuzz_prepare_end_to_end`) with the same `K0_FUZZ_ITERS`, `K0_FUZZ_SEED` and `K0_FUZZ_CASE` variables: run them with `-p k0-efi fuzz`. The unit tests of `k0-efi` use measured firmware memory maps as vectors; a crafted memory map or firmware DTB is the natural reproducer for the loader.
+- Host tests: `tools/host-test.sh` runs the unit tests of `k0-abi`, `k0-cap`, `k0-boot`, `k0-efi`, `k0-conin`, `k0-vault` and `k0-term` on any host and those of `k0-mm` on AArch64 hosts. `k0-cap` includes a model test over random retype, copy, move, delete and revoke sequences, and `k0-mm` runs the real user page table walkers and the address space registry. The DTB parser has a deterministic mutation fuzzer: `K0_FUZZ_ITERS=5000000 cargo test --release --offline --target "$(rustc -vV | sed -n 's/^host: //p')" -p k0-boot fuzz -- --nocapture`. A failing case prints `K0_FUZZ_CASE=0x...`, which replays it and dumps the input. The fuzzer's DTB builder in `crates/k0-boot/src/fdt/builder.rs` is a convenient way to write a crafted DTB for a reproducer. `k0-efi` has three more deterministic fuzzers (`fuzz_plan_with_random_maps`, `fuzz_rewrite_with_mutated_trees`, `fuzz_prepare_end_to_end`) with the same `K0_FUZZ_ITERS`, `K0_FUZZ_SEED` and `K0_FUZZ_CASE` variables: run them with `-p k0-efi fuzz`. The unit tests of `k0-efi` use measured firmware memory maps as vectors; a crafted memory map or firmware DTB is the natural reproducer for the loader.
- PAC, PAN and RNDR paths: the default `cortex-a72` model has none of them. `tools/qemu-boot-test.sh target/aarch64-unknown-none-softfloat/debug/k0-kernel -cpu max` (an image built with `--features console`) boots on a CPU that has all three.
- A boot that the kernel refuses before it has a console prints nothing, and an image without a console feature prints nothing on the serial port at all. The reason is in the boot log in memory: start QEMU with `K0_QEMU_MONITOR=` and read it with `tools/boot-log.py ` (the load address on QEMU `virt` is `0x40080000`).
- Debugging: append `-s -S` to the runner (`tools/qemu-virt-runner.sh -s -S`) and attach with `gdb-multiarch target/aarch64-unknown-none-softfloat/debug/k0-kernel -ex 'target remote :1234'`. `-d int,guest_errors` prints exception traces. `llvm-objdump -d` (from the pinned toolchain, linked into `/usr/local/bin`) disassembles both images.
@@ -63,6 +66,7 @@ Rate by what EL0 code can do to EL1 or, on the current `main` branch, to another
- **Critical**: any EL0 -> EL1 privilege escalation, and on the current `main` branch any break of task isolation (reading or writing another task's memory, using a slot or capability of another task, a revoked capability or stale mapping that still works). Executing attacker-chosen code at EL1; reading or writing kernel memory or arbitrary physical memory through a system call; obtaining a mapping, capability or object that the caller's slot arguments do not grant (bypassing a capability or permission check); mapping memory that is both writable and executable for EL0, or kernel memory into TTBR0; getting the kernel to restore EL1 state (mode, exception level, interrupt masks) that came from user input.
- **High**: memory-safety bugs in kernel code reachable from EL0, with or without a demonstrated exploit (out-of-bounds index, integer overflow or truncation in size or address arithmetic, stale raw pointers, aliasing `&mut`, unsound `unsafe`); a system call or fault sequence that halts the whole system (kernel panic, `exception_fatal`, an unbounded loop with interrupts masked, or a scheduler that cannot continue); missing TLB or cache maintenance that lets a task keep using memory after it was unmapped or retyped; kernel register or memory contents leaking to EL0 (registers not restored or cleared on the return path, uninitialised memory handed out by `retype` or `map`); checks that a race between the timer interrupt and a system call can bypass.
- **Loader findings** are rated by what the kernel ends up trusting. **Critical**: a memory map or firmware device tree that makes the loader pass the kernel a RAM range that includes memory firmware still uses (runtime or boot services memory, MMIO, a reservation) so that it can reach user space, or that makes the loader start a kernel image that fails its own check. **High**: memory-safety bugs in the loader, a refusal that is skipped (the loader boots on input it should refuse), or an `ExitBootServices` path that leaves the system in an undefined state. **Medium**: a panic or an overly cautious refusal on a valid map, a leak of memory the loader should have wiped, a plan that loses RAM beyond the stated policy. Findings that need hostile firmware are Low (see "Anything to leave alone").
+- **Input findings** are rated by what an outside party on the serial line gains. **Critical**: a byte stream or timing that gives code execution or memory access at EL1, or that makes a task do more than the operator's four operations. **High**: a stream that halts the machine or lets kernel work in interrupt context grow without the reader's bound; a wake-up or a byte delivered to a task that does not hold the read right. **Medium**: a stream that wedges the terminal or the input path until reboot. The lack of authentication on the serial line and the operator's power to erase the key are known (see "Anything to leave alone").
- **Medium**: malformed DTB input that panics, reads out of bounds, produces an unsafe memory map or gets a device mapped over memory that is handed out (the boot chain is trusted, so cap these at Medium unless they give code execution); exhaustion of kernel resources (for example untyped memory, TCB or endpoint objects; the kernel page tables and the address space registry are reserved at boot and no longer run out) by a single task that denies service to others without halting the kernel; scheduler starvation; mistakes in `write_bootinfo` beyond the known physical address exposure.
- **Low**: problems that need a misbehaving root task to trigger; `build.rs` issues with trusted source inputs; console formatting and diagnostic wording; hardening that is missing but has no exploitable consequence today.
- A root-cause analysis plus a patch is welcome at every level. A reproducer counts for more than a severity argument.
@@ -85,9 +89,10 @@ These are known, tracked in `SECURITY.md`, and are not new findings:
- DTB memory regions are not bounded by the physical address width (GHSA-hj3f-38h9-hrpj). The current `main` branch stops the boot on such a region; the advisory itself is still a draft.
- No KASLR: the kernel image always sits at the same virtual address. `write_bootinfo` exposes the physical addresses of `Untyped` regions to the root task.
- A wrong or hostile DTB can stop the boot, or point the console at another device that passes the checks (a 16550 and an SBSA UART have no identification register). An image without a console driver never maps or writes the console page, but it still refuses a device tree whose console node fails the checks. A pinned build (`K0_PIN`) compares values that come from the DTB, so it does not stop a hostile boot chain.
-- Signing oracle limits, all in `SECURITY.md` under "The signing oracle": the Ed25519 implementation is unvalidated and the key does not come from an approved random bit generator; no side-channel analysis; one key shared by all signers; no persistence, import, export or DRBG; the availability of the vault is not protected; the root task is trusted and could read the vault; only run in QEMU. The kernel zeroes the `rng-seed` and `kaslr-seed` bytes in the DTB once, right before it enters the root task; copies kept by firmware or the loader and live boot stack frames are not wiped.
+- Signing oracle limits, all in `SECURITY.md` under "The signing oracle": the Ed25519 implementation is unvalidated and the key does not come from an approved random bit generator; no side-channel analysis; one key shared by all signers, one key per boot; no persistence, import, export or DRBG; the availability of the vault is not protected; the root task is trusted and could read the vault; only run in QEMU. The kernel zeroes the `rng-seed` and `kaslr-seed` bytes in the DTB once, right before it enters the root task; copies kept by firmware or the loader and live boot stack frames are not wiped.
+- Serial input limits, all in `SECURITY.md` under "Serial input and the operator terminal": there is no authentication on the serial line, and the operator can erase the key (denial of service by design) but cannot sign, deliver a seed or change policy; the receive code runs at EL1 and a user-space driver would need device and interrupt delegation, which K0 does not have; an outside party can cause interrupts while tasks run (bounded by the reader), the reader learns arrival times finer than the tick and other tasks can notice the stolen time, a timing channel that has not been analysed; input waits behind running tasks (no priorities, up to a tick per ready task); a 16550 console has no input; the SBSA UART path, FIFO overruns, the receive timeout interrupt and the cut-off of an interrupt line without a UART cause are covered only by host tests with a fake UART; no test measures kernel time under a flood on a machine; "dropped before the prompt" counts bytes that reached the UART, and an emulator that holds bytes back delivers them later; a kernel line that appears while the operator types splits the screen line but not the buffer; the terminal can erase within its current line; no signing client exists in service mode; the terminal and the vault are not restarted if they die; terminal output counts against the user share of the in-memory boot log. Nothing ran on real hardware.
- The DTB pointer in `x0` is mapped read-only and read before any memory map exists. A boot loader that passes the address of a device makes the kernel read device registers as memory.
-- A task with a `Console` capability can print lines that look like kernel output (`k0: ...`), in the boot log and, in an image with a console driver, on the console. Its output is filtered for control bytes but not marked. That includes the `k0: console drivers [...]` line, so only its first occurrence, or the image file, identifies a build.
+- A task with a `Console` capability that has the write right can print lines that look like kernel output (`k0: ...`), in the boot log and, in an image with a console driver, on the console. Its output is filtered for control bytes (only a capability with the read right may also emit backspace) but not marked. That includes the `k0: console drivers [...]` line, so only its first occurrence, or the image file, identifies a build.
- Optional console output: an empty serial log shows only that no byte reached the serial port of QEMU virt (a PL011), not that no register was read; the symbol check runs on debug images and release (LTO) images without console are not booted; no image without console is booted through UEFI; the boot log in kernel memory is readable by anyone who can read RAM or attach a debugger. See "Optional console output" in `SECURITY.md`.
- A trap to EL2 after the kernel has dropped to EL1 parks the whole machine by design.
- PAC keys are shared between EL0 and EL1. No `pac-ret` code generation is enabled yet, so there is nothing to forge today.
@@ -96,5 +101,5 @@ These are known, tracked in `SECURITY.md`, and are not new findings:
- The root task is trusted; its image is embedded and hashed, not signed. Kernel image integrity belongs to the boot chain.
- The UEFI loader's known limits, all in `SECURITY.md` under "The UEFI loader": hostile firmware is not defended against, only wrong firmware; the SHA-256 of the embedded kernel is a corruption check and not a signature (only the firmware's Secure Boot gives authenticity); only this loader may start the kernel under UEFI, since a generic loader that passes the firmware device tree through hands firmware memory to user space; a refusal returns to the firmware unless the loader was built with `refuse-halt`; the cache flush and MMU-off sequence cannot be tested under QEMU (TCG has no caches) and is checked only for presence by `tools/pe-check.py`; a pinned build under UEFI is untested; a device left running by firmware can still write to memory (no IOMMU); the loader's entropy stays readable in the device tree in memory; the kernel never calls UEFI runtime services; firmware that types device registers as `EfiReservedMemoryType` or gives one malformed descriptor makes the loader refuse (fail closed); the block re-placement and free-on-refusal paths were not exercised; the loader file is not bit-for-bit reproducible across build directories. About 23 to 32 MiB of boot services memory is left unused on purpose. Firmware with neither a device tree nor ACPI static tables is refused. The ACPI path reads only the static tables (RSDP, XSDT, MADT, GTDT and SPCR, never AML) and has been booted only on QEMU virt.
- Real boards, U-Boot's EFI implementation, Raspberry Pi UEFI, firmware other than EDK2 `ArmVirtQemu`, and KVM have never been booted under UEFI either; do not report "untested on hardware".
-- Only QEMU runs in this image. Real boards, KVM and other hypervisors, the 16550 console driver (no test has executed it), the SBSA UART and CPUs with `HCR_EL2.E2H` fixed to 1 have never been booted. Review of those paths is welcome; do not report "untested on hardware".
+- Only QEMU runs in this image. Real boards, KVM and other hypervisors, the 16550 console driver (no test has executed it, and it has no input path), the SBSA UART and CPUs with `HCR_EL2.E2H` fixed to 1 have never been booted. Review of those paths is welcome; do not report "untested on hardware".
- Upstream issues in vendored crates that are not reachable from the kernel's SHA-256 use.
diff --git a/crates/k0-abi/src/lib.rs b/crates/k0-abi/src/lib.rs
index 3b2b87a..66050a9 100644
--- a/crates/k0-abi/src/lib.rs
+++ b/crates/k0-abi/src/lib.rs
@@ -34,9 +34,11 @@ pub const PA_CEILING: u64 = KERNEL_IMAGE_VA - KERNEL_VA_OFFSET;
pub mod syscall {
/// 바이트 하나를 커널 디버그 콘솔로 출력
///
- /// x0 = Console 슬롯, x1 = 바이트(하위 8비트만 사용). 출력 가능한
- /// ASCII(0x20-0x7E)와 개행만 그대로 나가고 그 외 바이트(터미널 제어
- /// 문자 등)는 `?`로 바뀝니다. 성공 시 x0 = 0, 실패 시 음수 에러
+ /// x0 = Console 슬롯(쓰기 권한 W 필요), x1 = 바이트(하위 8비트만 사용).
+ /// 출력 가능한 ASCII(0x20-0x7E)와 개행만 그대로 나가고 그 외 바이트(터미널
+ /// 제어 문자 등)는 `?`로 바뀝니다. `console-input`으로 빌드한 이미지에서
+ /// 읽기 권한 R도 있는 케이퍼빌리티로 부르면 백스페이스(0x08)가 그대로
+ /// 나갑니다(입력한 글자를 지우는 데 필요). 성공 시 x0 = 0, 실패 시 음수 에러
pub const DEBUG_PUTC: u64 = 0;
/// 스케줄러 양보(준비된 다른 태스크가 없으면 즉시 복귀)
pub const YIELD: u64 = 1;
@@ -104,8 +106,8 @@ pub mod syscall {
///
/// x0 = 원본 슬롯, x1 = 목적지 CNode를 가리키는 CNode 슬롯, x2 = 그
/// CNode 안의 빈 목적지 슬롯, x3 = 남길 권한 비트([super::rights]),
- /// x4 = 배지(0 = 붙이지 않음). 권한은 줄일 수만 있고 Frame / Endpoint에만
- /// 적용됩니다. 배지는 배지가 없는 Endpoint에만 붙일 수 있습니다. 복사본은
+ /// x4 = 배지(0 = 붙이지 않음). 권한은 줄일 수만 있고 Frame / Endpoint /
+ /// Console에만 적용됩니다. 배지는 배지가 없는 Endpoint에만 붙일 수 있습니다. 복사본은
/// 원본의 자식이라 원본을 회수하거나 삭제하면 함께 사라집니다. Untyped와
/// PageTable은 복사할 수 없습니다. 성공 시 x0 = 0
pub const CAP_COPY: u64 = 12;
@@ -125,6 +127,34 @@ pub mod syscall {
/// x0 = 슬롯. untyped를 회수하면 거기서 잘라낸 오브젝트가 전부 종료되고
/// 메모리를 다시 재분류할 수 있습니다. 성공 시 x0 = 0
pub const CAP_REVOKE: u64 = 15;
+ /// 콘솔 입력에서 바이트 하나를 읽음(커널을 `console-input`으로 빌드한
+ /// 이미지에만 있음)
+ ///
+ /// x0 = Console 슬롯(읽기 권한 R 필요), x1 = 플래그([super::console]).
+ /// 받아 둔 바이트가 없으면 올 때까지 블록됩니다. 한 번에 한 태스크만
+ /// 기다릴 수 있습니다. 성공 시 x0 = 0, x1 = 바이트, x2 = 이 바이트 바로
+ /// 앞에서 입력이 유실됐으면 [super::console::LOST], 아니면 0. 커널은
+ /// 바이트를 해석하지 않습니다. 기다리는 동안 그 케이퍼빌리티를 잃으면
+ /// REVOKED로 깨어납니다
+ pub const CONSOLE_READ: u64 = 16;
+}
+
+/// CONSOLE_READ의 플래그(x1)와 결과(x2) 모듈입니다.
+pub mod console {
+ /// 받아 둔 바이트가 없으면 블록 대신 WOULD_BLOCK으로 즉시 복귀
+ pub const NONBLOCK: u64 = 1;
+ /// 읽기 전에, 지금까지 받아 둔 입력과 유실 표시를 전부 버림
+ ///
+ /// 프롬프트를 내기 전에 들어온 입력이 명령으로 읽히지 않게 하는 데
+ /// 씁니다. 버리는 양은 커널의 버퍼와 장치의 FIFO 크기로 묶여 있습니다
+ pub const FLUSH: u64 = 2;
+ /// 플래그 레지스터에서 뜻이 정해지지 않은 비트. 하나라도 서 있으면
+ /// BAD_FLAGS로 거부됩니다. 상위 32비트는 IPC와 같은 형식의 타임아웃입니다
+ /// ([super::ipc::TIMEOUT_SHIFT])
+ pub const RESERVED: u64 = 0xFFFF_FFFC;
+ /// 결과(x2): 이 바이트 바로 앞에서 입력이 유실됨(장치의 FIFO가 넘쳤거나
+ /// 오류가 난 문자를 버렸음)
+ pub const LOST: u64 = 1;
}
/// IPC 플래그(x1) 모듈입니다.
@@ -185,9 +215,9 @@ pub mod perm {
/// 케이퍼빌리티 권한 비트 모듈입니다. (CAP_COPY의 x3)
pub mod rights {
- /// Frame: 읽기 매핑, Endpoint: 수신
+ /// Frame: 읽기 매핑, Endpoint: 수신, Console: 입력 읽기
pub const R: u64 = 1;
- /// Frame: 쓰기 매핑, Endpoint: 송신
+ /// Frame: 쓰기 매핑, Endpoint: 송신, Console: 출력
pub const W: u64 = 2;
/// Frame: 실행 매핑
pub const X: u64 = 4;
@@ -231,7 +261,8 @@ pub mod err {
pub const NO_REPLY: i64 = -15;
/// 케이퍼빌리티에 이 연산에 필요한 권한 비트가 없음
pub const NO_RIGHTS: i64 = -16;
- /// 대기하던 엔드포인트가 종료됨
+ /// 대기하던 엔드포인트가 종료됨. 콘솔 입력을 기다리던 중이라면 그
+ /// Console 케이퍼빌리티를 잃었음
pub const REVOKED: i64 = -17;
/// 배지를 붙일 수 없는 케이퍼빌리티이거나 이미 다른 배지가 있음
pub const BAD_BADGE: i64 = -18;
@@ -245,6 +276,10 @@ pub mod err {
pub const REPLY_TIMEOUT: i64 = -21;
/// IPC 플래그 레지스터에 뜻이 정해지지 않은 비트가 서 있음
pub const BAD_FLAGS: i64 = -22;
+ /// 다른 태스크가 이미 콘솔 입력을 기다리는 중임
+ pub const BUSY: i64 = -23;
+ /// 이 이미지나 이 기계에 콘솔 입력 경로가 없거나, 커널이 그 경로를 껐음
+ pub const NO_DEVICE: i64 = -24;
}
/// 커널이 루트 태스크에 RO로 매핑해 주는 bootinfo 페이지 모듈입니다.
@@ -257,7 +292,10 @@ pub mod bootinfo {
/// bootinfo 페이지의 사용자 VA(양 플랫폼 그래뉼 정렬)
pub const VA: u64 = 0x0F00_0000;
/// 레이아웃 버전(불일치 시 루트 태스크는 진행하면 안 됨)
- pub const VERSION: u64 = 3;
+ ///
+ /// 버전 4부터 Console 케이퍼빌리티에 권한 비트가 있습니다(R = 입력 읽기,
+ /// W = 출력). 디스크립터의 `rights`가 그 값을 알립니다
+ pub const VERSION: u64 = 4;
/// 루트 태스크의 진입 레지스터 x4로 오는 시드 정보에서, 시드에 들어간
/// `rng-seed` 바이트 수를 담는 비트
@@ -301,8 +339,9 @@ pub mod bootinfo {
///
/// untyped는 `base` / `size`가 물리 구간입니다. 루트 태스크 이미지의
/// Frame은 `base`가 그 프레임이 루트 주소 공간에 매핑된 VA, `size`가
- /// 프레임 크기, `rights`가 권한 비트([super::rights])입니다. 나머지
- /// 종류는 전부 0입니다(커널 내부 주소 노출 최소화).
+ /// 프레임 크기, `rights`가 권한 비트([super::rights])입니다. Console은
+ /// `rights`만 채웁니다. 나머지 종류는 전부 0입니다(커널 내부 주소 노출
+ /// 최소화).
#[repr(C)]
pub struct CapDesc {
pub kind: u64,
diff --git a/crates/k0-abi/src/tests.rs b/crates/k0-abi/src/tests.rs
index 389192d..e6b6c81 100644
--- a/crates/k0-abi/src/tests.rs
+++ b/crates/k0-abi/src/tests.rs
@@ -29,6 +29,7 @@ fn syscall_numbers_are_unique_and_dense() {
syscall::CAP_MOVE,
syscall::CAP_DELETE,
syscall::CAP_REVOKE,
+ syscall::CONSOLE_READ,
];
assert_unique(&nrs.map(i128::from));
for (i, nr) in nrs.iter().enumerate() {
@@ -61,6 +62,8 @@ fn error_codes_are_unique_and_negative() {
err::TIMEOUT,
err::REPLY_TIMEOUT,
err::BAD_FLAGS,
+ err::BUSY,
+ err::NO_DEVICE,
];
assert_unique(&errs.map(i128::from));
for e in errs {
@@ -132,9 +135,22 @@ fn flag_register_bits_are_all_accounted_for() {
assert_eq!(ipc::NONBLOCK | ipc::RESERVED | ipc::timeout(u32::MAX), u64::MAX);
}
+#[test]
+fn console_read_flag_bits_are_all_accounted_for() {
+ assert_eq!(console::NONBLOCK & console::FLUSH, 0);
+ assert_eq!((console::NONBLOCK | console::FLUSH) & console::RESERVED, 0);
+ assert_eq!(
+ console::NONBLOCK | console::FLUSH | console::RESERVED | ipc::timeout(u32::MAX),
+ u64::MAX
+ );
+ // 블록하지 않는 읽기는 IPC와 같은 비트를 씀
+ assert_eq!(console::NONBLOCK, ipc::NONBLOCK);
+ assert_eq!(console::LOST, 1);
+}
+
#[test]
fn bootinfo_layout_is_stable() {
- assert_eq!(bootinfo::VERSION, 3);
+ assert_eq!(bootinfo::VERSION, 4);
assert_eq!(bootinfo::SEED_RNG_SEED_BYTES & bootinfo::SEED_RNDR, 0);
assert_eq!(size_of::(), 32);
assert_eq!(offset_of!(bootinfo::Header, version), 0);
diff --git a/crates/k0-arch/Cargo.toml b/crates/k0-arch/Cargo.toml
index e35d1ff..ba1c618 100644
--- a/crates/k0-arch/Cargo.toml
+++ b/crates/k0-arch/Cargo.toml
@@ -13,6 +13,10 @@ publish.workspace = true
console-pl011 = []
# 16550 계열. 읽기만으로 확인할 식별 레지스터가 없음
console-16550 = []
+# 콘솔 입력의 수신 경로(UART 수신 인터럽트와 그 SPI 하나). 수신 드라이버는
+# PL011과 SBSA UART에만 있어서 console-pl011과 함께 골라야 입력이 생김
+console-input = ["dep:k0-conin"]
[dependencies]
k0-abi = { path = "../k0-abi" }
+k0-conin = { path = "../k0-conin", optional = true }
diff --git a/crates/k0-arch/src/conin.rs b/crates/k0-arch/src/conin.rs
new file mode 100644
index 0000000..04de2ef
--- /dev/null
+++ b/crates/k0-arch/src/conin.rs
@@ -0,0 +1,205 @@
+//! 콘솔 입력의 커널 쪽 접착부 모듈입니다.
+//!
+//! # Features
+//! 수신 로직(링, 게이트, 유실 표시, 원인 없는 인터럽트의 차단)은 `k0-conin`
+//! 크레이트에 있고 호스트에서 가짜 UART로 시험됩니다. 이 모듈은 그 로직을 실제
+//! UART의 레지스터와 커널의 static 하나에 잇기만 합니다. feature
+//! `console-input`이 켜져 있을 때만 빌드되므로, 고르지 않은 이미지에는 UART에서
+//! 읽는 코드가 없습니다.
+//!
+//! 수신 드라이버는 PL011과 SBSA UART에만 있습니다(feature `console-pl011`).
+//! 16550 콘솔에서는 [prepare]가 false를 돌려주고 입력이 없습니다.
+//!
+//! 수신 상태는 인터럽트 핸들러와 시스템 콜 경로가 함께 씁니다. 단일 코어이고
+//! 모든 접근이 인터럽트를 마스크한 구간 안에서 이루어지므로 서로 겹치지
+//! 않습니다. 핸들러는 링에 바이트를 옮기기만 하고 스케줄러는 건드리지 않습니다.
+//! 기다리는 태스크를 깨우는 일은 커널이 자기 문맥에서 합니다.
+
+#[cfg(feature = "console-pl011")]
+mod pl011 {
+ use core::cell::UnsafeCell;
+ use core::sync::atomic::{AtomicBool, Ordering};
+
+ use k0_conin::{Irq, Reg, Regs, Rx};
+
+ use crate::earlycon::{mask_irqs, pl011_base, restore_irqs};
+
+ /// 매핑된 UART 레지스터에 닿는 통로입니다.
+ struct Mmio(usize);
+
+ impl Regs for Mmio {
+ fn read(&mut self, reg: Reg) -> u32 {
+ // SAFETY: prepare의 계약대로 매핑된 PL011 레지스터에 대한 volatile 접근
+ unsafe { core::ptr::read_volatile((self.0 + reg.offset()) as *const u32) }
+ }
+
+ fn write(&mut self, reg: Reg, value: u32) {
+ // SAFETY: prepare의 계약대로 매핑된 PL011 레지스터에 대한 volatile 접근
+ unsafe { core::ptr::write_volatile((self.0 + reg.offset()) as *mut u32, value) }
+ }
+ }
+
+ struct Cell(UnsafeCell);
+
+ // SAFETY: 단일 코어이고 모든 접근이 with 안에서 인터럽트를 마스크한 채
+ // 이루어지므로 동시에 두 곳에서 접근하지 않음
+ unsafe impl Sync for Cell {}
+
+ static RX: Cell = Cell(UnsafeCell::new(Rx::new(true)));
+ /// prepare가 끝나 수신 경로가 준비됐는지
+ static READY: AtomicBool = AtomicBool::new(false);
+
+ /// 인터럽트를 마스크한 채 수신 상태에 접근하는 함수입니다. 수신 경로가
+ /// 준비되지 않았으면 `None`입니다.
+ fn with(f: impl FnOnce(&mut Rx, &mut Mmio) -> R) -> Option {
+ if !READY.load(Ordering::Relaxed) {
+ return None;
+ }
+ let base = pl011_base()?;
+ let daif = mask_irqs();
+ // SAFETY: 인터럽트가 마스크된 단일 코어 구간이라 이 가변 참조는 유일함.
+ // 핸들러 안에서 불려도 그 핸들러가 끊은 코드는 이 구간 밖에 있음
+ let r = f(unsafe { &mut *RX.0.get() }, &mut Mmio(base));
+ restore_irqs(daif);
+ Some(r)
+ }
+
+ pub unsafe fn prepare(has_cr: bool) -> bool {
+ let Some(base) = pl011_base() else {
+ return false;
+ };
+ let daif = mask_irqs();
+ // SAFETY: 인터럽트가 마스크된 단일 코어 구간이고, 아직 READY가 아니라
+ // 다른 경로는 이 상태에 접근하지 않음
+ unsafe { *RX.0.get() = Rx::new(has_cr) };
+ Rx::quiesce(&mut Mmio(base));
+ READY.store(true, Ordering::Relaxed);
+ restore_irqs(daif);
+ true
+ }
+
+ pub fn available() -> bool {
+ with(|rx, _| !rx.is_off()).unwrap_or(false)
+ }
+
+ pub fn open() {
+ with(|rx, regs| rx.open(regs));
+ }
+
+ pub fn pop() -> Option<(u8, bool)> {
+ with(|rx, regs| rx.pop(regs)).flatten()
+ }
+
+ pub fn flush() {
+ with(|rx, regs| rx.flush(regs));
+ }
+
+ pub fn poll() {
+ with(|rx, regs| rx.poll(regs));
+ }
+
+ pub fn has_data() -> bool {
+ with(|rx, _| rx.has_data()).unwrap_or(false)
+ }
+
+ pub fn shut() {
+ with(|rx, regs| rx.turn_off(regs));
+ }
+
+ pub(crate) fn interrupt() -> Irq {
+ with(|rx, regs| rx.interrupt(regs)).unwrap_or(Irq::Spurious)
+ }
+}
+
+/// 수신 드라이버가 없는 빌드(16550만 고른 커널)에서 자리를 채우는 모듈입니다.
+/// 이 빌드에는 UART에서 읽는 코드가 없습니다.
+#[cfg(not(feature = "console-pl011"))]
+mod pl011 {
+ pub unsafe fn prepare(_has_cr: bool) -> bool {
+ false
+ }
+
+ pub fn available() -> bool {
+ false
+ }
+
+ pub fn open() {}
+
+ pub fn pop() -> Option<(u8, bool)> {
+ None
+ }
+
+ pub fn flush() {}
+
+ pub fn poll() {}
+
+ pub fn has_data() -> bool {
+ false
+ }
+
+ pub fn shut() {}
+
+ pub(crate) fn interrupt() -> k0_conin::Irq {
+ k0_conin::Irq::Spurious
+ }
+}
+
+/// 붙어 있는 콘솔에 수신 경로를 준비하는 함수입니다. UART의 인터럽트를 전부
+/// 막아 두기만 하고 켜지는 않습니다(켜는 것은 [open]).
+///
+/// 인터럽트 컨트롤러에서 콘솔의 선을 켜기 전에 불러야 합니다. 수신 드라이버가
+/// 없는 UART면 false를 돌려줍니다.
+///
+/// # Arguments
+/// `has_cr` - 제어 레지스터가 있는 UART(PL011)면 true, SBSA UART면 false
+///
+/// # Safety
+/// 콘솔이 [crate::earlycon::attach]로 붙어 있어야 하고, 그 레지스터 프레임에서
+/// 수신 로직이 쓰는 범위(오프셋 0x48 미만)가 Device로 매핑돼 있어야 합니다.
+pub unsafe fn prepare(has_cr: bool) -> bool {
+ // SAFETY: 함수 계약을 그대로 전달
+ unsafe { pl011::prepare(has_cr) }
+}
+
+/// 입력 경로가 있고 꺼지지 않았는지 알려 주는 함수입니다.
+pub fn available() -> bool {
+ pl011::available()
+}
+
+/// 입력을 쓰기 시작하는 함수입니다. 그동안 장치에 쌓인 바이트를 버리고 수신
+/// 인터럽트를 켭니다. 이미 열린 경로에는 아무 일도 하지 않습니다.
+pub fn open() {
+ pl011::open();
+}
+
+/// 받아 둔 바이트 하나를 꺼내는 함수입니다. 둘째 값은 이 바이트 바로 앞에서
+/// 입력이 유실됐는지입니다.
+pub fn pop() -> Option<(u8, bool)> {
+ pl011::pop()
+}
+
+/// 받아 둔 입력과 유실 표시를 전부 버리는 함수입니다.
+pub fn flush() {
+ pl011::flush();
+}
+
+/// 인터럽트 없이 장치의 FIFO를 들여다보는 함수입니다. 틱마다, 그리고 읽는
+/// 태스크가 잠들기 직전에 부릅니다.
+pub fn poll() {
+ pl011::poll();
+}
+
+/// 꺼낼 바이트가 있는지 알려 주는 함수입니다.
+pub fn has_data() -> bool {
+ pl011::has_data()
+}
+
+/// 입력 경로를 끄는 함수입니다. 되돌리지 않습니다.
+pub fn shut() {
+ pl011::shut();
+}
+
+/// 콘솔 인터럽트 하나를 처리하는 함수입니다.
+pub(crate) fn interrupt() -> k0_conin::Irq {
+ pl011::interrupt()
+}
diff --git a/crates/k0-arch/src/earlycon.rs b/crates/k0-arch/src/earlycon.rs
index 74d1119..87f7a6b 100644
--- a/crates/k0-arch/src/earlycon.rs
+++ b/crates/k0-arch/src/earlycon.rs
@@ -38,6 +38,8 @@ pub use uart::{Uart, attach, attached};
#[cfg(any(feature = "console-pl011", feature = "console-16550"))]
use uart::hw_put;
+#[cfg(all(feature = "console-pl011", feature = "console-input"))]
+pub(crate) use uart::pl011_base;
/// 드라이버가 하나도 없는 빌드에서 UART 송신 자리를 채우는 함수입니다.
/// 아무것도 하지 않으며, 이 빌드에는 UART에 접근하는 코드가 없습니다.
@@ -123,14 +125,14 @@ fn log_push(b: u8, user: bool) {
restore_irqs(daif);
}
-fn mask_irqs() -> u64 {
+pub(crate) fn mask_irqs() -> u64 {
let daif: u64;
// SAFETY: DAIF를 읽고 전부 마스크함, 호출자가 restore_irqs로 되돌림
unsafe { asm!("mrs {}, daif", "msr daifset, #0xf", out(reg) daif, options(nostack)) };
daif
}
-fn restore_irqs(daif: u64) {
+pub(crate) fn restore_irqs(daif: u64) {
// SAFETY: mask_irqs가 읽어 둔 값을 그대로 복원함
unsafe { asm!("msr daif, {}", in(reg) daif, options(nostack)) };
}
diff --git a/crates/k0-arch/src/earlycon/uart.rs b/crates/k0-arch/src/earlycon/uart.rs
index e74340f..13c8e48 100644
--- a/crates/k0-arch/src/earlycon/uart.rs
+++ b/crates/k0-arch/src/earlycon/uart.rs
@@ -1,7 +1,9 @@
//! 콘솔 UART 송신 드라이버 모듈입니다.
//!
//! # Features
-//! 커널이 기계 밖으로 출력을 내보내는 유일한 경로입니다. 송신만 합니다.
+//! 커널이 기계 밖으로 출력을 내보내는 유일한 경로입니다. 송신만 합니다(수신은
+//! feature `console-input`을 고른 빌드에서 [crate::conin]이 같은 레지스터
+//! 프레임으로 따로 합니다).
//! 초기화 쓰기와 보율 설정은 하지 않고 부트로더가 켜 둔 상태를 그대로 씁니다.
//! 송신 가능 대기에는 시간 상한이 있어서, 응답 없는 UART가 인터럽트를 막은 채
//! 커널을 붙잡지 못합니다.
@@ -188,6 +190,13 @@ pub unsafe fn attach(uart: Uart, base: usize, counter_hz: u64) {
}
}
+/// 붙어 있는 콘솔이 PL011(또는 SBSA UART)이면 그 레지스터 0의 주소를 주는
+/// 함수입니다. 수신 경로가 같은 레지스터 프레임을 씁니다.
+#[cfg(all(feature = "console-pl011", feature = "console-input"))]
+pub(crate) fn pl011_base() -> Option {
+ (KIND.load(Ordering::Relaxed) == KIND_PL011).then(|| BASE.load(Ordering::Relaxed))
+}
+
/// 콘솔이 붙어 있는지 알려 주는 함수입니다.
pub fn attached() -> bool {
KIND.load(Ordering::Relaxed) != KIND_NONE
diff --git a/crates/k0-arch/src/irq.rs b/crates/k0-arch/src/irq.rs
index 2567ed7..e49befc 100644
--- a/crates/k0-arch/src/irq.rs
+++ b/crates/k0-arch/src/irq.rs
@@ -9,6 +9,10 @@
//! 정리한 뒤, 타이머 PPI 하나만 켭니다. 가상 타이머를 쓰는 이유는 하이퍼바이저
//! 게스트에서도 항상 쓸 수 있는 타이머가 그것뿐이기 때문입니다.
//!
+//! feature `console-input`을 고른 빌드에서는 콘솔 UART의 SPI 하나를 더 받을 수
+//! 있습니다([enable_console_irq]). 그 번호는 DTB가 알려 준 것이라 틀릴 수 있고,
+//! 틀린 번호가 선을 붙들면 수신 로직이 몇 번 만에 그 선을 끕니다([crate::conin]).
+//!
//! 설계상 발생할 수 없는 FIQ와 미지의 `INTID`는 fail-secure로 정지합니다.
//!
//! 틱 주기는 1초입니다. 틱은 선점 신호이면서 IPC 타임아웃의 단위이고, EL0가
@@ -62,6 +66,15 @@ pub enum IrqError {
NoFrequency,
/// 타이머의 INTID가 PPI 범위(16..=31) 밖
BadIntid,
+ /// 콘솔 인터럽트 번호가 이 컨트롤러의 SPI 범위 밖임
+ #[cfg(feature = "console-input")]
+ SpiOutOfRange,
+ /// 콘솔의 SPI를 레벨 트리거로 둘 수 없음
+ #[cfg(feature = "console-input")]
+ SpiNotLevel,
+ /// 콘솔의 SPI가 이 보안 상태의 것이 아님(켜기 비트가 서지 않음)
+ #[cfg(feature = "console-input")]
+ SpiNotOwned,
}
const KIND_NONE: u8 = 0;
@@ -74,6 +87,18 @@ static GICC: AtomicUsize = AtomicUsize::new(0);
static TIMER_INTID: AtomicU32 = AtomicU32::new(0);
static TIMER_HZ: AtomicU64 = AtomicU64::new(0);
static TICKS: AtomicU64 = AtomicU64::new(0);
+/// 디스트리뷰터 레지스터의 가상 주소(콘솔의 SPI를 켜고 끄는 데 씀)
+#[cfg(feature = "console-input")]
+static GICD: AtomicUsize = AtomicUsize::new(0);
+/// 이 컨트롤러가 구현한 INTID의 수(1020을 넘지 않게 묶음)
+#[cfg(feature = "console-input")]
+static INTID_LIMIT: AtomicU32 = AtomicU32::new(0);
+/// 콘솔의 INTID. 켠 적이 없으면 어떤 INTID와도 같지 않은 값
+#[cfg(feature = "console-input")]
+static CONSOLE_INTID: AtomicU32 = AtomicU32::new(u32::MAX);
+/// 주기적인 틱 줄을 멈췄는지
+#[cfg(feature = "console-input")]
+static QUIET_TICKS: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false);
/// 로그에 남기는 틱 줄의 수. 이후의 틱은 콘솔에만 찍음
const LOGGED_TICKS: u64 = 4;
@@ -137,10 +162,33 @@ pub mod gicv3 {
use super::*;
const GICD_CTLR: usize = 0x0000;
- const GICD_TYPER: usize = 0x0004;
+ pub(super) const GICD_TYPER: usize = 0x0004;
+ #[cfg(feature = "console-input")]
+ const GICD_IGROUPR: usize = 0x0080;
+ #[cfg(feature = "console-input")]
+ const GICD_ISENABLER: usize = 0x0100;
const GICD_ICENABLER: usize = 0x0180;
const GICD_ICPENDR: usize = 0x0280;
const GICD_ICACTIVER: usize = 0x0380;
+ #[cfg(feature = "console-input")]
+ const GICD_IPRIORITYR: usize = 0x0400;
+ #[cfg(feature = "console-input")]
+ const GICD_ICFGR: usize = 0x0C00;
+ #[cfg(feature = "console-input")]
+ const GICD_IGRPMODR: usize = 0x0D00;
+ #[cfg(feature = "console-input")]
+ const GICD_IROUTER: u64 = 0x6000;
+
+ /// SPI의 라우팅 레지스터(GICD_IROUTER)가 디스트리뷰터 프레임 안에서 놓이는
+ /// 위치를 주는 함수입니다. 초기화에 쓰는 첫 페이지 밖에 있어서, 콘솔의
+ /// SPI를 켜려면 호출자가 그 페이지를 따로 매핑해야 합니다.
+ ///
+ /// # Arguments
+ /// `intid` - SPI의 INTID
+ #[cfg(feature = "console-input")]
+ pub const fn router_offset(intid: u32) -> u64 {
+ GICD_IROUTER + 8 * intid as u64
+ }
/// 식별 레지스터 PIDR2가 프레임 안에서 놓이는 위치
pub const PIDR2: u64 = 0xFFE8;
pub const GICR_TYPER: u64 = 0x0008;
@@ -379,6 +427,59 @@ pub mod gicv3 {
Ok(())
}
+ /// SPI 하나를 이 코어로 오게 구성하고 켜는 함수입니다.
+ ///
+ /// 비보안 Group 1, 타이머와 같은 우선순위, 레벨 트리거로 두고 이 코어의
+ /// 어피니티로 보냅니다. 보안 상태가 소유한 SPI는 비보안에서 쓰기가
+ /// 무시되므로 켜기 비트를 읽어 보아 가립니다.
+ ///
+ /// # Safety
+ /// `dist`는 [init]이 초기화를 마친 디스트리뷰터 프레임의 매핑된 주소,
+ /// `router`는 이 SPI의 라우팅 레지스터([router_offset])가 매핑된 주소여야
+ /// 하고, `intid`는 이 컨트롤러가 구현한 SPI여야 합니다.
+ #[cfg(feature = "console-input")]
+ pub(super) unsafe fn enable_spi(dist: usize, router: usize, intid: u32) -> Result<(), IrqError> {
+ let n = intid as usize;
+ let (word, bit) = (4 * (n / 32), 1u32 << (n % 32));
+ let mpidr: u64;
+ // SAFETY: MPIDR_EL1 읽기는 부작용이 없음
+ unsafe { asm!("mrs {}, mpidr_el1", out(reg) mpidr, options(nomem, nostack)) };
+ // GICD_IROUTER의 어피니티 배치는 MPIDR과 같음(Aff3이 비트 39..32). 비트
+ // 31(아무 코어로나 보내기)은 0으로 둠
+ let route = mpidr & 0xFF_00FF_FFFF;
+ // SAFETY: 함수 계약대로 매핑된 디스트리뷰터 레지스터에 대한 접근
+ unsafe {
+ write32(dist + GICD_IGROUPR + word, read32(dist + GICD_IGROUPR + word) | bit);
+ write32(dist + GICD_IGRPMODR + word, read32(dist + GICD_IGRPMODR + word) & !bit);
+ write8(dist + GICD_IPRIORITYR + n, PRIORITY as u8);
+ // 설정은 꺼진 동안에만 바꿀 수 있음. init이 SPI를 전부 꺼 두었음
+ let cfg = dist + GICD_ICFGR + 4 * (n / 16);
+ let cfg_bit = 1u32 << (2 * (n % 16) + 1);
+ write32(cfg, read32(cfg) & !cfg_bit);
+ if read32(cfg) & cfg_bit != 0 {
+ return Err(IrqError::SpiNotLevel);
+ }
+ core::ptr::write_volatile(router as *mut u64, route);
+ write32(dist + GICD_ISENABLER + word, bit);
+ wait_clear(dist + GICD_CTLR, CTLR_RWP, IrqError::GicRwpTimeout)?;
+ if read32(dist + GICD_ISENABLER + word) & bit == 0 {
+ return Err(IrqError::SpiNotOwned);
+ }
+ }
+ Ok(())
+ }
+
+ /// SPI 하나를 끄는 함수입니다.
+ ///
+ /// # Safety
+ /// [enable_spi]와 같습니다.
+ #[cfg(feature = "console-input")]
+ pub(super) unsafe fn disable_spi(dist: usize, intid: u32) {
+ let n = intid as usize;
+ // SAFETY: 함수 계약대로 매핑된 디스트리뷰터 레지스터에 대한 접근
+ unsafe { write32(dist + GICD_ICENABLER + 4 * (n / 32), 1u32 << (n % 32)) };
+ }
+
pub(super) fn ack() -> u64 {
let iar: u64;
// SAFETY: ICC_IAR1_EL1 읽기는 최고 우선순위 대기 인터럽트를 승인함
@@ -397,13 +498,15 @@ pub mod gicv2 {
use super::*;
const GICD_CTLR: usize = 0x000;
- const GICD_TYPER: usize = 0x004;
+ pub(super) const GICD_TYPER: usize = 0x004;
const GICD_IGROUPR: usize = 0x080;
const GICD_ISENABLER: usize = 0x100;
const GICD_ICENABLER: usize = 0x180;
const GICD_ICPENDR: usize = 0x280;
const GICD_ICACTIVER: usize = 0x380;
const GICD_IPRIORITYR: usize = 0x400;
+ #[cfg(feature = "console-input")]
+ const GICD_ITARGETSR: usize = 0x800;
const GICD_ICFGR: usize = 0xC00;
const GICD_PIDR2: usize = 0xFE8;
const GICC_CTLR: usize = 0x00;
@@ -481,6 +584,55 @@ pub mod gicv2 {
}
Ok(())
}
+
+ /// SPI 하나를 이 코어로 오게 구성하고 켜는 함수입니다.
+ ///
+ /// # Safety
+ /// `dist`는 [init]이 초기화를 마친 디스트리뷰터 프레임의 매핑된 주소여야
+ /// 하고, `intid`는 이 컨트롤러가 구현한 SPI여야 합니다.
+ #[cfg(feature = "console-input")]
+ pub(super) unsafe fn enable_spi(dist: usize, intid: u32) -> Result<(), IrqError> {
+ let n = intid as usize;
+ let (word, bit) = (4 * (n / 32), 1u32 << (n % 32));
+ // SAFETY: 함수 계약대로 매핑된 디스트리뷰터 레지스터에 대한 접근
+ unsafe {
+ // 타이머와 같은 그룹에 둠. 보안 확장이 있으면 이 레지스터는
+ // 비보안에서 읽기 0 / 쓰기 무시임
+ if read32(dist + GICD_TYPER) & (1 << 10) == 0 {
+ write32(dist + GICD_IGROUPR + word, read32(dist + GICD_IGROUPR + word) & !bit);
+ }
+ write8(dist + GICD_IPRIORITYR + n, PRIORITY as u8);
+ let cfg = dist + GICD_ICFGR + 4 * (n / 16);
+ let cfg_bit = 1u32 << (2 * (n % 16) + 1);
+ write32(cfg, read32(cfg) & !cfg_bit);
+ if read32(cfg) & cfg_bit != 0 {
+ return Err(IrqError::SpiNotLevel);
+ }
+ // 이 CPU 인터페이스의 마스크는 ITARGETSR0의 첫 바이트로 읽힘. CPU가
+ // 하나뿐인 구현에서는 이 레지스터가 읽기 0 / 쓰기 무시이고 모든
+ // 인터럽트가 그 CPU로 가므로, 0이면 쓰지 않음
+ let me = read32(dist + GICD_ITARGETSR) & 0xFF;
+ if me != 0 {
+ write8(dist + GICD_ITARGETSR + n, me as u8);
+ }
+ write32(dist + GICD_ISENABLER + word, bit);
+ if read32(dist + GICD_ISENABLER + word) & bit == 0 {
+ return Err(IrqError::SpiNotOwned);
+ }
+ }
+ Ok(())
+ }
+
+ /// SPI 하나를 끄는 함수입니다.
+ ///
+ /// # Safety
+ /// [enable_spi]와 같습니다.
+ #[cfg(feature = "console-input")]
+ pub(super) unsafe fn disable_spi(dist: usize, intid: u32) {
+ let n = intid as usize;
+ // SAFETY: 함수 계약대로 매핑된 디스트리뷰터 레지스터에 대한 접근
+ unsafe { write32(dist + GICD_ICENABLER + 4 * (n / 32), 1u32 << (n % 32)) };
+ }
}
/// 초기화할 인터럽트 컨트롤러와 그 레지스터의 가상 주소입니다.
@@ -524,8 +676,20 @@ fn timer_arm(interval: u64) {
fn timer_tick() {
let n = TICKS.load(Ordering::Relaxed) + 1;
TICKS.store(n, Ordering::Relaxed);
+ // 수신 인터럽트가 오지 않는 UART(수신 타임아웃이 없거나 번호가 조용히
+ // 틀린 경우)에서도 입력이 늦게나마 도착하게 틱마다 한 번 들여다봄. 닫혀
+ // 있는 동안에는 아무 일도 하지 않음
+ #[cfg(feature = "console-input")]
+ crate::conin::poll();
+ // 태스크가 콘솔 입력을 쓰기 시작한 뒤에는 틱 줄을 내지 않음(입력하는 줄
+ // 사이에 끼어들지 않게). 틱과 타임아웃은 그대로 동작함
+ #[cfg(feature = "console-input")]
+ let quiet = QUIET_TICKS.load(Ordering::Relaxed);
+ #[cfg(not(feature = "console-input"))]
+ let quiet = false;
// 틱은 끝없이 이어지므로 처음 몇 줄만 로그에 남김
- if n <= LOGGED_TICKS {
+ if quiet {
+ } else if n <= LOGGED_TICKS {
let _ = writeln!(EarlyCon, "k0: tick {n}");
} else {
// 콘솔 드라이버가 없는 빌드에는 쓸 곳이 없으므로 서식 작업도 하지 않음
@@ -543,6 +707,100 @@ pub fn ticks() -> u64 {
TICKS.load(Ordering::Relaxed)
}
+/// 주기적인 틱 줄을 멈추는 함수입니다. 처음 불렸으면 true를 돌려줍니다.
+///
+/// 태스크가 콘솔 입력을 쓰기 시작할 때 커널이 부릅니다. 틱 자체와 IPC
+/// 타임아웃은 그대로 동작합니다.
+#[cfg(feature = "console-input")]
+pub fn quiet_ticks() -> bool {
+ !QUIET_TICKS.swap(true, Ordering::Relaxed)
+}
+
+/// 콘솔 UART의 SPI를 이 코어로 오게 구성하고 켜는 함수입니다.
+///
+/// UART 쪽의 인터럽트는 [crate::conin::prepare]가 먼저 전부 막아 두었어야
+/// 합니다. 그래야 여기서 선을 켜도 태스크가 입력을 쓰기 전까지는 인터럽트가
+/// 오지 않습니다.
+///
+/// # Arguments
+/// `_irq` - 컨트롤러가 초기화됐음을 증명하는 토큰
+/// `intid` - DTB가 알려 준 콘솔의 INTID
+/// `router` - GICv3에서 이 SPI의 라우팅 레지스터([gicv3::router_offset])가
+/// 매핑된 주소. GICv2에서는 쓰지 않음
+///
+/// # Safety
+/// [init]에 넘긴 디스트리뷰터의 매핑이 그대로 살아 있어야 하고, GICv3라면
+/// `router`가 Device로 매핑된 그 레지스터의 주소여야 합니다.
+///
+/// # Errors
+/// 번호가 이 컨트롤러의 SPI가 아니거나 타이머의 번호이면 `SpiOutOfRange`,
+/// 레벨 트리거로 둘 수 없으면 `SpiNotLevel`, 켜기 비트가 서지 않으면
+/// `SpiNotOwned`. 어느 경우든 잃는 것은 콘솔 입력뿐이고 부팅은 계속됩니다
+#[cfg(feature = "console-input")]
+pub unsafe fn enable_console_irq(_irq: &Irq, intid: u32, router: Option) -> Result<(), IrqError> {
+ let limit = INTID_LIMIT.load(Ordering::Relaxed);
+ if !(32..limit).contains(&intid) || intid == TIMER_INTID.load(Ordering::Relaxed) {
+ return Err(IrqError::SpiOutOfRange);
+ }
+ let dist = GICD.load(Ordering::Relaxed);
+ // 켜자마자 인터럽트가 올 수 있으므로 분배기가 알아볼 번호를 먼저 적어 둠
+ CONSOLE_INTID.store(intid, Ordering::Relaxed);
+ // SAFETY: 함수 계약대로 매핑된 디스트리뷰터이고 번호는 위에서 확인한 SPI임
+ let r = unsafe {
+ match KIND.load(Ordering::Relaxed) {
+ KIND_V3 => match router {
+ Some(router) => gicv3::enable_spi(dist, router, intid),
+ None => Err(IrqError::ProbeFailed),
+ },
+ KIND_V2 => gicv2::enable_spi(dist, intid),
+ _ => Err(IrqError::WrongGic),
+ }
+ };
+ if r.is_err() {
+ // 반쯤 구성된 선은 꺼 둠. 번호는 그대로 두어, 이미 전달돼 있던
+ // 인터럽트가 "미지의 INTID"로 커널을 멈추지 않게 함
+ // SAFETY: 위와 같음
+ unsafe { disable_console_irq() };
+ }
+ r
+}
+
+/// 콘솔의 SPI를 끄는 함수입니다.
+///
+/// # Safety
+/// [enable_console_irq]와 같습니다.
+#[cfg(feature = "console-input")]
+unsafe fn disable_console_irq() {
+ let (dist, intid) = (GICD.load(Ordering::Relaxed), CONSOLE_INTID.load(Ordering::Relaxed));
+ if intid == u32::MAX {
+ return;
+ }
+ // SAFETY: 함수 계약을 그대로 전달
+ unsafe {
+ match KIND.load(Ordering::Relaxed) {
+ KIND_V3 => gicv3::disable_spi(dist, intid),
+ KIND_V2 => gicv2::disable_spi(dist, intid),
+ _ => {}
+ }
+ }
+}
+
+/// 콘솔 인터럽트 하나를 처리하는 함수입니다.
+///
+/// 수신 로직이 원인 없는 인터럽트가 이어진다고 판단하면(DTB가 다른 장치의
+/// 번호를 준 경우) 컨트롤러에서 그 선을 끄고 한 줄을 남깁니다. 커널은 계속
+/// 실행되고 입력만 없어집니다.
+#[cfg(feature = "console-input")]
+fn console_irq() {
+ if crate::conin::interrupt() == k0_conin::Irq::CutOff {
+ // SAFETY: 이 인터럽트가 왔다는 것은 enable_console_irq가 선을 켰다는
+ // 뜻이고, 그 계약대로 디스트리뷰터가 매핑돼 있음
+ unsafe { disable_console_irq() };
+ let intid = CONSOLE_INTID.load(Ordering::Relaxed);
+ let _ = writeln!(EarlyCon, "k0: console input off (interrupt {intid} fired without a uart cause)");
+ }
+}
+
/// 실행할 태스크가 없을 때 다음 인터럽트까지 코어를 재우고 그 인터럽트를
/// 처리하는 함수입니다.
///
@@ -596,12 +854,16 @@ pub unsafe fn init(_vectors: &Vectors, gic: &Gic, intid: u32, hz: u64) -> Result
Gic::V3(frames) => unsafe {
gicv3::init(frames, intid)?;
KIND.store(KIND_V3, Ordering::Relaxed);
+ #[cfg(feature = "console-input")]
+ remember_distributor(frames.dist, read32(frames.dist + gicv3::GICD_TYPER));
},
// SAFETY: 함수 계약을 그대로 전달
Gic::V2 { dist, cpu } => unsafe {
gicv2::init(*dist, *cpu, intid)?;
GICC.store(*cpu, Ordering::Relaxed);
KIND.store(KIND_V2, Ordering::Relaxed);
+ #[cfg(feature = "console-input")]
+ remember_distributor(*dist, read32(*dist + gicv2::GICD_TYPER));
},
}
TIMER_INTID.store(intid, Ordering::Relaxed);
@@ -614,6 +876,15 @@ pub unsafe fn init(_vectors: &Vectors, gic: &Gic, intid: u32, hz: u64) -> Result
Ok(Irq { _sealed: () })
}
+/// 콘솔의 SPI를 켤 때 쓸 디스트리뷰터 주소와 INTID의 상한을 적어 두는
+/// 함수입니다. 상한은 GICD_TYPER의 ITLinesNumber에서 나오고, 1020부터는 특수
+/// 번호라 넘지 않게 묶습니다.
+#[cfg(feature = "console-input")]
+fn remember_distributor(dist: usize, typer: u32) {
+ GICD.store(dist, Ordering::Relaxed);
+ INTID_LIMIT.store((32 * ((typer & 0x1F) + 1)).min(1020), Ordering::Relaxed);
+}
+
/// 설계상 발생할 수 없는 인터럽트를 fail-secure로 정지시키는 함수입니다.
///
/// # Arguments
@@ -637,13 +908,32 @@ unsafe extern "C" {
/// EL0에서 진입한 IRQ/FIQ 컨텍스트에서 벡터가 사용자 컨텍스트 저장을
/// 마친 뒤에만 호출됩니다.
fn k0_preempt();
+
+ /// 콘솔 입력이 도착했을 때 기다리는 태스크를 깨우는 정책, 커널 바이너리가
+ /// 정의함 (링크 계약)
+ ///
+ /// # Safety
+ /// [k0_preempt]와 같습니다.
+ #[cfg(feature = "console-input")]
+ fn k0_console_event();
}
+/// 분배 결과: 타이머 틱이었음(EL0 경로의 선점 판단용)
+const EV_TICK: u8 = 1;
+/// 분배 결과: 콘솔 인터럽트였음(기다리는 태스크를 깨울지 커널이 판단)
+#[cfg(feature = "console-input")]
+const EV_CONSOLE: u8 = 2;
+
/// EL1과 EL0 양쪽 IRQ 벡터가 공유하는 실제 분배 함수입니다.
///
-/// 타이머 틱이었으면 true를 반환합니다(EL0 경로의 선점 판단용).
-fn dispatch_irq() -> bool {
+/// 무슨 인터럽트였는지를 `EV_` 비트로 돌려줍니다. 콘솔 인터럽트의 가지는 그
+/// 선을 끈 뒤에도 남겨 둡니다. 끄기 전에 이미 CPU로 전달돼 있던 인터럽트가
+/// 미지의 INTID로 취급되어 커널을 멈추면 안 되기 때문입니다(그때의 수신
+/// 로직은 레지스터를 건드리지 않고 돌아옴).
+fn dispatch_irq() -> u8 {
let timer = u64::from(TIMER_INTID.load(Ordering::Relaxed));
+ #[cfg(feature = "console-input")]
+ let console = u64::from(CONSOLE_INTID.load(Ordering::Relaxed));
match KIND.load(Ordering::Relaxed) {
KIND_V3 => {
let iar = gicv3::ack();
@@ -651,9 +941,15 @@ fn dispatch_irq() -> bool {
id if id == timer => {
timer_tick();
gicv3::eoi(iar);
- true
+ EV_TICK
}
- 1020..=1023 => false, // 스퓨리어스: 승인 없이 복귀
+ #[cfg(feature = "console-input")]
+ id if id == console => {
+ console_irq();
+ gicv3::eoi(iar);
+ EV_CONSOLE
+ }
+ 1020..=1023 => 0, // 스퓨리어스: 승인 없이 복귀
other => unexpected("irq", other),
}
}
@@ -666,9 +962,16 @@ fn dispatch_irq() -> bool {
timer_tick();
// SAFETY: 승인에서 받은 값 그대로 완료 통지
unsafe { write32(cpu + gicv2::GICC_EOIR, iar) };
- true
+ EV_TICK
}
- 1020..=1023 => false,
+ #[cfg(feature = "console-input")]
+ id if id == console => {
+ console_irq();
+ // SAFETY: 승인에서 받은 값 그대로 완료 통지
+ unsafe { write32(cpu + gicv2::GICC_EOIR, iar) };
+ EV_CONSOLE
+ }
+ 1020..=1023 => 0,
other => unexpected("irq", other),
}
}
@@ -680,7 +983,7 @@ fn dispatch_irq() -> bool {
///
/// 커널은 모든 인터럽트를 IRQ로만 받으므로 FIQ는 설계상 없고, 들어오면
/// fail-secure로 정지합니다.
-fn dispatch_fiq() -> bool {
+fn dispatch_fiq() -> u8 {
unexpected("fiq", 0)
}
@@ -705,7 +1008,13 @@ extern "C" fn fiq_current() {
/// 복원하며 수행합니다.
#[unsafe(no_mangle)]
extern "C" fn irq_lower(_ctx: &mut crate::usermode::Context) {
- if dispatch_irq() {
+ let events = dispatch_irq();
+ #[cfg(feature = "console-input")]
+ if events & EV_CONSOLE != 0 {
+ // SAFETY: 벡터가 사용자 컨텍스트 저장을 마친 EL0 IRQ 경로임
+ unsafe { k0_console_event() };
+ }
+ if events & EV_TICK != 0 {
// SAFETY: 벡터가 사용자 컨텍스트 저장을 마친 EL0 IRQ 경로임
unsafe { k0_preempt() };
}
@@ -714,7 +1023,7 @@ extern "C" fn irq_lower(_ctx: &mut crate::usermode::Context) {
/// 사용자 공간(EL0) 실행 중 FIQ 벡터가 사용하는 디스패처 함수입니다.
#[unsafe(no_mangle)]
extern "C" fn fiq_lower(_ctx: &mut crate::usermode::Context) {
- if dispatch_fiq() {
+ if dispatch_fiq() & EV_TICK != 0 {
// SAFETY: 벡터가 사용자 컨텍스트 저장을 마친 EL0 FIQ 경로임
unsafe { k0_preempt() };
}
diff --git a/crates/k0-arch/src/lib.rs b/crates/k0-arch/src/lib.rs
index 52d44b9..a87afeb 100644
--- a/crates/k0-arch/src/lib.rs
+++ b/crates/k0-arch/src/lib.rs
@@ -7,6 +7,8 @@
#![no_std]
+#[cfg(feature = "console-input")]
+pub mod conin;
pub mod earlycon;
pub mod hardening;
pub mod irq;
diff --git a/crates/k0-boot/Cargo.toml b/crates/k0-boot/Cargo.toml
index 49853ec..73b1087 100644
--- a/crates/k0-boot/Cargo.toml
+++ b/crates/k0-boot/Cargo.toml
@@ -13,6 +13,10 @@ roottask = []
# 보고 루트 태스크의 빌드에 같은 이름의 feature를 넘김
vault = ["roottask"]
vault-ed25519 = ["vault"]
+# 콘솔 입력: 루트 태스크의 자가 검증에 입력 시스템 콜의 시험을 넣음
+console-input = ["roottask"]
+# 운영자 터미널: 자가 검증 뒤에 서비스(볼트가 있으면 볼트와 터미널)를 시작함
+terminal = ["console-input"]
# 테스트용 DTB 빌더와 퍼즈 도우미를 다른 크레이트의 테스트에 공개함(std 필요)
test-support = []
diff --git a/crates/k0-boot/build.rs b/crates/k0-boot/build.rs
index d19ed2f..8e12e32 100644
--- a/crates/k0-boot/build.rs
+++ b/crates/k0-boot/build.rs
@@ -152,6 +152,8 @@ fn main() {
for (var, name) in [
("CARGO_FEATURE_VAULT", "vault"),
("CARGO_FEATURE_VAULT_ED25519", "vault-ed25519"),
+ ("CARGO_FEATURE_CONSOLE_INPUT", "console-input"),
+ ("CARGO_FEATURE_TERMINAL", "terminal"),
] {
if env::var_os(var).is_some() {
features.push(name);
@@ -252,6 +254,8 @@ fn main() {
"userspace/root-task/src",
"userspace/k0-vault/src",
"userspace/k0-vault/Cargo.toml",
+ "userspace/k0-term/src",
+ "userspace/k0-term/Cargo.toml",
"Cargo.lock",
"userspace/root-task/Cargo.toml",
"userspace/root-task/build.rs",
diff --git a/crates/k0-boot/src/platform.rs b/crates/k0-boot/src/platform.rs
index f64f06f..037de83 100644
--- a/crates/k0-boot/src/platform.rs
+++ b/crates/k0-boot/src/platform.rs
@@ -65,6 +65,10 @@ pub struct Console {
pub span: u64,
/// DTB가 선언한 레지스터 구간 전체 (겹침 검사용)
pub reg: Region,
+ /// 콘솔의 인터럽트 번호(INTID). 노드에 없거나, 발견한 인터럽트 컨트롤러의
+ /// SPI 하나로 읽히지 않으면 `None`이고 그때는 콘솔 입력이 없습니다.
+ /// 인터럽트를 못 읽는 것은 부팅 거부 사유가 아닙니다.
+ pub irq: Option,
}
/// 인터럽트 컨트롤러를 나타내는 열거형입니다.
@@ -240,12 +244,13 @@ pub fn discover_blob(blob: &[u8]) -> Result {
return Err(DiscoverError::DuplicatePhandle);
}
let (intc, interrupt_cells) = intc.ok_or(DiscoverError::IntcNotFound)??;
+ let timer_parent = timer.parent;
let timer = Timer {
intid: timer_intid(&timer, interrupt_cells)?,
clock_hz: timer.clock.unwrap_or(0),
};
- let (console, no_console) = match find_console(&fdt, stdout)? {
+ let (console, no_console) = match find_console(&fdt, stdout, Some((timer_parent, interrupt_cells)))? {
Ok(c) => (Some(c), None),
Err(why) => (None, Some(why)),
};
@@ -531,7 +536,15 @@ fn read_intc(levels: &Levels<'_>, node: &Node<'_>, depth: usize) -> Result<(Intc
///
/// 콘솔을 못 찾는 경우는 전부 안쪽 `Err(NoConsole)`이고, 바깥 `Err`는 DTB
/// 구조 위반뿐입니다.
-fn find_console(fdt: &Fdt<'_>, stdout: Option<&[u8]>) -> Result, BootError> {
+///
+/// `gic`는 발견한 인터럽트 컨트롤러의 phandle과 `#interrupt-cells`입니다. 주면
+/// 콘솔의 인터럽트도 읽고, `None`이면(컨트롤러를 찾기 전의 조기 콘솔 탐색)
+/// 인터럽트 없이 돌려줍니다.
+fn find_console(
+ fdt: &Fdt<'_>,
+ stdout: Option<&[u8]>,
+ gic: Option<(u32, u32)>,
+) -> Result, BootError> {
let Some(value) = stdout else {
return Ok(Err(NoConsole::NoStdoutPath));
};
@@ -569,7 +582,10 @@ fn find_console(fdt: &Fdt<'_>, stdout: Option<&[u8]>) -> Result, stdout: Option<&[u8]>) -> Result, node: &Node<'_>, depth: usize, gic: u32, cells: u32) -> Option {
+ if node.has(P::InterruptsExtended) {
+ return None;
+ }
+ let spec = node.get(P::Interrupts)?;
+ let mut parent = node.u32(P::InterruptParent).ok()?;
+ let mut k = depth;
+ while parent.is_none() && k > 1 {
+ k -= 1;
+ if levels[k].has_interrupt_cells {
+ return None;
+ }
+ parent = levels[k].interrupt_parent().ok()?;
+ }
+ if parent? != gic || cells != 3 || spec.len() != 12 {
+ return None;
+ }
+ let cell = |i: usize| read_cells(&spec[i * 4..i * 4 + 4]);
+ // SPI 번호의 상한 987은 INTID 1019(1020부터는 특수 번호)
+ if cell(0) != 0 || cell(1) > 987 || cell(2) != 4 {
+ return None;
+ }
+ Some(32 + cell(1) as u32)
+}
+
fn read_console(levels: &Levels<'_>, node: &Node<'_>, depth: usize) -> Result {
if !usable(levels, node, depth) {
return Err(NoConsole::Disabled);
@@ -651,6 +700,7 @@ fn read_console(levels: &Levels<'_>, node: &Node<'_>, depth: usize) -> Result Option {
Ok(Flow::Continue)
})
.ok()?;
- find_console(&fdt, stdout).ok()?.ok()
+ find_console(&fdt, stdout, None).ok()?.ok()
}
impl fmt::Display for Platform {
@@ -808,13 +858,19 @@ impl fmt::Display for Platform {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.console {
None => write!(f, "con=none")?,
- Some(c) => match c.kind {
- ConsoleKind::Pl011 => write!(f, "con=pl011@{:#x}", c.base)?,
- ConsoleKind::SbsaUart => write!(f, "con=sbsa@{:#x}", c.base)?,
- ConsoleKind::Ns16550 { reg_shift, io_width } => {
- write!(f, "con=ns16550@{:#x},s{reg_shift},w{io_width}", c.base)?;
+ Some(c) => {
+ match c.kind {
+ ConsoleKind::Pl011 => write!(f, "con=pl011@{:#x}", c.base)?,
+ ConsoleKind::SbsaUart => write!(f, "con=sbsa@{:#x}", c.base)?,
+ ConsoleKind::Ns16550 { reg_shift, io_width } => {
+ write!(f, "con=ns16550@{:#x},s{reg_shift},w{io_width}", c.base)?;
+ }
}
- },
+ // 커널이 켜는 인터럽트이므로 플랫폼 줄(고정 모드의 대조 대상)에 넣음
+ if let Some(irq) = c.irq {
+ write!(f, ",irq{irq}")?;
+ }
+ }
}
match &self.intc {
Intc::GicV2 { dist, cpu } => write!(f, " gic=v2@{:#x} cpu={:#x}", dist.base, cpu.base)?,
diff --git a/crates/k0-boot/src/platform/tests.rs b/crates/k0-boot/src/platform/tests.rs
index 6c7c5fc..89d42f4 100644
--- a/crates/k0-boot/src/platform/tests.rs
+++ b/crates/k0-boot/src/platform/tests.rs
@@ -36,6 +36,7 @@ fn qemu_virt_gicv3_is_discovered() {
base: 0x900_0000,
span: 0x1C,
reg: Region { base: 0x900_0000, size: 0x1000 },
+ irq: Some(33),
}),
intc: Intc::GicV3 {
dist: Region { base: 0x800_0000, size: 0x1_0000 },
@@ -48,7 +49,7 @@ fn qemu_virt_gicv3_is_discovered() {
);
assert_eq!(
d.platform.to_string(),
- "con=pl011@0x9000000 gic=v3@0x8000000 rd=0x80a0000+0xf60000 tmr=27"
+ "con=pl011@0x9000000,irq33 gic=v3@0x8000000 rd=0x80a0000+0xf60000 tmr=27"
);
}
@@ -65,7 +66,7 @@ fn qemu_virt_gicv2_is_discovered() {
assert_eq!(d.platform.timer.intid, 27);
assert_eq!(
d.platform.to_string(),
- "con=pl011@0x9000000 gic=v2@0x8000000 cpu=0x8010000 tmr=27"
+ "con=pl011@0x9000000,irq33 gic=v2@0x8000000 cpu=0x8010000 tmr=27"
);
}
@@ -79,6 +80,7 @@ fn raspberry_pi_4_shape_is_translated_through_soc_ranges() {
base: 0xfe21_5040,
span: 24,
reg: Region { base: 0xfe21_5040, size: 0x40 },
+ irq: None,
})
);
assert_eq!(
@@ -104,12 +106,89 @@ fn rk3399_shape_uses_four_cell_specifiers_and_a_shifted_uart() {
base: 0xff1a_0000,
span: 24,
reg: Region { base: 0xff1a_0000, size: 0x100 },
+ irq: None,
})
);
assert_eq!(d.platform.intc.redist(), &[Region { base: 0xfef0_0000, size: 0xc_0000 }]);
assert_eq!(d.platform.timer.intid, 27);
}
+#[test]
+fn the_console_interrupt_is_one_level_high_spi_of_the_discovered_controller() {
+ let irq = |t: &N| ok(t).platform.console.unwrap().irq;
+ assert_eq!(irq(&virt3()), Some(33));
+ assert_eq!(irq(&virt2()), Some(33));
+
+ // 가장 큰 SPI 번호는 INTID 1019
+ let mut t = virt3();
+ t.kid("pl011@9000000").set("interrupts", cells(&[0, 987, 4]));
+ assert_eq!(irq(&t), Some(1019));
+ assert!(ok(&t).platform.to_string().starts_with("con=pl011@0x9000000,irq1019 "));
+
+ // 받지 않는 모양은 전부 "인터럽트 없음"이고 부팅 거부가 아님
+ let bad: [&[u32]; 9] = [
+ &[0, 988, 4], // 특수 INTID에 닿는 번호
+ &[1, 1, 4], // PPI
+ &[2, 1, 4], // 모르는 종류
+ &[0, 1, 1], // 에지 트리거
+ &[0, 1, 8], // 액티브 로우
+ &[0, 1, 0x104], // 플래그에 다른 비트
+ &[0, 1], // 셀이 모자람
+ &[0, 1, 4, 0], // 셀이 남음
+ &[0, 1, 4, 0, 2, 4], // 항목이 둘
+ ];
+ for spec in bad {
+ let mut t = virt3();
+ t.kid("pl011@9000000").set("interrupts", cells(spec));
+ let d = ok(&t);
+ assert_eq!(d.platform.console.unwrap().irq, None, "{spec:?}");
+ assert!(d.platform.to_string().starts_with("con=pl011@0x9000000 gic="), "{spec:?}");
+ }
+
+ // 속성이 없는 콘솔, interrupts-extended를 쓰는 콘솔
+ let mut t = virt3();
+ t.kid("pl011@9000000").del("interrupts");
+ assert_eq!(irq(&t), None);
+ let mut t = virt3();
+ t.kid("pl011@9000000").set("interrupts-extended", cells(&[GIC_PHANDLE, 0, 1, 4]));
+ assert_eq!(irq(&t), None);
+
+ // 인터럽트 부모가 발견한 컨트롤러가 아니면 읽지 않음
+ let mut t = virt3();
+ t.kid("pl011@9000000").set("interrupt-parent", cells(&[GIC_PHANDLE + 1]));
+ assert_eq!(irq(&t), None);
+ // 노드 자신의 interrupt-parent가 그 컨트롤러면 읽음
+ let mut t = virt3();
+ t.kid("pl011@9000000").set("interrupt-parent", cells(&[GIC_PHANDLE]));
+ assert_eq!(irq(&t), Some(33));
+}
+
+#[test]
+fn a_controller_with_four_cell_specifiers_gives_no_console_interrupt() {
+ // rk3399 모양: 컨트롤러의 #interrupt-cells가 4라서 셀 셋짜리 지정자를
+ // 추측해 읽지 않음
+ let mut t = rk3399();
+ let d = ok(&t);
+ assert_eq!(d.platform.console.unwrap().irq, None);
+ // 지정자를 넷으로 맞춰 줘도 받지 않음(받는 모양은 셀 셋뿐)
+ fn uart(n: &mut N) -> Option<&mut N> {
+ if n.name.starts_with("serial@") {
+ return Some(n);
+ }
+ n.kids.iter_mut().find_map(uart)
+ }
+ if let Some(u) = uart(&mut t) {
+ u.set("interrupts", cells(&[0, 100, 4, 0]));
+ }
+ assert_eq!(ok(&t).platform.console.unwrap().irq, None);
+}
+
+#[test]
+fn early_console_discovery_does_not_read_the_interrupt() {
+ // 컨트롤러를 찾기 전의 조기 탐색은 출력만 쓰므로 인터럽트를 읽지 않음
+ assert_eq!(console_of(&virt3().blob()).unwrap().irq, None);
+}
+
#[test]
fn the_virtual_timer_number_comes_from_the_tree() {
// Qualcomm sdm845: <1 1>, <1 2>, <1 3>, <1 0>
@@ -217,7 +296,7 @@ fn console_nodes_are_checked_before_use() {
let mut t = virt3();
t.kid("pl011@9000000").set("compatible", strs(&["arm,sbsa-uart"]));
assert_eq!(ok(&t).platform.console.map(|c| c.kind), Some(ConsoleKind::SbsaUart));
- assert!(ok(&t).platform.to_string().starts_with("con=sbsa@0x9000000 "));
+ assert!(ok(&t).platform.to_string().starts_with("con=sbsa@0x9000000,irq33 "));
}
#[test]
diff --git a/crates/k0-boot/src/testing.rs b/crates/k0-boot/src/testing.rs
index 7a7da70..3c8be64 100644
--- a/crates/k0-boot/src/testing.rs
+++ b/crates/k0-boot/src/testing.rs
@@ -237,6 +237,7 @@ pub fn pl011() -> N {
N::new("pl011@9000000")
.p("compatible", strs(&["arm,pl011", "arm,primecell"]))
.p("reg", cells(&[0, 0x900_0000, 0, 0x1000]))
+ .p("interrupts", cells(&[0, 1, 4]))
}
pub fn gicv3() -> N {
diff --git a/crates/k0-cap/Cargo.toml b/crates/k0-cap/Cargo.toml
index b200c33..06d36e7 100644
--- a/crates/k0-cap/Cargo.toml
+++ b/crates/k0-cap/Cargo.toml
@@ -5,4 +5,9 @@ edition.workspace = true
license.workspace = true
publish.workspace = true
+# 루트 CNode를 1024슬롯으로 만듦. 자가 검증 뒤에 서비스를 새로 띄우는 이미지
+# (터미널)가 켬. 주지 않으면 512슬롯 그대로임
+[features]
+root-cnode-1024 = []
+
[dependencies]
diff --git a/crates/k0-cap/src/lib.rs b/crates/k0-cap/src/lib.rs
index f808044..237e471 100644
--- a/crates/k0-cap/src/lib.rs
+++ b/crates/k0-cap/src/lib.rs
@@ -38,7 +38,14 @@ use core::ptr;
pub const SLOT_SIZE: usize = 64;
/// 루트 CNode의 슬롯 수
+///
+/// 자가 검증 뒤에 서비스(볼트와 터미널)를 새로 띄우는 이미지는 주소 공간 둘을
+/// 더 만들 슬롯이 필요하므로 feature `root-cnode-1024`로 두 배를 받습니다.
+/// 그 밖의 이미지는 그대로입니다.
+#[cfg(not(feature = "root-cnode-1024"))]
pub const ROOT_CNODE_SLOTS: usize = 512;
+#[cfg(feature = "root-cnode-1024")]
+pub const ROOT_CNODE_SLOTS: usize = 1024;
/// 파생 깊이 상한, 초과하는 복사는 거부됩니다
pub const MAX_DEPTH: u64 = 1 << 32;
@@ -46,7 +53,8 @@ pub const MAX_DEPTH: u64 = 1 << 32;
/// 케이퍼빌리티 권한 비트 모듈입니다.
///
/// Frame은 R/W/X를 매핑 권한의 상한으로 쓰고, Endpoint는 R을 수신, W를
-/// 송신으로 씁니다. 다른 종류는 권한 비트를 갖지 않습니다.
+/// 송신으로, Console은 R을 입력 읽기, W를 출력으로 씁니다. 다른 종류는 권한
+/// 비트를 갖지 않습니다.
pub mod rights {
pub const R: u8 = 1;
pub const W: u8 = 2;
@@ -123,8 +131,9 @@ pub enum Cap {
CNode { base: u64, slots: u64 },
/// 사용자 주소 공간(TTBR0 루트 테이블)
AddrSpace { root_pa: u64, asid: u64 },
- /// 커널 디버그 콘솔 출력 권한(오브젝트 없음)
- Console,
+ /// 커널 콘솔에 대한 권한(오브젝트 없음), `rights`의 W가 출력이고 R이
+ /// 입력 읽기
+ Console { rights: u8 },
}
/// 재분류로 만들 수 있는 커널 오브젝트 종류를 나타내는 열거형입니다.
@@ -270,7 +279,7 @@ fn encode(cap: &Cap) -> [u64; 4] {
],
Cap::CNode { base, slots } => [base | KIND_CNODE, *slots, 0, 0],
Cap::AddrSpace { root_pa, asid } => [root_pa | KIND_ADDR_SPACE, *asid, 0, 0],
- Cap::Console => [KIND_CONSOLE, 0, 0, 0],
+ Cap::Console { rights } => [KIND_CONSOLE | (u64::from(*rights) << RIGHTS_SHIFT), 0, 0, 0],
}
}
@@ -387,11 +396,11 @@ fn decode(w: &[u64; 4]) -> Result