diff --git a/.gitignore b/.gitignore
index b811de2..d30354c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -72,3 +72,7 @@ NO-COMMIT*
bootcheck-*.log
.DS_Store
docs/
+
+# vendor 아래의 파일은 위 규칙에 걸려도 전부 추적함. cargo가 크레이트의 모든
+# 파일을 체크섬으로 확인하므로 하나라도 빠지면 오프라인 빌드가 실패함
+!vendor/**
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index bf4bdb7..387df6a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -59,6 +59,7 @@ $ cargo virt # build the generic image with console and boot it on QEMU virt
$ cargo build -p k0-kernel --features console --offline # build the generic 4 KiB image with console only
$ cargo build -p k0-kernel --offline --no-default-features --features granule-16k,console --target-dir target/g16 # 16 KiB image with console
$ cargo build -p k0-kernel --offline --target-dir target/quiet # image without console
+$ cargo build -p k0-kernel --features console,vault-ed25519 --offline --target-dir target/vault # image with the signing oracle
$ tools/build-loader.sh # put the built kernel into the UEFI loader, prints the .efi path
```
@@ -91,10 +92,12 @@ $ 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` and `k0-efi` on any host (250 tests on an AArch64 host, 164 elsewhere). 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` 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/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.
+
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:
```sh
@@ -123,6 +126,7 @@ In the following table, you can see where each area is tested.
| `k0-abi` constants and shared layouts | yes | indirectly |
| `k0-cap` untyped bootstrap and retype | yes | yes |
| `k0-boot` DTB parser, PAC key derivation, root task image | yes, plus fuzzing | yes |
+| `k0-vault` request state machine, protocol, policy and provider boundary | yes, with and without `vault-ed25519` | yes, in images built with `vault`, through `test_oracle` and the `vault*` rows of the boot matrix |
| `k0-efi` memory plan from the UEFI memory map, DTB rewrite, independent check, ACPI table reader and tree synthesis | yes, plus fuzzing | yes, through the `uefi-*` rows of the boot matrix |
| `loader` (UEFI application: firmware calls, cache flush, MMU off, jump) | no | yes, through the `uefi-*` rows, plus the static check `tools/pe-check.py` |
| `k0-mm` page tables and W^X attributes | yes, on AArch64 hosts | yes |
@@ -178,6 +182,8 @@ Developers still use rustup on their own machines. Only the CI image changed.
- **Outside input**: treat every input from outside the kernel as hostile. This includes the DTB and every system call argument. Use checked arithmetic and validate before you dereference.
- **W^X**: keep it. No mapping is ever both writable and executable, at either exception level.
- **New input or output paths**: every new path goes behind a Cargo feature from the start. Features only add I/O and are never put in `default`. Every supported combination gets a row in the boot matrix (`tools/boot-matrix.sh`), and the scripts, the `virt` alias and CI name the features explicitly. An image without the feature must contain none of that code and must not map or touch the device.
+- **Confined task code**: code that runs in a confined task, such as the vault, must not use mutable statics or allocation. Its state lives on its own stack or in frames it was given.
+- **New algorithms**: a new algorithm goes behind its own Cargo feature, which includes the feature of the service it belongs to. An image without it must contain none of its code. Give it a row in the boot matrix, and extend the static check `vault-symbols` if it adds code to the vault image.
- **Tests**: add a test with every behavior change. Pure logic gets a host unit test. System call behavior gets a root task self-test.
- **Code comments**: they are written in Korean in this repository. You may write yours in English. A maintainer may translate them when merging.
@@ -186,7 +192,7 @@ Developers still use rustup on their own machines. Only the CI image changed.
- One logical change per commit. A reviewer should be able to read each commit on its own.
- Keep the subject line short and plain. Korean or English are both fine. Do not use type prefixes such as `feat:` or `fix:`.
- In the pull request, say what changed, why, and how you tested it. Link the issue if there is one.
-- **CI must pass**. It builds the 4 KiB and the 16 KiB image and the UEFI loader, runs the host tests on x86-64 and AArch64, and runs the boot matrix (`tools/boot-matrix.sh`) under QEMU, including the rows that boot through the UEFI loader and the rows for images without console.
+- **CI must pass**. It builds the 4 KiB and the 16 KiB image and the UEFI loader, runs the host tests on x86-64 and AArch64, and runs the boot matrix (`tools/boot-matrix.sh`) under QEMU, including the rows that boot through the UEFI loader, the rows for images without console and the rows for images with the signing oracle.
## AI-assisted contributions
diff --git a/CONTRIBUTING_KR.md b/CONTRIBUTING_KR.md
index 6c8da7f..0f8268e 100644
--- a/CONTRIBUTING_KR.md
+++ b/CONTRIBUTING_KR.md
@@ -61,6 +61,7 @@ $ cargo virt # 콘솔이 있는 범용 이미지를 빌드해 QEMU virt에서
$ cargo build -p k0-kernel --features console --offline # 콘솔이 있는 범용 4 KiB 이미지만 빌드
$ cargo build -p k0-kernel --offline --no-default-features --features granule-16k,console --target-dir target/g16 # 콘솔이 있는 16 KiB 이미지
$ cargo build -p k0-kernel --offline --target-dir target/quiet # 콘솔 없는 이미지
+$ cargo build -p k0-kernel --features console,vault-ed25519 --offline --target-dir target/vault # 서명 오라클이 있는 이미지
$ tools/build-loader.sh # 빌드한 커널을 UEFI 로더에 포함하고 .efi 경로를 출력
```
@@ -93,10 +94,12 @@ $ 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`의 테스트를 어느 호스트에서나 실행합니다(AArch64 호스트에서 250개, 그 밖에서 164개). `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-vault`의 테스트를 어느 호스트에서나 실행합니다(AArch64 호스트에서 276개, 그 밖에서 190개). `k0-vault`는 알고리즘 feature `vault-ed25519`를 포함한 경우와 포함하지 않은 경우로 두 번 실행하며, 각각 13개와 7개입니다. `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)에 있습니다.
+
기본 QEMU CPU 모델(`cortex-a72`)에는 PAC, PAN, RNDR이 없습니다. 이 경로까지 검증하려면 QEMU의 `max` 모델로 부팅하고 해당 로그 줄을 필수로 지정하세요. 커널 경로 뒤의 인자는 그대로 QEMU에 전달됩니다. 다음과 같이 입력할 수 있습니다.
```sh
@@ -125,6 +128,7 @@ $ tools/qemu-boot-test.sh target/aarch64-unknown-none-softfloat/debug/k0-kernel.
| `k0-abi` 상수와 공유 레이아웃 | 있음 | 간접적으로 |
| `k0-cap` untyped 부트스트랩과 retype | 있음 | 있음 |
| `k0-boot` DTB 파서, PAC 키 파생, 루트 태스크 이미지 | 있음, 퍼징 포함 | 있음 |
+| `k0-vault` 요청 상태 기계, 프로토콜, 정책, 프로바이더 경계 | 있음, `vault-ed25519` 포함과 미포함 | 있음, `vault`를 포함해 빌드한 이미지에서 `test_oracle`과 부팅 매트릭스의 `vault*` 행으로 |
| `k0-efi` UEFI 메모리 맵에서의 메모리 계획, DTB 재작성, 독립 검증, ACPI 테이블 읽기와 트리 합성 | 있음, 퍼징 포함 | 있음, 부팅 매트릭스의 `uefi-*` 행으로 |
| `loader` (UEFI 애플리케이션: 펌웨어 호출, 캐시 비우기, MMU 끄기, 점프) | 없음 | 있음, `uefi-*` 행과 정적 검사 `tools/pe-check.py`로 |
| `k0-mm` 페이지 테이블과 W^X 속성 | AArch64 호스트에서 있음 | 있음 |
@@ -182,6 +186,8 @@ $ docker run --rm --network none k0-ci tools/boot-matrix.sh
- **커널 밖에서 온 입력**: 전부 적대적으로 취급합니다. DTB와 모든 시스템 콜 인자가 여기에 해당합니다. 검사 산술을 사용하고, 역참조 전에 검증합니다.
- **W^X**: 어느 예외 레벨에서든 쓰기 가능하면서 실행 가능한 매핑은 없습니다.
- **새 입력 또는 출력 경로**: 처음부터 Cargo feature 뒤에 둡니다. feature는 I/O를 더하기만 하며 `default`에 추가하지 않습니다. 지원하는 조합마다 부팅 매트릭스(`tools/boot-matrix.sh`)에 행을 두고, 스크립트와 `virt` 별칭과 CI는 feature를 직접 적습니다. feature 없이 빌드한 이미지에는 그 코드가 없어야 하며 장치를 매핑하거나 건드려서도 안 됩니다.
+- **격리된 태스크의 코드**: 볼트처럼 격리된 태스크에서 도는 코드는 가변 정적 변수와 할당을 사용하지 않습니다. 상태는 자기 스택이나 받은 프레임에 둡니다.
+- **새 알고리즘**: 새 알고리즘은 자기만의 Cargo feature 뒤에 두며, 이 feature는 그 알고리즘이 속한 서비스의 feature를 포함합니다. feature 없이 빌드한 이미지에는 그 코드가 없어야 합니다. 부팅 매트릭스에 행을 두고, 볼트 이미지에 코드를 더한다면 정적 검사 `vault-symbols`도 확장합니다.
- **테스트**: 동작을 바꾸면 테스트를 함께 추가합니다. 순수 로직은 호스트 단위 테스트로, 시스템 콜 동작은 루트 태스크 자가 테스트로 검증합니다.
- **코드 주석**: 이 저장소의 코드 주석은 한국어로 작성합니다. 기여자는 영어로 작성해도 되고, 병합할 때 메인테이너가 번역할 수 있습니다.
@@ -190,7 +196,7 @@ $ docker run --rm --network none k0-ci tools/boot-matrix.sh
- 커밋 하나에는 논리적 변경 하나만 담습니다. 리뷰어가 커밋을 하나씩 따로 읽을 수 있어야 합니다.
- 제목은 짧고 평이하게 작성합니다. 한국어와 영어 모두 괜찮습니다. `feat:`나 `fix:` 같은 접두어는 사용하지 않습니다.
- 풀 리퀘스트에는 무엇을, 왜 바꿨고, 어떻게 테스트했는지 적고, 관련 이슈가 있으면 연결합니다.
-- **CI를 통과해야 합니다**. CI는 4 KiB 이미지, 16 KiB 이미지, UEFI 로더를 빌드하고, x86-64와 AArch64에서 호스트 테스트를 돌리고, QEMU로 부팅 매트릭스(`tools/boot-matrix.sh`)를 UEFI 로더를 거치는 행과 콘솔 없는 이미지의 행까지 포함해 실행합니다.
+- **CI를 통과해야 합니다**. CI는 4 KiB 이미지, 16 KiB 이미지, UEFI 로더를 빌드하고, x86-64와 AArch64에서 호스트 테스트를 돌리고, QEMU로 부팅 매트릭스(`tools/boot-matrix.sh`)를 UEFI 로더를 거치는 행, 콘솔 없는 이미지의 행, 서명 오라클이 있는 이미지의 행까지 포함해 실행합니다.
## AI 보조 기여
diff --git a/Cargo.lock b/Cargo.lock
index d94453b..ad657a8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -36,6 +36,33 @@ dependencies = [
"typenum",
]
+[[package]]
+name = "curve25519-dalek"
+version = "4.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "curve25519-dalek-derive",
+ "digest",
+ "fiat-crypto",
+ "rustc_version",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "curve25519-dalek-derive"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
[[package]]
name = "digest"
version = "0.10.7"
@@ -46,6 +73,34 @@ dependencies = [
"crypto-common",
]
+[[package]]
+name = "ed25519"
+version = "2.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53"
+dependencies = [
+ "signature",
+]
+
+[[package]]
+name = "ed25519-dalek"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9"
+dependencies = [
+ "curve25519-dalek",
+ "ed25519",
+ "sha2",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "fiat-crypto"
+version = "0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
+
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -147,19 +202,62 @@ dependencies = [
"k0-mm",
]
+[[package]]
+name = "k0-vault"
+version = "0.1.0"
+dependencies = [
+ "ed25519-dalek",
+ "k0-abi",
+ "zeroize",
+]
+
[[package]]
name = "libc"
version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
[[package]]
name = "root-task"
version = "0.1.0"
dependencies = [
"k0-abi",
+ "k0-vault",
]
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
[[package]]
name = "sha2"
version = "0.10.9"
@@ -171,14 +269,49 @@ dependencies = [
"digest",
]
+[[package]]
+name = "signature"
+version = "2.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
+
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+[[package]]
+name = "unicode-ident"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "zeroize"
+version = "1.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
diff --git a/Cargo.toml b/Cargo.toml
index dceea34..4de7ed5 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -12,6 +12,7 @@ members = [
"crates/k0-abi",
"crates/k0-efi",
"userspace/root-task",
+ "userspace/k0-vault",
"loader",
]
# UEFI 로더는 타겟이 달라(aarch64-unknown-uefi) 기본 빌드 대상에서 뺌.
diff --git a/INTRODUCTION.md b/INTRODUCTION.md
index feb6e35..97fdd82 100644
--- a/INTRODUCTION.md
+++ b/INTRODUCTION.md
@@ -46,7 +46,7 @@ K0 is meant to become the isolation core of high-security systems. The targets a
- **Research base**: formal verification and certification research
> [!NOTE]
-> None of these works yet. Today K0 is a research platform: it boots and checks its own security properties, but it does no useful work of its own yet.
+> 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.
## What works today
@@ -144,8 +144,14 @@ These features only add and are not in `default`, so **every build command must
No memory is ever writable in one place and executable in another.
- **Checking the first program**: the root task is built into the kernel image, and at every boot its fingerprint (a SHA-256 hash) is checked again. This catches corruption, but it does not prove who made the image the way a signature would. [SECURITY.md](SECURITY.md) explains why under "Scope".
+- **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.
-The root task tests every item above with self-tests on every boot.
+The root task tests every item above with self-tests on every boot. The signing oracle is tested in the images built with it.
## Where it has run
@@ -179,6 +185,7 @@ The following picture summarizes what each evidence tier means.
- Starting from a FAT drive instead of `-kernel`
- 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.
- **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
@@ -245,8 +252,10 @@ What it does not stop:
- The kernel cannot be interrupted while it handles a system call. A long call, such as taking back a key to a large block of memory, delays every other task and every timeout.
- A fatal error inside the kernel, or an error from the hardware that the kernel cannot attribute to one task, still stops the whole machine.
- The kernel part of the boot log can be filled up by crash and exit lines.
+ - The 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.
- **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.
## Not there yet
@@ -263,7 +272,14 @@ Missing features:
- **Device access**: programs cannot access hardware devices (device memory and interrupts).
- **Loading new executable code after boot**: this is the flip side of the write-or-run rule. Executable memory exists only for the root task image, so a confined task runs code from that image.
- **Multi-level key lookup and ASIDs**: multi-level key lookup and hardware address space tags (ASIDs) do not exist. Today every switch to another address space empties the processor's cache of memory map lookups (the TLB).
-- **Signature checking**: checking a digital signature (Ed25519) once the root task ships separately from the kernel.
+- **More for the signing oracle**: the oracle has the following limits today.
+ - 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 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).
+- **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.
- UEFI with a firmware device tree, and UEFI with ACPI static tables only (the loader builds a minimal device tree), exist (see above).
@@ -308,7 +324,8 @@ 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 |
+| `userspace/root-task` | The first program and its self-tests, and the wiring and self-test of the signing oracle (`oracle.rs`) |
+| `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`) |
| `ci/` | The CI build and test image (`Dockerfile`) and the threat model (`threat_model.md`) |
-| `vendor/` | Third-party crates kept in the repository (`sha2` and its dependencies) |
+| `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 5a83295..dc8420d 100644
--- a/INTRODUCTION_KR.md
+++ b/INTRODUCTION_KR.md
@@ -46,7 +46,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
- **연구용 기반**: 정형 검증과 인증 연구
> [!NOTE]
-> 이 가운데 아직 동작하는 것은 없습니다. 지금의 K0는 연구용 플랫폼으로, 부팅해서 자신의 보안 성질을 스스로 확인하지만 아직 그 자체로 쓸모 있는 일을 하지는 않습니다.
+> 첫 작은 걸음만 있습니다. "지금 동작하는 것"에 적은 선택 사항인 서명 오라클입니다. 나머지는 아직 동작하지 않습니다. 지금의 K0는 연구용 플랫폼으로, 부팅해서 자신의 보안 성질을 스스로 확인하지만 기본값으로는 아직 그 자체로 쓸모 있는 일을 하지는 않습니다.
## 지금 동작하는 것
@@ -145,7 +145,14 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
어떤 메모리도 한 곳에서는 쓰기 가능하고 다른 곳에서는 실행 가능한 일이 없습니다.
- **첫 프로그램 검사**: 루트 태스크는 커널 이미지 안에 들어 있고, 부팅할 때마다 그 지문(SHA-256 해시)을 다시 확인합니다. 이것은 손상을 잡아내지만, 서명처럼 누가 만들었는지를 증명하지는 않습니다. 이유는 [SECURITY_KR.md](SECURITY_KR.md)의 범위 절에 있습니다.
-위 항목은 전부 루트 태스크가 부팅할 때마다 자가 테스트로 확인합니다.
+- **서명 오라클(선택 사항)**: 다른 프로그램을 위해 일하는 첫 번째 서비스입니다. 디지털 서명은 어떤 메시지를 비밀 키를 가진 쪽이 승인했음을 보여 주는 짧은 값이고, 짝이 되는 공개 키가 있으면 누구나 검증할 수 있습니다. 서명 오라클은 다른 프로그램의 메시지에 서명해 주면서 비밀 키는 절대 보여 주지 않는 프로그램입니다. 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`로 끝납니다. 테스트 클라이언트는 한 주소 공간에서 차례로 실행되므로, 이 테스트가 보여 주는 것은 볼트와 클라이언트 사이의 격리이며 클라이언트끼리의 격리가 아닙니다.
+
+위 항목은 전부 루트 태스크가 부팅할 때마다 자가 테스트로 확인합니다. 서명 오라클은 그것을 포함해 빌드한 이미지에서 테스트합니다.
## 어디서 돌려 봤나
@@ -179,6 +186,7 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
- `-kernel` 대신 FAT 드라이브에서 시작
- 로더 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`는 기본 이미지에 볼트 코드와 암호 코드가 없는지 확인합니다.
- **거부 확인**: 시리얼 로그로 확인하는 거부는 두 가지입니다.
- 16 KiB 페이지가 없는 CPU에서의 16 KiB 이미지
- 내장 커널의 한 바이트를 뒤집은 로더
@@ -245,8 +253,10 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
- 커널은 시스템 콜을 처리하는 동안 중단할 수 없습니다. 큰 메모리 블록의 열쇠를 회수하는 것 같은 긴 호출은 다른 모든 태스크와 모든 타임아웃을 늦춥니다.
- 커널 안의 치명적 오류, 또는 커널이 한 태스크의 탓으로 돌릴 수 없는 하드웨어 오류는 여전히 기계 전체를 멈춥니다.
- 부트 로그의 커널 부분은 충돌과 종료 줄로 가득 찰 수 있습니다.
+ - 서명 오라클도 예외가 아닙니다. 클라이언트는 볼트로 가는 우편함 하나를 함께 사용하므로 모든 호출에 타임아웃을 줘야 하며, 그렇지 않으면 멈춘 볼트가 클라이언트를 붙잡습니다.
- **열쇠고리와 주소 공간을 함께 사용하는 태스크**: 이런 태스크끼리는 격리되지 않습니다. 모든 것을 함께 사용하는 한 프로그램의 일부, 즉 스레드처럼 동작합니다.
- **태스크 통제**: 어떤 태스크나 그 태스크의 열쇠고리, 주소 공간의 열쇠를 가진 쪽이 그 태스크를 통제합니다.
+- **루트 태스크**: 모든 태스크, 열쇠고리, 주소 공간을 만들기 때문에 신뢰해야 하며 격리 바깥에 있습니다. 서명 오라클의 메모리와 그 안의 키를 읽을 수 있습니다. "루트 태스크 이외의 어떤 태스크도 볼트의 메모리를 매핑할 수 없다"만 성립합니다.
## 아직 없는 것
@@ -263,7 +273,14 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
- **장치 접근**: 프로그램이 하드웨어 장치를 쓰게 해 주는 기능입니다(장치 메모리와 인터럽트).
- **부팅 뒤 새 실행 코드 적재**: 쓰기와 실행을 함께 허용하지 않는 규칙의 대가입니다. 실행 가능한 메모리는 루트 태스크 이미지에만 있어서 격리된 태스크도 그 이미지의 코드를 실행합니다.
- **여러 단계의 열쇠 조회와 ASID**: 여러 단계의 열쇠 조회, 하드웨어 주소 공간 표식(ASID)입니다. 지금은 다른 주소 공간으로 바꿀 때마다 프로세서가 메모리 지도 조회 결과를 담아 두는 캐시(TLB)를 전부 비웁니다.
-- **서명 검증**: 루트 태스크를 커널과 따로 배포할 때의 디지털 서명(Ed25519) 검증입니다.
+- **서명 오라클의 남은 한계**: 오라클에는 지금 다음 한계가 있습니다.
+ - 영속성이 없습니다. 키는 메모리에만 있고 재부팅이나 ZEROIZE 뒤에는 사라집니다.
+ - 키는 하나뿐이며, 키를 가져오거나 내보내는 방법이 없습니다.
+ - 양자내성(PQC) 알고리즘은 아직 없습니다.
+ - 운영자 입력이 없습니다. 어떤 종류의 입력도 없으므로 아무도 명령을 입력할 수 없습니다.
+ - 구현은 검증받지 않았고, 이 커널에서 암호 크레이트의 타이밍·캐시 사이드 채널을 분석하지 않았으며, 부팅 시드 이외의 난수 비트 생성기도 없습니다.
+ - QEMU(TCG와 HVF)에서만 실행했습니다.
+- **서명 검증**: 루트 태스크를 커널과 따로 배포할 때의 디지털 서명(Ed25519) 검증입니다. 서명 오라클은 서명을 만들지만, 그 서명으로 루트 태스크를 검증하지는 않습니다.
- **실제 보드와 가상화 환경 부팅**: 실제 보드, 그리고 KVM·Firecracker·Cloud Hypervisor·crosvm에서의 부팅입니다(위 3단계).
- **EL3 진입과 정적 테이블 너머의 ACPI**: 이 둘은 없습니다.
- 펌웨어 디바이스 트리가 있는 UEFI와 ACPI 정적 테이블만 있는 UEFI(로더가 최소한의 디바이스 트리를 만듦)는 위와 같이 있습니다.
@@ -308,7 +325,8 @@ K0는 고보안 시스템의 격리 코어가 되는 것을 목표로 합니다.
| `crates/k0-sched` | 라운드 로빈 스케줄러 |
| `crates/k0-ipc` | 동기 메시지 |
| `loader/` | 빌드된 커널 이미지를 품고 시작시키는 UEFI 응용 프로그램(`k0-loader`, 타겟 `aarch64-unknown-uefi`). UEFI 호출, 흐름, 마지막의 캐시 비우기·MMU 끄기·점프 |
-| `userspace/root-task` | 첫 프로그램과 자가 테스트 |
+| `userspace/root-task` | 첫 프로그램과 자가 테스트, 서명 오라클의 연결과 자가 테스트(`oracle.rs`) |
+| `userspace/k0-vault` | 서명 오라클 서비스. 프로토콜과 고정 정책, 요청 처리, 암호 크레이트를 감싸는 경계 |
| `tools/` | QEMU 러너(`.efi`도 지원), 부팅 테스트, 부팅 매트릭스, 부트 로그 읽기, 호스트 테스트, 로더 빌드(`build-loader.sh`), PE와 명령 순서 검사(`pe-check.py`) |
| `ci/` | CI 빌드·테스트 이미지(`Dockerfile`)와 위협 모델(`threat_model.md`) |
-| `vendor/` | 저장소 안에 함께 넣어 둔 서드파티 크레이트(`sha2`와 그 의존성) |
+| `vendor/` | 저장소 안에 함께 넣어 둔 서드파티 크레이트(`sha2`, `ed25519-dalek`과 그 의존성) |
diff --git a/README.md b/README.md
index 9210d43..ceae4f0 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,7 @@ K0 is a small operating system kernel for 64-bit ARM (AArch64) computers. It is
>
> So far it has been booted on several QEMU machines, directly and through UEFI firmware (EDK2, also under UEFI Secure Boot). It has also been booted on real Apple cores as a hypervisor guest. It has not been booted on any real board or on any firmware other than EDK2.
>
-> Today K0 is a research platform for the isolation core of high-security systems. It boots and checks its own security properties, but it does no useful work of its own yet.
+> Today K0 is a research platform for the isolation core of high-security systems. It boots and checks its own security properties, but by default it does no useful work of its own yet.
## Security status
@@ -33,6 +33,7 @@ K0 is a small operating system kernel for 64-bit ARM (AArch64) computers. It is
- **Wiped before reuse**: memory is filled with zeros every time it is handed out again.
- **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).
The first program checks these properties with self-tests on every boot.
diff --git a/README_KR.md b/README_KR.md
index 7283674..555bbfd 100644
--- a/README_KR.md
+++ b/README_KR.md
@@ -13,7 +13,7 @@ K0는 64비트 ARM(AArch64) 컴퓨터용 작은 운영체제 커널입니다. Ru
>
> 지금까지는 여러 QEMU 머신에서 직접, 그리고 UEFI 펌웨어(EDK2, UEFI Secure Boot 포함)를 거쳐 부팅했습니다. 하이퍼바이저 게스트로 돌린 실제 Apple 코어에서도 부팅했습니다. 실제 보드나 EDK2 이외의 펌웨어에서는 아직 부팅해 보지 않았습니다.
>
-> 지금의 K0는 고보안 시스템의 격리 코어를 연구하는 플랫폼입니다. 부팅해서 자신의 보안 성질을 스스로 확인하지만, 아직 그 자체로 쓸모 있는 일을 하지는 않습니다.
+> 지금의 K0는 고보안 시스템의 격리 코어를 연구하는 플랫폼입니다. 부팅해서 자신의 보안 성질을 스스로 확인하지만, 기본값으로는 아직 그 자체로 쓸모 있는 일을 하지는 않습니다.
## 보안 상태
@@ -33,6 +33,7 @@ K0는 64비트 ARM(AArch64) 컴퓨터용 작은 운영체제 커널입니다. Ru
- **재사용 전 소거**: 메모리를 다시 내줄 때마다 0으로 채웁니다.
- **쓰기와 실행은 동시에 불가**: 어떤 메모리도 쓰기와 실행이 동시에 되지 않습니다. 그 대가로 부팅 뒤에는 새 코드를 실행 가능하게 만들 수 없어서, 프로그램이 새 코드를 불러올 수 없습니다.
- **부팅 입력 불신**: 부팅 때 넘겨받는 하드웨어 설명은 공격자가 작성한 것처럼 검사합니다.
+- **선택 사항인 서명 오라클**: 빌드 옵션으로 다른 태스크를 위해 메시지에 서명하고 키는 절대 내주지 않는 태스크를 추가합니다. 기본값은 꺼짐이고, Ed25519 구현은 검증받지 않았으며, 키는 하나를 메모리에만 둡니다. [INTRODUCTION_KR.md](INTRODUCTION_KR.md)를 참고하세요.
첫 프로그램이 부팅할 때마다 자가 테스트로 위 성질들을 확인합니다.
diff --git a/SECURITY.md b/SECURITY.md
index 1ba2407..e6f23e3 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 2).
+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).
A confined task has the following properties:
@@ -75,11 +75,11 @@ What is still NOT provided on `main`:
- **Executable code**: new executable code cannot be loaded after boot, so a confined task runs code from the root task image.
- **Supported scope**: only the evidence tiers in [INTRODUCTION.md](INTRODUCTION.md) count as supported. Real boards, KVM and other hypervisors, the 16550 console driver, and processors with `HCR_EL2.E2H` fixed to 1 have never been booted.
- **Device tree**: the device tree is not trusted, but it now supplies device addresses. A wrong or hostile device tree can point the console at another device. The kernel limits this: it checks the platform descriptor against the memory map, checks the identification registers of the GIC and the PL011 (the PL011 through a temporary probe mapping, so a device that fails the check is not left mapped; no such register exists for a 16550 or an SBSA UART, so those have no such check), maps a device page only after validation, bounds every console wait, and offers a pinned build (`K0_PIN`) that refuses a different platform. The pinned build compares values that come from the device tree, so it does not stop a hostile boot chain.
-- **Device tree address**: the address of the device tree cannot be checked before the first read. The boot loader passes it in `x0`, and the kernel has no memory map until it has read that blob. The kernel refuses a null or misaligned address, an address at or above 2^47 and a range that overlaps the kernel image. It then maps the address as read-only normal memory and reads eight bytes. It reads further, up to 2 MiB, only if those bytes look like a device tree header. A boot loader that passes the address of a device therefore makes the kernel read device registers as if they were memory, and reading some registers has side effects. The mapping is cacheable, so the processor may fetch more of that page than the eight bytes the kernel asks for. The later check that the device tree lies inside declared memory uses the memory map from the same blob. The kernel never writes through this mapping.
+- **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").
- **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.
+- **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").
> [!WARNING]
> Even on `main`, treat running untrusted code as experimental. The availability limits above still apply.
@@ -104,7 +104,7 @@ Limits and residual risks of the loader:
5. QEMU cannot test the cache flush and MMU-off sequence: TCG has no caches, and HVF did not expose a missing flush either. It rests on the architecture rules, on the sequence Linux used when it entered the kernel with the MMU off, and on `tools/pe-check.py`, which checks that the instructions and both flush calls are present, not that they are right on real hardware.
6. A pinned build (`K0_PIN`) under UEFI is untested. The pin line includes the RAM range, which under UEFI depends on the firmware build and the RAM size. A mismatch stops the kernel with nothing on the screen. The reason is in the kernel's boot log in memory, and the loader prints the address needed to read it (`k0-loader: image at 0x..., dtb at 0x...`).
7. Boot services memory is never used, but nothing stops a device that firmware left running from writing to other memory after the firmware services end. K0 has no IOMMU support.
-8. The entropy the loader adds stays readable in the device tree in memory for the whole run. Without `EFI_RNG_PROTOCOL` the kernel gets only what the firmware device tree carried, and nothing at all when the tree was built from ACPI tables (the kernel then relies on RNDR if the CPU has it).
+8. The entropy the loader adds stays readable in the device tree in memory until the kernel zeroes the `rng-seed` bytes right before it enters the root task. Copies that the firmware or the loader keep elsewhere are not wiped. Without `EFI_RNG_PROTOCOL` the kernel gets only what the firmware device tree carried, and nothing at all when the tree was built from ACPI tables (the kernel then relies on RNDR if the CPU has it).
9. The kernel never calls UEFI runtime services: no variable access, no reset or power-off through firmware. Runtime regions stay unused.
10. Firmware that describes device registers as `EfiReservedMemoryType` (instead of leaving them out of the map or typing them as MMIO) makes the loader refuse, and one malformed descriptor makes it refuse the whole map. Both fail closed.
11. The paths that move the block to another place and that free memory after a refusal could not be exercised under QEMU.
@@ -173,6 +173,41 @@ The limits are as follows:
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.
+## 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.
+
+> [!WARNING]
+> The Ed25519 implementation has no validation of any kind, and the key does not come from an approved random bit generator. Do not read this feature as FIPS validated, certified or compliant.
+
+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.
+- **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.
+
+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.
+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.
+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.
+
+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.
+
+### 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.
+
+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.
+
## Known advisories
The following advisories are tracked as GitHub Security Advisories in this repository. The first two were published on 2026-11-07. All of them affect version 0.1.0 and earlier, and none has a fixed version yet.
@@ -198,7 +233,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 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 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
@@ -208,7 +243,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/` and `userspace/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` 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.
**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 cf2982f..84ff69f 100644
--- a/SECURITY_KR.md
+++ b/SECURITY_KR.md
@@ -47,7 +47,7 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다.
### 현재 `main` 브랜치(릴리즈 전)
-현재 `main` 브랜치에는 태스크 격리가 들어 있습니다. 아직 어떤 릴리즈나 태그에도 포함되지 않았고, 시스템 콜 ABI가 `v0.1.0`과 호환되지 않습니다(bootinfo 레이아웃 버전 2).
+현재 `main` 브랜치에는 태스크 격리가 들어 있습니다. 아직 어떤 릴리즈나 태그에도 포함되지 않았고, 시스템 콜 ABI가 `v0.1.0`과 호환되지 않습니다(bootinfo 레이아웃 버전 3).
격리된 태스크의 성질은 다음과 같습니다.
@@ -75,11 +75,11 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다.
- **실행 코드**: 부팅 후에는 새 실행 코드를 로드할 수 없으므로, 격리된 태스크는 루트 태스크 이미지의 코드를 실행합니다.
- **지원 범위**: [INTRODUCTION_KR.md](INTRODUCTION_KR.md)의 증거 단계에 든 것만 지원한다고 봅니다. 실제 보드, KVM 등 다른 하이퍼바이저, 16550 콘솔 드라이버, `HCR_EL2.E2H`가 1로 고정된 프로세서는 한 번도 부팅한 적이 없습니다.
- **디바이스 트리**: 디바이스 트리는 신뢰하지 않지만, 이제 장치 주소를 여기서 가져옵니다. 잘못되었거나 악의적인 디바이스 트리가 콘솔을 다른 장치로 향하게 할 수 있습니다. 커널은 이를 다음과 같이 제한합니다. 플랫폼 기술자를 메모리 맵과 대조합니다. GIC와 PL011의 식별 레지스터를 확인합니다(PL011은 임시 프로브 매핑으로 확인하므로 확인에 실패한 장치는 매핑된 채 남지 않습니다. 16550과 SBSA UART에는 그런 레지스터가 없어서 이 확인이 없습니다). 검증이 끝난 뒤에만 장치 페이지를 매핑합니다. 콘솔 대기는 모두 시간 제한으로 묶습니다. 다른 플랫폼을 거부하는 고정 빌드(`K0_PIN`)도 제공합니다. 고정 빌드는 디바이스 트리에서 나온 값을 비교하므로 악의적인 부트 체인은 막지 못합니다.
-- **디바이스 트리의 주소**: 디바이스 트리의 주소는 처음 읽기 전에 검사할 방법이 없습니다. 부트로더가 이 주소를 `x0`로 넘기는데, 커널은 그 블롭을 읽기 전에는 메모리 맵을 모릅니다. 커널은 널이거나 정렬이 맞지 않는 주소, 2^47 이상인 주소, 커널 이미지와 겹치는 구간을 거부합니다. 그런 다음 그 주소를 읽기 전용 일반 메모리로 매핑하고 8바이트를 읽습니다. 그 바이트가 디바이스 트리 헤더처럼 보일 때만 더 읽습니다(최대 2 MiB). 따라서 부트로더가 장치의 주소를 넘기면 커널은 장치 레지스터를 메모리처럼 읽게 되고, 일부 레지스터는 읽기만 해도 부작용이 생깁니다. 이 매핑은 캐시 가능한 메모리라서 프로세서가 커널이 요청한 8바이트보다 그 페이지를 더 많이 가져올 수 있습니다. 디바이스 트리가 선언된 메모리 안에 있는지 보는 나중의 검사는 같은 블롭에서 나온 메모리 맵을 사용합니다. 커널은 이 매핑으로 쓰기를 하지 않습니다.
+- **디바이스 트리의 주소**: 디바이스 트리의 주소는 처음 읽기 전에 검사할 방법이 없습니다. 부트로더가 이 주소를 `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 [...]` 줄도 여기에 포함됩니다("선택적 콘솔 출력" 참고).
- **EL2 트랩**: 격리는 기밀성과 무결성을 다루고 가용성은 다루지 않습니다. 커널이 EL1로 내려온 뒤 EL2로 트랩이 오면 설계상 기계 전체를 멈춥니다.
- **EL2 진입**: EL2 진입은 Linux와 같은 펌웨어 약속을 전제로 합니다. EL3 펌웨어는 세분화된 트랩과 HCRX 제어 기능이 있으면 이를 켜 주어야 합니다.
-- **루트 태스크**: 루트 태스크는 여전히 신뢰 대상이며 최초의 `Untyped` 케이퍼빌리티를 가지고, `write_bootinfo`는 그 물리 주소를 루트 태스크에 계속 노출합니다.
+- **루트 태스크**: 루트 태스크는 여전히 신뢰 대상이며 최초의 `Untyped` 케이퍼빌리티를 가지고, `write_bootinfo`는 그 물리 주소를 루트 태스크에 계속 노출합니다. 서명 오라클이 있는 이미지에서는 루트 태스크가 볼트도 만들며 볼트의 메모리를 읽을 수 있습니다("서명 오라클" 참고).
> [!WARNING]
> `main`에서도 신뢰하지 않는 코드의 실행은 실험적인 것으로 취급하세요. 위의 가용성 한계는 그대로 적용됩니다.
@@ -104,7 +104,7 @@ K0는 **정식 릴리즈 전 단계의 연구용 마이크로커널**입니다.
5. QEMU로는 캐시 비우기와 MMU 끄기 순서를 시험할 수 없습니다. TCG에는 캐시가 없고, HVF도 빠진 비우기를 드러내지 못했습니다. 이 순서는 아키텍처 규칙, Linux가 MMU를 끈 채 커널에 진입할 때 쓰던 순서, 그리고 명령과 두 번의 비우기 호출이 있는지를 보는 `tools/pe-check.py`에 의존하며, 이 검사는 실제 하드웨어에서 옳은지가 아니라 있는지만 봅니다.
6. UEFI에서의 고정 빌드(`K0_PIN`)는 시험하지 않았습니다. 고정 줄에는 RAM 범위가 들어 있는데, UEFI에서는 이 값이 펌웨어 빌드와 RAM 크기에 따라 달라집니다. 맞지 않으면 커널은 화면에 아무것도 없이 멈춥니다. 사유는 메모리에 있는 커널의 부트 로그에 있고, 로더는 그것을 읽는 데 필요한 주소를 출력합니다(`k0-loader: image at 0x..., dtb at 0x...`).
7. 부트 서비스 메모리는 사용하지 않지만, 펌웨어가 켜 둔 채 남긴 장치가 펌웨어 서비스가 끝난 뒤 다른 메모리에 쓰는 것은 막을 방법이 없습니다. K0에는 IOMMU 지원이 없습니다.
-8. 로더가 더하는 엔트로피는 실행 내내 메모리의 디바이스 트리에서 읽을 수 있는 채로 남습니다. `EFI_RNG_PROTOCOL`이 없으면 커널은 펌웨어 디바이스 트리에 있던 것만 받고, 트리를 ACPI 테이블로 만들었다면 아무것도 받지 못합니다(이때 커널은 CPU에 RNDR이 있으면 그것에 의존합니다).
+8. 로더가 더하는 엔트로피는 커널이 루트 태스크에 진입하기 직전에 `rng-seed` 바이트를 0으로 지울 때까지 메모리의 디바이스 트리에서 읽을 수 있는 채로 남습니다. 펌웨어나 로더가 다른 곳에 보관한 사본은 지우지 않습니다. `EFI_RNG_PROTOCOL`이 없으면 커널은 펌웨어 디바이스 트리에 있던 것만 받고, 트리를 ACPI 테이블로 만들었다면 아무것도 받지 못합니다(이때 커널은 CPU에 RNDR이 있으면 그것에 의존합니다).
9. 커널은 UEFI 런타임 서비스를 부르지 않습니다. 변수 접근도, 펌웨어를 통한 리셋이나 전원 끄기도 없으며, 런타임 영역은 사용되지 않은 채 남습니다.
10. 장치 레지스터를 `EfiReservedMemoryType`으로 기술하는 펌웨어(맵에서 제외하거나 MMIO 유형으로 적는 대신)는 로더가 거부하고, 잘못된 디스크립터가 하나만 있어도 맵 전체를 거부합니다. 둘 다 안전한 쪽으로 실패합니다.
11. 블록을 다른 자리로 옮기는 경로와, 거부한 뒤 메모리를 해제하는 경로는 QEMU에서 실행해 볼 수 없었습니다.
@@ -173,6 +173,41 @@ $ grep -a 'k0: console drivers' <이미지 파일>
4. 콘솔 없는 이미지가 줄이는 것은 출력 경로이지 커널이 메모리에 가진 내용이 아닙니다. 부트 로그는 평범한 커널 메모리이며, RAM을 읽거나 디버거를 붙일 수 있는 사람은 누구나 봅니다.
5. `Console` 케이퍼빌리티를 가진 태스크는 커널 줄처럼 보이는 줄을 출력할 수 있으며, `k0: console drivers [...]`도 여기에 포함됩니다. 로그에서 그 줄의 첫 번째 등장 또는 이미지 파일만이 빌드를 식별합니다. 이 줄은 증거가 아니라 표지입니다.
+## 서명 오라클
+
+서명 오라클은 격리 코어 위에 올라가는 첫 번째 서비스입니다. 볼트 태스크 하나가 Ed25519 키 하나를 보관합니다. 클라이언트 태스크는 IPC로 서명과 공개 키를 받으며 키 자체는 받지 못합니다. 이 기능은 선택 사항이며 기본으로 꺼져 있습니다.
+
+> [!WARNING]
+> Ed25519 구현은 어떤 종류의 검증도 받지 않았고, 키는 승인된 난수 비트 생성기에서 나오지 않습니다. 이 기능을 FIPS 검증, 인증 또는 준수로 읽지 마세요.
+
+오라클이 주장하는 것은 다음과 같습니다.
+
+- **키 분리**: 키는 볼트 자신의 주소 공간과 스택에 있습니다. 루트 태스크가 볼트를 만들며, 루트 태스크 외의 어떤 태스크도 볼트의 메모리를 매핑할 수 없습니다. 클라이언트의 CNode에는 볼트 엔드포인트의 송신 전용 배지 사본만 들어 있습니다.
+- **프레임 권한**: 호출자마다 요청 프레임(호출자 읽기·쓰기, 볼트 읽기 전용)과 응답 프레임(볼트 읽기·쓰기, 호출자 읽기 전용)이 있으며, 권한을 줄인 프레임 케이퍼빌리티 사본으로 강제합니다.
+- **고정 정책**: 정책은 빌드 시점에 고정되고 엔드포인트 배지를 키로 삼습니다. 배지는 커널이 전달하므로 클라이언트가 위조할 수 없습니다. 역할은 admin(루트 태스크: STATUS, INIT, ZEROIZE, SIGN은 불가), signer(STATUS, PUBLIC_KEY, SIGN), reader(STATUS, PUBLIC_KEY)입니다. 배지가 없거나 알 수 없는 배지로 한 호출은 거부합니다. 정책을 바꾸는 연산은 없습니다.
+- **고정 이미지**: 볼트 코드는 루트 태스크 이미지의 일부이며 이전처럼 부팅할 때 SHA-256으로 검사합니다. 부팅 후에는 아무것도 로드하지 않습니다.
+- **요청을 한 번만 읽음**: 볼트는 길이를 먼저 확정한 뒤 요청 본문을 비공개 버퍼로 한 번만 읽고 그 사본만 사용합니다. 응답은 항상 레지스터 네 개(상태, 길이, 표시 비트, 호출자의 nonce)를 채웁니다. 클라이언트는 자신의 nonce가 담긴 OK 응답을 받은 뒤에만 응답 프레임을 신뢰해야 합니다.
+- **실패 상태**: 알려진 답 자가 시험(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, 운영자 입력이 없습니다. 양자 내성 알고리즘은 아직 없습니다.
+4. 모든 signer가 키 하나를 공유하므로 서명에는 클라이언트 신원이 담기지 않습니다.
+5. 볼트의 가용성은 보호하지 않습니다. 클라이언트는 엔드포인트 하나를 공유하며 타임아웃을 사용해야 합니다.
+6. 루트 태스크는 신뢰 대상이며 볼트를 읽을 수 있습니다.
+7. 오라클은 QEMU(TCG와 HVF)에서만 실행했습니다. 스택 사본(커널 부트 스택, 서명 뒤의 볼트 스택)의 삭제는 최선을 다하는 수준입니다.
+8. 자가 시험은 클라이언트를 하나의 클라이언트 주소 공간에서 차례로 실행하므로, 클라이언트 사이가 아니라 볼트와 클라이언트 사이의 격리를 보여 줍니다.
+
+엔트로피 규칙은 다음과 같습니다. 볼트는 부트 시드에 `rng-seed` 바이트가 32바이트 이상 있거나 RNDR에서 온 256비트가 있지 않으면 키 생성을 거부합니다(상태 `NO_ENTROPY`). QEMU virt는 32바이트 `rng-seed`를 제공합니다. 모든 응답에는 표시 비트가 담깁니다. 알고리즘이 FIPS 186-5에 있는지, 자가 시험이 통과했는지, `rng-seed`가 32바이트 이상 키 시드에 들어갔는지, RNDR이 키 시드에 들어갔는지입니다. 이 비트는 일어난 일을 보고할 뿐 검증 주장이 아닙니다.
+
+### 부트 시드와 시드 삭제
+
+커널은 루트 태스크용 32바이트를 디바이스 트리 엔트로피, 카운터, CPU에 RNDR이 있으면 새 RNDR 워드 네 개로부터 자기만의 도메인 문자열을 붙인 SHA-256으로 유도합니다. 도메인 분리 덕분에 PAC 키와는 독립입니다. 시드는 입력만큼만 좋고 그 이상은 아닙니다. 시드는 진입 레지스터 `x0`~`x3`로 루트 태스크에 전달되며, `x4`가 사용한 `rng-seed` 바이트 수와 RNDR 기여 여부를 알려 줍니다. bootinfo 페이지에는 없고, 루트 태스크는 시드가 아니라 출처만 출력합니다.
+
+커널은 루트 태스크에 진입하기 직전에 디바이스 트리의 `rng-seed`와 `kaslr-seed` 바이트를 0으로 지웁니다. 그 페이지의 읽기 전용 별칭 항목을 제자리에서 읽기·쓰기로 바꾸고, 0을 쓰고, 캐시 줄을 비우고 무효화한 뒤, 다시 되돌리고 바이트를 읽어 확인합니다. 그런 다음 `BootInfo` 안의 자기 사본을 지우고, `k0: dtb seeds wiped B`를 출력하고, 활성 프레임 아래의 부트 스택을 0으로 지웁니다. 펌웨어나 UEFI 로더가 보관한 사본과 부트 스택의 활성 프레임에 있는 것은 지우지 않습니다.
+
## 알려진 어드바이저리
다음 어드바이저리는 이 저장소의 GitHub Security Advisories에서 추적합니다. 앞의 두 건은 2026-11-07에 게시했습니다. 모두 0.1.0 이하 버전에 영향을 주며, 아직 수정된 버전은 없습니다.
@@ -198,7 +233,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 상태 기계에 관한 신고는 언제든 환영합니다.
## 범위
@@ -208,7 +243,7 @@ $ grep -a 'k0: console drivers' <이미지 파일>
-**범위 안**: `kernel/`, `crates/`(`crates/k0-efi` 포함), `loader/`, `userspace/root-task/` 하위의 모든 코드입니다. UEFI 로더는 부트 체인의 일부이지만 이 저장소의 코드이므로, 메모리 맵과 디바이스 트리와 커널 이미지를 다루는 부분은 범위 안입니다.
+**범위 안**: `kernel/`, `crates/`(`crates/k0-efi` 포함), `loader/`, `userspace/root-task/`, `userspace/k0-vault`(루트 태스크 안의 연결 코드 포함) 하위의 모든 코드입니다. UEFI 로더는 부트 체인의 일부이지만 이 저장소의 코드이므로, 메모리 맵과 디바이스 트리와 커널 이미지를 다루는 부분은 범위 안입니다.
**범위 밖**: 커널 진입점 이전의 나머지 부트 체인(예: 펌웨어, 다른 부트로더, 하이퍼바이저)과 커널 이미지 자체의 무결성입니다(커널 이미지 서명은 부트 체인의 책임입니다). UEFI에서는 이것이 펌웨어의 Secure Boot를 뜻합니다. 로더의 SHA-256 검사는 서명이 아니기 때문입니다("UEFI 로더" 절 참고).
diff --git a/USAGE.md b/USAGE.md
index 38aa57e..7e8e692 100644
--- a/USAGE.md
+++ b/USAGE.md
@@ -82,13 +82,17 @@ The following table lists the lines that an image with a console driver prints,
| Line | Meaning |
| --- | --- |
| `root: hello from EL0` | The first program is running in user mode |
+| `k0: dtb seeds wiped B` | Right before the root task starts, the kernel zeroed the random seed bytes (`rng-seed`, `kaslr-seed`) in the device tree copy and read them back. It reads `40B` on QEMU virt. It is printed by every image |
+| `root: boot seed from rng-seed bytes 0x... and rndr` or `... without rndr` | How much randomness the kernel put into the boot seed it gave the root task: the number of `rng-seed` bytes, and whether the CPU random number instruction RNDR added to it. The seed itself is never printed. It is printed by every image |
| `root: ... pass` | One group of self-tests passed |
| `root: secret at 0x...`, then `k0: task fault ... far 0x...` with the same address | A confined task tried to read memory that only the root task may see, and it was stopped at exactly that address |
-| `k0: task fault ...` and `k0: unknown syscall 65535, killing task` | Rule violations that the tests cause on purpose. Each one stops only the task that broke the rule. A normal run has exactly 6 `k0: task fault` lines and 1 `k0: unknown syscall` line |
+| `k0: task fault ...` and `k0: unknown syscall 65535, killing task` | Rule violations that the tests cause on purpose. Each one stops only the task that broke the rule. A normal run has exactly 6 `k0: task fault` lines and 1 `k0: unknown syscall` line. An image built with a `vault` feature has 8 `k0: task fault` lines |
| `k0: kernel reserve tables + address space entries = bytes in ranges` | The kernel set aside memory at the top of each range it hands out, for its own page tables and for the list of address spaces. It is printed before the `k0: untyped` lines. On QEMU virt with 512 MiB it reads `262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges`. The entry count depends on the image size |
| `k0: memory + not handed out ()` | A memory range was too small to hold its own share of that reserve, or the share could not be mapped, so the kernel did not hand the range out. The boot continues. A normal run on QEMU virt does not print it |
| `root: timeout tests pass` | The self-tests of IPC timeouts passed |
| `root: kernel reserve tests pass` | The self-tests of the kernel reserve passed (300 address spaces alive at once, and frames made from untyped memory across many page table blocks) |
+| `root: oracle tests pass` | The self-tests of the signing oracle passed. Only an image built with a `vault` feature prints it (see "Signing oracle" below) |
+| `root: oracle made no key (boot seed has no entropy)` | The vault refused to make a key because the boot seed was too weak. Only an image built with a `vault` feature can print it, and then `root: oracle tests pass` does not follow |
| `root: sched tests pass` | The last group of self-tests passed |
| `k0: idle (waiting for a timeout)` | Every task was waiting and at least one wait had a time limit, so the kernel waited for the next interrupt instead of stopping. It is printed at most once per boot |
| `k0: all tasks stopped (none ready, no timeout pending)` | Every task is waiting and no wait has a time limit. Nothing can wake a task today, so the machine stays idle. A normal run never prints it, and the boot test treats it as a failure. It is printed at most once per boot |
@@ -159,6 +163,39 @@ $ tools/boot-log.py
The load address is the physical address where the image was loaded. On QEMU `virt` with an unchanged image it is `0x40080000`.
+### Signing oracle
+
+The signing oracle is the first service that runs on top of the isolation core. A vault task holds one Ed25519 key. Client tasks get signatures and the public key from it over IPC and never see the key. The oracle is optional and off by default. The kernel crate has two features for it, and features only add:
+
+| Feature | What it adds |
+| --- | --- |
+| `vault` | The vault service with its protocol, its fixed policy and its self-test, but no signing algorithm. Every signing request is answered with "unsupported" |
+| `vault-ed25519` | Includes `vault` and adds Ed25519 (PureEdDSA with SHA-512, as in FIPS 186-5 and RFC 8032) |
+
+The code of the vault is part of the root task image, so a build must name the feature, and `cargo virt` does not include it. You can build and run an image with the oracle as follows:
+
+```sh
+$ cargo run -p k0-kernel --features console,vault-ed25519
+```
+
+You can also check it with the boot test. The self-test of the oracle adds two intended faults, so the test has to expect 8 `k0: task fault` lines instead of 6. You can enter it as follows:
+
+```sh
+$ cargo build -p k0-kernel --features console,vault-ed25519 --offline
+$ K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE='k0: dtb seeds wiped 40B|root: oracle tests pass' tools/qemu-boot-test.sh
+```
+
+In the boot log you should see these lines, in addition to the lines in "Reading the output":
+
+- `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.
+
+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).
+
## Booting through UEFI
UEFI is the standard way for firmware to start a program on many computers. The firmware loads a program file with the ending `.efi` from a disk, runs it, and describes the machine to it. A loader is a small program that does this one job: it prepares the machine and then starts another program. K0 has its own UEFI loader, `crates/k0-efi` and `loader/`. It carries the kernel inside itself, so the one `.efi` file is all the firmware needs. The kernel does not change and boots the same way as without UEFI. The following picture shows the path of a UEFI boot.
@@ -270,9 +307,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 250 host tests (164 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 250 are 14 (`k0-abi`), 42 (`k0-cap`), 76 (`k0-boot`), 32 (`k0-efi`) 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 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/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` and a pinned image. It also checks statically that the image does not touch the physical timer. 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 61 rows on a Mac with HVF and 51 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.
@@ -284,11 +321,22 @@ The console rows check the console features. The following table lists the conso
| `pl011-identity` | The device tree is patched so that the console node points at the RTC, and the kernel must print `k0: console is not a pl011, ignored`, write nothing and not keep that page mapped |
| `serial-check` | The judgement itself: a console image judged as quiet must fail on its serial output |
+The oracle rows check the signing oracle. In the following table, `root: oracle tests pass` is required in every boot row, and the boot rows expect 8 fault lines.
+
+| Row | What it checks |
+| --- | --- |
+| `vault` | An image with `vault-ed25519` on the default CPU. It also requires `k0: dtb seeds wiped 40B` |
+| `vault-max` | The same image on the `max` CPU, so that RNDR goes into the boot seed (`... and rndr`) |
+| `vault-el2` | The same image started at EL2 |
+| `vault-16k` | The 16 KiB image with `vault-ed25519` |
+| `vault-no-alg` | An image with `vault` only, which answers every signing request with "unsupported" |
+| `vault-symbols` | A static check. The default image has no vault code and no crypto code, and the vault image has no writable static variable from them |
+
The `uefi-*` rows boot the kernel through the UEFI loader on EDK2: GICv3 and GICv2 at EL1 and EL2, the `max` CPU, 4 cores, the 16 KiB image, a random number source from the firmware and the FAT drive path. The `uefi-acpi-*` rows (`uefi-acpi-gic3-el1`, `uefi-acpi-gic3-el2`, `uefi-acpi-gic2-el1`, `uefi-acpi-smp4`, `uefi-acpi-16k`, `uefi-acpi-rng`) boot QEMU's default machine with ACPI on and no device tree. A static check (`tools/pe-check.py`) covers the loader file's form and its cache and MMU instruction order, which QEMU cannot test.
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 is `hvf-quiet` for the image without console.
+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.
### Testing an image without console
@@ -340,6 +388,8 @@ The following table lists what to do for each problem.
| `boot-test: the serial log has no kernel line` | The same cause: a kernel built without a console feature writes nothing to the serial port. Build with `--features console`, or judge the log in guest memory with `K0_BOOT_MEMLOG=` |
| `boot-test` fails on a line that starts with `k0: all tasks` | Every task is waiting and no wait has a time limit, so nothing can wake a task. In the normal self-tests this does not happen. If you changed the root task, give each wait a timeout |
| `k0: memory + not handed out ()` appears in the boot log | The kernel found a memory range that is too small for its own reserve, or whose reserve it could not map. It left that range out and kept booting. The range is simply not usable as untyped memory. Check the memory size and the load address you gave QEMU |
+| `root: oracle made no key (boot seed has no entropy)` appears, or `root: oracle tests pass` is missing | The boot seed held fewer than 32 `rng-seed` bytes and no RNDR. Use a machine whose device tree has an `rng-seed`, as QEMU virt does, or a CPU with RNDR (`K0_QEMU_CPU=max`) |
+| `boot-test` fails on the number of `k0: task fault` lines for an image with a `vault` feature | That image prints 8 of them. Run the test with `K0_BOOT_FAULTS=8` |
| The boot test times out on a slow computer | Give it more time, for example `K0_BOOT_TIMEOUT=300 tools/qemu-boot-test.sh` |
| The 16 KiB image does not boot on `cortex-a72` | Expected: that CPU has no 16 KiB page support. Use `K0_QEMU_CPU=max` |
| A boot stops early and nothing is printed | There may be no supported console, or the image has no driver for it (an image with only one driver is silent on a console of the other kind). Read the boot log from memory with `tools/boot-log.py` |
diff --git a/USAGE_KR.md b/USAGE_KR.md
index 9f88c23..9ca5f66 100644
--- a/USAGE_KR.md
+++ b/USAGE_KR.md
@@ -82,13 +82,17 @@ $ grep -a 'k0: console drivers' <이미지 파일>
| 줄 | 뜻 |
| --- | --- |
| `root: hello from EL0` | 첫 프로그램이 사용자 모드에서 돌기 시작함 |
+| `k0: dtb seeds wiped B` | 루트 태스크를 시작하기 직전에, 커널이 디바이스 트리 사본 안의 난수 시드 바이트(`rng-seed`, `kaslr-seed`)를 0으로 지우고 다시 읽어 확인함. QEMU virt에서는 `40B`로 나옴. 모든 이미지가 출력함 |
+| `root: boot seed from rng-seed bytes 0x... and rndr` 또는 `... without rndr` | 커널이 루트 태스크에 넘긴 부트 시드에 난수 재료를 얼마나 넣었는지 알려 줌. `rng-seed` 바이트 수와, CPU의 난수 명령 RNDR이 보탰는지 여부임. 시드 자체는 출력하지 않음. 모든 이미지가 출력함 |
| `root: ... pass` | 자가 테스트 한 묶음이 통과함 |
| `root: secret at 0x...` 다음에 같은 주소의 `k0: task fault ... far 0x...` | 격리된 태스크가 루트 태스크만 볼 수 있는 메모리를 읽으려다 정확히 그 주소에서 멈춤 |
-| `k0: task fault ...`와 `k0: unknown syscall 65535, killing task` | 테스트가 일부러 일으킨 규칙 위반. 매번 규칙을 어긴 태스크만 멈춤. 정상 실행에서는 `k0: task fault` 줄이 정확히 6개, `k0: unknown syscall` 줄이 1개 나옴 |
+| `k0: task fault ...`와 `k0: unknown syscall 65535, killing task` | 테스트가 일부러 일으킨 규칙 위반. 매번 규칙을 어긴 태스크만 멈춤. 정상 실행에서는 `k0: task fault` 줄이 정확히 6개, `k0: unknown syscall` 줄이 1개 나옴. `vault` feature를 포함해 빌드한 이미지에서는 `k0: task fault` 줄이 8개 나옴 |
| `k0: kernel reserve tables + address space entries = bytes in ranges` | 커널이 넘겨 주는 메모리 범위마다 맨 위에 자기 페이지 테이블과 주소 공간 목록용 메모리를 따로 떼어 둠. `k0: untyped` 줄보다 먼저 출력됨. QEMU virt 512 MiB에서는 `262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges`로 나오며, 항목 수는 이미지 크기에 따라 달라짐 |
| `k0: memory + not handed out ()` | 메모리 범위가 너무 작아 그 예비 몫을 담지 못하거나 몫을 매핑하지 못해서, 커널이 그 범위를 넘겨 주지 않음. 부팅은 계속됨. QEMU virt의 정상 실행에서는 나오지 않음 |
| `root: timeout tests pass` | IPC 타임아웃 자가 테스트가 통과함 |
| `root: kernel reserve tests pass` | 커널 예비 공간 자가 테스트가 통과함(주소 공간 300개를 동시에 유지, 여러 페이지 테이블 블록에 걸친 untyped 메모리에서 프레임 생성) |
+| `root: oracle tests pass` | 서명 오라클 자가 테스트가 통과함. `vault` feature를 포함해 빌드한 이미지만 출력함(뒤의 "서명 오라클" 참고) |
+| `root: oracle made no key (boot seed has no entropy)` | 부트 시드가 약해서 볼트가 키 생성을 거부함. `vault` feature를 포함해 빌드한 이미지만 출력할 수 있으며, 이때 `root: oracle tests pass`는 뒤따르지 않음 |
| `root: sched tests pass` | 마지막 자가 테스트 묶음이 통과함 |
| `k0: idle (waiting for a timeout)` | 모든 태스크가 기다리는 중이고 시간 제한이 있는 대기가 하나 이상이어서, 커널이 멈추지 않고 다음 인터럽트를 기다림. 부팅당 최대 한 번 출력됨 |
| `k0: all tasks stopped (none ready, no timeout pending)` | 모든 태스크가 기다리는 중이고 시간 제한이 있는 대기가 없음. 지금은 태스크를 깨울 수 있는 것이 없어서 머신은 유휴 상태로 남음. 정상 실행에서는 나오지 않고, 부팅 테스트는 이 줄을 실패로 처리함. 부팅당 최대 한 번 출력됨 |
@@ -159,6 +163,39 @@ $ tools/boot-log.py <커널 ELF> <적재 주소>
적재 주소는 이미지를 올린 물리 주소입니다. 이미지를 고치지 않은 QEMU `virt`에서는 `0x40080000`입니다.
+### 서명 오라클
+
+서명 오라클은 격리 코어 위에서 도는 첫 번째 서비스입니다. 볼트 태스크가 Ed25519 키 하나를 가지고 있고, 클라이언트 태스크는 IPC로 서명과 공개 키를 받을 뿐 키는 보지 못합니다. 오라클은 선택 사항이며 기본으로는 꺼져 있습니다. 커널 크레이트에는 이를 위한 feature가 두 개 있으며, feature는 더하기만 합니다.
+
+| Feature | 추가하는 것 |
+| --- | --- |
+| `vault` | 볼트 서비스와 그 프로토콜, 고정된 정책, 자가 테스트. 서명 알고리즘은 없으며 모든 서명 요청에 "unsupported"로 답함 |
+| `vault-ed25519` | `vault`를 포함하고 Ed25519(FIPS 186-5와 RFC 8032의 SHA-512를 사용하는 PureEdDSA)를 추가함 |
+
+볼트의 코드는 루트 태스크 이미지에 포함되므로 빌드할 때 feature를 직접 적어야 하며, `cargo virt`에는 들어 있지 않습니다. 오라클이 있는 이미지는 다음과 같이 빌드하고 실행할 수 있습니다.
+
+```sh
+$ cargo run -p k0-kernel --features console,vault-ed25519
+```
+
+부팅 테스트로도 확인할 수 있습니다. 오라클 자가 테스트는 일부러 일으키는 폴트를 두 번 더 추가하므로, 테스트는 `k0: task fault` 줄이 6개가 아니라 8개라고 기대해야 합니다. 다음과 같이 입력할 수 있습니다.
+
+```sh
+$ cargo build -p k0-kernel --features console,vault-ed25519 --offline
+$ K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE='k0: dtb seeds wiped 40B|root: oracle tests pass' tools/qemu-boot-test.sh
+```
+
+부트 로그에는 "출력 읽는 법"의 줄에 더해 다음 줄이 보여야 합니다.
+
+- `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`입니다. 이 줄은 오라클의 검사가 모두 통과했다는 뜻입니다. 볼트가 부트 시드로 키를 만들었고, 서명자가 검증되는 서명을 받았으며, 메시지나 서명을 바꾸면 검증되지 않고, 관리자와 읽기 전용 클라이언트는 서명을 요청했을 때 거부되었으며, 키를 지운 뒤에는 서명이 거부되었습니다.
+
+볼트는 부트 시드에 `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)에 있습니다.
+
## UEFI로 부팅
UEFI는 많은 컴퓨터에서 펌웨어가 프로그램을 시작하는 표준 방식입니다. 펌웨어가 디스크에서 확장자가 `.efi`인 프로그램 파일을 읽어 실행하고, 그 프로그램에 기계의 구성을 알려 줍니다. 로더는 기계를 준비한 다음 다른 프로그램을 시작하는 일 하나만 하는 작은 프로그램입니다. K0에는 자체 UEFI 로더(`crates/k0-efi`와 `loader/`)가 있습니다. 로더가 커널을 안에 품고 있으므로, 펌웨어에는 `.efi` 파일 하나만 있으면 됩니다. 커널은 바뀌지 않으며 UEFI 없이 부팅할 때와 똑같이 시작합니다. 다음 그림은 UEFI 부팅의 경로를 보여 줍니다.
@@ -270,9 +307,9 @@ $ tools/qemu-boot-test.sh # QEMU에서 부팅하
$ tools/boot-matrix.sh # 지원하는 구성을 전부 부팅(16 KiB 이미지, 고정 이미지, UEFI 로더 이미지도 빌드함)
```
-- `tools/host-test.sh`는 호스트 테스트 250개를 실행합니다(x86-64 컴퓨터에서는 164개). 커널의 부분 하나하나를 내 컴퓨터에서 일반 프로그램처럼 돌리는 작은 테스트(단위 테스트)입니다. **퍼징**도 합니다. 디바이스 트리 파서와 UEFI 로더의 계획 코드에 무작위로 망가뜨린 입력을 넣어 충돌을 찾는 방법입니다. 250개는 `k0-abi` 14개, `k0-cap` 42개, `k0-boot` 76개, `k0-efi` 32개, `k0-mm` 43개씩 두 페이지 크기분입니다. 메모리 관리 테스트는 ARM 명령을 사용하므로 ARM 컴퓨터(Apple Silicon Mac이나 Linux arm64)에서만 돌고, x86-64의 개수는 그 86개를 뺀 것입니다.
+- `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/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`, 고정 이미지도 부팅합니다. 이미지가 물리 타이머를 건드리지 않는지는 정적으로 검사합니다. 행 이름을 인자로 주면 그 행만 돌립니다. CI가 이것을 실행합니다.
+- `tools/boot-matrix.sh`는 K0가 지원한다고 말하는 **구성마다** 커널을 부팅해서 결과를 확인합니다. GICv3와 GICv2의 QEMU virt를 EL1과 EL2에서 부팅하고, CPU 모델 세 가지, 코어 4개, 16 KiB 이미지, 다른 적재 주소, `xlnx-versal-virt`, 고정 이미지, 서명 오라클이 있는 이미지도 부팅합니다. 이미지가 물리 타이머를 건드리지 않는지는 정적으로 검사합니다. 행렬은 HVF가 있는 Mac에서 61행, CI에서 51행입니다. 행 이름을 인자로 주면 그 행만 돌립니다. CI가 이것을 실행합니다.
콘솔 행은 콘솔 feature를 확인합니다. 다음 표는 콘솔 행과 확인하는 내용입니다.
@@ -284,11 +321,22 @@ $ tools/boot-matrix.sh # 지원하는 구성
| `pl011-identity` | 콘솔 노드가 RTC를 가리키도록 디바이스 트리를 고치면, 커널이 `k0: console is not a pl011, ignored`를 출력하고 아무것도 쓰지 않으며 그 페이지를 매핑한 채로 두지 않아야 함 |
| `serial-check` | 판정 자체를 시험. 콘솔 이미지를 조용한 이미지로 판정하면 직렬 출력 때문에 실패해야 함 |
+오라클 행은 서명 오라클을 확인합니다. 다음 표에서 부팅 행은 모두 `root: oracle tests pass`를 요구하고, 폴트 줄 8개를 기대합니다.
+
+| 행 | 확인하는 것 |
+| --- | --- |
+| `vault` | 기본 CPU에서 `vault-ed25519`를 포함한 이미지. `k0: dtb seeds wiped 40B`도 요구함 |
+| `vault-max` | 같은 이미지를 `max` CPU에서 부팅해, RNDR이 부트 시드에 들어가는지 확인(`... and rndr`) |
+| `vault-el2` | 같은 이미지를 EL2에서 시작 |
+| `vault-16k` | `vault-ed25519`를 포함한 16 KiB 이미지 |
+| `vault-no-alg` | `vault`만 포함한 이미지. 모든 서명 요청에 "unsupported"로 답함 |
+| `vault-symbols` | 정적 검사. 기본 이미지에는 볼트 코드와 암호 코드가 없고, 볼트 이미지에는 그 코드의 쓰기 가능한 정적 변수가 없음 |
+
`uefi-*` 행은 EDK2 위에서 UEFI 로더를 거쳐 커널을 부팅합니다. GICv3와 GICv2를 EL1과 EL2에서, `max` CPU, 코어 4개, 16 KiB 이미지, 펌웨어의 난수 장치, FAT 드라이브 경로를 부팅합니다. ACPI를 켠 QEMU 기본 머신을 디바이스 트리 없이 부팅하는 `uefi-acpi-*` 행(`uefi-acpi-gic3-el1`, `uefi-acpi-gic3-el2`, `uefi-acpi-gic2-el1`, `uefi-acpi-smp4`, `uefi-acpi-16k`, `uefi-acpi-rng`)도 있습니다. 정적 검사(`tools/pe-check.py`)는 로더 파일의 형식과, QEMU로는 시험할 수 없는 캐시와 MMU 명령의 순서를 확인합니다.
거부해야 하는 구성에서는 커널의 사유를 메모리에 남은 부트 로그에서 읽고, 로더의 사유는 직렬 로그에서 읽습니다. 이런 구성으로 `cortex-a72`에서의 16 KiB 커널과 한 바이트를 바꾼 커널이 있습니다.
-Apple Silicon Mac에서는 `K0_MATRIX_HVF=1 tools/boot-matrix.sh`로 QEMU의 HVF 가속기를 통해 실제 CPU 코어에서 커널을 (UEFI 로더를 거치는 경우도 포함해) 돌리는 행을 더할 수 있습니다. 콘솔 없는 이미지용으로는 `hvf-quiet`이 있습니다.
+Apple Silicon Mac에서는 `K0_MATRIX_HVF=1 tools/boot-matrix.sh`로 QEMU의 HVF 가속기를 통해 실제 CPU 코어에서 커널을 (UEFI 로더를 거치는 경우도 포함해) 돌리는 행을 더할 수 있습니다. 콘솔 없는 이미지용으로는 `hvf-quiet`이, 오라클이 있는 이미지용으로는 `hvf-vault`가 있습니다.
### 콘솔 없는 이미지 시험
@@ -340,6 +388,8 @@ GitHub도 풀 리퀘스트와 `main` 푸시가 있을 때마다 이 테스트를
| `boot-test: the serial log has no kernel line` | 같은 원인입니다. 콘솔 feature 없이 빌드한 커널은 직렬 포트에 아무것도 쓰지 않습니다. `--features console`로 빌드하거나 `K0_BOOT_MEMLOG=<적재 주소>`로 게스트 메모리의 로그를 판정하세요 |
| `boot-test`가 `k0: all tasks`로 시작하는 줄에서 실패함 | 모든 태스크가 기다리는 중인데 시간 제한이 있는 대기가 없어서 태스크를 깨울 수 있는 것이 없습니다. 기본 자가 테스트에서는 일어나지 않습니다. 루트 태스크를 바꿨다면 대기마다 타임아웃을 지정하세요 |
| 부트 로그에 `k0: memory + not handed out ()`가 나옴 | 커널이 자기 예비 공간을 담기에 너무 작거나 그 몫을 매핑하지 못하는 메모리 범위를 찾았습니다. 그 범위를 제외하고 부팅을 계속했으며, 해당 범위는 untyped 메모리로 쓸 수 없습니다. QEMU에 준 메모리 크기와 적재 주소를 확인하세요 |
+| `root: oracle made no key (boot seed has no entropy)`가 나오거나 `root: oracle tests pass`가 없음 | 부트 시드에 `rng-seed` 바이트가 32개보다 적고 RNDR도 없었음. QEMU virt처럼 디바이스 트리에 `rng-seed`가 있는 머신이나 RNDR이 있는 CPU(`K0_QEMU_CPU=max`)를 사용하세요 |
+| `vault` feature를 포함한 이미지에서 `boot-test`가 `k0: task fault` 줄 수 때문에 실패 | 그 이미지는 8개를 출력함. `K0_BOOT_FAULTS=8`로 테스트를 실행하세요 |
| 느린 컴퓨터에서 부팅 테스트가 시간 초과 | 시간을 늘리세요. 예: `K0_BOOT_TIMEOUT=300 tools/qemu-boot-test.sh` |
| 16 KiB 이미지가 `cortex-a72`에서 부팅되지 않음 | 정상입니다. 그 CPU는 16 KiB 페이지를 지원하지 않습니다. `K0_QEMU_CPU=max`를 사용하세요 |
| 부팅이 일찍 멈추고 아무것도 출력되지 않음 | 지원하는 콘솔이 없거나, 이미지에 그 콘솔의 드라이버가 없을 수 있습니다(드라이버가 하나뿐인 이미지는 다른 종류의 콘솔에서 조용합니다). `tools/boot-log.py`로 메모리에서 부트 로그를 읽으세요 |
diff --git a/assets/vault-flow.svg b/assets/vault-flow.svg
new file mode 100644
index 0000000..6385e23
--- /dev/null
+++ b/assets/vault-flow.svg
@@ -0,0 +1,61 @@
+
diff --git a/assets/vault-flow_KR.svg b/assets/vault-flow_KR.svg
new file mode 100644
index 0000000..666bb40
--- /dev/null
+++ b/assets/vault-flow_KR.svg
@@ -0,0 +1,61 @@
+
diff --git a/ci/threat_model.md b/ci/threat_model.md
index 8277352..f9df62f 100644
--- a/ci/threat_model.md
+++ b/ci/threat_model.md
@@ -15,6 +15,7 @@ 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.
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.
@@ -33,9 +34,11 @@ Highest value, all in scope:
- `crates/k0-abi`: system call numbers and ABI structures shared with user space.
- `crates/k0-efi` and `loader/`: the memory policy (`memmap.rs`: only `EfiConventionalMemory`, `EfiLoaderCode` and `EfiLoaderData` with the WB attribute and without RUNTIME, SP or NV are RAM; overlaps and unknown types are not RAM; the firmware device tree's own memory nodes, reservations and discovered devices are cut out), the device tree rewriter (`fdtw.rs`), the independent verifier (`verify.rs`), the composition and self-check (`prepare.rs`), the image header check (`image.rs`), the UEFI bindings and flow (`loader/src/efi.rs`, `load.rs`), the `ExitBootServices` retry, wiping and freeing on a refusal, the entropy handling, and the cache flush, MMU-off trampoline and jump (`handoff.rs`).
+- `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.
+
Lower value:
-- `userspace/root-task`: the trusted root task and test harness. Bugs here are not kernel vulnerabilities, but it is the right place to write reproducers.
+- `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.
- `vendor/`: third-party crates vendored with pinned checksums. Only `sha2` and its dependencies are linked into the kernel, for the boot-time hash of the fixed root task image. Report issues there only if reachable through that use; generic upstream findings are out of scope.
- `tools/qemu-virt-runner.sh`, `tools/boot-matrix.sh`, `tools/boot-log.py`, `kernel/build.rs`, `crates/k0-boot/build.rs`, `userspace/root-task/build.rs`, `loader/build.rs`, `tools/build-loader.sh`, `tools/pe-check.py`: developer tooling that runs on the trusted build host.
- Documentation, `.idea/`, `.claude/`.
@@ -44,7 +47,7 @@ Lower value:
- 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.
- 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`.
+- 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).
- 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.
@@ -82,6 +85,7 @@ 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.
- 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.
- Optional console output: an empty serial log shows only that no byte reached the serial port of QEMU virt (a PL011), not that no register was read; the symbol check runs on debug images and release (LTO) images without console are not booted; no image without console is booted through UEFI; the boot log in kernel memory is readable by anyone who can read RAM or attach a debugger. See "Optional console output" in `SECURITY.md`.
diff --git a/crates/k0-abi/src/lib.rs b/crates/k0-abi/src/lib.rs
index 50df889..3b2b87a 100644
--- a/crates/k0-abi/src/lib.rs
+++ b/crates/k0-abi/src/lib.rs
@@ -257,7 +257,20 @@ pub mod bootinfo {
/// bootinfo 페이지의 사용자 VA(양 플랫폼 그래뉼 정렬)
pub const VA: u64 = 0x0F00_0000;
/// 레이아웃 버전(불일치 시 루트 태스크는 진행하면 안 됨)
- pub const VERSION: u64 = 2;
+ pub const VERSION: u64 = 3;
+
+ /// 루트 태스크의 진입 레지스터 x4로 오는 시드 정보에서, 시드에 들어간
+ /// `rng-seed` 바이트 수를 담는 비트
+ ///
+ /// 버전 3부터 커널은 부트 엔트로피에서 파생한 32바이트 시드를 루트
+ /// 태스크의 진입 레지스터 x0-x3에(리틀 엔디언 워드 넷), 그 재료에 관한
+ /// 정보를 x4에 줍니다. 시드는 bootinfo 페이지에 두지 않습니다. 페이지는
+ /// 루트 태스크가 사는 동안 읽기 전용으로 매핑돼 있기 때문입니다. 시드의
+ /// 품질은 재료보다 나을 수 없으므로 받는 쪽은 이 정보를 보고 판단해야
+ /// 합니다
+ pub const SEED_RNG_SEED_BYTES: u64 = 0xFFFF;
+ /// 시드 정보에서, RNDR 난수 256비트가 재료에 들어갔음을 뜻하는 비트
+ pub const SEED_RNDR: u64 = 1 << 16;
/// 루트 CNode에서 위치가 고정된 케이퍼빌리티의 슬롯 번호 모듈입니다.
pub mod slot {
diff --git a/crates/k0-abi/src/tests.rs b/crates/k0-abi/src/tests.rs
index 058063c..389192d 100644
--- a/crates/k0-abi/src/tests.rs
+++ b/crates/k0-abi/src/tests.rs
@@ -134,7 +134,8 @@ fn flag_register_bits_are_all_accounted_for() {
#[test]
fn bootinfo_layout_is_stable() {
- assert_eq!(bootinfo::VERSION, 2);
+ assert_eq!(bootinfo::VERSION, 3);
+ assert_eq!(bootinfo::SEED_RNG_SEED_BYTES & bootinfo::SEED_RNDR, 0);
assert_eq!(size_of::(), 32);
assert_eq!(offset_of!(bootinfo::Header, version), 0);
assert_eq!(offset_of!(bootinfo::Header, frame_size), 8);
diff --git a/crates/k0-boot/Cargo.toml b/crates/k0-boot/Cargo.toml
index c1aa75c..49853ec 100644
--- a/crates/k0-boot/Cargo.toml
+++ b/crates/k0-boot/Cargo.toml
@@ -9,6 +9,10 @@ publish.workspace = true
default = ["roottask"]
# 루트 태스크 이미지를 빌드해 내장함. 커널이 씀
roottask = []
+# 루트 태스크 이미지에 키 볼트(서명 오라클)를 넣음. build.rs가 이 feature를
+# 보고 루트 태스크의 빌드에 같은 이름의 feature를 넘김
+vault = ["roottask"]
+vault-ed25519 = ["vault"]
# 테스트용 DTB 빌더와 퍼즈 도우미를 다른 크레이트의 테스트에 공개함(std 필요)
test-support = []
diff --git a/crates/k0-boot/build.rs b/crates/k0-boot/build.rs
index 7406dce..d19ed2f 100644
--- a/crates/k0-boot/build.rs
+++ b/crates/k0-boot/build.rs
@@ -145,7 +145,20 @@ fn main() {
// 바깥 cargo와의 락 충돌을 피하려고 전용 타겟 디렉터리에서 빌드
let rt_target = out_dir.join("root-task-target");
let cargo = env::var("CARGO").unwrap();
- let status = Command::new(&cargo)
+ // 이 크레이트의 feature를 루트 태스크의 같은 이름 feature로 넘김. 넘기는
+ // feature가 달라지면 cargo가 이 스크립트를 다시 돌림(feature는 스크립트의
+ // 입력이므로)
+ let mut features = Vec::new();
+ for (var, name) in [
+ ("CARGO_FEATURE_VAULT", "vault"),
+ ("CARGO_FEATURE_VAULT_ED25519", "vault-ed25519"),
+ ] {
+ if env::var_os(var).is_some() {
+ features.push(name);
+ }
+ }
+ let mut build = Command::new(&cargo);
+ build
.current_dir(workspace)
.env("CARGO_TARGET_DIR", &rt_target)
.args([
@@ -155,7 +168,11 @@ fn main() {
"--release",
"--target",
"aarch64-unknown-none-softfloat",
- ])
+ ]);
+ if !features.is_empty() {
+ build.args(["--features", &features.join(",")]);
+ }
+ let status = build
.status()
.expect("root-task 빌드 실행 실패");
assert!(status.success(), "root-task 빌드 실패");
@@ -229,8 +246,13 @@ fn main() {
);
fs::write(out_dir.join("roottask_gen.rs"), generated).unwrap();
+ // 디렉토리를 주면 cargo가 그 안의 모든 파일을 봄. 볼트의 소스가 바뀌어도
+ // 낡은 이미지가 그대로 내장되지 않게 함
for rel in [
- "userspace/root-task/src/main.rs",
+ "userspace/root-task/src",
+ "userspace/k0-vault/src",
+ "userspace/k0-vault/Cargo.toml",
+ "Cargo.lock",
"userspace/root-task/Cargo.toml",
"userspace/root-task/build.rs",
"userspace/root-task/user.ld",
diff --git a/crates/k0-boot/src/entropy.rs b/crates/k0-boot/src/entropy.rs
index 66ebe6c..2145336 100644
--- a/crates/k0-boot/src/entropy.rs
+++ b/crates/k0-boot/src/entropy.rs
@@ -19,6 +19,7 @@ use sha2::{Digest, Sha256};
/// # Arguments
/// `dtb_entropy` - /chosen에서 수집한 바이트(비어 있을 수 있음)
/// `extra` - 아키텍처 재료(CNTPCT, RNDR 값 등)
+#[inline(never)]
pub fn derive_pac_keys(dtb_entropy: &[u8], extra: &[u64]) -> [u64; 10] {
let mut keys = [0u64; 10];
let mut i = 0;
@@ -45,5 +46,32 @@ pub fn derive_pac_keys(dtb_entropy: &[u8], extra: &[u64]) -> [u64; 10] {
keys
}
+/// 엔트로피 재료를 혼합해 루트 태스크에 넘길 시드 32바이트를 파생하는
+/// 함수입니다.
+///
+/// PAC 키와 같은 재료를 받더라도 도메인 문자열이 달라 서로 독립인 값이
+/// 나옵니다. 한쪽을 알아도 다른 쪽을 계산할 수 없습니다(SHA-256의 안전성에
+/// 귀속). 결과는 가장 좋은 재료보다 나을 수 없으므로, 호출자는 어떤 재료가
+/// 있었는지를 시드와 함께 알려야 합니다.
+///
+/// 호출한 쪽의 프레임에 합쳐지지 않게 해 두었습니다(PAC 키 파생도 같음).
+/// 해시 상태가 이 함수의 프레임에만 남아야, 커널이 EL0로 넘어가기 전에 살아
+/// 있는 프레임 아래를 지울 때 함께 지워집니다.
+///
+/// # Arguments
+/// `dtb_entropy` - /chosen에서 수집한 바이트(비어 있을 수 있음)
+/// `extra` - 아키텍처 재료(카운터, RNDR 값 등)
+#[inline(never)]
+pub fn derive_root_seed(dtb_entropy: &[u8], extra: &[u64]) -> [u8; 32] {
+ let mut h = Sha256::new();
+ h.update(b"k0-root-task-seed-v1");
+ h.update((dtb_entropy.len() as u64).to_le_bytes());
+ h.update(dtb_entropy);
+ for w in extra {
+ h.update(w.to_le_bytes());
+ }
+ h.finalize().into()
+}
+
#[cfg(test)]
mod tests;
diff --git a/crates/k0-boot/src/entropy/tests.rs b/crates/k0-boot/src/entropy/tests.rs
index ad13cae..9922e99 100644
--- a/crates/k0-boot/src/entropy/tests.rs
+++ b/crates/k0-boot/src/entropy/tests.rs
@@ -68,3 +68,38 @@ fn key_words_are_distinct() {
}
}
}
+
+fn hex(s: &str) -> Vec {
+ (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect()
+}
+
+#[test]
+fn root_seed_matches_independent_known_answers() {
+ // Python hashlib로 따로 계산한 값
+ assert_eq!(
+ derive_root_seed(&[], &[]).to_vec(),
+ hex("1fd07e587112efbf09cabed0587f70aab66fc7b863becf6e10a78021986bef4e")
+ );
+ assert_eq!(
+ derive_root_seed(&virt_seed(), &[0x0123_4567_89ab_cdef, 0xfedc_ba98_7654_3210]).to_vec(),
+ hex("d0b6a805e0d9a276642dc45946a20ba8c3abb62bf37055395d038ac812855d55")
+ );
+}
+
+#[test]
+fn root_seed_is_independent_of_the_pac_keys_and_follows_every_input() {
+ let seed = virt_seed();
+ let base = derive_root_seed(&seed, &[7, 9]);
+ // 같은 재료에서 나온 PAC 키의 어느 워드도 시드에 나타나지 않음
+ for k in derive_pac_keys(&seed, &[7, 9]) {
+ assert!(!base.windows(8).any(|w| w == k.to_le_bytes()));
+ }
+ let mut flipped = seed.clone();
+ flipped[39] ^= 1;
+ assert_ne!(derive_root_seed(&flipped, &[7, 9]), base);
+ assert_ne!(derive_root_seed(&seed, &[7, 8]), base);
+ assert_ne!(derive_root_seed(&seed[..39], &[7, 9]), base);
+ // 길이 접두사가 DTB 바이트와 뒤따르는 워드를 구분함
+ let tail = u64::from_le_bytes(seed[32..40].try_into().unwrap());
+ assert_ne!(derive_root_seed(&seed[..32], &[tail, 7, 9]), base);
+}
diff --git a/crates/k0-boot/src/fdt.rs b/crates/k0-boot/src/fdt.rs
index e27b3d9..512f023 100644
--- a/crates/k0-boot/src/fdt.rs
+++ b/crates/k0-boot/src/fdt.rs
@@ -31,6 +31,9 @@ pub const MAX_MEM_REGIONS: usize = 8;
/// 저장 가능한 예약 구간(memreserve + /reserved-memory) 수의 상한
pub const MAX_RSV_REGIONS: usize = 32;
+/// 시드 값이 놓인 구간의 최대 수(`rng-seed`와 `kaslr-seed` 하나씩)
+pub const MAX_SEED_SPANS: usize = 2;
+
/// /chosen에서 수집하는 엔트로피 바이트 상한 (rng-seed + kaslr-seed)
pub const MAX_ENTROPY: usize = 72;
@@ -58,9 +61,48 @@ pub struct BootInfo {
reserved_count: usize,
entropy: [u8; MAX_ENTROPY],
entropy_len: usize,
+ /// 엔트로피에 들어간 `rng-seed` 바이트 수(`kaslr-seed`는 세지 않음)
+ rng_seed_len: usize,
+ /// DTB 안에서 시드 값이 놓인 구간들(blob 시작으로부터의 오프셋, 길이)
+ seed_spans: [(usize, usize); MAX_SEED_SPANS],
+ seed_span_count: usize,
+ chosen_seen: bool,
}
impl BootInfo {
+ /// 엔트로피에 들어간 `rng-seed` 바이트 수를 주는 함수입니다.
+ ///
+ /// 시드의 품질을 말할 때 쓰는 값입니다. `kaslr-seed`는 8바이트뿐이라
+ /// 여기에 세지 않습니다.
+ pub fn rng_seed_len(&self) -> usize {
+ self.rng_seed_len
+ }
+
+ /// DTB 안에서 시드 값(`rng-seed`, `kaslr-seed`)이 놓인 구간을 주는
+ /// 함수입니다. 각 항목은 (DTB 시작으로부터의 오프셋, 길이)이고 값 전체를
+ /// 덮습니다(엔트로피 사본은 앞의 일부만 담을 수 있음).
+ ///
+ /// 커널이 시드를 쓴 뒤 DTB에 남은 원본을 지우는 데 씁니다.
+ pub fn seed_spans(&self) -> &[(usize, usize)] {
+ &self.seed_spans[..self.seed_span_count]
+ }
+
+ /// 엔트로피 사본을 지우는 함수입니다. 이후 [BootInfo::entropy]는 빈
+ /// 구간을 줍니다.
+ ///
+ /// 시드를 다 쓴 뒤에 불러, 나중의 코드가 지워진 시드를 재료로 삼는 일이
+ /// 없게 합니다.
+ pub fn wipe_entropy(&mut self) {
+ for b in self.entropy.iter_mut() {
+ // SAFETY: b는 이 구조체 안의 유효한 바이트임. volatile이라 소거가
+ // 최적화로 사라지지 않음
+ unsafe { core::ptr::write_volatile(b, 0) };
+ }
+ core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
+ self.entropy_len = 0;
+ self.rng_seed_len = 0;
+ }
+
pub fn memory(&self) -> &[MemRegion] {
&self.regions[..self.region_count]
}
@@ -103,6 +145,9 @@ pub enum BootError {
UnsupportedRanges,
MemoryLimited,
BadInitrd,
+ /// `/chosen` 노드가 둘 이상임. 시드가 어느 노드에 있는지 모호해져 쓴 뒤에
+ /// 전부 지웠다고 말할 수 없음
+ DuplicateChosen,
}
/// DTB 헤더만 검사해 blob이 차지하는 물리 범위를 얻는 함수입니다.
@@ -220,6 +265,10 @@ pub fn parse_blob(blob: &[u8], dtb: Range) -> Result
reserved_count: 0,
entropy: [0; MAX_ENTROPY],
entropy_len: 0,
+ rng_seed_len: 0,
+ seed_spans: [(0, 0); MAX_SEED_SPANS],
+ seed_span_count: 0,
+ chosen_seen: false,
};
fdt.memreserve(|base, size| push_reserved(&mut info, base, size))?;
@@ -249,9 +298,24 @@ pub fn parse_blob(blob: &[u8], dtb: Range) -> Result
if node.has(P::UsableMemoryRange) {
return Err(BootError::MemoryLimited);
}
+ if info.chosen_seen {
+ return Err(BootError::DuplicateChosen);
+ }
+ info.chosen_seen = true;
for p in [P::RngSeed, P::KaslrSeed] {
if let Some(value) = node.get(p) {
- push_entropy(value, &mut info);
+ let taken = push_entropy(value, &mut info);
+ if matches!(p, P::RngSeed) {
+ info.rng_seed_len = taken;
+ }
+ // 값은 blob 안의 조각이므로 주소 차이가 곧 오프셋임.
+ // 노드 하나에 같은 프로퍼티가 둘일 수 없고 /chosen도
+ // 하나뿐이라 칸이 모자랄 수 없음
+ let offset = value.as_ptr() as usize - blob.as_ptr() as usize;
+ if !value.is_empty() && offset + value.len() <= blob.len() {
+ info.seed_spans[info.seed_span_count] = (offset, value.len());
+ info.seed_span_count += 1;
+ }
}
}
push_initrd(node, &mut info)?;
@@ -355,11 +419,13 @@ fn push_initrd(node: &Node<'_>, info: &mut BootInfo) -> Result<(), BootError> {
/// /chosen의 엔트로피 프로퍼티를 상한까지 수집하는 함수입니다.
///
/// 내용은 검증하지 않고(해시 혼합 재료일 뿐) 넘치는 바이트는 버립니다.
-fn push_entropy(value: &[u8], info: &mut BootInfo) {
+/// 수집한 바이트 수를 반환합니다.
+fn push_entropy(value: &[u8], info: &mut BootInfo) -> usize {
let cap = MAX_ENTROPY - info.entropy_len;
let n = value.len().min(cap);
info.entropy[info.entropy_len..info.entropy_len + n].copy_from_slice(&value[..n]);
info.entropy_len += n;
+ n
}
/// 다른 모듈의 테스트 도구가 blob 하나의 메모리 맵을 보기 위한 통로입니다.
diff --git a/crates/k0-boot/src/fdt/tests.rs b/crates/k0-boot/src/fdt/tests.rs
index af44885..f48a733 100644
--- a/crates/k0-boot/src/fdt/tests.rs
+++ b/crates/k0-boot/src/fdt/tests.rs
@@ -701,3 +701,86 @@ fn malformed_branches_the_kernel_does_not_read_are_tolerated() {
.end();
assert!(run(&b.build()).is_ok());
}
+
+#[test]
+fn seed_spans_cover_the_whole_values_in_the_blob() {
+ // 엔트로피 사본은 상한까지만 담지만, 구간은 값 전체를 덮어야 지울 때
+ // 남는 바이트가 없음
+ let blob = Board {
+ rng_seed: Some(vec![0xA5; 96]),
+ kaslr_seed: Some(vec![0x5A; 8]),
+ ..Board::qemu_virt()
+ }
+ .blob();
+ let info = run(&blob).unwrap();
+ assert_eq!(info.entropy().len(), MAX_ENTROPY);
+ assert_eq!(info.rng_seed_len(), MAX_ENTROPY, "only rng-seed bytes that were used are counted");
+ let spans = info.seed_spans();
+ assert_eq!(spans.len(), 2);
+ assert_eq!(spans[0].1, 96);
+ assert_eq!(spans[1].1, 8);
+ assert!(blob[spans[0].0..spans[0].0 + 96].iter().all(|&b| b == 0xA5));
+ assert!(blob[spans[1].0..spans[1].0 + 8].iter().all(|&b| b == 0x5A));
+
+ // 구간을 0으로 덮은 blob에는 시드 바이트가 어디에도 남지 않고, 다시
+ // 파싱해도 같은 메모리 맵이 나옴
+ let mut wiped = blob.clone();
+ for &(off, len) in spans {
+ wiped[off..off + len].fill(0);
+ }
+ assert!(!wiped.windows(8).any(|w| w == [0xA5; 8] || w == [0x5A; 8]));
+ let again = run(&wiped).unwrap();
+ assert_eq!(again.memory(), info.memory());
+ assert!(again.entropy().iter().all(|&b| b == 0));
+}
+
+#[test]
+fn rng_seed_length_does_not_count_the_kaslr_seed() {
+ let info = run(&Board {
+ rng_seed: None,
+ kaslr_seed: Some(vec![9; 8]),
+ ..Board::qemu_virt()
+ }
+ .blob())
+ .unwrap();
+ assert_eq!(info.entropy().len(), 8);
+ assert_eq!(info.rng_seed_len(), 0);
+ assert_eq!(info.seed_spans().len(), 1);
+
+ let info = run(&Board {
+ rng_seed: Some(vec![3; 32]),
+ kaslr_seed: None,
+ ..Board::qemu_virt()
+ }
+ .blob())
+ .unwrap();
+ assert_eq!(info.rng_seed_len(), 32);
+}
+
+#[test]
+fn wiping_the_entropy_copy_leaves_nothing_to_derive_from() {
+ let mut info = run(&Board {
+ rng_seed: Some(vec![0xEE; 32]),
+ ..Board::qemu_virt()
+ }
+ .blob())
+ .unwrap();
+ assert_eq!(info.rng_seed_len(), 32);
+ info.wipe_entropy();
+ assert!(info.entropy().is_empty());
+ assert_eq!(info.rng_seed_len(), 0);
+}
+
+#[test]
+fn a_second_chosen_node_is_refused() {
+ // 시드가 어느 노드에 있는지 모호하면 쓴 뒤에 전부 지웠다고 말할 수 없음
+ let mut b = Builder::new();
+ b.begin("")
+ .begin("memory").prop("device_type", b"memory\0")
+ .prop("reg", ®(&[(0x4000_0000, 0x1000)], 2, 1))
+ .end()
+ .begin("chosen").prop("rng-seed", &[7; 16]).end()
+ .begin("chosen").prop("rng-seed", &[8; 16]).end()
+ .end();
+ assert_eq!(run(&b.build()).err(), Some(BootError::DuplicateChosen));
+}
diff --git a/crates/k0-boot/src/lib.rs b/crates/k0-boot/src/lib.rs
index 3c40cc4..93d1b0a 100644
--- a/crates/k0-boot/src/lib.rs
+++ b/crates/k0-boot/src/lib.rs
@@ -22,7 +22,7 @@ mod roottask;
pub mod testing;
mod window;
-pub use entropy::derive_pac_keys;
+pub use entropy::{derive_pac_keys, derive_root_seed};
pub use fdt::walk::{be32, be64, read_cells, Cursor, Fdt, Token};
pub use fdt::{
dtb_span, parse, parse_blob, BootError, BootInfo, MemRegion, MAX_DTB_SIZE, MAX_ENTROPY, MAX_MEM_REGIONS,
diff --git a/crates/k0-mm/src/lib.rs b/crates/k0-mm/src/lib.rs
index 933fd3c..643a00e 100644
--- a/crates/k0-mm/src/lib.rs
+++ b/crates/k0-mm/src/lib.rs
@@ -19,7 +19,7 @@ pub mod user;
pub use paging::{
alias_object, alias_tables_for, can_read, can_write, device_pages, enable_paging, image_pa,
image_range, map_device, map_dtb, map_kernel_window, null_user_root, pa_bits, probe_clear,
- probe_map, reserve_tables, table_pool_usage, table_reserve_usage, KernelLayout, Mmu,
+ probe_map, reserve_tables, table_pool_usage, table_reserve_usage, wipe_ro_alias, KernelLayout, Mmu,
MmuError, GRANULE, KERNEL_IMAGE_VA, KERNEL_VA_OFFSET, MAX_TABLE_RESERVES, PA_CEILING,
};
pub use user::{
diff --git a/crates/k0-mm/src/paging.rs b/crates/k0-mm/src/paging.rs
index e603068..396d694 100644
--- a/crates/k0-mm/src/paging.rs
+++ b/crates/k0-mm/src/paging.rs
@@ -755,6 +755,89 @@ impl Pool {
}
}
+/// 읽기 전용 별칭으로 매핑된 RAM의 한 구간을 0으로 덮는 함수입니다.
+///
+/// DTB에 남은 시드를 지우는 데 씁니다. 구간이 걸친 페이지마다 별칭의 리프를
+/// 잠깐 쓰기 가능으로 바꿨다가 되돌립니다. 같은 물리 페이지에 속성이 다른
+/// 두 번째 매핑을 만들지 않으려고 기존 리프를 그 자리에서 바꾸며, 바꿀
+/// 때마다 무효 엔트리와 TLB 무효화를 거칩니다(break-before-make). 덮은 뒤에는
+/// 그 캐시 라인을 메모리까지 내보내고 캐시에서 비웁니다. 그래서 호출자가 그
+/// 구간을 다시 읽으면 캐시에 남은 값이 아니라 메모리의 값을 보게 됩니다.
+///
+/// # Arguments
+/// `range` - 지울 물리 구간(정렬 불필요). 전부 [map_dtb]가 매핑한 페이지
+/// 안이어야 함
+///
+/// # Errors
+/// MMU 비활성 시 `NotEnabled`, 구간의 페이지가 매핑돼 있지 않으면
+/// `MissingTable`, 읽기 전용 별칭이 아닌 다른 매핑이면 `Overlap`
+pub fn wipe_ro_alias(range: Range) -> Result<(), MmuError> {
+ let g = GRANULE as u64;
+ // SAFETY: 부트 코어의 초기화 시퀀스에서만 호출되어 이 가변 참조는 유일함
+ let pool = unsafe { &mut *POOL.0.get() };
+ if !pool.enabled {
+ return Err(MmuError::NotEnabled);
+ }
+ let ctr: u64;
+ // SAFETY: CTR_EL0 읽기는 부작용이 없음
+ unsafe { asm!("mrs {}, ctr_el0", out(reg) ctr, options(nomem, nostack)) };
+ let line = 4u64 << ((ctr >> 16) & 0xF);
+ let root1 = pool.root1;
+ let mut at = range.start;
+ while at < range.end {
+ let page = at & !(g - 1);
+ let end = range.end.min(page + g);
+ let va = page + KERNEL_VA_OFFSET;
+ let (t, i) = pool.leaf_of(root1, va)?;
+ let ro = page | Perm::Ro.attrs();
+ if pool.tbl(t)[i] != ro {
+ return Err(MmuError::Overlap);
+ }
+ pool.tbl_mut(t)[i] = 0;
+ flush_leaf(va);
+ pool.tbl_mut(t)[i] = page | Perm::Rw.attrs();
+ // SAFETY: 방금 이 페이지를 쓰기 가능으로 바꿨고, 구간은 그 페이지
+ // 안이며 커널만 접근함. 배리어는 새 엔트리를 워커가 보게 하고,
+ // dc cvac는 캐시 유지 보수만 함
+ unsafe {
+ asm!("dsb ishst", "isb", options(nostack));
+ core::ptr::write_bytes((at + KERNEL_VA_OFFSET) as *mut u8, 0, (end - at) as usize);
+ let mut p = (at + KERNEL_VA_OFFSET) & !(line - 1);
+ while p < end + KERNEL_VA_OFFSET {
+ asm!("dc civac, {}", in(reg) p, options(nostack));
+ p += line;
+ }
+ asm!("dsb ish", options(nostack));
+ }
+ pool.tbl_mut(t)[i] = 0;
+ flush_leaf(va);
+ pool.tbl_mut(t)[i] = ro;
+ // SAFETY: 되돌린 엔트리를 워커가 보기 전에 쓰기를 완료시킴
+ unsafe { asm!("dsb ishst", "isb", options(nostack)) };
+ at = end;
+ }
+ Ok(())
+}
+
+/// 무효로 만든 리프의 변환을 TLB에서 지우는 함수입니다.
+///
+/// # Arguments
+/// `va` - 그 리프가 변환하던 가상 주소
+fn flush_leaf(va: u64) {
+ // SAFETY: 무효 엔트리 쓰기를 완료시킨 뒤 해당 VA의 마지막 레벨 변환만
+ // 지우고, 그 완료를 기다림 (TLBI의 피연산자는 VA를 12비트 내린 값)
+ unsafe {
+ asm!(
+ "dsb ishst",
+ "tlbi vale1is, {va}",
+ "dsb ish",
+ "isb",
+ va = in(reg) (va >> 12) & ((1 << 44) - 1),
+ options(nostack),
+ );
+ }
+}
+
/// 디바이스 레지스터가 있는 물리 페이지를 디바이스 창에 매핑하는 함수입니다.
///
/// `pa`가 속한 그래뉼 페이지 하나를 Device 속성으로 매핑하고 `pa`에 해당하는
diff --git a/design/en/README.md b/design/en/README.md
index f119886..14f7abb 100644
--- a/design/en/README.md
+++ b/design/en/README.md
@@ -25,5 +25,6 @@ Read them in the order of the following table the first time. This order follows
| [exceptions.md](exceptions.md) | The vector table, saving user state, system call dispatch, and fault isolation |
| [scheduling.md](scheduling.md) | TCBs and their bound CNode and address space, task creation and teardown, the round-robin scheduler, and timer preemption |
| [ipc.md](ipc.md) | Endpoints and badges, `SEND`, `RECV`, `CALL` and `REPLY_RECV`, the single-use reply right, and what happens to waiting tasks when an endpoint is deleted |
+| [vault.md](vault.md) | The signing oracle: the vault task and its frames, the `CALL` protocol and nonce, the fixed badge policy, the provider boundary, the boot seed and its wipe, features, tests, and known gaps |
Every note ends with a "**Known gaps**" section. The open security advisories are listed in [SECURITY.md](../../SECURITY.md).
diff --git a/design/en/boot.md b/design/en/boot.md
index 273b8aa..dc537a5 100644
--- a/design/en/boot.md
+++ b/design/en/boot.md
@@ -110,16 +110,18 @@ In the following table, each row gives a log line and the step it stands for, in
| `k0: console drivers [...]` | The first line of platform bring-up, printed even when the platform is later refused. It names the console drivers built into this image (see "Optional console output"). |
| `k0: platform ...` | `bring_up_platform` finds the console, the interrupt controller and the timer interrupt in the DTB and builds one immutable platform descriptor. It checks the descriptor against the memory map before it maps any device page: RAM must lie below 2^47, the kernel image and the DTB must lie inside declared memory, and no device range, widened to whole granules, may overlap memory or a reserved range or reach beyond the CPU's physical address width (`k0_mm::pa_bits`). In pinned mode it then compares the line with the expected one. Only after that does it attach the console. An image with a driver for this kind of console maps it and attaches it, which replays the buffered log. An image without one maps nothing and prints `k0: no console (driver not built in)`. If the platform is refused, the kernel attaches the console first when the console alone passes the checks (and the image is not pinned, and a driver exists), so that the reason is visible. `k0: no console (...)` names the reason when there is none. See [dtb.md](dtb.md). |
| `k0: root task integrity ok (...)` | The embedded root task image is hashed again and compared with the hash fixed at build time. |
-| `k0: entropy ...`, `k0: pac=... bti=... pan=...` | PAC keys are derived and loaded, and the key words are wiped from the boot stack. PAN is enabled and EL0 access to counters, debug and PMU is turned off. See [hardening.md](hardening.md). |
+| `k0: entropy ...`, `k0: pac=... bti=... pan=...` | PAC keys are derived and loaded, and the key words are wiped from the boot stack. The 32-byte seed for the root task is derived here too, independent of the PAC keys, and kept for the handoff. PAN is enabled and EL0 access to counters, debug and PMU is turned off. See [hardening.md](hardening.md). |
| `k0: irq on (timer 1s)` | `setup_irq` maps only the interrupt controller pages it needs. For GICv3 it looks at the redistributor frames one at a time to find the boot CPU's frame, then maps that frame and its SGI frame. The driver checks the GIC identification registers against what the DTB claimed. The EL1 virtual timer is programmed with the interrupt number from the platform descriptor. IRQ and SError are unmasked. |
| `k0: kernel table pool N/40` | A 2 MiB boot frame window is chosen and mapped, then the number of kernel page tables in use is printed (for example `16/40` on QEMU virt). The static pool of 40 tables is used only during boot. |
| `k0: root task loaded (entry ...)` | The root task is copied into frames from the window, its root TCB is made in the window, and its address space is built. The kernel does not print the physical address of the user root table. The address space is then entered in the address space registry. See [user-address-space.md](user-address-space.md). |
| `k0: memory + not handed out ()` (only when it happens), `k0: kernel reserve tables + address space entries = bytes in ranges` | `reserve_kernel_share` carves the kernel share out of each free physical range before any untyped capability exists (see "Carving the kernel share out of untyped memory"). A range that cannot hold its share is not handed out, and the kernel prints the first kind of line with the reason. The second line is printed once, for example `k0: kernel reserve 262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges` on QEMU virt with 512 MiB and the 4 KiB granule. |
| `k0: untyped ...`, `k0: root cnode ready (N caps, N untyped, N image frames, N slots)` | The root CNode (an object in the window with `ROOT_CNODE_SLOTS` = 512 slots, as the log shows) is filled: slot 1 the root TCB, slot 2 the root address space, slot 3 the console, slot 4 the root CNode itself, then every free physical range that was handed out as an untyped capability, then one Frame capability per mapped granule of the root task image (text with R and X, read-only data with R, data with R and W). Finally the root task is bound to its CNode and address space, exactly as any other task is: copies of those two capabilities go into its TCB. See [capabilities.md](capabilities.md). |
-| `k0: bootinfo page ready` | The capability list is written into the read-only bootinfo page: a header and one descriptor per slot, with the VA, size and rights of every image Frame. |
+| `k0: bootinfo page ready` | The capability list is written into the read-only bootinfo page (layout version 3): a header and one descriptor per slot, with the VA, size and rights of every image Frame. The page does not hold the boot seed. |
| `k0: user w^x checks pass` | `TTBR0` now points at the user tables, the identity map is gone, and the user mappings are checked from both EL0 and EL1. |
+| `k0: dtb seeds wiped B` | The DTB is not needed any more, so the kernel zeroes the `rng-seed` and `kaslr-seed` bytes in it (through the read-only alias, switched to read-write for the write), reads them back, and wipes its own copy. The line is `40B` on QEMU virt. If the read-back is not zero, the line is `k0: WARNING dtb seeds not wiped`. See [hardening.md](hardening.md). |
| `k0: device pages [...] of 0x1000 bytes` | Every device page the kernel keeps mapped. After this line the kernel maps no further device. |
-| `k0: entering root task (el0)` | `k0_sched::handoff` enters EL0. |
+| `k0: entering root task (el0)` | `k0_sched::handoff` enters EL0. The boot seed travels in the root task's entry registers `x0` to `x3`, with `x4` saying how many `rng-seed` bytes went in and whether `RNDR` did. Just after this line the kernel zeroes the boot stack below its live frames. |
+| `root: boot seed from rng-seed bytes 0x... and rndr` or `... without rndr` | An early line of the root task, not of the kernel. After the bootinfo version check it prints where the seed material came from, never the seed. |
### Choosing the boot frame window
@@ -147,6 +149,8 @@ This step **never refuses to boot**. The worst case is that memory is not handed
### After the handoff
+The root task starts with the boot seed in its registers `x0` to `x3` and the seed info word in `x4`. These values are in its saved context, and the first time the root task enters the kernel, its own registers overwrite them. The kernel's copies of the seed on its stack were zeroed before, and the stack scrub described in the table above is best effort: the live frames of `kernel_main` cannot be cleared. See [hardening.md](hardening.md).
+
`handoff` records the root task as the running task and points the vector code at its saved context. `enter_user` then masks all exceptions (`DAIFSet`), rewinds the kernel stack to the top, and returns to EL0 through the same path every later return uses. **The mask comes first** because that path writes `ELR_EL1` and `SPSR_EL1` before `eret`. The boot path has already unmasked the timer, and an interrupt in between would overwrite both registers with EL1 values. From then on, kernel code runs only in response to an exception: a system call, a fault, or the timer interrupt. [exceptions.md](exceptions.md) describes that path.
## The boot log
diff --git a/design/en/capabilities.md b/design/en/capabilities.md
index 03ca7e0..d2de923 100644
--- a/design/en/capabilities.md
+++ b/design/en/capabilities.md
@@ -23,7 +23,7 @@ The related code is in the files of the following table.
| `crates/k0-abi/src/lib.rs` | numbers and error codes (the source of truth for the ABI) |
> [!IMPORTANT]
-> The system call ABI changed incompatibly with this model (bootinfo layout version 2). Read the "Known gaps" section before relying on any of this.
+> The system call ABI changed incompatibly with this model (bootinfo version 2, now 3). Read the "Known gaps" section before relying on any of this.
Capability-based isolation covers confidentiality and integrity between tasks. It does not cover availability.
@@ -138,7 +138,7 @@ Running out of slots also stops the boot. A DTB memory region beyond the CPU's p
## The bootinfo page
-Just before the handoff, the kernel writes a description of the root CNode into the bootinfo page, which is mapped read-only for the root task at `bootinfo::VA`. This is layout version 2 (`bootinfo::VERSION`). A root task that sees another version must not proceed.
+Just before the handoff, the kernel writes a description of the root CNode into the bootinfo page, which is mapped read-only for the root task at `bootinfo::VA`. The version is 3 (`bootinfo::VERSION`). The page layout did not change from version 2; the version changed because the root task now receives a boot seed in its entry registers (the seed in `x0..x3`, its description in `x4`; see [boot.md](boot.md)), and the seed is not in this page. A root task that sees another version must not proceed.
The page starts with a header `{version, frame_size, cap_count, cnode_slots}`, followed by `cap_count` descriptors `{kind, base, size, rights}`. The index of a descriptor is its slot number in the root CNode, and every slot at or beyond `cap_count` is empty. A descriptor is filled in by kind as follows:
diff --git a/design/en/dtb.md b/design/en/dtb.md
index 88375df..a967d72 100644
--- a/design/en/dtb.md
+++ b/design/en/dtb.md
@@ -40,7 +40,7 @@ The parsers follow one principle.
The following items apply this principle.
- **Reserved ranges**: they only remove memory. A hostile reservation can at worst shrink the memory handed to user space.
-- **Entropy**: it is only one input among several. The bytes from `/chosen` are mixed with other sources through SHA-256, so hostile entropy cannot weaken the PAC keys. A missing seed does lower their quality, and the kernel says so in the boot log (see [hardening.md](hardening.md)).
+- **Entropy**: it is only one input among several. The bytes from `/chosen` are mixed with other sources through SHA-256, so hostile entropy cannot weaken the PAC keys. A missing seed does lower their quality, and the kernel says so in the boot log (see [hardening.md](hardening.md)). The parser also records where the seed values lie in the blob, so that the kernel can zero them before it enters the root task.
- **Memory nodes**: they grant memory, so they are checked hardest. Every memory region becomes untyped memory that user space can map. A region that claimed to be RAM but covered a device would hand EL0 direct access to that device. After parsing, the kernel compares every memory region with the device ranges it found in the same DTB (see below) and stops the boot on any overlap. It also stops the boot if a RAM region reaches 2^47 or a device range extends beyond the CPU's physical address width (`k0_mm::pa_bits`), because such a region could not be mapped. The CNode bootstrap also rejects memory regions that overlap each other, so no frame can be retyped twice.
- **Device addresses**: they come from the DTB, so they are checked the hardest. A wrong DTB can point the console at another device. The kernel does not map a device page until the descriptor has passed the memory map check, it verifies the hardware identification registers where they exist, its console waits are bounded in time, and a pinned build can fix the expected platform (see "The platform descriptor").
@@ -64,7 +64,7 @@ The header must announce version 17 or later and be backward compatible with ver
| root node | `#address-cells` and `#size-cells`. The defaults are 2 and 1. Only 1 and 2 are supported. |
| top-level `memory` or `memory@...` nodes | `reg`, decoded with the root cell sizes. The node must also have `device_type = "memory"` and an enabled `status`. A `linux,usable-memory` property makes the kernel refuse to boot. |
| children of `/reserved-memory` | `reg`, decoded with the cell sizes of `/reserved-memory` itself. A non-empty `ranges` on `/reserved-memory` is refused. |
-| `/chosen` | `rng-seed` and `kaslr-seed`, concatenated and capped at 72 bytes. The initrd range, if both `linux,initrd-start` and `linux,initrd-end` exist, is added to the reserved ranges (the kernel does not use an initrd). A `linux,usable-memory-range` property makes the kernel refuse to boot. |
+| `/chosen` | `rng-seed` and `kaslr-seed`, concatenated and capped at 72 bytes. The parser also records the position and length of each of these two values (at most two spans) and how many bytes of `rng-seed` it took. A second `/chosen` node is refused. The initrd range, if both `linux,initrd-start` and `linux,initrd-end` exist, is added to the reserved ranges (the kernel does not use an initrd). A `linux,usable-memory-range` property makes the kernel refuse to boot. |
Nodes with these names at other depths are ignored. A node called `memory` inside `/soc` is not RAM. Reserved-memory children that give only a size and no `reg` are dynamic allocations that the firmware has not pinned to an address, so they are ignored too.
@@ -91,7 +91,7 @@ Every violation returns a `BootError`, and the kernel then prints `k0: dtb rejec
- any region whose base plus size overflows 64 bits,
- more regions than the limits allow,
- no memory at all,
-- a memory-limiting property (`linux,usable-memory`, `linux,usable-memory-range`), a non-empty `ranges` on `/reserved-memory`, a half-present or inverted initrd range, or a repeated property that the kernel reads.
+- a memory-limiting property (`linux,usable-memory`, `linux,usable-memory-range`), a non-empty `ranges` on `/reserved-memory`, a half-present or inverted initrd range, a second `/chosen` node (`DuplicateChosen`, also checked by the UEFI loader, which shares the parser), or a repeated property that the kernel reads.
## The platform descriptor
@@ -148,7 +148,7 @@ The loader's own logic (`crates/k0-efi`) has three more fuzzers of the same kind
- Under UEFI the memory map is no longer the DTB's own claim: the loader plans it from the UEFI memory map, and the firmware's own memory nodes are dropped. The gaps below that talk about the DTB's own memory map describe the case without the loader. The firmware that supplies the UEFI memory map is trusted to be wrong at worst, not hostile (see [uefi.md](uefi.md)).
- The memory parser itself does not know the CPU's physical address width. The check against it is in `Platform::validate`, with the limit passed in from `kernel/src/main.rs`. See advisory GHSA-hj3f-38h9-hrpj in [SECURITY.md](../../SECURITY.md) for the status of the earlier memory-map finding. A DTB controlled by an attacker can still stop the boot, which is the intended fail-secure result.
-- The DTB pointer is used before anything can validate it. `map_dtb` in `kernel/src/main.rs` refuses a null or misaligned pointer, an address at or above 2^47 and a range that overlaps the kernel image, and nothing else, because the memory map comes from the blob itself. If a boot loader passes the address of a device, the kernel maps that page as read-only normal memory and reads the first eight bytes. Reading a device register can have side effects, and because the mapping is cacheable the processor may fetch more of the page than those eight bytes. The kernel reads further only if the bytes hold the DTB magic and a valid size, and it never writes through the mapping. `Platform::validate` later checks that the DTB lies inside declared memory, but that memory map is the DTB's own claim. A pinned build could refuse a pointer outside its pinned RAM range before the first read. That check does not exist yet.
+- The DTB pointer is used before anything can validate it. `map_dtb` in `kernel/src/main.rs` refuses a null or misaligned pointer, an address at or above 2^47 and a range that overlaps the kernel image, and nothing else, because the memory map comes from the blob itself. If a boot loader passes the address of a device, the kernel maps that page as read-only normal memory and reads the first eight bytes. Reading a device register can have side effects, and because the mapping is cacheable the processor may fetch more of the page than those eight bytes. The kernel reads further only if the bytes hold the DTB magic and a valid size, and the kernel writes through the mapping exactly once: it zeroes the recorded `rng-seed` and `kaslr-seed` bytes just before it enters the root task, after the DTB has been parsed and validated (see [hardening.md](hardening.md)). `Platform::validate` later checks that the DTB lies inside declared memory, but that memory map is the DTB's own claim. A pinned build could refuse a pointer outside its pinned RAM range before the first read. That check does not exist yet.
- The overlap checks know only the devices the kernel itself found. A DTB that describes some other device range as RAM is not caught, because the kernel has no independent list of devices.
- A wrong DTB can still point the console at a different device that passes the checks. The 16550 family and the SBSA UART have no identification check, so nothing confirms that the hardware is one of them. An image without a console driver does not write to the device, but it does not read its identity either. Pinned mode narrows this but compares DTB-derived values.
- Isolation covers confidentiality and integrity, not availability. A hostile DTB can always stop the boot.
diff --git a/design/en/hardening.md b/design/en/hardening.md
index 38d927e..8b408a1 100644
--- a/design/en/hardening.md
+++ b/design/en/hardening.md
@@ -21,7 +21,7 @@ The following figure groups the protections the way the sections of this note do
`derive_pac_keys` produces the ten 64-bit words that make up the PAC keys: an instruction key pair A and B, a data key pair A and B, and the generic key, two words each. It mixes the following three inputs:
-- **DTB seed**: the bytes of `rng-seed` and `kaslr-seed` from the DTB's `/chosen` node (up to 72 bytes, possibly none). Under UEFI the UEFI loader adds 32 bytes from `EFI_RNG_PROTOCOL` to `rng-seed` when the firmware has it, and these stay readable in the DTB in memory (see [uefi.md](uefi.md)).
+- **DTB seed**: the bytes of `rng-seed` and `kaslr-seed` from the DTB's `/chosen` node (up to 72 bytes, possibly none). Under UEFI the UEFI loader adds 32 bytes from `EFI_RNG_PROTOCOL` to `rng-seed` when the firmware has it, and the kernel wipes these bytes from the DTB in memory just before it enters the root task (see "Wiping the seed from the DTB" below and [uefi.md](uefi.md)).
- **System counter**: `CNTPCT_EL0`.
- **Random number instruction**: one value from the `RNDR` instruction, if the CPU implements FEAT_RNG and the instruction succeeds.
@@ -35,13 +35,35 @@ The derivation is SHA-256 in counter mode. Each 32-byte block hashes the followi
The length prefix keeps DTB bytes from being confused with the words that follow them. Three blocks give the ten words.
-After `hardening::enable` has loaded the keys into system registers, `kernel_main` overwrites the ten words on the boot stack with volatile stores followed by a compiler fence. The boot stack becomes the system call stack later, so no copy of the keys is left there. This does not wipe the seed itself: the `rng-seed` and `kaslr-seed` bytes stay in the DTB, which remains mapped read-only.
+After `hardening::enable` has loaded the keys into system registers, `kernel_main` overwrites the ten words on the boot stack with volatile stores followed by a compiler fence. The boot stack becomes the system call stack later, so no copy of the keys is left there.
Because the inputs are hashed together, a hostile or predictable input cannot cancel out the entropy of another input.
> [!WARNING]
> The result is still no better than the best input. If the DTB provides no seed and the CPU has no `RNDR`, the only input is the counter, and the boot log says `k0: WARNING pac key entropy low (cntpct only)`.
+### Root seed for the root task
+
+The kernel also derives a 32-byte seed for the root task (`k0_boot::derive_root_seed`). It is SHA-256 over its own domain string (`k0-root-task-seed-v1`), the length of the DTB entropy, the DTB entropy itself, the counter and, when the CPU has `RNDR`, four fresh `RNDR` words. The domain string differs from the one of the PAC keys, so the two outputs are independent of each other by domain separation: knowing one does not give the other. They do share the DTB entropy and the counter, so the seed is as good as its inputs and no better.
+
+The seed is not in the bootinfo page. The kernel puts it into the saved context of the root task, so it arrives in the entry registers `x0` to `x3`. Register `x4` is the seed info word: bits 15..0 hold how many `rng-seed` bytes went into the seed, and bit 16 is set when `RNDR` contributed. The layout of the bootinfo page is now version 3 (`bootinfo::VERSION`), and a root task that sees another version stops. The kernel wipes its own copies of the seed from the boot stack. The root task prints only the material, never the seed: `root: boot seed from rng-seed bytes 0x... and rndr` or `... without rndr`.
+
+### Wiping the seed from the DTB
+
+Hashing the seed into keys is not enough if the original bytes stay in memory, because anyone who could later read that memory could recompute the keys. So the kernel wipes them. The FDT parser records where the values of `rng-seed` and `kaslr-seed` lie in the blob (`seed_spans`), and a second `/chosen` node is refused (`DuplicateChosen`), so the recorded places are the only ones.
+
+Right before the kernel enters the root task, after it has finished reading the DTB, `wipe_dtb_seeds` does the following for each recorded span:
+
+1. `k0_mm::wipe_ro_alias` changes the read-only alias entry of the page to read-write in place, with break-before-make.
+2. It writes zeros.
+3. It cleans and invalidates the cache lines, so that a read-back comes from memory.
+4. It switches the entry back to read-only.
+
+The kernel then reads the bytes back through the read-only alias and checks that they are zero. Only then does it wipe its own copy in `BootInfo` and print `k0: dtb seeds wiped B` (`40B` on QEMU virt). If a span cannot be wiped or the read-back is not zero, it prints `k0: WARNING dtb seeds not wiped`. Last, the kernel zeroes the boot stack below its live frames, which clears the leftovers of the hash computations.
+
+> [!NOTE]
+> The wipe is not complete. Copies that the firmware or the UEFI loader keep in their own memory are out of reach, and so is anything in the live frames of the boot stack. The scrubs of stack copies are best effort.
+
## Pointer authentication (PAC)
If the CPU implements address authentication, `hardening::enable` writes the four address keys and, if generic authentication exists, the generic key. It then sets `EnIA`, `EnIB`, `EnDA` and `EnDB` in `SCTLR_EL1`. When the kernel entered at EL2, `boot.S` already set `HCR_EL2.APK` and `HCR_EL2.API`, so key access and PAC instructions at EL1 do not trap to EL2.
@@ -120,14 +142,14 @@ The panic handler masks all interrupts and parks the core. Debug builds print th
## How it is tested
-- `crates/k0-boot/src/entropy/tests.rs` pins the key derivation with known answers computed independently with Python's `hashlib`, and checks that flipping any input bit changes the keys and that the length prefix separates the inputs.
+- `crates/k0-boot/src/entropy/tests.rs` pins the key derivation with known answers computed independently with Python's `hashlib`, and checks that flipping any input bit changes the keys and that the length prefix separates the inputs. The same file tests the root seed, including that it differs from the PAC keys.
- `crates/k0-boot/src/roottask/tests.rs` checks the embedded image against its own hash and the layout rules from the consumer side.
- The default QEMU CPU (`cortex-a72`) has none of PAC, PAN or RNDR. CI therefore boots a second time on QEMU's `max` CPU and requires `rndr=on` and `k0: pac=on bti=present pan=on` in the log, along with every other boot check and self-test, including the PAN-aware user check.
- The root task self-tests confirm that a new task starts with zeroed thread pointer registers, that the root task's values survive the other task's changes, and that an FP/SIMD instruction terminates only the task that issued it.
## Known gaps
-- **PAC unused**: PAC keys are loaded, but no code uses them yet, so return addresses are not protected. The key words are wiped from the boot stack, but the seed bytes stay in the read-only DTB mapping.
+- **PAC unused**: PAC keys are loaded, but no code uses them yet, so return addresses are not protected. The key words are wiped from the boot stack, and the seed bytes in the DTB are wiped before the root task starts. Copies kept by the firmware or the UEFI loader and the live frames of the boot stack are not wiped, and the scrubs of stack copies are best effort.
- **Whole core stops**: `k0_arch::fatal` and the panic handler stop the whole core. They are the intended response to a corrupt kernel structure, but they also mean one such bug is a denial of service for every task.
- **Shared PAC keys**: the same PAC keys serve EL0 and EL1 and every task. Once code starts signing pointers, a task could forge pointers the kernel accepts. Per-task or per-level keys are not implemented.
- **BTI**: BTI is not enabled.
diff --git a/design/en/memory.md b/design/en/memory.md
index 0622c81..35a44fa 100644
--- a/design/en/memory.md
+++ b/design/en/memory.md
@@ -125,14 +125,16 @@ If `ID_AA64MMFR2_EL1` reports FEAT_E0PD, `enable_paging` also sets `TCR_EL1.E0PD
## Adding mappings later
-Two functions add read-write ranges to the higher half after boot. Both share one walker and differ in a single flag.
+Two functions add read-write ranges to the higher half after boot. Both share one walker and differ in a single flag. A third function, `wipe_ro_alias`, changes an existing entry and is described after them.
- `map_kernel_window` maps the 2 MiB boot frame window before the root task is loaded. Any existing translation in the range is an error (`Overlap`), identical or not.
- `alias_object` maps one granule for an object created by `RETYPE`, so that the kernel can zero and use it through the alias. If the leaf already holds exactly the same mapping (same physical address, same attributes), the call succeeds. Any different mapping is still `Overlap`.
The identical case exists because aliases are never removed. When a `CAP_REVOKE` or `CAP_DELETE` returns untyped memory and it is retyped again, the alias of the same physical frame is already there. Accepting **only an identical entry** keeps reuse working without letting a retype replace a mapping that points somewhere else. The window mapping does not get this leniency, because a boot window overlapping an existing mapping would be a mistake.
-These calls only turn invalid entries into valid ones. Existing translations never change, so no break-before-make sequence is needed. A store barrier and an instruction barrier make the new entries visible to the table walker before the memory is used.
+These two calls only turn invalid entries into valid ones. Existing translations never change, so no break-before-make sequence is needed. A store barrier and an instruction barrier make the new entries visible to the table walker before the memory is used.
+
+`wipe_ro_alias` is the only place where a read-only alias entry is switched to read-write. The kernel calls it right before it enters the root task, to zero the `rng-seed` and `kaslr-seed` bytes in the DTB (see [boot.md](boot.md)). It switches the entry of the page to read-write in place, with break-before-make, writes zeros, cleans and invalidates the cache lines so that the read-back comes from memory, and switches the entry back to read-only.
## Self-checks at boot
diff --git a/design/en/uefi.md b/design/en/uefi.md
index b2290dd..cd5691c 100644
--- a/design/en/uefi.md
+++ b/design/en/uefi.md
@@ -107,7 +107,7 @@ A malformed descriptor (a start that is not 4 KiB aligned, an address calculatio
## The rewrite
-`crates/k0-efi/src/fdtw.rs` writes the DTB for the kernel. It does not build one from nothing. It reads the firmware DTB with the kernel's own walker and writes it again token by token, so a structure the kernel would refuse is refused here too (more than 8 memory entries, more than 32 reservations, `linux,usable-memory` properties, two `/chosen` nodes). The string block is new. The rewrite **changes only what the following table lists**.
+`crates/k0-efi/src/fdtw.rs` writes the DTB for the kernel. It does not build one from nothing. It reads the firmware DTB with the kernel's own walker and writes it again token by token, so a structure the kernel would refuse is refused here too (more than 8 memory entries, more than 32 reservations, `linux,usable-memory` properties, two `/chosen` nodes, which the kernel's parser reports as `DuplicateChosen` and which the loader's check of the firmware DTB therefore refuses before the rewrite starts). The string block is new. The rewrite **changes only what the following table lists**.
| Target | Action |
| --- | --- |
@@ -183,7 +183,7 @@ The loader has no signature code. Under Secure Boot the firmware verifies the wh
- **Host unit tests**: `crates/k0-efi/src/tests.rs` holds 32 tests. The vectors are measured firmware memory maps. They cover the descriptor rules, overlap, the entry limit, the writer, the rewrite, the verifier, the ACPI reader and the tree synthesis. A fourth fuzzer, `fuzz_acpi_with_mutated_tables`, mutates table images. Campaigns of 2 to 3 million cases passed on 2026-11-12, and it found one real mismatch earlier (the reader accepted a GIC frame alignment that the kernel's discovery refuses), which is fixed by applying the kernel's placement rules in the reader.
- **Three deterministic fuzzers**: `fuzz_plan_with_random_maps`, `fuzz_rewrite_with_mutated_trees` and `fuzz_prepare_end_to_end` in `k0-efi`. They use the same variables as the other fuzzers: `K0_FUZZ_ITERS`, `K0_FUZZ_SEED`, `K0_FUZZ_CASE`. The defaults are 20,000, 20,000 and 5,000 cases. The weekly workflow runs all three at 5 million cases. Campaigns of 5 million cases each passed on 2026-11-12. The planner fuzzer found one real bug earlier (a block at physical address 0 was accepted). It is fixed.
-- **Host test script**: `tools/host-test.sh` now runs 250 tests on an ARM host (`k0-abi` 14, `k0-cap` 42, `k0-boot` 76, `k0-efi` 32, and `k0-mm` 43 for each of the two granules) and 164 on an x86-64 host, where the `k0-mm` tests are skipped.
+- **Host test script**: `tools/host-test.sh` now runs 276 tests on an ARM host (`k0-abi` 14, `k0-cap` 42, `k0-boot` 82, `k0-efi` 32, `k0-vault` 13 with Ed25519 and 7 without, and `k0-mm` 43 for each of the two granules) and 190 on other hosts, where the `k0-mm` tests are skipped.
- **PE check**: `tools/pe-check.py .efi` checks the PE form (four sections, none both writable and executable) and the order of the cache and MMU instructions, and prints `pe-check: ok (...)`.
- **Boot tests under EDK2**: `tools/qemu-virt-runner.sh` boots a `.efi` argument through EDK2 firmware. The default machine is `virt,gic-version=3,acpi=off`, so it uses the device tree path. The ACPI rows pass `K0_QEMU_MACHINE=virt,gic-version=3` or `virt,gic-version=2`. `tools/qemu-boot-test.sh` judges a failure from the loader's first line, `k0-loader: start`, so firmware messages do not count. `tools/build-loader.sh ` embeds an already built kernel and prints the path of the `.efi`, which is `.efi`. This way the UEFI rows boot the same kernel binary as the other rows. The usage notes in [USAGE.md](../../USAGE.md) show the commands.
@@ -225,7 +225,7 @@ The loader has no signature code. Under Secure Boot the firmware verifies the wh
5. **Cache flush and MMU switch-off**: QEMU cannot test them. See "The handoff". `tools/pe-check.py` checks presence, not correctness on hardware.
6. **Pinned mode under UEFI**: it is untested. The pin line contains the RAM range, and under UEFI that range depends on the firmware build and the RAM size. A mismatch stops the kernel with nothing on the screen. The reason is in the kernel's in-memory boot log, and the loader prints the address needed to read it: `k0-loader: image at 0x..., dtb at 0x...`.
7. **Boot services memory and devices**: boot services memory is never used, but a device that firmware left running can still write to other memory after `ExitBootServices`. K0 has no IOMMU support.
-8. **Entropy the loader adds**: it stays readable in the device tree in memory for the whole run. With no `EFI_RNG_PROTOCOL` the kernel gets only what the firmware device tree carried, and a tree built from ACPI carries no firmware seed, so it gets nothing then.
+8. **Entropy the loader adds**: the kernel zeroes the `rng-seed` bytes in the device tree right before it enters the root task (see [boot.md](boot.md)), and it prints `k0: dtb seeds wiped B`. Copies that the loader or the firmware keep elsewhere are not wiped. With no `EFI_RNG_PROTOCOL` the kernel gets only what the firmware device tree carried, and a tree built from ACPI carries no firmware seed, so it gets nothing then.
9. **UEFI runtime services**: the kernel never calls them. There is no variable access and no reset or power-off through the firmware, and the runtime regions stay unused.
10. **Device registers typed as reserved**: firmware that describes device registers as `EfiReservedMemoryType` (instead of leaving them out of the map or typing them as MMIO) makes the loader refuse. One malformed descriptor makes it refuse the whole map. Both fail closed.
11. **Paths never exercised**: the paths that place the block again and that free memory on a refusal could not be exercised under QEMU.
diff --git a/design/en/user-address-space.md b/design/en/user-address-space.md
index ecce229..91689f6 100644
--- a/design/en/user-address-space.md
+++ b/design/en/user-address-space.md
@@ -183,6 +183,7 @@ When the CPU has FEAT_PAN, the kernel runs with PAN set, so any EL1 access throu
## Known gaps
- **Availability**: isolation does not cover availability. The kernel no longer halts when every task is blocked, and the registry and the kernel page tables can no longer be used up by a task (see [memory.md](memory.md) and [SECURITY.md](../../SECURITY.md)). A task that waits without a timeout can still wait forever, and there is no priority and no CPU budget. A task that holds untyped memory can create many address spaces and tasks and dilute the share of the others.
+- **No data segment in confined tasks**: a confined task maps only the image text and read-only data, so it has no writable static data. The key vault relies on this rule: the vault runs in an address space of its own, and its key lives on its own stack and in frames it was given (see [vault.md](vault.md)).
- **New executable code**: no new executable code can be loaded after boot, by design (per-frame W^X). A confined task can only run code from the root task image.
- **Hardware ASIDs**: there are no hardware ASIDs, so every `TTBR0` switch and every unmap flushes the whole TLB. This costs performance, not safety.
- **Kernel alias**: every frame mapped into user space is also mapped read-write in the kernel alias, because the kernel zeroed it there during retype.
diff --git a/design/en/vault.md b/design/en/vault.md
new file mode 100644
index 0000000..fda9683
--- /dev/null
+++ b/design/en/vault.md
@@ -0,0 +1,143 @@
+# Signing oracle (key vault)
+
+
+
+English | [한국어](../kr/vault_KR.md)
+
+
+
+This note describes the first service on top of K0's isolation core. A **vault** task holds one Ed25519 key. Client tasks get signatures and the public key over IPC, and they never get the key. The code is in `userspace/k0-vault` (the crate), `userspace/root-task/src/oracle.rs` (wiring and self-test) and `crates/k0-boot` (the boot seed).
+
+> [!NOTE]
+> The vault is optional and off by default. The default image has no vault and no crypto code.
+
+## Purpose and scope
+
+The vault shows that the isolation core can keep a secret away from the tasks that use it. It offers a small, fixed service: report status, return the public key, and sign a message of up to 1024 bytes.
+
+The algorithm is Ed25519 (PureEdDSA with SHA-512, as in FIPS 186-5 and RFC 8032). The implementation is the vendored crate `ed25519-dalek` 2.2.0 and has no validation of any kind. The key does not come from an approved random bit generator. 14 crates were added to `vendor/` for it, and half of them are build-time or other-target code that is not compiled into a K0 image.
+
+## Objects and who can map what
+
+
+
+The root task creates the following objects:
+
+- **one endpoint**: the vault receives on it. A client's CNode holds only a send-only, badged copy of it (and a report endpoint in the self-test).
+- **the vault task**: it has its own address space and its own stack. The key lives there.
+- **per caller, a request frame and a response frame**: the request frame is read-write for the caller and read-only for the vault. The response frame is read-write for the vault and read-only for the caller. This is enforced by reduced-rights copies of the frame capabilities.
+
+> [!WARNING]
+> The root task builds all of this, so it is outside the isolation and could read the vault. The statement that holds is "no task other than the root task can map the vault's memory".
+
+## The protocol
+
+A client uses `CALL` (see [ipc.md](ipc.md)). The request registers are the following:
+
+| Register | Content |
+| --- | --- |
+| MR0 | the operation and the algorithm (`proto::word`) |
+| MR1 | the length of the body in the request frame |
+| MR2 | a nonce chosen by the caller |
+
+The reply sets all four registers:
+
+| Register | Content |
+| --- | --- |
+| MR0 | the status |
+| MR1 | the length (for `STATUS`, the vault state) |
+| MR2 | the indicator bits |
+| MR3 | the nonce |
+
+The operations are `STATUS`, `PUBLIC_KEY`, `SIGN` (a message of up to 1024 bytes in the request frame) and, for the admin badge only, `INIT` (the seed and the seed info, 40 bytes, once) and `ZEROIZE`.
+
+**The single fetch**: `server::fetch` fixes the length first, then reads the body once into a private buffer with volatile reads. Only the copy is used, so a caller that changes the frame during the call gains nothing. The response frame starts with the nonce and the length, and `server::publish` writes the nonce last. A client must trust the frame only after an `OK` reply that carries its own nonce.
+
+The state machine is `Vault::handle` in `userspace/k0-vault/src/server.rs`.
+
+## The fixed policy and badges
+
+The policy is fixed at build time and keyed by the endpoint badge. The kernel delivers the badge, and a client cannot forge it (see [ipc.md](ipc.md)). The roles are the following:
+
+| Role | Operations |
+| --- | --- |
+| admin (the root task) | `STATUS`, `INIT`, `ZEROIZE`, not `SIGN` |
+| signer | `STATUS`, `PUBLIC_KEY`, `SIGN` |
+| reader | `STATUS`, `PUBLIC_KEY` |
+
+A call without a badge or with an unknown badge is refused. No operation changes the policy. All signers share the one key, so a signature carries no client identity.
+
+## The provider boundary
+
+`userspace/k0-vault/src/provider.rs` is the only place that touches the crypto crate.
+
+- **Self-test**: at start the vault runs a known-answer test with two RFC 8032 vectors (public key, signature, verification, and rejection of a changed message and of a changed signature).
+- **Key generation and the entropy rule**: the vault refuses to make a key (status `NO_ENTROPY`) unless the boot seed contains at least 32 bytes of `rng-seed` or 256 bits from RNDR. QEMU virt provides a 32-byte `rng-seed`.
+- **Pairwise test**: after key generation the vault checks that its own signature verifies. A failed self-test or a failed pairwise test puts the vault into a failed state that refuses everything but `STATUS`.
+- **Strict verification**: verification uses `verify_strict`.
+- **No key export**: no operation returns the key.
+- **Zeroization**: `ZEROIZE` drops the key (the crate wipes it). The vault then refuses `SIGN` and `PUBLIC_KEY`.
+- **Indicator bits**: every reply carries four bits: the algorithm is in FIPS 186-5, the self-tests passed, at least 32 `rng-seed` bytes went into the key seed, and RNDR went into the key seed.
+
+## The boot seed path
+
+The kernel derives 32 bytes for the root task with SHA-256 under its own domain string from the DTB entropy, the counter and, when the CPU has RNDR, four fresh RNDR words (`k0_boot::derive_root_seed`). It is independent of the PAC keys by domain separation. The seed is as good as its inputs and no better.
+
+The seed is delivered in the root task's entry registers `x0` to `x3`. `x4` holds how many `rng-seed` bytes were used (bits 15 to 0), and bit 16 says that RNDR contributed. It is not in the bootinfo page, and `bootinfo::VERSION` is 3. The root task prints only `root: boot seed from rng-seed bytes 0x... and rndr` or `... without rndr`, never the seed. It then gives the seed to the vault with `INIT`.
+
+**Seed wipe**: the FDT parser records where the `rng-seed` and `kaslr-seed` values are, and a second `/chosen` node is refused (`DuplicateChosen`, also in the UEFI loader's pre-check, which shares the parser). Right before the kernel enters the root task, it zeroes those bytes. `k0_mm::wipe_ro_alias` switches the read-only alias entry of the page to read-write in place (break-before-make), writes zeros, cleans and invalidates the cache lines, and switches it back. The kernel then reads the bytes back, wipes its own copy in `BootInfo`, prints `k0: dtb seeds wiped B` (40B on QEMU virt) and zeroes the boot stack below the live frames. This is the only write the kernel makes through the DTB mapping, and it happens after the DTB was parsed and validated.
+
+> [!NOTE]
+> Copies that the firmware or the UEFI loader keep are not wiped, and neither is anything in the live frames of the boot stack. The scrubs of stack copies (the kernel boot stack, the vault stack after signing) are best effort.
+
+## Features and the fixed image
+
+The `k0-kernel` crate has two features, and features only add:
+
+- `vault`: the service, its protocol, policy and self-test, with no signing algorithm. Every signing request answers `UNSUPPORTED`.
+- `vault-ed25519`: adds Ed25519.
+
+You can build it as follows:
+
+```sh
+$ cargo build -p k0-kernel --features console,vault-ed25519
+```
+
+`crates/k0-boot/build.rs` forwards the feature to the nested build of the root task. The vault's code is part of the root task image, which is checked by SHA-256 at boot like before. Nothing is loaded after boot. With Ed25519 the image has 24 frames of 4 KiB (the limit is 78).
+
+## How it is tested
+
+**Host tests** (`tools/host-test.sh` runs `k0-vault` with and without the algorithm feature). The tests are in `userspace/k0-vault/src/tests.rs`: 13 with Ed25519 and 7 without. The test names are the following:
+
+- always: `badges_map_to_fixed_roles`, `policy_is_enforced_before_anything_else`, `malformed_requests_are_refused_whole`, `a_seed_without_real_entropy_makes_no_key`, `init_happens_once_and_zeroize_is_final`, `fetch_clamps_the_length_and_publish_writes_header_and_body`, and `without_an_algorithm_every_signing_request_is_unsupported` (the last one without the algorithm only).
+- with Ed25519: `the_self_test_passes_and_is_reported`, `signatures_verify_and_the_key_follows_the_seed`, `a_public_key_request_carries_no_body`, `unknown_algorithms_are_unsupported`, `nothing_is_served_after_zeroize`, `a_small_order_public_key_is_refused_even_with_a_matching_signature`, `a_failed_vault_refuses_everything_but_status`.
+
+With the other crates, the host suite has 276 tests on an ARM host and 190 on other hosts (without `k0-mm`).
+
+**Root task self-test** (`test_oracle` in `userspace/root-task/src/oracle.rs`, only in images built with `vault`). It checks the following:
+
+- the self-test is reported, and an unbadged call is refused,
+- a key is made from the boot seed, and a second `INIT` is refused,
+- the admin cannot sign,
+- a signer client gets a signature that verifies, and that does not verify for a changed message or a changed signature,
+- a reader is refused `SIGN`,
+- a client that writes its read-only response frame and a client that reads where the vault sees another caller's request are killed by a fault (two more `k0: task fault` lines, so 8 instead of 6),
+- after `ZEROIZE` signing is refused,
+- a call to a deleted vault ends with `TIMEOUT`, and
+- memory taken back from the vault reads as zero after retype.
+
+The marker is `root: oracle tests pass`. The client tasks run one after another in one client address space, because root CNode slots are scarce. The test shows isolation between the vault and a client, not between clients.
+
+**Boot matrix rows**: `vault`, `vault-max` (RNDR), `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`, and the static row `vault-symbols` (the default image has no vault or crypto code, and the vault image has no writable static from them). The matrix has 61 rows on a Mac with HVF and 51 in CI. Every image now also prints `k0: dtb seeds wiped B` and `root: boot seed from rng-seed bytes ...`.
+
+## Known gaps
+
+> [!NOTE]
+> The implementation is unvalidated, there is no side-channel analysis of the crate on this kernel, and the oracle was only run in QEMU (TCG and HVF).
+
+- **One key**: there is no persistence, no key import or export, no DRBG, no operator input and no post-quantum algorithm yet.
+- **Availability is not protected**: clients share one endpoint and must use timeouts on every call (see [ipc.md](ipc.md)).
+- **The root task is trusted**: it builds the vault and could read it.
+- **No client identity**: all signers share the one key.
+- **Entropy**: the seed is as good as its inputs. The key does not come from an approved random bit generator.
+- **Best-effort wipes**: see the note in the boot seed section.
diff --git a/design/kr/README.md b/design/kr/README.md
index 59528b8..88976b7 100644
--- a/design/kr/README.md
+++ b/design/kr/README.md
@@ -25,5 +25,6 @@
| [exceptions_KR.md](exceptions_KR.md) | 벡터 테이블, 사용자 상태 저장, 시스템 콜 디스패치, 폴트 격리 |
| [scheduling_KR.md](scheduling_KR.md) | TCB와 거기에 묶인 CNode, 주소 공간, 태스크 생성과 정리, 라운드 로빈 스케줄러, 타이머 선점 |
| [ipc_KR.md](ipc_KR.md) | 엔드포인트와 배지, `SEND`, `RECV`, `CALL`, `REPLY_RECV`, 1회성 응답 자격, 엔드포인트가 삭제될 때 대기 중인 태스크의 처리 |
+| [vault_KR.md](vault_KR.md) | 서명 오라클: 볼트 태스크와 프레임, `CALL` 프로토콜과 nonce, 고정된 배지 정책, 프로바이더 경계, 부팅 시드와 지우기, feature, 테스트, 알려진 공백 |
모든 노트는 "**알려진 공백**" 절로 끝납니다. 열려 있는 보안 어드바이저리는 [SECURITY_KR.md](../../SECURITY_KR.md)에 정리되어 있습니다.
diff --git a/design/kr/boot_KR.md b/design/kr/boot_KR.md
index f57de57..771c4e8 100644
--- a/design/kr/boot_KR.md
+++ b/design/kr/boot_KR.md
@@ -104,16 +104,18 @@ $ cargo build -p k0-kernel --offline --no-default-features --features granule-16
| `k0: console drivers [...]` | 플랫폼 기동의 첫 줄이며, 나중에 플랫폼이 거부되더라도 출력됩니다. 이 이미지에 들어 있는 콘솔 드라이버를 알려 줍니다("선택적 콘솔 출력" 참고). |
| `k0: platform ...` | `bring_up_platform`이 DTB에서 콘솔, 인터럽트 컨트롤러, 타이머 인터럽트를 찾아 불변인 플랫폼 기술서 하나를 만듭니다. 디바이스 페이지를 매핑하기 전에 기술서를 메모리 맵과 대조합니다. RAM은 2^47 아래여야 하고, 커널 이미지와 DTB는 선언된 메모리 안에 있어야 하며, 그래뉼 단위로 넓힌 디바이스 구간은 메모리나 예약 구간과 겹치거나 CPU의 물리 주소 폭(`k0_mm::pa_bits`)을 넘으면 안 됩니다. 고정 모드에서는 이어서 이 줄을 기대값과 비교합니다. 그 뒤에야 콘솔을 연결합니다. 이 종류의 콘솔 드라이버가 있는 이미지는 콘솔을 매핑하고 연결하며, 이때 버퍼에 쌓인 로그가 재생됩니다. 드라이버가 없는 이미지는 아무것도 매핑하지 않고 `k0: no console (driver not built in)`을 출력합니다. 플랫폼이 거부되더라도 콘솔만으로 대조를 통과하면(그리고 이미지가 고정 모드가 아니고 드라이버가 있으면) 사유가 보이도록 콘솔을 먼저 연결합니다. 콘솔이 없으면 `k0: no console (...)`이 이유를 알려 줍니다. [dtb_KR.md](dtb_KR.md)를 참고하세요. |
| `k0: root task integrity ok (...)` | 내장 루트 태스크 이미지를 다시 해시하고 빌드 시점에 고정된 해시와 비교합니다. |
-| `k0: entropy ...`, `k0: pac=... bti=... pan=...` | PAC 키를 파생해 적재하고 키 워드를 부트 스택에서 지우며, PAN을 켜고, 카운터·디버그·PMU에 대한 EL0 접근을 끕니다. [hardening_KR.md](hardening_KR.md)를 참고하세요. |
+| `k0: entropy ...`, `k0: pac=... bti=... pan=...` | PAC 키를 파생해 적재하고 키 워드를 부트 스택에서 지웁니다. 루트 태스크에 넘길 32바이트 시드도 여기서 PAC 키와 독립적으로 파생하여 이양까지 보관합니다. PAN을 켜고, 카운터·디버그·PMU에 대한 EL0 접근을 끕니다. [hardening_KR.md](hardening_KR.md)를 참고하세요. |
| `k0: irq on (timer 1s)` | `setup_irq`가 필요한 인터럽트 컨트롤러 페이지만 매핑합니다. GICv3는 리디스트리뷰터 프레임을 하나씩 들여다보며 부트 CPU의 프레임을 찾은 뒤, 그 프레임과 SGI 프레임만 매핑합니다. 드라이버는 GIC 식별 레지스터가 DTB의 설명과 맞는지 확인합니다. EL1 가상 타이머는 플랫폼 기술서의 인터럽트 번호로 설정합니다. IRQ와 SError의 마스크를 해제합니다. |
| `k0: kernel table pool N/40` | 2 MiB 부트 프레임 윈도우를 고르고 매핑한 뒤, 사용 중인 커널 페이지 테이블 수를 출력합니다(예: QEMU virt에서 `16/40`). 40개짜리 정적 풀은 부트 중에만 사용합니다. |
| `k0: root task loaded (entry ...)` | 루트 태스크를 윈도우의 프레임에 복사하고, 윈도우에 루트 TCB를 만들고, 주소 공간을 만듭니다. 커널은 사용자 루트 테이블의 물리 주소를 출력하지 않습니다. 이후 이 주소 공간을 주소 공간 등록부에 올립니다. [user-address-space_KR.md](user-address-space_KR.md)를 참고하세요. |
| `k0: memory + not handed out ()`(일어날 때만), `k0: kernel reserve tables + address space entries = bytes in ranges` | `reserve_kernel_share`가 untyped 케이퍼빌리티가 만들어지기 전에 비어 있는 물리 범위마다 커널 몫을 떼어 냅니다("untyped 메모리에서 커널 몫 떼어 내기" 참고). 자기 몫을 담지 못하는 범위는 넘기지 않으며, 이때 커널은 첫 번째 종류의 줄에 이유를 출력합니다. 두 번째 줄은 한 번 출력됩니다. 예를 들어 512 MiB, 4 KiB 그래뉼의 QEMU virt에서는 `k0: kernel reserve 262 tables + 130130 address space entries = 0x206000 bytes in 3 ranges`입니다. |
| `k0: untyped ...`, `k0: root cnode ready (N caps, N untyped, N image frames, N slots)` | 루트 CNode(윈도우 안의 오브젝트이며 슬롯은 `ROOT_CNODE_SLOTS` = 512개, 로그에도 그렇게 나옵니다)를 채웁니다. 슬롯 1은 루트 TCB, 2는 루트 주소 공간, 3은 콘솔, 4는 루트 CNode 자신이고, 이어서 넘기기로 한 비어 있는 물리 범위마다 untyped 케이퍼빌리티, 루트 태스크 이미지의 매핑된 그래뉼마다 Frame 케이퍼빌리티 하나(text는 R과 X, 읽기 전용 데이터는 R, 데이터는 R과 W)가 들어갑니다. 마지막으로 루트 태스크를 다른 태스크와 똑같이 자신의 CNode와 주소 공간에 묶습니다. 두 케이퍼빌리티의 복사본이 TCB에 들어갑니다. [capabilities_KR.md](capabilities_KR.md)를 참고하세요. |
-| `k0: bootinfo page ready` | 케이퍼빌리티 목록을 읽기 전용 bootinfo 페이지에 기록합니다. 헤더와 슬롯마다 하나의 디스크립터이며, 이미지 Frame마다 VA, 크기, 권한이 들어갑니다. |
+| `k0: bootinfo page ready` | 케이퍼빌리티 목록을 읽기 전용 bootinfo 페이지(레이아웃 버전 3)에 기록합니다. 헤더와 슬롯마다 하나의 디스크립터이며, 이미지 Frame마다 VA, 크기, 권한이 들어갑니다. 이 페이지에는 부트 시드가 들어 있지 않습니다. |
| `k0: user w^x checks pass` | `TTBR0`가 사용자 테이블을 가리키고, identity 매핑은 사라졌으며, 사용자 매핑을 EL0와 EL1 양쪽에서 검사합니다. |
+| `k0: dtb seeds wiped B` | 이제 DTB는 필요 없으므로 커널이 그 안의 `rng-seed`와 `kaslr-seed` 바이트를 0으로 지웁니다(읽기 전용 별칭을 쓰는 동안만 읽기·쓰기로 바꿈). 지운 바이트를 다시 읽어 확인하고, 커널이 가진 자기 사본도 지웁니다. QEMU virt에서는 `40B`입니다. 다시 읽은 값이 0이 아니면 줄은 `k0: WARNING dtb seeds not wiped`가 됩니다. [hardening_KR.md](hardening_KR.md)를 참고하세요. |
| `k0: device pages [...] of 0x1000 bytes` | 커널이 매핑한 채로 두는 모든 디바이스 페이지입니다. 이 줄 뒤에 커널은 더 이상 디바이스를 매핑하지 않습니다. |
-| `k0: entering root task (el0)` | `k0_sched::handoff`가 EL0로 진입합니다. |
+| `k0: entering root task (el0)` | `k0_sched::handoff`가 EL0로 진입합니다. 부트 시드는 루트 태스크의 진입 레지스터 `x0`부터 `x3`으로 전달되고, `x4`는 `rng-seed` 바이트가 몇 개 들어갔는지와 `RNDR`이 들어갔는지를 알립니다. 이 줄 직후에 커널은 살아 있는 프레임 아래의 부트 스택을 0으로 채웁니다. |
+| `root: boot seed from rng-seed bytes 0x... and rndr` 또는 `... without rndr` | 커널이 아니라 루트 태스크가 초기에 출력하는 줄입니다. bootinfo 버전을 확인한 뒤 시드 재료가 어디서 왔는지를 출력하며, 시드 자체는 출력하지 않습니다. |
### 부트 프레임 윈도우 고르기
@@ -141,6 +143,8 @@ $ cargo build -p k0-kernel --offline --no-default-features --features granule-16
### 이양 이후
+루트 태스크는 레지스터 `x0`부터 `x3`에 부트 시드를, `x4`에 시드 정보 워드를 담고 시작합니다. 이 값은 저장된 컨텍스트에 있으며, 루트 태스크가 처음 커널에 들어올 때 그 시점의 자기 레지스터로 덮입니다. 스택에 있던 커널의 시드 사본은 그 전에 0으로 지웠고, 위 표에서 설명한 스택 지우기는 최선의 노력입니다. `kernel_main`의 살아 있는 프레임은 지울 수 없기 때문입니다. [hardening_KR.md](hardening_KR.md)를 참고하세요.
+
`handoff`는 루트 태스크를 실행 중인 태스크로 기록하고, 벡터 코드가 루트 태스크의 저장된 컨텍스트를 가리키게 합니다. 이어서 `enter_user`가 모든 예외를 마스크(`DAIFSet`)하고, 커널 스택을 꼭대기로 되감은 뒤, 이후의 모든 복귀가 사용하는 것과 같은 경로로 EL0에 복귀합니다. **마스크를 먼저 하는 이유**는 이 경로가 `eret` 전에 `ELR_EL1`과 `SPSR_EL1`을 기록하기 때문입니다. 부트 경로는 이미 타이머를 언마스크했으므로, 그 사이에 인터럽트가 들어오면 두 레지스터가 EL1 값으로 덮입니다. 이때부터 커널 코드는 예외에 대한 응답으로만 실행됩니다. 시스템 콜, 폴트, 타이머 인터럽트가 그 예외입니다. 이 경로는 [exceptions_KR.md](exceptions_KR.md)에서 설명합니다.
## 부트 로그
diff --git a/design/kr/capabilities_KR.md b/design/kr/capabilities_KR.md
index 283593c..a6bdd90 100644
--- a/design/kr/capabilities_KR.md
+++ b/design/kr/capabilities_KR.md
@@ -23,7 +23,7 @@
| `crates/k0-abi/src/lib.rs` | 번호와 에러 코드(ABI의 기준) |
> [!IMPORTANT]
-> 이 모델과 함께 시스템 콜 ABI가 호환되지 않게 바뀌었습니다(bootinfo 레이아웃 버전 2). 이 내용에 의존하기 전에 "알려진 공백" 절을 먼저 읽어 주세요.
+> 이 모델과 함께 시스템 콜 ABI가 호환되지 않게 바뀌었습니다(bootinfo 버전 2, 현재 3). 이 내용에 의존하기 전에 "알려진 공백" 절을 먼저 읽어 주세요.
케이퍼빌리티 기반 격리가 다루는 것은 태스크 간 기밀성과 무결성입니다. 가용성은 포함하지 않습니다.
@@ -138,7 +138,7 @@ untyped 케이퍼빌리티는 디바이스 트리가 보고한 RAM의 모든 바
## bootinfo 페이지
-이양 직전에 커널은 루트 CNode의 설명을 bootinfo 페이지에 기록합니다. 이 페이지는 루트 태스크에 읽기 전용으로 `bootinfo::VA`에 매핑됩니다. 레이아웃 버전은 2입니다(`bootinfo::VERSION`). 다른 버전이면 루트 태스크는 진행하면 안 됩니다.
+이양 직전에 커널은 루트 CNode의 설명을 bootinfo 페이지에 기록합니다. 이 페이지는 루트 태스크에 읽기 전용으로 `bootinfo::VA`에 매핑됩니다. 버전은 3입니다(`bootinfo::VERSION`). 페이지 레이아웃은 버전 2와 같습니다. 버전이 바뀐 이유는 루트 태스크가 이제 진입 레지스터로 부트 시드를 받기 때문이며(시드는 `x0..x3`, 그 설명은 `x4`)(자세한 내용은 [boot_KR.md](boot_KR.md) 참고), 시드는 이 페이지에 없습니다. 다른 버전이면 루트 태스크는 진행하면 안 됩니다.
페이지는 헤더 `{version, frame_size, cap_count, cnode_slots}`로 시작하고, 그 뒤에 `cap_count`개의 디스크립터 `{kind, base, size, rights}`가 이어집니다. 디스크립터의 인덱스가 곧 루트 CNode의 슬롯 번호이며, `cap_count` 이상의 슬롯은 전부 비어 있습니다. 디스크립터는 종류에 따라 다음과 같이 채워집니다.
diff --git a/design/kr/dtb_KR.md b/design/kr/dtb_KR.md
index 745222d..16fb372 100644
--- a/design/kr/dtb_KR.md
+++ b/design/kr/dtb_KR.md
@@ -40,7 +40,7 @@ UEFI에는 구체적인 사례가 있습니다. EDK2를 사용하는 QEMU에서
다음 항목은 이 원칙을 적용한 결과입니다.
- **예약 구간**: 메모리를 제거할 뿐입니다. 적대적인 예약이 할 수 있는 일은 사용자 공간에 넘기는 메모리를 줄이는 것이 최대입니다.
-- **엔트로피**: 여러 입력 중 하나일 뿐입니다. `/chosen`의 바이트는 SHA-256을 통해 다른 소스와 섞이므로, 적대적인 엔트로피로 PAC 키를 약화할 수 없습니다. 시드가 없으면 키의 품질이 낮아지며, 커널은 부팅 로그에 이를 알립니다([hardening_KR.md](hardening_KR.md) 참고).
+- **엔트로피**: 여러 입력 중 하나일 뿐입니다. `/chosen`의 바이트는 SHA-256을 통해 다른 소스와 섞이므로, 적대적인 엔트로피로 PAC 키를 약화할 수 없습니다. 시드가 없으면 키의 품질이 낮아지며, 커널은 부팅 로그에 이를 알립니다([hardening_KR.md](hardening_KR.md) 참고). 파서는 시드 값이 블롭 안의 어디에 있는지도 기록하여, 커널이 루트 태스크에 진입하기 전에 그 값을 0으로 지울 수 있게 합니다.
- **메모리 노드**: 메모리를 부여하므로 가장 엄격하게 검사합니다. 모든 메모리 리전은 사용자 공간이 매핑할 수 있는 untyped 메모리가 됩니다. RAM이라고 주장하지만 실제로는 디바이스를 덮는 리전은 EL0에 그 디바이스 직접 접근을 넘기게 됩니다. 파싱 후 커널은 모든 메모리 리전을 같은 DTB에서 찾은 디바이스 구간(뒤의 "플랫폼 기술서" 절 참고)과 비교하고, 겹치면 부팅을 중단합니다. RAM 리전이 2^47에 닿거나 디바이스 구간이 CPU의 물리 주소 폭(`k0_mm::pa_bits`)을 넘어서도 부팅을 중단합니다. 그런 구간은 매핑할 수 없기 때문입니다. CNode bootstrap도 서로 겹치는 메모리 리전을 거부하므로 어떤 프레임도 두 번 retype될 수 없습니다.
- **디바이스 주소**: DTB에서 오므로 가장 엄격하게 검사합니다. 잘못된 DTB는 콘솔을 다른 디바이스로 향하게 할 수 있습니다. 커널은 기술서가 메모리 맵 대조를 통과하기 전에는 디바이스 페이지를 매핑하지 않고, 하드웨어 식별 레지스터가 있는 곳에서는 이를 확인하며, 콘솔 대기에 시간 상한을 두고, 고정 빌드로 기대 플랫폼을 못 박을 수 있습니다("플랫폼 기술서" 참고).
@@ -64,7 +64,7 @@ MMU가 켜진 상태에서 커널이 블롭을 읽으려면 먼저 매핑해야
| 루트 노드 | `#address-cells`와 `#size-cells`. 기본값은 2와 1입니다. 1과 2만 지원합니다. |
| 최상위 `memory` 또는 `memory@...` 노드 | `reg`. 루트의 셀 크기로 디코딩합니다. 노드에 `device_type = "memory"`가 있고 `status`가 사용 가능이어야 합니다. `linux,usable-memory` 프로퍼티가 있으면 커널은 부팅을 거부합니다. |
| `/reserved-memory`의 자식 노드 | `reg`. `/reserved-memory` 자체의 셀 크기로 디코딩합니다. `/reserved-memory`에 비어 있지 않은 `ranges`가 있으면 거부합니다. |
-| `/chosen` | `rng-seed`와 `kaslr-seed`. 이어 붙여 72바이트로 제한합니다. `linux,initrd-start`와 `linux,initrd-end`가 둘 다 있으면 그 구간을 예약 구간에 더합니다(커널은 initrd를 사용하지 않습니다). `linux,usable-memory-range` 프로퍼티가 있으면 커널은 부팅을 거부합니다. |
+| `/chosen` | `rng-seed`와 `kaslr-seed`. 이어 붙여 72바이트로 제한합니다. 파서는 이 두 값 각각의 위치와 길이(최대 두 구간)와 `rng-seed`에서 가져온 바이트 수도 기록합니다. 두 번째 `/chosen` 노드는 거부합니다. `linux,initrd-start`와 `linux,initrd-end`가 둘 다 있으면 그 구간을 예약 구간에 더합니다(커널은 initrd를 사용하지 않습니다). `linux,usable-memory-range` 프로퍼티가 있으면 커널은 부팅을 거부합니다. |
다른 깊이에 있는 같은 이름의 노드는 무시합니다. `/soc` 안의 `memory`라는 노드는 RAM이 아닙니다. 크기만 주고 `reg`가 없는 reserved-memory 자식 노드는 펌웨어가 주소에 고정하지 않은 동적 할당이므로 역시 무시합니다.
@@ -91,7 +91,7 @@ MMU가 켜진 상태에서 커널이 블롭을 읽으려면 먼저 매핑해야
- 베이스에 크기를 더하면 64비트를 넘는 모든 리전
- 제한보다 많은 리전
- 메모리가 전혀 없는 경우
-- 메모리를 제한하는 프로퍼티(`linux,usable-memory`, `linux,usable-memory-range`), `/reserved-memory`의 비어 있지 않은 `ranges`, 한쪽만 있거나 뒤집힌 initrd 구간, 커널이 읽는 프로퍼티의 중복
+- 메모리를 제한하는 프로퍼티(`linux,usable-memory`, `linux,usable-memory-range`), `/reserved-memory`의 비어 있지 않은 `ranges`, 한쪽만 있거나 뒤집힌 initrd 구간, 두 번째 `/chosen` 노드(`DuplicateChosen`, 파서를 공유하는 UEFI 로더의 사전 검사에서도 거부), 커널이 읽는 프로퍼티의 중복
## 플랫폼 기술서
@@ -148,7 +148,7 @@ MMU가 켜진 상태에서 커널이 블롭을 읽으려면 먼저 매핑해야
- UEFI에서는 메모리 맵이 더 이상 DTB 자신의 주장이 아닙니다. 로더가 UEFI 메모리 맵으로 계획하고 펌웨어 자신의 메모리 노드는 버립니다. 다음 공백 중 DTB 자신의 메모리 맵을 말하는 것은 로더가 없는 경우를 설명합니다. UEFI 메모리 맵을 주는 펌웨어는 잘못될 수는 있어도 적대적이지는 않다고 가정합니다([uefi_KR.md](uefi_KR.md) 참고).
- 메모리 파서 자체는 CPU의 물리 주소 폭을 모릅니다. 그에 대한 검사는 `Platform::validate`에 있고 한계값은 `kernel/src/main.rs`에서 넘겨줍니다. 이전 메모리 맵 발견 사항의 상태는 [SECURITY_KR.md](../../SECURITY_KR.md)의 어드바이저리 GHSA-hj3f-38h9-hrpj를 참고하세요. 공격자가 제어하는 DTB는 여전히 부팅을 멈출 수 있으며, 이것이 의도한 fail-secure 결과입니다.
-- DTB 포인터는 무엇으로도 검증할 수 없는 시점에 쓰입니다. `kernel/src/main.rs`의 `map_dtb`는 널이거나 정렬이 맞지 않는 포인터, 2^47 이상인 주소, 커널 이미지와 겹치는 구간만 거부합니다. 메모리 맵이 바로 그 블롭에서 나오기 때문입니다. 부트로더가 디바이스의 주소를 넘기면 커널은 그 페이지를 읽기 전용 일반 메모리로 매핑하고 처음 8바이트를 읽습니다. 디바이스 레지스터는 읽기만 해도 부작용이 있을 수 있고, 매핑이 캐시 가능하므로 프로세서가 그 8바이트보다 페이지를 더 많이 가져올 수 있습니다. 커널은 그 바이트에 DTB 매직과 올바른 크기가 있을 때만 더 읽으며, 이 매핑으로 쓰기는 하지 않습니다. 나중에 `Platform::validate`가 DTB가 선언된 메모리 안에 있는지 검사하지만, 그 메모리 맵은 DTB 자신의 주장입니다. 고정 빌드라면 처음 읽기 전에 고정된 RAM 범위 밖의 포인터를 거부할 수 있습니다. 이 검사는 아직 없습니다.
+- DTB 포인터는 무엇으로도 검증할 수 없는 시점에 쓰입니다. `kernel/src/main.rs`의 `map_dtb`는 널이거나 정렬이 맞지 않는 포인터, 2^47 이상인 주소, 커널 이미지와 겹치는 구간만 거부합니다. 메모리 맵이 바로 그 블롭에서 나오기 때문입니다. 부트로더가 디바이스의 주소를 넘기면 커널은 그 페이지를 읽기 전용 일반 메모리로 매핑하고 처음 8바이트를 읽습니다. 디바이스 레지스터는 읽기만 해도 부작용이 있을 수 있고, 매핑이 캐시 가능하므로 프로세서가 그 8바이트보다 페이지를 더 많이 가져올 수 있습니다. 커널은 그 바이트에 DTB 매직과 올바른 크기가 있을 때만 더 읽으며, 이 매핑으로 쓰기는 정확히 한 번만 합니다. DTB를 파싱하고 검증한 뒤 루트 태스크에 진입하기 직전에, 기록해 둔 `rng-seed`와 `kaslr-seed` 바이트를 0으로 지웁니다([hardening_KR.md](hardening_KR.md) 참고). 나중에 `Platform::validate`가 DTB가 선언된 메모리 안에 있는지 검사하지만, 그 메모리 맵은 DTB 자신의 주장입니다. 고정 빌드라면 처음 읽기 전에 고정된 RAM 범위 밖의 포인터를 거부할 수 있습니다. 이 검사는 아직 없습니다.
- 겹침 검사는 커널이 스스로 찾은 디바이스만 압니다. 다른 디바이스 구간을 RAM으로 기술하는 DTB는 잡아내지 못합니다. 커널에 독립적인 디바이스 목록이 없기 때문입니다.
- 잘못된 DTB가 검사를 통과하는 다른 디바이스로 콘솔을 향하게 할 수 있습니다. 16550 계열과 SBSA UART는 식별 확인이 없어 하드웨어가 그것들인지 확인하는 것이 없습니다. 콘솔 드라이버 없이 빌드한 이미지는 그 디바이스에 쓰지 않지만 정체를 읽지도 않습니다. 고정 모드는 이를 좁히지만 DTB에서 나온 값을 비교합니다.
- 격리는 기밀성과 무결성을 다루며 가용성은 다루지 않습니다. 적대적인 DTB는 언제나 부팅을 멈출 수 있습니다.
diff --git a/design/kr/hardening_KR.md b/design/kr/hardening_KR.md
index 077037f..6daad77 100644
--- a/design/kr/hardening_KR.md
+++ b/design/kr/hardening_KR.md
@@ -21,7 +21,7 @@
`derive_pac_keys`는 PAC 키를 이루는 10개의 64비트 워드를 만듭니다. 명령어 키 쌍 A와 B, 데이터 키 쌍 A와 B, 제네릭 키이며, 각각 두 워드입니다. 다음 세 가지 입력을 섞습니다.
-- **DTB 시드**: DTB의 `/chosen` 노드에 있는 `rng-seed`와 `kaslr-seed`의 바이트입니다(최대 72바이트, 없을 수도 있음). UEFI에서는 펌웨어에 `EFI_RNG_PROTOCOL`이 있으면 UEFI 로더가 거기서 받은 32바이트를 `rng-seed`에 더하며, 이 바이트는 메모리의 DTB에서 계속 읽을 수 있습니다([uefi_KR.md](uefi_KR.md) 참고).
+- **DTB 시드**: DTB의 `/chosen` 노드에 있는 `rng-seed`와 `kaslr-seed`의 바이트입니다(최대 72바이트, 없을 수도 있음). UEFI에서는 펌웨어에 `EFI_RNG_PROTOCOL`이 있으면 UEFI 로더가 거기서 받은 32바이트를 `rng-seed`에 더하며, 커널은 루트 태스크에 진입하기 직전에 메모리의 DTB에서 이 바이트를 지웁니다(아래의 "DTB에서 시드 지우기"와 [uefi_KR.md](uefi_KR.md) 참고).
- **시스템 카운터**: `CNTPCT_EL0`입니다.
- **난수 명령**: CPU가 FEAT_RNG를 구현하고 명령이 성공하면 `RNDR` 난수 명령의 값 하나입니다.
@@ -35,13 +35,35 @@
길이 접두사는 DTB 바이트가 그 뒤에 오는 워드와 혼동되지 않게 합니다. 블록 세 개로 10개의 워드가 나옵니다.
-`hardening::enable`이 키를 시스템 레지스터에 적재하고 나면, `kernel_main`은 부트 스택에 있는 10개의 워드를 volatile 쓰기와 컴파일러 펜스로 덮어씁니다. 부트 스택은 나중에 시스템 콜 스택이 되므로 키의 사본이 남지 않게 하려는 것입니다. 시드 자체는 지우지 않습니다. `rng-seed`와 `kaslr-seed` 바이트는 읽기 전용으로 계속 매핑된 DTB에 남아 있습니다.
+`hardening::enable`이 키를 시스템 레지스터에 적재하고 나면, `kernel_main`은 부트 스택에 있는 10개의 워드를 volatile 쓰기와 컴파일러 펜스로 덮어씁니다. 부트 스택은 나중에 시스템 콜 스택이 되므로 키의 사본이 남지 않게 하려는 것입니다.
입력을 함께 해시하므로 적대적이거나 예측 가능한 입력이 다른 입력의 엔트로피를 상쇄할 수 없습니다.
> [!WARNING]
> 그래도 결과는 가장 좋은 입력보다 나을 수 없습니다. DTB가 시드를 제공하지 않고 CPU에 `RNDR`도 없으면 입력은 카운터뿐이며, 부팅 로그에 `k0: WARNING pac key entropy low (cntpct only)`가 출력됩니다.
+### 루트 태스크용 루트 시드
+
+커널은 루트 태스크에 넘길 32바이트 시드도 파생합니다(`k0_boot::derive_root_seed`). 자체 도메인 문자열(`k0-root-task-seed-v1`), DTB 엔트로피의 길이, DTB 엔트로피 자체, 카운터를 SHA-256으로 해시하고, CPU에 `RNDR`이 있으면 새로 뽑은 `RNDR` 워드 네 개를 더합니다. 도메인 문자열이 PAC 키의 것과 다르므로 두 출력은 도메인 분리로 서로 독립입니다. 하나를 안다고 다른 하나를 알 수는 없습니다. 다만 DTB 엔트로피와 카운터는 공유하므로, 시드는 입력만큼만 좋고 그보다 낫지 않습니다.
+
+시드는 bootinfo 페이지에 없습니다. 커널이 루트 태스크의 저장된 컨텍스트에 넣으므로 진입 레지스터 `x0`부터 `x3`으로 도착합니다. `x4`는 시드 정보 워드입니다. 비트 15..0은 시드에 들어간 `rng-seed` 바이트 수이고, 비트 16은 `RNDR`이 기여했을 때 설정됩니다. bootinfo 페이지의 레이아웃은 이제 버전 3(`bootinfo::VERSION`)이며, 다른 버전을 본 루트 태스크는 멈춥니다. 커널은 부트 스택에 있던 시드 사본을 직접 지웁니다. 루트 태스크는 시드가 아니라 재료만 출력합니다. `root: boot seed from rng-seed bytes 0x... and rndr` 또는 `... without rndr`입니다.
+
+### DTB에서 시드 지우기
+
+시드를 해시해 키로 만든 뒤에도 원본 바이트가 메모리에 남아 있으면, 나중에 그 메모리를 읽을 수 있는 쪽이 키를 다시 계산할 수 있습니다. 그래서 커널이 그 바이트를 지웁니다. FDT 파서는 블롭 안에서 `rng-seed`와 `kaslr-seed`의 값이 놓인 위치를 기록하고(`seed_spans`), 두 번째 `/chosen` 노드는 거부하므로(`DuplicateChosen`) 기록된 위치가 전부입니다.
+
+커널이 DTB 읽기를 모두 마치고 루트 태스크에 진입하기 직전에, `wipe_dtb_seeds`가 기록된 구간마다 다음을 수행합니다.
+
+1. `k0_mm::wipe_ro_alias`가 그 페이지의 읽기 전용 별칭 항목을 break-before-make로 그 자리에서 읽기·쓰기로 바꿉니다.
+2. 0을 씁니다.
+3. 캐시 라인을 clean하고 invalidate하여 다시 읽을 때 값이 메모리에서 오게 합니다.
+4. 항목을 다시 읽기 전용으로 되돌립니다.
+
+그다음 커널은 읽기 전용 별칭으로 그 바이트를 다시 읽어 0인지 확인합니다. 확인된 뒤에야 `BootInfo`에 있는 자기 사본을 지우고 `k0: dtb seeds wiped B`를 출력합니다(QEMU virt에서는 `40B`). 구간을 지우지 못했거나 다시 읽은 값이 0이 아니면 `k0: WARNING dtb seeds not wiped`를 출력합니다. 마지막으로 커널은 살아 있는 프레임 아래의 부트 스택을 0으로 채워, 해시 계산이 남긴 찌꺼기를 지웁니다.
+
+> [!NOTE]
+> 이 삭제는 완전하지 않습니다. 펌웨어나 UEFI 로더가 자기 메모리에 가진 사본에는 닿을 수 없고, 부트 스택의 살아 있는 프레임에 있는 것도 지우지 못합니다. 스택 사본을 지우는 일은 최선의 노력입니다.
+
## 포인터 인증(PAC)
CPU가 주소 인증을 구현하면 `hardening::enable`이 네 개의 주소 키를 기록하고, 제네릭 인증이 있으면 제네릭 키도 기록합니다. 그다음 `SCTLR_EL1`에서 `EnIA`, `EnIB`, `EnDA`, `EnDB`를 설정합니다. 커널이 EL2에서 진입했다면 `boot.S`가 이미 `HCR_EL2.APK`와 `HCR_EL2.API`를 설정했으므로, EL1의 키 접근과 PAC 명령이 EL2로 트랩되지 않습니다.
@@ -120,14 +142,14 @@ EL0 스레드 포인터 레지스터 `TPIDR_EL0`와 `TPIDRRO_EL0`는 각 태스
## 테스트 방법
-- `crates/k0-boot/src/entropy/tests.rs`는 Python의 `hashlib`로 독립적으로 계산한 기지 답으로 키 파생을 고정하고, 입력 비트를 하나라도 뒤집으면 키가 바뀌는지, 길이 접두사가 입력을 구분하는지 검사합니다.
+- `crates/k0-boot/src/entropy/tests.rs`는 Python의 `hashlib`로 독립적으로 계산한 기지 답으로 키 파생을 고정하고, 입력 비트를 하나라도 뒤집으면 키가 바뀌는지, 길이 접두사가 입력을 구분하는지 검사합니다. 같은 파일이 루트 시드도 검사하며, 그것이 PAC 키와 다르다는 점도 포함합니다.
- `crates/k0-boot/src/roottask/tests.rs`는 내장된 이미지를 자체 해시와 대조하고, 소비하는 쪽에서 본 레이아웃 규칙을 검사합니다.
- 기본 QEMU CPU(`cortex-a72`)에는 PAC, PAN, RNDR이 모두 없습니다. 그래서 CI는 QEMU의 `max` CPU로 한 번 더 부팅하고, 로그에 `rndr=on`과 `k0: pac=on bti=present pan=on`이 있어야 하며, PAN을 인식하는 사용자 검사를 포함한 다른 모든 부팅 검사와 자가 테스트도 통과해야 합니다.
- 루트 태스크 자가 테스트는 새 태스크가 0으로 채워진 스레드 포인터 레지스터로 시작하는지, 루트 태스크의 값이 다른 태스크의 변경에도 유지되는지, FP/SIMD 명령이 그것을 실행한 태스크만 종료시키는지 확인합니다.
## 알려진 공백
-- **PAC 미사용**: PAC 키는 로드되지만 아직 이를 사용하는 코드가 없으므로 복귀 주소는 보호되지 않습니다. 키 워드는 부트 스택에서 지우지만 시드 바이트는 읽기 전용 DTB 매핑에 남습니다.
+- **PAC 미사용**: PAC 키는 로드되지만 아직 이를 사용하는 코드가 없으므로 복귀 주소는 보호되지 않습니다. 키 워드는 부트 스택에서 지우고, DTB의 시드 바이트는 루트 태스크가 시작되기 전에 지웁니다. 펌웨어나 UEFI 로더가 가진 사본과 부트 스택의 살아 있는 프레임은 지우지 못하며, 스택 사본을 지우는 일은 최선의 노력입니다.
- **코어 전체 정지**: `k0_arch::fatal`과 패닉 핸들러는 코어 전체를 정지시킵니다. 손상된 커널 구조에 대한 의도한 대응이지만, 그런 버그 하나가 모든 태스크에 대한 서비스 거부가 된다는 뜻이기도 합니다.
- **공용 PAC 키**: 같은 PAC 키가 EL0와 EL1, 그리고 모든 태스크에 쓰입니다. 코드가 포인터를 서명하기 시작하면 태스크가 커널이 받아들이는 포인터를 위조할 수 있습니다. 태스크별 또는 레벨별 키는 구현되어 있지 않습니다.
- **BTI**: BTI는 활성화되어 있지 않습니다.
diff --git a/design/kr/memory_KR.md b/design/kr/memory_KR.md
index 0fb18ac..4d8953f 100644
--- a/design/kr/memory_KR.md
+++ b/design/kr/memory_KR.md
@@ -125,14 +125,16 @@ DTB는 헤더를 검사한 뒤에야 별칭으로 읽기 전용 매핑되고,
## 이후의 매핑 추가
-함수 두 개가 부팅 이후 higher-half에 읽기·쓰기 범위를 추가합니다. 둘은 워커를 공유하고 플래그 하나만 다릅니다.
+함수 두 개가 부팅 이후 higher-half에 읽기·쓰기 범위를 추가합니다. 둘은 워커를 공유하고 플래그 하나만 다릅니다. 세 번째 함수 `wipe_ro_alias`는 기존 엔트리를 바꾸며, 두 함수 다음에 설명합니다.
- `map_kernel_window`는 루트 태스크를 적재하기 전에 2 MiB 부트 프레임 윈도우를 매핑합니다. 범위 안에 기존 변환이 있으면 같든 다르든 오류(`Overlap`)입니다.
- `alias_object`는 `RETYPE`으로 만든 오브젝트의 그래뉼 하나를 매핑합니다. 커널이 별칭을 통해 이를 0으로 채우고 사용할 수 있게 하기 위해서입니다. 리프에 이미 완전히 같은 매핑(같은 물리 주소, 같은 속성)이 있으면 성공합니다. 다른 매핑이 있으면 여전히 `Overlap`입니다.
같은 매핑을 받아 주는 이유는 별칭을 제거하지 않기 때문입니다. `CAP_REVOKE`나 `CAP_DELETE`가 untyped 메모리를 돌려주고 그것을 다시 retype하면, 같은 물리 프레임의 별칭이 이미 있습니다. **완전히 같은 엔트리만** 받으면 다른 곳을 가리키는 매핑을 retype이 덮어쓰게 하지 않으면서 재사용이 동작합니다. 윈도우 매핑에는 이 관대함을 주지 않습니다. 부트 윈도우가 기존 매핑과 겹치면 실수이기 때문입니다.
-이 호출들은 유효하지 않은 엔트리를 유효하게 바꾸기만 합니다. 기존 변환은 바뀌지 않으므로 break-before-make 시퀀스가 필요 없습니다. 스토어 배리어와 명령 배리어가 메모리를 사용하기 전에 새 엔트리를 테이블 워커에게 보이게 합니다.
+이 두 호출은 유효하지 않은 엔트리를 유효하게 바꾸기만 합니다. 기존 변환은 바뀌지 않으므로 break-before-make 시퀀스가 필요 없습니다. 스토어 배리어와 명령 배리어가 메모리를 사용하기 전에 새 엔트리를 테이블 워커에게 보이게 합니다.
+
+`wipe_ro_alias`는 읽기 전용 별칭 엔트리를 읽기·쓰기로 바꾸는 유일한 곳입니다. 커널은 루트 태스크에 진입하기 직전에 이 함수를 호출해 DTB의 `rng-seed`와 `kaslr-seed` 바이트를 0으로 채웁니다(자세한 내용은 [boot_KR.md](boot_KR.md) 참고). 해당 페이지의 엔트리를 break-before-make로 제자리에서 읽기·쓰기로 바꾸고, 0을 쓰고, 읽어 올 값이 메모리에서 오도록 캐시 라인을 정리 및 무효화한 다음, 엔트리를 다시 읽기 전용으로 되돌립니다.
## 부팅 시 자가 검사
diff --git a/design/kr/uefi_KR.md b/design/kr/uefi_KR.md
index badde47..f7d606f 100644
--- a/design/kr/uefi_KR.md
+++ b/design/kr/uefi_KR.md
@@ -107,7 +107,7 @@ k0-loader: exiting boot services
## 재작성
-`crates/k0-efi/src/fdtw.rs`가 커널용 DTB를 작성합니다. 처음부터 만들지는 않습니다. 커널의 순회기로 펌웨어 DTB를 읽고 토큰 단위로 다시 작성하므로, 커널이 거부할 구조는 여기서도 거부됩니다(메모리 항목 8개 초과, 예약 32개 초과, `linux,usable-memory` 프로퍼티, `/chosen` 노드 두 개). 문자열 블록은 새로 만듭니다. 재작성이 **바꾸는 것은 다음 표가 전부**입니다.
+`crates/k0-efi/src/fdtw.rs`가 커널용 DTB를 작성합니다. 처음부터 만들지는 않습니다. 커널의 순회기로 펌웨어 DTB를 읽고 토큰 단위로 다시 작성하므로, 커널이 거부할 구조는 여기서도 거부됩니다(메모리 항목 8개 초과, 예약 32개 초과, `linux,usable-memory` 프로퍼티, `/chosen` 노드 두 개. 마지막 경우를 커널의 파서는 `DuplicateChosen`으로 보고하므로, 로더가 펌웨어 DTB를 검사하는 단계에서 다시 쓰기 전에 거부됩니다). 문자열 블록은 새로 만듭니다. 재작성이 **바꾸는 것은 다음 표가 전부**입니다.
| 대상 | 동작 |
| --- | --- |
@@ -183,7 +183,7 @@ $ K0_LOADER_FEATURES=refuse-halt tools/build-loader.sh
- **호스트 단위 테스트**: `crates/k0-efi/src/tests.rs`에 32개가 있습니다. 벡터는 실제로 측정한 펌웨어 메모리 맵입니다. 디스크립터 규칙, 겹침, 항목 한계, 작성기와 재작성, 검증기, ACPI 리더, 트리 합성을 다룹니다. 네 번째 퍼저 `fuzz_acpi_with_mutated_tables`는 테이블 이미지를 변형합니다. 2026-11-12에 200만에서 300만 케이스의 캠페인이 통과했고, 앞서 실제 불일치 하나를 찾았습니다(리더가 커널의 디스커버리가 거부하는 GIC 프레임 정렬을 받아들였습니다). 커널의 배치 규칙을 리더에 적용해 수정했습니다.
- **결정적 퍼저 셋**: `k0-efi`의 `fuzz_plan_with_random_maps`, `fuzz_rewrite_with_mutated_trees`, `fuzz_prepare_end_to_end`입니다. 다른 퍼저와 같은 변수 `K0_FUZZ_ITERS`, `K0_FUZZ_SEED`, `K0_FUZZ_CASE`를 사용합니다. 기본값은 각각 20,000, 20,000, 5,000개의 케이스입니다. 주간 워크플로가 셋 모두를 500만 케이스로 실행합니다. 2026-11-12에 각각 500만 케이스의 캠페인이 통과했습니다. 계획 퍼저는 앞서 실제 버그 하나를 찾았습니다(물리 주소 0의 블록이 받아들여졌습니다). 수정되었습니다.
-- **호스트 테스트 스크립트**: `tools/host-test.sh`는 이제 ARM 호스트에서 250개(`k0-abi` 14, `k0-cap` 42, `k0-boot` 76, `k0-efi` 32, 두 그래뉼 각각에 `k0-mm` 43)를, `k0-mm` 테스트를 건너뛰는 x86-64 호스트에서 164개를 실행합니다.
+- **호스트 테스트 스크립트**: `tools/host-test.sh`는 이제 ARM 호스트에서 276개(`k0-abi` 14, `k0-cap` 42, `k0-boot` 82, `k0-efi` 32, Ed25519 포함 13개와 제외 7개의 `k0-vault`, 두 그래뉼 각각에 `k0-mm` 43)를, `k0-mm` 테스트를 건너뛰는 그 밖의 호스트에서 190개를 실행합니다.
- **PE 검사**: `tools/pe-check.py .efi`는 PE 형태(섹션 4개, 쓰기와 실행이 함께 가능한 섹션 없음)와 캐시 및 MMU 명령의 순서를 검사하고 `pe-check: ok (...)`를 출력합니다.
- **EDK2 부팅 테스트**: `tools/qemu-virt-runner.sh`는 `.efi` 인자를 EDK2 펌웨어로 부팅합니다. 기본 머신은 `virt,gic-version=3,acpi=off`이므로 디바이스 트리 경로입니다. ACPI 행은 `K0_QEMU_MACHINE=virt,gic-version=3` 또는 `virt,gic-version=2`를 넘깁니다. `tools/qemu-boot-test.sh`는 로더의 첫 줄 `k0-loader: start`부터 실패를 판정하므로 펌웨어 메시지는 세지 않습니다. `tools/build-loader.sh <커널 ELF>`는 이미 빌드된 커널을 내장하고 `.efi`의 경로(`<커널 ELF>.efi`)를 출력합니다. 그래서 UEFI 행도 다른 행과 같은 커널 바이너리를 부팅합니다. 명령은 [USAGE_KR.md](../../USAGE_KR.md)에 있습니다.
@@ -225,7 +225,7 @@ $ K0_LOADER_FEATURES=refuse-halt tools/build-loader.sh
5. **캐시 비우기와 MMU 끄기**: QEMU로 테스트할 수 없습니다. "넘기기"를 참고하세요. `tools/pe-check.py`는 존재를 검사할 뿐 하드웨어에서의 정확성을 검사하지 않습니다.
6. **UEFI에서의 고정 모드**: 테스트하지 않았습니다. 고정 줄에는 RAM 범위가 들어 있고, UEFI에서 이 범위는 펌웨어 빌드와 RAM 크기에 따라 달라집니다. 불일치하면 커널이 화면에 아무것도 남기지 않고 멈춥니다. 사유는 커널의 메모리 내 부트 로그에 있으며, 읽는 데 필요한 주소를 로더가 출력합니다. `k0-loader: image at 0x..., dtb at 0x...`입니다.
7. **부트 서비스 메모리와 디바이스**: 부트 서비스 메모리는 사용하지 않지만, 펌웨어가 켜 둔 디바이스가 `ExitBootServices` 뒤에 다른 메모리에 쓰는 것은 막지 못합니다. K0에는 IOMMU 지원이 없습니다.
-8. **로더가 더한 엔트로피**: 실행 내내 메모리의 디바이스 트리에서 읽을 수 있습니다. `EFI_RNG_PROTOCOL`이 없으면 커널은 펌웨어 디바이스 트리가 담고 온 것만 받는데, ACPI로 만든 트리에는 펌웨어 시드가 없으므로 그때는 아무것도 받지 못합니다.
+8. **로더가 더한 엔트로피**: 커널이 루트 태스크에 진입하기 직전에 디바이스 트리의 `rng-seed` 바이트를 0으로 채우고 `k0: dtb seeds wiped B`를 출력합니다(자세한 내용은 [boot_KR.md](boot_KR.md) 참고). 로더나 펌웨어가 다른 곳에 보관하는 사본은 지우지 않습니다. `EFI_RNG_PROTOCOL`이 없으면 커널은 펌웨어 디바이스 트리가 담고 온 것만 받는데, ACPI로 만든 트리에는 펌웨어 시드가 없으므로 그때는 아무것도 받지 못합니다.
9. **UEFI 런타임 서비스**: 커널은 호출하지 않습니다. 변수 접근도, 펌웨어를 통한 리셋이나 전원 끄기도 없고, 런타임 영역은 사용되지 않은 채 남습니다.
10. **예약 타입으로 기술된 디바이스 레지스터**: 펌웨어가 디바이스 레지스터를 `EfiReservedMemoryType`으로 기술하면(맵에서 제외하거나 MMIO로 표시하는 대신) 로더가 거부합니다. 형식이 잘못된 디스크립터 하나도 맵 전체의 거부를 부릅니다. 둘 다 닫힌 채로 실패합니다.
11. **실행해 보지 못한 경로**: 블록을 다시 배치하는 경로와 거부할 때 메모리를 푸는 경로는 QEMU에서 실행해 볼 수 없었습니다.
diff --git a/design/kr/user-address-space_KR.md b/design/kr/user-address-space_KR.md
index d36946f..f0bfa2e 100644
--- a/design/kr/user-address-space_KR.md
+++ b/design/kr/user-address-space_KR.md
@@ -183,6 +183,7 @@ CPU에 FEAT_PAN이 있으면 커널은 PAN을 설정한 채 실행되므로, 사
## 알려진 공백
- **가용성**: 격리는 가용성을 포함하지 않습니다. 모든 태스크가 막혀도 커널은 더 이상 멈추지 않으며, 등록부와 커널 페이지 테이블은 태스크가 소진시킬 수 없게 되었습니다([memory_KR.md](memory_KR.md)와 [SECURITY_KR.md](../../SECURITY_KR.md) 참고). 타임아웃 없이 기다리는 태스크는 여전히 영원히 기다릴 수 있고, 우선순위와 CPU 예산은 없습니다. untyped 메모리를 가진 태스크는 주소 공간과 태스크를 많이 만들어 다른 태스크의 몫을 희석시킬 수 있습니다.
+- **격리 태스크에 데이터 세그먼트 없음**: 격리된 태스크는 이미지 text와 읽기 전용 데이터만 매핑하므로 쓰기 가능한 정적 데이터가 없습니다. 키 볼트는 이 규칙에 의존합니다. 볼트는 자기 주소 공간에서 실행되고, 키는 자기 스택과 받은 프레임에 있습니다(자세한 내용은 [vault_KR.md](vault_KR.md) 참고).
- **새 실행 코드**: 설계상(프레임 단위 W^X) 부팅 이후에는 새 실행 코드를 적재할 수 없습니다. 격리된 태스크는 루트 태스크 이미지의 코드만 실행할 수 있습니다.
- **하드웨어 ASID**: 하드웨어 ASID가 없으므로 `TTBR0` 전환과 모든 매핑 해제마다 TLB 전체를 비웁니다. 안전이 아니라 성능의 비용입니다.
- **커널 별칭**: 사용자 공간에 매핑된 모든 프레임은 커널 별칭에도 읽기·쓰기로 매핑되어 있습니다. retype 중에 커널이 그곳에서 프레임을 0으로 채웠기 때문입니다.
diff --git a/design/kr/vault_KR.md b/design/kr/vault_KR.md
new file mode 100644
index 0000000..f533a7f
--- /dev/null
+++ b/design/kr/vault_KR.md
@@ -0,0 +1,143 @@
+# 서명 오라클 (키 볼트)
+
+
+
+[English](../en/vault.md) | 한국어
+
+
+
+이 노트는 K0의 격리 코어 위에 올라가는 첫 번째 서비스를 설명합니다. **볼트** 태스크가 Ed25519 키 하나를 보관합니다. 클라이언트 태스크는 IPC로 서명과 공개 키를 받고, 키는 받지 못합니다. 코드는 `userspace/k0-vault`(크레이트), `userspace/root-task/src/oracle.rs`(연결과 자가 테스트), `crates/k0-boot`(부팅 시드)에 있습니다.
+
+> [!NOTE]
+> 볼트는 선택 사항이며 기본값은 꺼짐입니다. 기본 이미지에는 볼트도 암호 코드도 없습니다.
+
+## 목적과 범위
+
+볼트는 격리 코어가 비밀을 그것을 쓰는 태스크로부터 떼어 놓을 수 있음을 보여 줍니다. 서비스는 작고 고정되어 있습니다. 상태를 알려 주고, 공개 키를 돌려주고, 1024바이트까지의 메시지에 서명합니다.
+
+알고리즘은 Ed25519입니다(SHA-512를 쓰는 PureEdDSA, FIPS 186-5와 RFC 8032). 구현은 vendor에 넣은 크레이트 `ed25519-dalek` 2.2.0이며 어떤 종류의 검증도 받지 않았습니다. 키는 승인된 난수 비트 생성기에서 나오지 않습니다. 이를 위해 `vendor/`에 크레이트 14개를 추가했고, 그중 절반은 빌드 시점 또는 다른 타겟용 코드라서 K0 이미지에 컴파일되어 들어가지 않습니다.
+
+## 오브젝트와 누가 무엇을 매핑할 수 있는가
+
+
+
+루트 태스크는 다음 오브젝트를 만듭니다.
+
+- **엔드포인트 하나**: 볼트가 여기서 받습니다. 클라이언트의 CNode에는 송신 전용 배지 복사본만 있습니다(자가 테스트에서는 보고용 엔드포인트도 있습니다).
+- **볼트 태스크**: 자체 주소 공간과 자체 스택을 가집니다. 키는 여기에 있습니다.
+- **호출자마다 요청 프레임과 응답 프레임**: 요청 프레임은 호출자가 읽기·쓰기, 볼트가 읽기 전용입니다. 응답 프레임은 볼트가 읽기·쓰기, 호출자가 읽기 전용입니다. 프레임 케이퍼빌리티의 권한을 줄인 복사본으로 강제합니다.
+
+> [!WARNING]
+> 루트 태스크가 이 모든 것을 만들므로 격리의 바깥에 있으며 볼트를 읽을 수 있습니다. 성립하는 문장은 "루트 태스크 외의 어떤 태스크도 볼트의 메모리를 매핑할 수 없다"입니다.
+
+## 프로토콜
+
+클라이언트는 `CALL`을 사용합니다([ipc_KR.md](ipc_KR.md) 참고). 요청 레지스터는 다음과 같습니다.
+
+| 레지스터 | 내용 |
+| --- | --- |
+| MR0 | 연산과 알고리즘(`proto::word`) |
+| MR1 | 요청 프레임에 있는 본문의 길이 |
+| MR2 | 호출자가 고른 nonce |
+
+응답은 네 레지스터를 모두 설정합니다.
+
+| 레지스터 | 내용 |
+| --- | --- |
+| MR0 | 상태 |
+| MR1 | 길이(`STATUS`에서는 볼트 상태) |
+| MR2 | 지표 비트 |
+| MR3 | nonce |
+
+연산은 `STATUS`, `PUBLIC_KEY`, `SIGN`(요청 프레임에 1024바이트까지의 메시지)이며, admin 배지에만 `INIT`(시드와 시드 정보 40바이트, 한 번)과 `ZEROIZE`가 있습니다.
+
+**단일 가져오기**: `server::fetch`는 길이를 먼저 고정한 뒤 본문을 volatile 읽기로 비공개 버퍼에 한 번만 읽습니다. 사본만 사용하므로 호출 중에 프레임을 바꾸는 호출자는 얻는 것이 없습니다. 응답 프레임은 nonce와 길이로 시작하고, `server::publish`는 nonce를 마지막에 기록합니다. 클라이언트는 자신의 nonce가 담긴 `OK` 응답을 받은 뒤에만 프레임을 믿어야 합니다.
+
+상태 기계는 `userspace/k0-vault/src/server.rs`의 `Vault::handle`입니다.
+
+## 고정된 정책과 배지
+
+정책은 빌드 시점에 고정되며 엔드포인트 배지를 키로 사용합니다. 배지는 커널이 전달하며 클라이언트가 위조할 수 없습니다([ipc_KR.md](ipc_KR.md) 참고). 역할은 다음과 같습니다.
+
+| 역할 | 연산 |
+| --- | --- |
+| admin (루트 태스크) | `STATUS`, `INIT`, `ZEROIZE`, `SIGN`은 불가 |
+| signer | `STATUS`, `PUBLIC_KEY`, `SIGN` |
+| reader | `STATUS`, `PUBLIC_KEY` |
+
+배지가 없거나 알 수 없는 배지의 호출은 거부됩니다. 어떤 연산도 정책을 바꾸지 않습니다. 모든 signer가 키 하나를 공유하므로 서명에는 클라이언트 신원이 담기지 않습니다.
+
+## 프로바이더 경계
+
+`userspace/k0-vault/src/provider.rs`만 암호 크레이트에 닿습니다.
+
+- **자가 테스트**: 시작할 때 RFC 8032 벡터 두 개로 알려진 답 테스트를 합니다(공개 키, 서명, 검증, 바뀐 메시지와 바뀐 서명의 거부).
+- **키 생성과 엔트로피 규칙**: 부팅 시드에 `rng-seed` 32바이트 이상 또는 RNDR 256비트가 없으면 볼트는 키 생성을 거부합니다(상태 `NO_ENTROPY`). QEMU virt는 32바이트 `rng-seed`를 제공합니다.
+- **쌍 일관성 테스트**: 키 생성 뒤에 자신의 서명이 검증되는지 확인합니다. 자가 테스트 실패 또는 쌍 일관성 테스트 실패는 볼트를 `STATUS` 외의 모든 것을 거부하는 실패 상태로 만듭니다.
+- **엄격한 검증**: 검증은 `verify_strict`를 사용합니다.
+- **키 내보내기 없음**: 키를 돌려주는 연산이 없습니다.
+- **제로화**: `ZEROIZE`는 키를 버립니다(크레이트가 지웁니다). 이후 볼트는 `SIGN`과 `PUBLIC_KEY`를 거부합니다.
+- **지표 비트**: 모든 응답에 비트 네 개가 있습니다. 알고리즘이 FIPS 186-5에 있음, 자가 테스트 통과, `rng-seed` 32바이트 이상이 키 시드에 들어감, RNDR이 키 시드에 들어감입니다.
+
+## 부팅 시드 경로
+
+커널은 루트 태스크용 32바이트를 자체 도메인 문자열로 SHA-256에 넣어 만듭니다. 입력은 DTB 엔트로피, 카운터, 그리고 CPU에 RNDR이 있으면 새 RNDR 워드 네 개입니다(`k0_boot::derive_root_seed`). 도메인 분리로 PAC 키와는 서로 독립입니다. 시드는 입력만큼만 좋습니다.
+
+시드는 루트 태스크의 진입 레지스터 `x0`부터 `x3`로 전달됩니다. `x4`는 사용한 `rng-seed` 바이트 수(비트 15부터 0)이고, 비트 16은 RNDR이 기여했음을 뜻합니다. bootinfo 페이지에는 없으며 `bootinfo::VERSION`은 3입니다. 루트 태스크는 `root: boot seed from rng-seed bytes 0x... and rndr` 또는 `... without rndr`만 출력하고 시드는 출력하지 않습니다. 이후 `INIT`으로 시드를 볼트에 줍니다.
+
+**시드 지우기**: FDT 파서는 `rng-seed`와 `kaslr-seed` 값의 위치를 기록하고, 두 번째 `/chosen` 노드는 거부합니다(`DuplicateChosen`, 파서를 공유하는 UEFI 로더의 사전 검사에서도 같습니다). 커널은 루트 태스크에 진입하기 직전에 그 바이트를 0으로 만듭니다. `k0_mm::wipe_ro_alias`가 페이지의 읽기 전용 별칭 항목을 제자리에서 읽기·쓰기로 바꾸고(break-before-make), 0을 쓰고, 캐시 라인을 clean 및 invalidate한 뒤 되돌립니다. 이어서 커널은 그 바이트를 다시 읽어 확인하고, `BootInfo`에 있는 자신의 사본을 지우고, `k0: dtb seeds wiped B`(QEMU virt에서는 40B)를 출력하고, 살아 있는 프레임 아래의 부트 스택을 0으로 만듭니다. 이것이 커널이 DTB 매핑으로 하는 유일한 쓰기이며, DTB를 파싱하고 검증한 뒤에 일어납니다.
+
+> [!NOTE]
+> 펌웨어나 UEFI 로더가 보관하는 사본과 부트 스택의 살아 있는 프레임 안의 값은 지워지지 않습니다. 스택 사본 지우기(커널 부트 스택, 서명 뒤의 볼트 스택)는 최선 노력입니다.
+
+## feature와 고정된 이미지
+
+`k0-kernel` 크레이트에는 feature가 둘 있으며 feature는 더하기만 합니다.
+
+- `vault`: 서비스, 프로토콜, 정책, 자가 테스트이며 서명 알고리즘은 없습니다. 모든 서명 요청에 `UNSUPPORTED`로 답합니다.
+- `vault-ed25519`: Ed25519를 추가합니다.
+
+다음과 같이 빌드할 수 있습니다.
+
+```sh
+$ cargo build -p k0-kernel --features console,vault-ed25519
+```
+
+`crates/k0-boot/build.rs`가 feature를 루트 태스크의 중첩 빌드로 전달합니다. 볼트의 코드는 루트 태스크 이미지의 일부이며 이전처럼 부팅 시 SHA-256으로 검사됩니다. 부팅 뒤에는 아무것도 적재하지 않습니다. Ed25519를 넣으면 이미지는 4 KiB 프레임 24개입니다(한도 78개).
+
+## 테스트 방법
+
+**호스트 테스트**(`tools/host-test.sh`가 알고리즘 feature 유무로 `k0-vault`를 실행합니다). 테스트는 `userspace/k0-vault/src/tests.rs`에 있으며 Ed25519가 있으면 13개, 없으면 7개입니다. 이름은 다음과 같습니다.
+
+- 항상: `badges_map_to_fixed_roles`, `policy_is_enforced_before_anything_else`, `malformed_requests_are_refused_whole`, `a_seed_without_real_entropy_makes_no_key`, `init_happens_once_and_zeroize_is_final`, `fetch_clamps_the_length_and_publish_writes_header_and_body`, 그리고 `without_an_algorithm_every_signing_request_is_unsupported`(마지막 것은 알고리즘이 없을 때만).
+- Ed25519가 있을 때: `the_self_test_passes_and_is_reported`, `signatures_verify_and_the_key_follows_the_seed`, `a_public_key_request_carries_no_body`, `unknown_algorithms_are_unsupported`, `nothing_is_served_after_zeroize`, `a_small_order_public_key_is_refused_even_with_a_matching_signature`, `a_failed_vault_refuses_everything_but_status`.
+
+다른 크레이트와 합치면 호스트 테스트는 ARM 호스트에서 276개, 그 외 호스트에서 190개입니다(`k0-mm` 제외).
+
+**루트 태스크 자가 테스트**(`userspace/root-task/src/oracle.rs`의 `test_oracle`, `vault`로 빌드한 이미지에만 있음). 다음을 검사합니다.
+
+- 자가 테스트가 보고되고, 배지 없는 호출이 거부됩니다.
+- 부팅 시드로 키가 만들어지고, 두 번째 `INIT`은 거부됩니다.
+- admin은 서명할 수 없습니다.
+- signer 클라이언트는 검증되는 서명을 받고, 바뀐 메시지나 바뀐 서명에는 검증이 실패합니다.
+- reader는 `SIGN`을 거부당합니다.
+- 읽기 전용 응답 프레임에 쓰는 클라이언트와, 볼트가 다른 호출자의 요청을 보는 위치를 읽는 클라이언트는 폴트로 종료됩니다(`k0: task fault` 줄이 6개가 아니라 8개).
+- `ZEROIZE` 뒤에는 서명이 거부됩니다.
+- 삭제된 볼트에 대한 호출은 `TIMEOUT`으로 끝납니다.
+- 볼트에서 회수한 메모리는 retype 뒤에 0으로 읽힙니다.
+
+표지는 `root: oracle tests pass`입니다. 클라이언트 태스크는 루트 CNode 슬롯이 부족해 하나의 클라이언트 주소 공간에서 차례로 실행됩니다. 이 테스트는 볼트와 클라이언트 사이의 격리를 보여 주며 클라이언트끼리의 격리는 보여 주지 않습니다.
+
+**부팅 매트릭스 행**: `vault`, `vault-max`(RNDR), `vault-el2`, `vault-16k`, `vault-no-alg`, `hvf-vault`, 그리고 정적 행 `vault-symbols`(기본 이미지에는 볼트나 암호 코드가 없고, 볼트 이미지에는 그 코드에서 온 쓰기 가능한 정적 변수가 없음)입니다. 매트릭스는 HVF가 있는 Mac에서 61행, CI에서 51행입니다. 이제 모든 이미지는 `k0: dtb seeds wiped B`와 `root: boot seed from rng-seed bytes ...`도 출력합니다.
+
+## 알려진 공백
+
+> [!NOTE]
+> 구현은 검증을 받지 않았고, 이 커널에서 크레이트의 부채널 분석은 없으며, 오라클은 QEMU(TCG와 HVF)에서만 실행했습니다.
+
+- **키 하나**: 영속성, 키 가져오기·내보내기, DRBG, 운영자 입력, 양자 내성 알고리즘이 아직 없습니다.
+- **가용성은 보호되지 않습니다**: 클라이언트는 엔드포인트 하나를 공유하며 모든 호출에 타임아웃을 써야 합니다([ipc_KR.md](ipc_KR.md) 참고).
+- **루트 태스크는 신뢰 대상입니다**: 볼트를 만들고 읽을 수 있습니다.
+- **클라이언트 신원 없음**: 모든 signer가 키 하나를 공유합니다.
+- **엔트로피**: 시드는 입력만큼만 좋습니다. 키는 승인된 난수 비트 생성기에서 나오지 않습니다.
+- **최선 노력의 지우기**: 부팅 시드 경로 절의 참고를 보십시오.
diff --git a/kernel/Cargo.toml b/kernel/Cargo.toml
index b2d9b88..ecd4bae 100644
--- a/kernel/Cargo.toml
+++ b/kernel/Cargo.toml
@@ -32,6 +32,11 @@ granule-16k = [
console-pl011 = ["k0-arch/console-pl011"]
console-16550 = ["k0-arch/console-16550"]
console = ["console-pl011", "console-16550"]
+# 루트 태스크 이미지에 키 볼트(서명 오라클)를 넣음. 알고리즘은 따로 더함
+# vault 볼트 서비스와 그 자가 검증(서명 알고리즘 없음)
+# vault-ed25519 위에 Ed25519를 더함
+vault = ["k0-boot/vault"]
+vault-ed25519 = ["vault", "k0-boot/vault-ed25519"]
# 커널 크레이트는 외부(third-party) 의존성 0, 워크스페이스 크레이트만 허용
# 외부가 필요해진 경우: vendored + 해시 고정
diff --git a/kernel/src/main.rs b/kernel/src/main.rs
index f9dc0f0..272136d 100644
--- a/kernel/src/main.rs
+++ b/kernel/src/main.rs
@@ -120,7 +120,7 @@ extern "C" fn kernel_main(dtb_phys: usize) -> ! {
let image = k0_mm::image_range();
let kernel_image = image.start as usize..image.end as usize;
map_dtb(&mut con, dtb_phys);
- let bootinfo = match k0_boot::parse(
+ let mut bootinfo = match k0_boot::parse(
dtb_phys,
kernel_image.clone(),
k0_mm::KERNEL_VA_OFFSET as usize,
@@ -175,6 +175,25 @@ extern "C" fn kernel_main(dtb_phys: usize) -> ! {
let _ = writeln!(con, "k0: WARNING pac key entropy low (counter only)");
}
+ // 루트 태스크에 넘길 시드. PAC 키와 같은 DTB 재료를 쓰지만 도메인이 달라
+ // 서로 독립이고, RNDR이 있으면 여기에만 쓰는 256비트를 따로 뽑아 넣음
+ let mut fresh = [0u64; 4];
+ let mut rndr_full = true;
+ for w in fresh.iter_mut() {
+ match k0_arch::hardening::rndr() {
+ Some(v) => *w = v,
+ None => rndr_full = false,
+ }
+ }
+ let mut root_seed =
+ k0_boot::derive_root_seed(bootinfo.entropy(), &[cntpct, fresh[0], fresh[1], fresh[2], fresh[3]]);
+ let seed_info = (bootinfo.rng_seed_len() as u64 & k0_abi::bootinfo::SEED_RNG_SEED_BYTES)
+ | if rndr_full { k0_abi::bootinfo::SEED_RNDR } else { 0 };
+ for w in fresh.iter_mut() {
+ // SAFETY: w는 이 스택 프레임의 유효한 배열 원소임
+ unsafe { core::ptr::write_volatile(w, 0) };
+ }
+
let hard = k0_arch::hardening::enable(&pac_keys);
// 키는 이제 시스템 레지스터에만 있어야 함. 부트 스택은 이후 시스템 콜
// 스택으로 재사용되므로 사본을 남기지 않음 (volatile이라 소거가 최적화로
@@ -408,6 +427,18 @@ extern "C" fn kernel_main(dtb_phys: usize) -> ! {
// 루트 태스크를 자기 CNode와 주소 공간에 묶음. 다른 태스크와 똑같이 TCB의
// 내장 슬롯에 두 케이퍼빌리티의 복사본을 넣음
let tcb = root.tcb;
+ // 시드는 루트 태스크의 진입 레지스터로 넘김(x0-x3 = 시드, x4 = 재료 정보).
+ // 저장된 컨텍스트의 사본은 루트 태스크가 처음 커널에 들어올 때 그때의
+ // 레지스터로 덮이고, 이 스택의 사본은 여기서 지움
+ for (i, chunk) in root_seed.chunks_exact(8).enumerate() {
+ tcb.ctx.x[i] = u64::from_le_bytes(chunk.try_into().unwrap_or([0; 8]));
+ }
+ tcb.ctx.x[4] = seed_info;
+ for b in root_seed.iter_mut() {
+ // SAFETY: b는 이 스택 프레임의 유효한 배열 원소임
+ unsafe { core::ptr::write_volatile(b, 0) };
+ }
+ core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
let tcb_ptr = core::ptr::from_mut(tcb);
let bound = match (
cnode.slot(k0_cap::boot_slot::CNODE),
@@ -455,8 +486,12 @@ extern "C" fn kernel_main(dtb_phys: usize) -> ! {
check_user_wx(&mut con, segs, &hard);
+ // DTB를 읽는 일이 전부 끝났으므로 거기 남은 시드와 그 사본을 지움
+ wipe_dtb_seeds(&mut con, &mut bootinfo);
+
print_device_pages(&mut con);
let _ = writeln!(con, "k0: entering root task (el0)");
+ scrub_boot_stack();
// SAFETY: 주소 공간 설치와 컨텍스트 준비가 끝난 발산 지점에서의 이양이고,
// tcb_ptr은 부트 윈도우의 루트 TCB 프레임으로 이후 해제되지 않음
unsafe { k0_sched::handoff(&mut *tcb_ptr) }
@@ -469,6 +504,67 @@ struct ImageMap {
len: u64,
}
+/// DTB에 남은 시드 값과 커널이 가진 그 사본을 지우는 함수입니다.
+///
+/// 파서가 기록한 구간(`rng-seed`와 `kaslr-seed`의 값 전체)을 0으로 덮고, 읽기
+/// 전용 별칭으로 다시 읽어 확인한 뒤에만 지웠다고 알립니다. 시드로 PAC 키와
+/// 루트 태스크의 시드를 이미 만든 뒤이므로, 남겨 두면 나중에 그 메모리를 읽는
+/// 쪽이 둘을 다시 계산할 수 있습니다. 구간은 파서가 blob 안이라고 확인한
+/// 것이고 DTB는 선언된 메모리 안에 있다는 검증을 통과한 뒤입니다.
+///
+/// 커널이 닿을 수 없는 사본(펌웨어가 가진 원본, UEFI 로더의 버퍼)은 지우지
+/// 못합니다.
+fn wipe_dtb_seeds(con: &mut EarlyCon, bootinfo: &mut k0_boot::BootInfo) {
+ let base = bootinfo.dtb.start as u64;
+ let mut wiped = 0;
+ let mut clean = true;
+ for &(offset, len) in bootinfo.seed_spans() {
+ let start = base + offset as u64;
+ if k0_mm::wipe_ro_alias(start..start + len as u64).is_err() {
+ clean = false;
+ continue;
+ }
+ // SAFETY: DTB 전체가 읽기 전용 별칭으로 매핑돼 있고 구간은 그 안임
+ let left = unsafe {
+ core::slice::from_raw_parts((start + k0_mm::KERNEL_VA_OFFSET) as *const u8, len)
+ };
+ if left.iter().any(|&b| b != 0) {
+ clean = false;
+ } else {
+ wiped += len;
+ }
+ }
+ bootinfo.wipe_entropy();
+ if clean {
+ let _ = writeln!(con, "k0: dtb seeds wiped {wiped}B");
+ } else {
+ let _ = writeln!(con, "k0: WARNING dtb seeds not wiped");
+ }
+}
+
+/// 부트 스택에서 지금 쓰는 부분 아래를 전부 0으로 덮는 함수입니다.
+///
+/// 시드를 해시하던 함수들의 지역 변수와 해시 상태가 이미 끝난 프레임에
+/// 남아 있을 수 있어서, EL0로 넘어가기 직전에 한꺼번에 지웁니다. 이 스택은
+/// 이후 시스템 콜 스택으로 다시 쓰입니다. 지금 살아 있는 프레임(kernel_main과
+/// 이 함수)은 지우지 못하므로 최선의 노력입니다.
+#[inline(never)]
+fn scrub_boot_stack() {
+ let sp: u64;
+ // SAFETY: 스택 포인터를 읽기만 함
+ unsafe { core::arch::asm!("mov {}, sp", out(reg) sp, options(nomem, nostack)) };
+ let bottom = &raw const __boot_stack_bottom as u64;
+ // 이 함수 자신의 프레임과 벡터가 쓸 자리를 남김
+ let top = sp.saturating_sub(256) & !7;
+ let mut p = bottom;
+ while p < top {
+ // SAFETY: [bottom, top)은 부트 스택에서 현재 프레임보다 아래의 쓰지
+ // 않는 구간이고 8바이트 정렬임
+ unsafe { core::ptr::write_volatile(p as *mut u64, 0) };
+ p += 8;
+ }
+}
+
/// untyped로 넘길 구간을 구하고, 구간마다 꼬리에서 커널 몫을 떼어 두는
/// 함수입니다.
///
diff --git a/tools/boot-matrix.sh b/tools/boot-matrix.sh
index 8344cc3..d23e4ef 100755
--- a/tools/boot-matrix.sh
+++ b/tools/boot-matrix.sh
@@ -35,6 +35,13 @@ cargo build -p k0-kernel --offline --target-dir target/quiet || exit 2
cargo build -p k0-kernel --offline --no-default-features --features granule-16k --target-dir target/quiet16 || exit 2
cargo build -p k0-kernel --offline --features console-pl011 --target-dir target/pl011 || exit 2
cargo build -p k0-kernel --offline --features console-16550 --target-dir target/u16550 || exit 2
+# 키 볼트(서명 오라클)를 넣은 이미지들: Ed25519 포함(4K, 16K), 알고리즘 없음
+cargo build -p k0-kernel --offline --features console,vault-ed25519 --target-dir target/vault || exit 2
+cargo build -p k0-kernel --offline --no-default-features --features granule-16k,console,vault-ed25519 --target-dir target/vault16 || exit 2
+cargo build -p k0-kernel --offline --features console,vault --target-dir target/vaultna || exit 2
+imgvault="$root/target/vault/aarch64-unknown-none-softfloat/debug/k0-kernel"
+imgvault16="$root/target/vault16/aarch64-unknown-none-softfloat/debug/k0-kernel"
+imgvaultna="$root/target/vaultna/aarch64-unknown-none-softfloat/debug/k0-kernel"
# UEFI 로더: 위에서 빌드한 바로 그 커널을 내장함
efi4="$(tools/build-loader.sh "$img4")" || exit 2
efi16="$(tools/build-loader.sh "$img16")" || exit 2
@@ -158,6 +165,40 @@ fi
# 콘솔 드라이버 심볼: feature가 코드에 그대로 반영되는지 이미지의 심볼로 확인
# 있어야 하는 심볼을 먼저 요구해서 심볼을 못 읽는 경우에 헛통과하지 않게 함
+# 볼트의 코드가 feature대로만 들어가는지, 그리고 쓰기 가능한 static을 쓰지
+# 않는지 루트 태스크의 ELF에서 확인합니다. 격리 태스크의 주소 공간에는 이미지의
+# .data와 .bss가 없어서, 볼트나 암호 구현이 static에 쓰면 그 태스크가 죽습니다.
+if want vault-symbols $only; then
+ ran=$((ran + 1))
+ host="$(rustc -vV | sed -n 's/^host: //p')"
+ nm="$(rustc --print sysroot)/lib/rustlib/${host}/bin/llvm-nm"
+ # 같은 타겟 디렉토리에 예전 빌드의 것이 남아 있을 수 있으므로 가장 새 것을 봄
+ rt() { find "$root/target/$1" -path '*root-task-target*' -name root-task -type f -exec ls -t {} + 2>/dev/null | head -n 1; }
+ crypto='dalek|sha2|subtle'
+ bad=""
+ for spec in ":0:0" "vault:1:1" "vaultna:1:0"; do
+ dir="${spec%%:*}"; rest="${spec#*:}"; want_vault="${rest%%:*}"; want_alg="${rest#*:}"
+ elf="$(rt "$dir" 2>/dev/null)"
+ [ -n "$dir" ] || elf="$(rt aarch64-unknown-none-softfloat)"
+ if [ -z "$elf" ]; then bad="$bad no-root-task-elf($dir)"; continue; fi
+ s="$("$nm" -C "$elf" 2>&1)" || { bad="$bad llvm-nm-failed($dir)"; continue; }
+ v=0; printf '%s\n' "$s" | grep -q 'k0_vault::' && v=1
+ a=0; printf '%s\n' "$s" | grep -Eq "$crypto" && a=1
+ [ "$v" = "$want_vault" ] || bad="$bad vault-code=$v($dir)"
+ [ "$a" = "$want_alg" ] || bad="$bad crypto-code=$a($dir)"
+ # 쓰기 가능한 데이터(d, D, b, B)에 볼트나 암호 구현의 심볼이 없어야 함
+ if printf '%s\n' "$s" | awk '$2 ~ /^[dDbB]$/' | grep -Eq "k0_vault::|$crypto"; then
+ bad="$bad writable-static($dir)"
+ fi
+ done
+ if [ -z "$bad" ]; then
+ echo "matrix: vault-symbols pass"
+ else
+ echo "matrix: vault-symbols FAIL (${bad# })"
+ failed="$failed vault-symbols"
+ fi
+fi
+
if want console-symbols $only; then
ran=$((ran + 1))
host="$(rustc -vV | sed -n 's/^host: //p')"
@@ -195,6 +236,13 @@ fi
# 인터럽트 컨트롤러와 진입 EL
pass gic3-el1 "$img4" K0_BOOT_REQUIRE="k0: console drivers [pl011 16550]" K0_BOOT_CONSOLE_PAGE=mapped
pass gic3-el1-a53 "$img4" K0_QEMU_CPU=cortex-a53
+# 키 볼트: 서명 오라클의 자가 검증까지 통과해야 함. 위반하는 클라이언트 둘이
+# 폴트로 종료되므로 폴트 줄이 8개임
+pass vault "$imgvault" K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE="k0: dtb seeds wiped 40B|root: oracle tests pass"
+pass vault-max "$imgvault" K0_QEMU_CPU=max K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE="rndr=on|root: boot seed from rng-seed bytes 0x0000000000000020 and rndr|root: oracle tests pass"
+pass vault-el2 "$imgvault" K0_QEMU_MACHINE=virt,gic-version=3,virtualization=on K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE="root: oracle tests pass"
+pass vault-16k "$imgvault16" K0_QEMU_CPU=max K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE="root: oracle tests pass"
+pass vault-no-alg "$imgvaultna" K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE="root: oracle tests pass"
pass gic3-el1-max "$img4" K0_QEMU_CPU=max K0_BOOT_REQUIRE="rndr=on|k0: pac=on bti=present pan=on"
pass gic3-el2 "$img4" K0_QEMU_MACHINE=virt,gic-version=3,virtualization=on
pass gic3-el2-max "$img4" K0_QEMU_MACHINE=virt,gic-version=3,virtualization=on K0_QEMU_CPU=max
@@ -354,6 +402,7 @@ if [ "${K0_MATRIX_HVF:-0}" = 1 ]; then
pass uefi-hvf-16k "$efi16" K0_BOOT_REUSE=skip K0_QEMU_ACCEL=hvf K0_QEMU_CPU=host
pass uefi-hvf-acpi "$efi4" K0_BOOT_REUSE=skip K0_QEMU_ACCEL=hvf K0_QEMU_CPU=host K0_QEMU_MACHINE=virt,gic-version=3 K0_BOOT_REQUIRE="$acpi"
pass hvf-el1 "$img4" K0_QEMU_ACCEL=hvf K0_QEMU_CPU=host
+ pass hvf-vault "$imgvault" K0_QEMU_ACCEL=hvf K0_QEMU_CPU=host K0_BOOT_FAULTS=8 K0_BOOT_REQUIRE="root: oracle tests pass"
pass hvf-el2 "$img4" K0_QEMU_ACCEL=hvf K0_QEMU_CPU=host K0_QEMU_MACHINE=virt,gic-version=3,virtualization=on
pass hvf-16k "$img16" K0_QEMU_ACCEL=hvf K0_QEMU_CPU=host
pass hvf-quiet "$imgquiet" K0_QEMU_ACCEL=hvf K0_QEMU_CPU=host K0_BOOT_MEMLOG=0x40080000 K0_BOOT_SERIAL=empty K0_BOOT_CONSOLE_PAGE=unmapped K0_BOOT_REQUIRE="$quietreq"
diff --git a/tools/host-test.sh b/tools/host-test.sh
index 5a4a7a2..12590b0 100755
--- a/tools/host-test.sh
+++ b/tools/host-test.sh
@@ -7,6 +7,9 @@ cd "$root"
host="$(rustc -vV | sed -n 's/^host: //p')"
cargo test --offline --target "$host" -p k0-abi -p k0-cap -p k0-boot -p k0-efi "$@"
+# 키 볼트: 알고리즘을 넣은 것과 뺀 것을 따로 돌림(feature가 다르면 다른 코드)
+cargo test --offline --target "$host" -p k0-vault --features ed25519 "$@"
+cargo test --offline --target "$host" -p k0-vault "$@"
case "$(uname -m)" in
arm64|aarch64)
diff --git a/tools/qemu-boot-test.sh b/tools/qemu-boot-test.sh
index 871a91a..7e6a526 100755
--- a/tools/qemu-boot-test.sh
+++ b/tools/qemu-boot-test.sh
@@ -146,7 +146,7 @@ else
reuse_sed=''
fi
-markers="k0: entry phase 1 (pre-MMU)|k0: dtb = |k0: mmu on (identity + fixed image address)|k0: jumping to higher half|k0: higher half (pc = |k0: w^x checks pass|k0: memory |k0: platform |k0: root task integrity ok|k0: entropy dtb=|k0: pac=|k0: irq on (timer 1s)|k0: kernel table pool |k0: root task loaded|k0: kernel reserve |k0: untyped |k0: root cnode ready|k0: bootinfo page ready|k0: user w^x checks pass|k0: entering root task (el0)|root: hello from EL0|root: control byte filter [?]|root: retype/map tests pass|root: capability tests pass|root: untyped reuse test pass|root: child exit test pass|root: ipc tests pass|k0: task fault dabort-lower|k0: task fault fp-simd|root: fault isolation tests pass|root: preempt test pass|root: secret at |root: confined task reported|k0: task fault dabort-lower|root: isolation tests pass|k0: task fault dabort-lower|k0: task fault iabort-lower|k0: task fault dabort-lower|k0: unknown syscall 65535, killing task|root: violation tests pass|root: teardown tests pass|k0: idle (waiting for a timeout)|root: timeout tests pass|root: revocation tests pass|root: kernel reserve tests pass|root: sched tests pass|k0: tick "
+markers="k0: entry phase 1 (pre-MMU)|k0: dtb = |k0: mmu on (identity + fixed image address)|k0: jumping to higher half|k0: higher half (pc = |k0: w^x checks pass|k0: memory |k0: platform |k0: root task integrity ok|k0: entropy dtb=|k0: pac=|k0: irq on (timer 1s)|k0: kernel table pool |k0: root task loaded|k0: kernel reserve |k0: untyped |k0: root cnode ready|k0: bootinfo page ready|k0: user w^x checks pass|k0: dtb seeds wiped |k0: entering root task (el0)|root: hello from EL0|root: boot seed from rng-seed bytes |root: control byte filter [?]|root: retype/map tests pass|root: capability tests pass|root: untyped reuse test pass|root: child exit test pass|root: ipc tests pass|k0: task fault dabort-lower|k0: task fault fp-simd|root: fault isolation tests pass|root: preempt test pass|root: secret at |root: confined task reported|k0: task fault dabort-lower|root: isolation tests pass|k0: task fault dabort-lower|k0: task fault iabort-lower|k0: task fault dabort-lower|k0: unknown syscall 65535, killing task|root: violation tests pass|root: teardown tests pass|k0: idle (waiting for a timeout)|root: timeout tests pass|root: revocation tests pass|root: kernel reserve tests pass|root: sched tests pass|k0: tick "
# 메모리의 로그에는 처음 몇 번의 틱만 남습니다. 자가 검증이 그보다 오래 걸리는
# 호스트에서는 끝의 틱이 로그에 없을 수 있으므로 순서 목록에서는 빼고, 첫 틱이
# 기록됐는지와(아래) 자가 검증 뒤에도 틱이 이어지는지를(위의 대기) 따로 봅니다.
diff --git a/userspace/k0-vault/Cargo.toml b/userspace/k0-vault/Cargo.toml
new file mode 100644
index 0000000..2e727d7
--- /dev/null
+++ b/userspace/k0-vault/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "k0-vault"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+publish.workspace = true
+
+# 알고리즘은 feature로 더하기만 합니다. 아무것도 주지 않으면 서명 알고리즘이
+# 하나도 없는 볼트가 됩니다(모든 서명 요청을 "지원하지 않는 알고리즘"으로 거부).
+[features]
+ed25519 = ["dep:ed25519-dalek", "dep:zeroize"]
+
+[dependencies]
+k0-abi = { path = "../../crates/k0-abi" }
+ed25519-dalek = { version = "=2.2.0", default-features = false, features = ["zeroize"], optional = true }
+zeroize = { version = "1", default-features = false, optional = true }
diff --git a/userspace/k0-vault/src/lib.rs b/userspace/k0-vault/src/lib.rs
new file mode 100644
index 0000000..2be7c5b
--- /dev/null
+++ b/userspace/k0-vault/src/lib.rs
@@ -0,0 +1,30 @@
+//! K0 키 볼트(서명 오라클) 크레이트입니다.
+//!
+//! # Features
+//! 격리된 태스크 하나(볼트)가 서명 키를 쥐고, 다른 태스크(클라이언트)는 IPC로
+//! 서명과 공개키만 받아 갑니다. 이 크레이트는 그 프로토콜([proto]), 요청을
+//! 처리하는 상태 기계([server]), 암호 구현을 감싼 경계([provider])를 담습니다.
+//! 시스템 콜은 쓰지 않습니다. 메시지를 주고받는 루프는 이 크레이트를 링크한
+//! 태스크의 몫이라서, 상태 기계와 암호 경계는 호스트에서 그대로 테스트됩니다.
+//!
+//! 볼트의 코드는 루트 태스크 이미지에 들어가고(부팅 뒤에 코드를 적재하지
+//! 않음), 격리 태스크의 주소 공간에는 이미지의 `.data`와 `.bss`가 없습니다.
+//! 그래서 이 크레이트는 할당도 가변 static도 쓰지 않습니다.
+//!
+//! 알고리즘은 Cargo feature로 더합니다. `ed25519`를 주면 Ed25519(SHA-512를
+//! 쓰는 PureEdDSA, FIPS 186-5와 RFC 8032)가 들어갑니다. 구현은 vendor에 둔
+//! `ed25519-dalek`이고 어떤 인증도 받지 않았습니다. 키는 승인된 난수
+//! 발생기가 아니라 커널이 넘긴 부트 시드에서 나옵니다.
+//!
+//! # Errors
+//! 시작 시 자가 시험이나 키 생성 뒤의 쌍 일치 시험이 실패하면 볼트는 오류
+//! 상태가 되어 상태 조회 말고는 모든 서비스를 거부합니다.
+
+#![cfg_attr(not(test), no_std)]
+
+pub mod proto;
+pub mod provider;
+pub mod server;
+
+#[cfg(test)]
+mod tests;
diff --git a/userspace/k0-vault/src/proto.rs b/userspace/k0-vault/src/proto.rs
new file mode 100644
index 0000000..b1fe75a
--- /dev/null
+++ b/userspace/k0-vault/src/proto.rs
@@ -0,0 +1,160 @@
+//! 볼트와 클라이언트가 공유하는 프로토콜 정의 모듈입니다.
+//!
+//! # Features
+//! 클라이언트는 볼트의 엔드포인트에 `CALL`합니다. 요청의 메시지 레지스터는
+//! MR0 = 연산과 알고리즘([request]), MR1 = 요청 프레임에 둔 바이트 수, MR2 =
+//! 클라이언트가 고른 일회용 번호입니다. 응답은 MR0 = [status], MR1 = 응답
+//! 프레임에 쓴 바이트 수(상태 조회에서는 볼트의 [state]), MR2 = [indicator],
+//! MR3 = 요청의 일회용 번호입니다. 볼트는 네 레지스터를 항상 전부 채웁니다.
+//!
+//! 본문은 프레임으로 오갑니다. 요청 프레임은 클라이언트만 쓰고 볼트는 읽기만
+//! 하며, 응답 프레임은 그 반대입니다. 응답 프레임의 앞 [RESPONSE_HEADER]
+//! 바이트는 일회용 번호와 길이이고 그 뒤가 본문입니다. 클라이언트는 응답이
+//! 성공이고 프레임의 번호가 자기 번호와 같을 때만 본문을 믿어야 합니다
+//! (타임아웃으로 버린 예전 요청의 답이 뒤늦게 쓰일 수 있음).
+//!
+//! 누가 무엇을 할 수 있는지는 엔드포인트 배지로 정하고 빌드 때 고정됩니다
+//! ([role_of]). 배지는 커널이 케이퍼빌리티에서 읽어 전달하므로 클라이언트가
+//! 꾸밀 수 없습니다. 정책을 바꾸는 연산은 없습니다.
+
+/// 요청 본문(서명할 메시지)의 최대 길이
+pub const MAX_MESSAGE: usize = 1024;
+/// 응답 본문의 최대 길이(가장 긴 응답은 서명)
+pub const MAX_RESPONSE: usize = 64;
+/// 응답 프레임 앞머리의 길이(일회용 번호 8바이트, 본문 길이 8바이트)
+pub const RESPONSE_HEADER: usize = 16;
+/// `INIT` 본문의 길이(시드 32바이트와 시드 재료 정보 8바이트)
+pub const INIT_LEN: usize = 40;
+/// 호출자 프레임 쌍의 수(관리자 제외). 볼트는 배지의 번호로 그 호출자의
+/// 프레임을 고르므로, 이 수는 볼트의 주소 공간에 실제로 매핑해 둔 쌍의 수와
+/// 같아야 합니다. 지금의 배선은 한 쌍입니다
+pub const MAX_CLIENTS: u64 = 1;
+
+/// 요청의 MR0을 만들고 푸는 모듈입니다. 하위 8비트가 연산, 그 위 8비트가
+/// 알고리즘이고 나머지 비트는 0이어야 합니다.
+pub mod request {
+ /// 볼트의 상태와 표시를 묻는 연산
+ pub const STATUS: u64 = 1;
+ /// 공개키를 응답 프레임으로 받는 연산
+ pub const PUBLIC_KEY: u64 = 2;
+ /// 요청 프레임의 메시지에 서명해 응답 프레임으로 받는 연산
+ pub const SIGN: u64 = 3;
+ /// 시드를 주어 키를 만들게 하는 연산(관리자 전용, 한 번만)
+ pub const INIT: u64 = 4;
+ /// 키를 지우게 하는 연산(관리자 전용)
+ pub const ZEROIZE: u64 = 5;
+
+ /// 연산과 알고리즘을 MR0 값으로 묶는 함수입니다.
+ pub const fn word(op: u64, alg: u64) -> u64 {
+ op | alg << 8
+ }
+}
+
+/// 알고리즘 번호 모듈입니다.
+pub mod alg {
+ /// 알고리즘을 가리지 않는 연산에 쓰는 값
+ pub const NONE: u64 = 0;
+ /// Ed25519(PureEdDSA, FIPS 186-5와 RFC 8032)
+ pub const ED25519: u64 = 1;
+}
+
+/// 응답의 MR0 값 모듈입니다.
+pub mod status {
+ pub const OK: u64 = 0;
+ /// 이 배지에는 허용되지 않은 연산이거나 배지가 없음
+ pub const DENIED: u64 = 1;
+ /// 연산 번호, 길이, 예약 비트가 잘못됨
+ pub const BAD_REQUEST: u64 = 2;
+ /// 이 이미지에 그 알고리즘이 들어 있지 않음
+ pub const UNSUPPORTED: u64 = 3;
+ /// 아직 키가 없음(`INIT` 전)
+ pub const NOT_READY: u64 = 4;
+ /// 자가 시험이나 쌍 일치 시험이 실패해 볼트가 오류 상태임
+ pub const FAILED: u64 = 5;
+ /// 키가 지워졌음
+ pub const ZEROIZED: u64 = 6;
+ /// 시드의 재료가 키를 만들기에 모자람
+ pub const NO_ENTROPY: u64 = 7;
+}
+
+/// 볼트의 상태(상태 조회 응답의 MR1) 모듈입니다.
+pub mod state {
+ pub const FRESH: u64 = 0;
+ pub const READY: u64 = 1;
+ pub const ZEROIZED: u64 = 2;
+ pub const FAILED: u64 = 3;
+}
+
+/// 응답의 MR2에 실리는 표시 비트 모듈입니다.
+///
+/// 어떤 비트도 "인증된 모듈"이나 "승인 모드"를 뜻하지 않습니다. 구현은
+/// 인증받지 않았고 키는 승인된 난수 발생기에서 나오지 않습니다.
+pub mod indicator {
+ /// 이 서비스가 쓴 알고리즘이 FIPS 186-5에 있는 알고리즘임
+ pub const FIPS_186_5_ALGORITHM: u64 = 1;
+ /// 시작 시 자가 시험을 통과했음
+ pub const SELF_TEST_PASSED: u64 = 2;
+ /// 키의 시드에 `rng-seed` 32바이트 이상이 들어갔음
+ pub const SEED_RNG_SEED: u64 = 4;
+ /// 키의 시드에 RNDR 난수 256비트가 들어갔음
+ pub const SEED_RNDR: u64 = 8;
+}
+
+/// 배지가 가리키는 역할을 나타내는 열거형입니다.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Role {
+ /// 루트 태스크. 키를 만들게 하고 지우게 할 수 있지만 서명은 받지 못함
+ Admin,
+ /// 공개키를 받고 서명을 받을 수 있는 클라이언트
+ Signer,
+ /// 공개키만 받을 수 있는 클라이언트
+ Reader,
+}
+
+/// 역할을 담는 배지의 윗부분
+const ROLE_ADMIN: u64 = 0xAD_0000_0000_0000;
+const ROLE_SIGNER: u64 = 0x51_0000_0000_0000;
+const ROLE_READER: u64 = 0x4E_0000_0000_0000;
+
+/// 관리자(루트 태스크)의 배지
+pub const ADMIN_BADGE: u64 = ROLE_ADMIN;
+
+/// 서명 클라이언트의 배지를 만드는 함수입니다.
+///
+/// # Arguments
+/// `client` - 클라이언트 번호(1부터 [MAX_CLIENTS]까지)
+pub const fn signer_badge(client: u64) -> u64 {
+ ROLE_SIGNER | client
+}
+
+/// 공개키만 받는 클라이언트의 배지를 만드는 함수입니다.
+///
+/// # Arguments
+/// `client` - 클라이언트 번호(1부터 [MAX_CLIENTS]까지)
+pub const fn reader_badge(client: u64) -> u64 {
+ ROLE_READER | client
+}
+
+/// 배지를 (역할, 프레임 번호)로 푸는 함수입니다. 이 표에 없는 배지와 배지
+/// 없는 호출(0)은 `None`입니다.
+///
+/// 프레임 번호는 볼트가 그 호출자의 요청 프레임과 응답 프레임을 고르는 데
+/// 씁니다. 관리자가 0번이고 클라이언트는 자기 번호입니다.
+pub const fn role_of(badge: u64) -> Option<(Role, u64)> {
+ let client = badge & 0xFFFF_FFFF_FFFF;
+ match badge & !0xFFFF_FFFF_FFFF {
+ ROLE_ADMIN if client == 0 => Some((Role::Admin, 0)),
+ ROLE_SIGNER if client >= 1 && client <= MAX_CLIENTS => Some((Role::Signer, client)),
+ ROLE_READER if client >= 1 && client <= MAX_CLIENTS => Some((Role::Reader, client)),
+ _ => None,
+ }
+}
+
+/// 역할이 그 연산을 해도 되는지 알려 주는 함수입니다.
+pub const fn allowed(role: Role, op: u64) -> bool {
+ match role {
+ Role::Admin => matches!(op, request::STATUS | request::INIT | request::ZEROIZE),
+ Role::Signer => matches!(op, request::STATUS | request::PUBLIC_KEY | request::SIGN),
+ Role::Reader => matches!(op, request::STATUS | request::PUBLIC_KEY),
+ }
+}
diff --git a/userspace/k0-vault/src/provider.rs b/userspace/k0-vault/src/provider.rs
new file mode 100644
index 0000000..907e197
--- /dev/null
+++ b/userspace/k0-vault/src/provider.rs
@@ -0,0 +1,201 @@
+//! 암호 구현을 감싼 경계 모듈입니다.
+//!
+//! # Features
+//! 볼트의 나머지 코드는 이 모듈의 함수로만 암호 연산을 합니다. 경계는 암호
+//! 모듈에 흔히 요구되는 것을 갖춥니다. 시작 시 기지 답 자가 시험([self_test]),
+//! 밖에서 받은 시드로 하는 키 생성과 그 직후의 쌍 일치 시험([keygen]), 키를
+//! 내보내는 함수의 부재, 명시적 소거([Key::wipe])입니다. 그렇다고 인증된
+//! 모듈이 되는 것은 아닙니다.
+//!
+//! feature `ed25519`가 없으면 알고리즘이 하나도 없는 경계가 되어 서명과
+//! 공개키 요청이 전부 거부됩니다.
+
+/// 공개키의 길이
+pub const PUBLIC_KEY_LEN: usize = 32;
+/// 서명의 길이
+pub const SIGNATURE_LEN: usize = 64;
+
+#[cfg(feature = "ed25519")]
+mod imp {
+ use super::{PUBLIC_KEY_LEN, SIGNATURE_LEN};
+ use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
+ use zeroize::Zeroize;
+
+ /// 이 이미지에 Ed25519가 들어 있음
+ pub const HAS_ED25519: bool = true;
+
+ /// 볼트가 쥔 서명 키 구조체입니다. 비밀을 꺼내는 길은 없습니다.
+ pub struct Key(Option);
+
+ impl Key {
+ /// 키가 없는 상태를 만드는 함수입니다.
+ pub const fn empty() -> Self {
+ Key(None)
+ }
+
+ /// 키를 지우는 함수입니다. `SigningKey`는 버려질 때 비밀을 소거합니다.
+ pub fn wipe(&mut self) {
+ self.0 = None;
+ }
+
+ /// 공개키를 주는 함수입니다. 키가 없으면 `None`
+ pub fn public(&self) -> Option<[u8; PUBLIC_KEY_LEN]> {
+ self.0.as_ref().map(|k| k.verifying_key().to_bytes())
+ }
+
+ /// 메시지에 서명하는 함수입니다. 키가 없으면 `None`
+ pub fn sign(&self, msg: &[u8]) -> Option<[u8; SIGNATURE_LEN]> {
+ self.0.as_ref().map(|k| k.sign(msg).to_bytes())
+ }
+ }
+
+ /// 시드로 키를 만드는 함수입니다.
+ ///
+ /// 만든 직후 고정 메시지에 서명하고 그 공개키로 검증합니다(쌍 일치 시험).
+ /// 실패하면 키를 지우고 `None`을 줍니다. 받은 시드 사본은 지웁니다.
+ ///
+ /// # Arguments
+ /// `seed` - 비밀 시드 32바이트(호출 뒤 0으로 덮임)
+ pub fn keygen(seed: &mut [u8; 32]) -> Option {
+ let key = SigningKey::from_bytes(seed);
+ seed.zeroize();
+ let probe = b"k0 vault pairwise consistency test";
+ let sig = key.sign(probe);
+ if key.verifying_key().verify_strict(probe, &sig).is_err() {
+ return None;
+ }
+ Some(Key(Some(key)))
+ }
+
+ /// 서명을 검증하는 함수입니다. 비밀을 다루지 않으므로 클라이언트도 씁니다.
+ ///
+ /// 약한 공개키와 표준형이 아닌 서명을 거부하는 엄격한 검증입니다.
+ pub fn verify(public: &[u8; PUBLIC_KEY_LEN], msg: &[u8], sig: &[u8; SIGNATURE_LEN]) -> bool {
+ match VerifyingKey::from_bytes(public) {
+ Ok(k) => k.verify_strict(msg, &Signature::from_bytes(sig)).is_ok(),
+ Err(_) => false,
+ }
+ }
+
+ /// RFC 8032 7.1절의 시험 벡터 하나
+ struct Kat {
+ seed: [u8; 32],
+ public: [u8; 32],
+ msg: &'static [u8],
+ sig: [u8; 64],
+ }
+
+ const KATS: [Kat; 2] = [
+ Kat {
+ seed: hex("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"),
+ public: hex("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"),
+ msg: &[],
+ sig: hex(
+ "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e06522490155\
+ 5fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b",
+ ),
+ },
+ Kat {
+ seed: hex("4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb"),
+ public: hex("3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c"),
+ msg: &[0x72],
+ sig: hex(
+ "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da\
+ 085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00",
+ ),
+ },
+ ];
+
+ /// 16진 문자열을 바이트 배열로 바꾸는 함수입니다(상수 문맥 전용). 공백은
+ /// 건너뜁니다.
+ const fn hex(s: &str) -> [u8; N] {
+ let b = s.as_bytes();
+ let mut out = [0u8; N];
+ let (mut i, mut n) = (0, 0);
+ while i < b.len() {
+ let c = b[i];
+ i += 1;
+ let v = match c {
+ b'0'..=b'9' => c - b'0',
+ b'a'..=b'f' => c - b'a' + 10,
+ _ => continue,
+ };
+ out[n / 2] |= v << if n % 2 == 0 { 4 } else { 0 };
+ n += 1;
+ }
+ assert!(n == 2 * N);
+ out
+ }
+
+ /// 기지 답 자가 시험 함수입니다.
+ ///
+ /// 시험 벡터의 시드에서 공개키와 서명이 그대로 나오는지, 그 서명이
+ /// 검증되는지, 한 비트를 바꾼 메시지와 서명은 거부되는지 봅니다.
+ pub fn self_test() -> bool {
+ for kat in &KATS {
+ let key = SigningKey::from_bytes(&kat.seed);
+ if key.verifying_key().to_bytes() != kat.public {
+ return false;
+ }
+ if key.sign(kat.msg).to_bytes() != kat.sig {
+ return false;
+ }
+ if !verify(&kat.public, kat.msg, &kat.sig) {
+ return false;
+ }
+ let mut bad = kat.sig;
+ bad[0] ^= 1;
+ if verify(&kat.public, kat.msg, &bad) || verify(&kat.public, b"other", &kat.sig) {
+ return false;
+ }
+ }
+ true
+ }
+}
+
+#[cfg(not(feature = "ed25519"))]
+mod imp {
+ use super::{PUBLIC_KEY_LEN, SIGNATURE_LEN};
+
+ /// 이 이미지에 Ed25519가 들어 있지 않음
+ pub const HAS_ED25519: bool = false;
+
+ /// 알고리즘이 없는 이미지의 키 자리 구조체입니다. 아무것도 담지 않습니다.
+ pub struct Key;
+
+ impl Key {
+ pub const fn empty() -> Self {
+ Key
+ }
+
+ pub fn wipe(&mut self) {}
+
+ pub fn public(&self) -> Option<[u8; PUBLIC_KEY_LEN]> {
+ None
+ }
+
+ pub fn sign(&self, _msg: &[u8]) -> Option<[u8; SIGNATURE_LEN]> {
+ None
+ }
+ }
+
+ /// 알고리즘이 없으므로 시드를 지우기만 하고 빈 키 자리를 주는 함수입니다.
+ pub fn keygen(seed: &mut [u8; 32]) -> Option {
+ for b in seed.iter_mut() {
+ // SAFETY: b는 호출자가 준 배열 안의 유효한 바이트임
+ unsafe { core::ptr::write_volatile(b, 0) };
+ }
+ Some(Key)
+ }
+
+ pub fn verify(_public: &[u8; PUBLIC_KEY_LEN], _msg: &[u8], _sig: &[u8; SIGNATURE_LEN]) -> bool {
+ false
+ }
+
+ /// 시험할 알고리즘이 없으므로 항상 통과하는 함수입니다.
+ pub fn self_test() -> bool {
+ true
+ }
+}
+
+pub use imp::{keygen, self_test, verify, Key, HAS_ED25519};
diff --git a/userspace/k0-vault/src/server.rs b/userspace/k0-vault/src/server.rs
new file mode 100644
index 0000000..8c2a9b6
--- /dev/null
+++ b/userspace/k0-vault/src/server.rs
@@ -0,0 +1,265 @@
+//! 볼트의 요청 처리 상태 기계 모듈입니다.
+//!
+//! # Features
+//! [Vault::handle]은 배지, 요청 레지스터, 요청 본문의 사본을 받아 응답
+//! 레지스터와 응답 본문을 만듭니다. 시스템 콜도 프레임 접근도 하지 않으므로
+//! 호스트에서 그대로 시험됩니다. 프레임에서 본문을 읽고 쓰는 일은 [fetch]와
+//! [publish]가 합니다.
+//!
+//! 요청 프레임은 클라이언트가 언제든 바꿀 수 있는 메모리입니다. 그래서
+//! [fetch]는 길이를 먼저 확정하고 바이트를 한 번씩만 읽어 볼트의 버퍼로
+//! 옮기며, 그 뒤로 볼트는 사본만 봅니다. 읽는 도중에 프레임이 바뀌면 사본이
+//! 뒤섞일 뿐이고, 그것은 클라이언트가 처음부터 보낼 수 있었던 내용입니다.
+//!
+//! # Errors
+//! 자가 시험이나 쌍 일치 시험이 실패하면 [state::FAILED]가 되어 상태 조회
+//! 말고는 전부 [status::FAILED]로 거부합니다.
+
+use crate::proto::{alg, allowed, indicator, request, role_of, state, status, Role};
+use crate::proto::{INIT_LEN, MAX_MESSAGE, MAX_RESPONSE, RESPONSE_HEADER};
+use crate::provider::{self, Key};
+
+/// `rng-seed`가 이만큼은 들어가야 시드로 키를 만듦(바이트)
+const MIN_RNG_SEED: u64 = 32;
+/// 커널이 준 시드 정보의 비트(k0-abi의 bootinfo 상수와 같음)
+const SEED_RNG_SEED_BYTES: u64 = k0_abi::bootinfo::SEED_RNG_SEED_BYTES;
+const SEED_RNDR: u64 = k0_abi::bootinfo::SEED_RNDR;
+
+/// 볼트의 상태를 담는 구조체입니다.
+pub struct Vault {
+ state: u64,
+ key: Key,
+ /// 표시 비트 가운데 자가 시험과 시드 재료에 관한 것
+ flags: u64,
+}
+
+impl Vault {
+ /// 자가 시험을 돌리고 볼트를 만드는 함수입니다.
+ ///
+ /// 시험이 실패하면 오류 상태로 시작해 어떤 서비스도 하지 않습니다.
+ pub fn new() -> Self {
+ let ok = provider::self_test();
+ Vault {
+ state: if ok { state::FRESH } else { state::FAILED },
+ key: Key::empty(),
+ flags: if ok { indicator::SELF_TEST_PASSED } else { 0 },
+ }
+ }
+
+ /// 요청 하나를 처리하는 함수입니다.
+ ///
+ /// 응답 레지스터 네 개를 전부 채워 돌려주고(쓰지 않는 값이 새지 않게),
+ /// 응답 본문은 `out`의 앞에 씁니다. 본문 길이는 응답의 두 번째 값입니다
+ /// (상태 조회에서는 그 자리가 볼트의 상태이고 본문은 없음).
+ ///
+ /// # Arguments
+ /// `badge` - 커널이 전달한 호출자의 배지
+ /// `mr` - 요청의 메시지 레지스터
+ /// `body` - 요청 프레임에서 옮겨 온 본문의 사본(길이는 이미 확정된 값)
+ /// `out` - 응답 본문을 받을 버퍼
+ pub fn handle(&mut self, badge: u64, mr: [u64; 4], body: &[u8], out: &mut [u8; MAX_RESPONSE]) -> [u64; 4] {
+ let nonce = mr[2];
+ let reply = |status: u64, len: u64, ind: u64| [status, len, ind, nonce];
+ let Some((role, _)) = role_of(badge) else {
+ return reply(status::DENIED, 0, 0);
+ };
+ let (op, algo) = (mr[0] & 0xFF, (mr[0] >> 8) & 0xFF);
+ // 예약 비트가 서 있거나, 말한 길이와 옮겨 온 본문의 길이가 다르면
+ // (버퍼보다 긴 본문은 잘려서 옴) 요청 전체를 거부함
+ if mr[0] >> 16 != 0 || mr[3] != 0 || mr[1] != body.len() as u64 {
+ return reply(status::BAD_REQUEST, 0, 0);
+ }
+ if !matches!(
+ op,
+ request::STATUS | request::PUBLIC_KEY | request::SIGN | request::INIT | request::ZEROIZE
+ ) {
+ return reply(status::BAD_REQUEST, 0, 0);
+ }
+ if !allowed(role, op) {
+ return reply(status::DENIED, 0, 0);
+ }
+ if op == request::STATUS {
+ return reply(status::OK, self.state, self.flags);
+ }
+ if self.state == state::FAILED {
+ return reply(status::FAILED, 0, self.flags);
+ }
+ match op {
+ request::INIT => self.init(role, body, reply),
+ request::ZEROIZE => {
+ self.key.wipe();
+ self.state = state::ZEROIZED;
+ scrub_stack();
+ reply(status::OK, 0, self.flags)
+ }
+ _ => self.serve(op, algo, body, out, reply),
+ }
+ }
+
+ fn init(&mut self, _role: Role, body: &[u8], reply: impl Fn(u64, u64, u64) -> [u64; 4]) -> [u64; 4] {
+ if self.state != state::FRESH {
+ return reply(status::DENIED, 0, self.flags);
+ }
+ if body.len() != INIT_LEN {
+ return reply(status::BAD_REQUEST, 0, self.flags);
+ }
+ let mut seed = [0u8; 32];
+ seed.copy_from_slice(&body[..32]);
+ let mut info = [0u8; 8];
+ info.copy_from_slice(&body[32..]);
+ let info = u64::from_le_bytes(info);
+ let mut seed_flags = 0;
+ if info & SEED_RNG_SEED_BYTES >= MIN_RNG_SEED {
+ seed_flags |= indicator::SEED_RNG_SEED;
+ }
+ if info & SEED_RNDR != 0 {
+ seed_flags |= indicator::SEED_RNDR;
+ }
+ if seed_flags == 0 {
+ // 재료가 카운터뿐인 시드로는 키를 만들지 않음
+ wipe(&mut seed);
+ return reply(status::NO_ENTROPY, 0, self.flags);
+ }
+ let made = provider::keygen(&mut seed);
+ wipe(&mut seed);
+ scrub_stack();
+ match made {
+ Some(key) => {
+ self.key = key;
+ self.state = state::READY;
+ self.flags |= seed_flags;
+ reply(status::OK, 0, self.flags)
+ }
+ None => {
+ self.state = state::FAILED;
+ self.flags &= !indicator::SELF_TEST_PASSED;
+ reply(status::FAILED, 0, self.flags)
+ }
+ }
+ }
+
+ fn serve(
+ &mut self,
+ op: u64,
+ algo: u64,
+ body: &[u8],
+ out: &mut [u8; MAX_RESPONSE],
+ reply: impl Fn(u64, u64, u64) -> [u64; 4],
+ ) -> [u64; 4] {
+ if algo != alg::ED25519 || !provider::HAS_ED25519 {
+ return reply(status::UNSUPPORTED, 0, self.flags);
+ }
+ match self.state {
+ state::FRESH => return reply(status::NOT_READY, 0, self.flags),
+ state::ZEROIZED => return reply(status::ZEROIZED, 0, self.flags),
+ _ => {}
+ }
+ let ind = self.flags | indicator::FIPS_186_5_ALGORITHM;
+ if op == request::PUBLIC_KEY {
+ if !body.is_empty() {
+ return reply(status::BAD_REQUEST, 0, self.flags);
+ }
+ let Some(public) = self.key.public() else {
+ return reply(status::NOT_READY, 0, self.flags);
+ };
+ out[..public.len()].copy_from_slice(&public);
+ return reply(status::OK, public.len() as u64, ind);
+ }
+ if body.len() > MAX_MESSAGE {
+ return reply(status::BAD_REQUEST, 0, self.flags);
+ }
+ let signed = self.key.sign(body);
+ scrub_stack();
+ let Some(sig) = signed else {
+ return reply(status::NOT_READY, 0, self.flags);
+ };
+ out[..sig.len()].copy_from_slice(&sig);
+ reply(status::OK, sig.len() as u64, ind)
+ }
+}
+
+#[cfg(test)]
+impl Vault {
+ /// 자가 시험이 실패했을 때의 볼트를 만드는 함수입니다(테스트 전용).
+ pub fn failed_for_test() -> Self {
+ Vault {
+ state: state::FAILED,
+ key: Key::empty(),
+ flags: 0,
+ }
+ }
+}
+
+impl Default for Vault {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// 바이트 배열을 0으로 덮는 함수입니다(최적화로 사라지지 않게 volatile).
+pub fn wipe(buf: &mut [u8]) {
+ for b in buf.iter_mut() {
+ // SAFETY: b는 배열 안의 유효한 바이트임
+ unsafe { core::ptr::write_volatile(b, 0) };
+ }
+ core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
+}
+
+/// 방금 끝난 암호 연산이 쓰던 스택 구간을 덮는 함수입니다.
+///
+/// 암호 구현은 키에서 나온 중간값을 자기 지역 변수에 두고 돌아옵니다. 그
+/// 프레임들이 있던 자리에 같은 깊이의 배열을 잡아 0으로 채웁니다. 구현이 쓴
+/// 깊이를 정확히 알 수는 없으므로 최선의 노력입니다. 볼트의 메모리 전체는
+/// 볼트가 사라진 뒤 다시 쓰이기 전에 커널이 소거합니다.
+#[inline(never)]
+fn scrub_stack() {
+ let mut pad = [0u8; 8192];
+ wipe(&mut pad);
+ core::hint::black_box(&pad);
+}
+
+/// 요청 프레임에서 본문을 볼트의 버퍼로 옮기는 함수입니다. 옮긴 길이를
+/// 반환합니다.
+///
+/// 길이를 버퍼 크기로 먼저 자르고, 바이트마다 한 번씩만 volatile로 읽습니다.
+/// 프레임을 가리키는 참조는 만들지 않습니다.
+///
+/// # Arguments
+/// `frame` - 요청 프레임의 시작 주소
+/// `len` - 요청이 말한 본문 길이(레지스터에서 온 값)
+/// `dst` - 사본을 받을 버퍼
+///
+/// # Safety
+/// `frame`부터 `dst.len()`바이트가 읽을 수 있게 매핑돼 있어야 합니다.
+pub unsafe fn fetch(frame: *const u8, len: u64, dst: &mut [u8]) -> usize {
+ let n = usize::try_from(len).unwrap_or(usize::MAX).min(dst.len());
+ for (i, b) in dst[..n].iter_mut().enumerate() {
+ // SAFETY: 함수 계약대로 i는 매핑된 범위 안임
+ *b = unsafe { frame.add(i).read_volatile() };
+ }
+ n
+}
+
+/// 응답 프레임에 앞머리(일회용 번호와 길이)와 본문을 쓰는 함수입니다.
+///
+/// # Arguments
+/// `frame` - 응답 프레임의 시작 주소
+/// `nonce` - 요청의 일회용 번호
+/// `body` - 응답 본문
+///
+/// # Safety
+/// `frame`부터 [RESPONSE_HEADER] + [MAX_RESPONSE]바이트가 쓸 수 있게 매핑돼
+/// 있어야 하고 8바이트로 정렬돼 있어야 합니다.
+pub unsafe fn publish(frame: *mut u8, nonce: u64, body: &[u8]) {
+ let n = body.len().min(MAX_RESPONSE);
+ // SAFETY: 함수 계약대로 범위 안이고 정렬돼 있음. 본문을 먼저 쓰고 번호를
+ // 마지막에 써서, 번호가 맞는 프레임에는 그 요청의 본문이 다 있음
+ unsafe {
+ frame.cast::().write_volatile(0);
+ frame.add(8).cast::().write_volatile(n as u64);
+ for (i, b) in body[..n].iter().enumerate() {
+ frame.add(RESPONSE_HEADER + i).write_volatile(*b);
+ }
+ frame.cast::().write_volatile(nonce);
+ }
+}
diff --git a/userspace/k0-vault/src/tests.rs b/userspace/k0-vault/src/tests.rs
new file mode 100644
index 0000000..9649f8d
--- /dev/null
+++ b/userspace/k0-vault/src/tests.rs
@@ -0,0 +1,245 @@
+use crate::proto::{alg, indicator, request, state, status};
+use crate::proto::{reader_badge, role_of, signer_badge, Role, ADMIN_BADGE, INIT_LEN, MAX_MESSAGE, MAX_RESPONSE};
+use crate::server::{fetch, publish, Vault};
+
+const SIGNER: u64 = signer_badge(1);
+const READER: u64 = reader_badge(1);
+/// 시드 정보: rng-seed 32바이트
+const GOOD_INFO: u64 = 32;
+
+fn call(v: &mut Vault, badge: u64, op: u64, algo: u64, body: &[u8]) -> ([u64; 4], Vec) {
+ let mut out = [0xEEu8; MAX_RESPONSE];
+ let r = v.handle(badge, [request::word(op, algo), body.len() as u64, 0x1234, 0], body, &mut out);
+ assert_eq!(r[3], 0x1234, "the nonce is always echoed");
+ let n = if op == request::STATUS { 0 } else { r[1] as usize };
+ // 응답 본문이 아닌 자리는 한 바이트도 건드리지 않았어야 함. 거부된 요청은
+ // 길이가 0이므로 버퍼 전체가 그대로여야 함
+ assert!(out[n..].iter().all(|&b| b == 0xEE), "bytes written beyond the reply body");
+ (r, out[..n].to_vec())
+}
+
+fn init_body(seed: [u8; 32], info: u64) -> Vec {
+ let mut b = seed.to_vec();
+ b.extend_from_slice(&info.to_le_bytes());
+ assert_eq!(b.len(), INIT_LEN);
+ b
+}
+
+fn ready() -> Vault {
+ let mut v = Vault::new();
+ let (r, _) = call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &init_body([7; 32], GOOD_INFO));
+ assert_eq!(r[0], status::OK);
+ v
+}
+
+#[test]
+fn badges_map_to_fixed_roles() {
+ assert_eq!(role_of(0), None, "a call without a badge has no role");
+ assert_eq!(role_of(ADMIN_BADGE), Some((Role::Admin, 0)));
+ assert_eq!(role_of(ADMIN_BADGE | 1), None);
+ assert_eq!(role_of(signer_badge(1)), Some((Role::Signer, 1)));
+ assert_eq!(role_of(signer_badge(0)), None);
+ assert_eq!(role_of(signer_badge(2)), None, "no frame pair is mapped for a second caller");
+ assert_eq!(role_of(reader_badge(1)), Some((Role::Reader, 1)));
+ assert_eq!(role_of(1), None);
+ assert_eq!(role_of(u64::MAX), None);
+}
+
+#[test]
+fn policy_is_enforced_before_anything_else() {
+ let mut v = ready();
+ let msg = b"m";
+ for (badge, op) in [
+ (0, request::STATUS),
+ (0, request::SIGN),
+ (0x99, request::SIGN),
+ (READER, request::SIGN),
+ (ADMIN_BADGE, request::SIGN),
+ (ADMIN_BADGE, request::PUBLIC_KEY),
+ (SIGNER, request::INIT),
+ (SIGNER, request::ZEROIZE),
+ (READER, request::ZEROIZE),
+ ] {
+ let (r, out) = call(&mut v, badge, op, alg::ED25519, msg);
+ assert_eq!(r[0], status::DENIED, "badge {badge:#x} op {op}");
+ assert!(out.is_empty());
+ }
+ // 거부된 요청들은 볼트의 상태를 바꾸지 않았음
+ assert_eq!(call(&mut v, SIGNER, request::STATUS, alg::NONE, &[]).0[1], state::READY);
+}
+
+#[test]
+fn malformed_requests_are_refused_whole() {
+ let mut v = ready();
+ let mut out = [0u8; MAX_RESPONSE];
+ let ok = request::word(request::SIGN, alg::ED25519);
+ // 예약 비트, 쓰지 않는 레지스터, 모르는 연산, 말한 길이와 다른 본문
+ for mr in [[ok | 1 << 16, 1, 0, 0], [ok, 1, 0, 9], [request::word(9, alg::ED25519), 1, 0, 0], [ok, 2, 0, 0]] {
+ assert_eq!(v.handle(SIGNER, mr, b"m", &mut out)[0], status::BAD_REQUEST, "{mr:x?}");
+ }
+ // 버퍼보다 길다고 말한 요청은 잘린 본문과 길이가 맞지 않아 거부됨
+ let body = [0u8; MAX_MESSAGE];
+ let r = v.handle(SIGNER, [ok, MAX_MESSAGE as u64 + 1, 0, 0], &body, &mut out);
+ assert_eq!(r[0], status::BAD_REQUEST);
+}
+
+#[test]
+fn a_seed_without_real_entropy_makes_no_key() {
+ use k0_abi::bootinfo::SEED_RNDR;
+ for info in [0, 8, 31] {
+ let mut v = Vault::new();
+ let (r, _) = call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &init_body([1; 32], info));
+ assert_eq!(r[0], status::NO_ENTROPY, "info {info}");
+ assert_eq!(call(&mut v, SIGNER, request::STATUS, alg::NONE, &[]).0[1], state::FRESH);
+ }
+ let mut v = Vault::new();
+ let (r, _) = call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &init_body([1; 32], SEED_RNDR));
+ assert_eq!(r[0], status::OK);
+ assert_eq!(r[2] & (indicator::SEED_RNDR | indicator::SEED_RNG_SEED), indicator::SEED_RNDR);
+ // 길이가 다른 INIT 본문
+ let mut v = Vault::new();
+ let (r, _) = call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &[1; 39]);
+ assert_eq!(r[0], status::BAD_REQUEST);
+}
+
+#[test]
+fn init_happens_once_and_zeroize_is_final() {
+ let mut v = ready();
+ let (r, _) = call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &init_body([9; 32], GOOD_INFO));
+ assert_eq!(r[0], status::DENIED, "a second key cannot replace the first");
+ let (r, _) = call(&mut v, ADMIN_BADGE, request::ZEROIZE, alg::NONE, &[]);
+ assert_eq!(r[0], status::OK);
+ assert_eq!(call(&mut v, SIGNER, request::STATUS, alg::NONE, &[]).0[1], state::ZEROIZED);
+ let (r, _) = call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &init_body([9; 32], GOOD_INFO));
+ assert_eq!(r[0], status::DENIED);
+}
+
+#[test]
+fn fetch_clamps_the_length_and_publish_writes_header_and_body() {
+ let frame = [0x5Au8; 64];
+ let mut dst = [0u8; 16];
+ // 말한 길이가 버퍼보다 길면 버퍼만큼만 옮김
+ // SAFETY: frame은 64바이트이고 dst는 16바이트임
+ assert_eq!(unsafe { fetch(frame.as_ptr(), 1000, &mut dst) }, 16);
+ assert_eq!(dst, [0x5A; 16]);
+ let mut dst = [0u8; 16];
+ // SAFETY: 위와 같음
+ assert_eq!(unsafe { fetch(frame.as_ptr(), 5, &mut dst) }, 5);
+ assert_eq!(&dst[..6], &[0x5A, 0x5A, 0x5A, 0x5A, 0x5A, 0]);
+
+ let mut resp = [0xFFu64; 16];
+ // SAFETY: resp는 128바이트이고 8바이트로 정렬돼 있음
+ unsafe { publish(resp.as_mut_ptr().cast(), 0xABCD, &[1, 2, 3]) };
+ assert_eq!(resp[0], 0xABCD);
+ assert_eq!(resp[1], 3);
+ assert_eq!(resp[2].to_le_bytes()[..3], [1, 2, 3]);
+}
+
+#[cfg(feature = "ed25519")]
+mod ed25519 {
+ use super::*;
+ use crate::provider;
+
+ #[test]
+ fn the_self_test_passes_and_is_reported() {
+ assert!(provider::self_test());
+ let mut v = Vault::new();
+ let (r, _) = call(&mut v, READER, request::STATUS, alg::NONE, &[]);
+ assert_eq!((r[0], r[1]), (status::OK, state::FRESH));
+ assert_eq!(r[2], indicator::SELF_TEST_PASSED);
+ }
+
+ #[test]
+ fn signatures_verify_and_the_key_follows_the_seed() {
+ let mut v = Vault::new();
+ let (r, _) = call(&mut v, SIGNER, request::SIGN, alg::ED25519, b"too early");
+ assert_eq!(r[0], status::NOT_READY);
+ let mut v = ready();
+ let (r, public) = call(&mut v, READER, request::PUBLIC_KEY, alg::ED25519, &[]);
+ assert_eq!((r[0], r[1]), (status::OK, 32));
+ let want = indicator::FIPS_186_5_ALGORITHM | indicator::SELF_TEST_PASSED | indicator::SEED_RNG_SEED;
+ assert_eq!(r[2], want);
+ let public: [u8; 32] = public.try_into().unwrap();
+ // 같은 시드에서 구현이 직접 내는 공개키와 같음
+ let direct = ed25519_dalek::SigningKey::from_bytes(&[7; 32]).verifying_key().to_bytes();
+ assert_eq!(public, direct);
+
+ let msg = b"pay 10 to alice";
+ let (r, sig) = call(&mut v, SIGNER, request::SIGN, alg::ED25519, msg);
+ assert_eq!((r[0], r[1], r[2]), (status::OK, 64, want));
+ let sig: [u8; 64] = sig.try_into().unwrap();
+ assert!(provider::verify(&public, msg, &sig));
+ assert!(!provider::verify(&public, b"pay 99 to alice", &sig));
+ let mut bad = sig;
+ bad[63] ^= 0x80;
+ assert!(!provider::verify(&public, msg, &bad));
+ // 가장 긴 메시지와 빈 메시지
+ for m in [&[0x33u8; MAX_MESSAGE][..], &[][..]] {
+ let (r, sig) = call(&mut v, SIGNER, request::SIGN, alg::ED25519, m);
+ assert_eq!(r[0], status::OK);
+ assert!(provider::verify(&public, m, &sig.try_into().unwrap()));
+ }
+ }
+
+ #[test]
+ fn a_public_key_request_carries_no_body() {
+ let mut v = ready();
+ let (r, _) = call(&mut v, SIGNER, request::PUBLIC_KEY, alg::ED25519, b"x");
+ assert_eq!(r[0], status::BAD_REQUEST);
+ }
+
+ #[test]
+ fn unknown_algorithms_are_unsupported() {
+ let mut v = ready();
+ for algo in [alg::NONE, 2, 0xFF] {
+ assert_eq!(call(&mut v, SIGNER, request::SIGN, algo, b"m").0[0], status::UNSUPPORTED);
+ assert_eq!(call(&mut v, READER, request::PUBLIC_KEY, algo, &[]).0[0], status::UNSUPPORTED);
+ }
+ }
+
+ #[test]
+ fn nothing_is_served_after_zeroize() {
+ let mut v = ready();
+ assert_eq!(call(&mut v, ADMIN_BADGE, request::ZEROIZE, alg::NONE, &[]).0[0], status::OK);
+ let (r, out) = call(&mut v, SIGNER, request::SIGN, alg::ED25519, b"m");
+ assert_eq!(r[0], status::ZEROIZED);
+ assert!(out.is_empty());
+ assert_eq!(call(&mut v, READER, request::PUBLIC_KEY, alg::ED25519, &[]).0[0], status::ZEROIZED);
+ }
+
+ #[test]
+ fn a_small_order_public_key_is_refused_even_with_a_matching_signature() {
+ // 공개키가 항등원이면 R = 항등원, S = 0인 서명이 어떤 메시지에도 등식을
+ // 만족함. 느슨한 검증은 이것을 받아들이므로, 거부된다는 것이 엄격한
+ // 검증을 쓰고 있다는 증거임
+ let mut identity = [0u8; 32];
+ identity[0] = 1;
+ let mut forged = [0u8; 64];
+ forged[0] = 1;
+ let loose = ed25519_dalek::VerifyingKey::from_bytes(&identity).unwrap();
+ assert!(ed25519_dalek::Verifier::verify(&loose, b"m", &ed25519_dalek::Signature::from_bytes(&forged)).is_ok());
+ assert!(!provider::verify(&identity, b"m", &forged));
+ assert!(!provider::verify(&[0xFF; 32], b"m", &[0; 64]));
+ }
+
+ #[test]
+ fn a_failed_vault_refuses_everything_but_status() {
+ let mut v = Vault::failed_for_test();
+ let (r, _) = call(&mut v, SIGNER, request::STATUS, alg::NONE, &[]);
+ assert_eq!((r[0], r[1], r[2]), (status::OK, state::FAILED, 0));
+ assert_eq!(call(&mut v, SIGNER, request::SIGN, alg::ED25519, b"m").0[0], status::FAILED);
+ assert_eq!(call(&mut v, READER, request::PUBLIC_KEY, alg::ED25519, &[]).0[0], status::FAILED);
+ let init = init_body([7; 32], GOOD_INFO);
+ assert_eq!(call(&mut v, ADMIN_BADGE, request::INIT, alg::NONE, &init).0[0], status::FAILED);
+ assert_eq!(call(&mut v, ADMIN_BADGE, request::ZEROIZE, alg::NONE, &[]).0[0], status::FAILED);
+ }
+}
+
+#[cfg(not(feature = "ed25519"))]
+#[test]
+fn without_an_algorithm_every_signing_request_is_unsupported() {
+ let mut v = ready();
+ assert_eq!(call(&mut v, SIGNER, request::SIGN, alg::ED25519, b"m").0[0], status::UNSUPPORTED);
+ assert_eq!(call(&mut v, READER, request::PUBLIC_KEY, alg::ED25519, &[]).0[0], status::UNSUPPORTED);
+ assert_eq!(call(&mut v, READER, request::STATUS, alg::NONE, &[]).0[0], status::OK);
+}
diff --git a/userspace/root-task/Cargo.toml b/userspace/root-task/Cargo.toml
index a697991..fff6685 100644
--- a/userspace/root-task/Cargo.toml
+++ b/userspace/root-task/Cargo.toml
@@ -7,3 +7,10 @@ publish.workspace = true
[dependencies]
k0-abi = { path = "../../crates/k0-abi" }
+k0-vault = { path = "../k0-vault", optional = true }
+
+# 키 볼트(서명 오라클)는 선택 기능입니다. `vault`는 서비스와 그 자가 검증을
+# 넣고, 알고리즘은 따로 더합니다. 아무것도 기본으로 켜지지 않습니다.
+[features]
+vault = ["dep:k0-vault"]
+vault-ed25519 = ["vault", "k0-vault/ed25519"]
diff --git a/userspace/root-task/src/main.rs b/userspace/root-task/src/main.rs
index 5e7bb7a..03661fa 100644
--- a/userspace/root-task/src/main.rs
+++ b/userspace/root-task/src/main.rs
@@ -36,6 +36,9 @@ use core::arch::asm;
use core::panic::PanicInfo;
use core::sync::atomic::{AtomicU64, Ordering};
+#[cfg(feature = "vault")]
+mod oracle;
+
use k0_abi::bootinfo::slot;
use k0_abi::{bootinfo, err, ipc, obj, perm, rights, syscall};
@@ -693,8 +696,37 @@ fn frames_in(d: &bootinfo::CapDesc, frame_size: u64) -> u64 {
if first >= end { 0 } else { (end - first) / frame_size }
}
+/// 커널이 진입 레지스터로 넘긴 부트 시드(워드 넷)와 그 재료 정보
+///
+/// 시드는 서비스(키 볼트)에 넘기기 위한 것이고 루트 태스크는 출력하지
+/// 않습니다. 넘긴 뒤에는 [take_boot_seed]가 이 자리를 지웁니다.
+static BOOT_SEED: [AtomicU64; 4] = [
+ AtomicU64::new(0),
+ AtomicU64::new(0),
+ AtomicU64::new(0),
+ AtomicU64::new(0),
+];
+static SEED_INFO: AtomicU64 = AtomicU64::new(0);
+
+/// 부트 시드를 꺼내고 보관하던 자리를 지우는 함수입니다. 두 번째부터는 0만
+/// 나옵니다.
+#[allow(dead_code)]
+fn take_boot_seed() -> ([u8; 32], u64) {
+ let mut seed = [0u8; 32];
+ for (chunk, word) in seed.chunks_exact_mut(8).zip(&BOOT_SEED) {
+ chunk.copy_from_slice(&word.swap(0, Ordering::Relaxed).to_le_bytes());
+ }
+ (seed, SEED_INFO.load(Ordering::Relaxed))
+}
+
#[unsafe(no_mangle)]
-extern "C" fn _start() -> ! {
+extern "C" fn _start(s0: u64, s1: u64, s2: u64, s3: u64, seed_info: u64) -> ! {
+ // 시드는 레지스터로만 오므로 다른 일을 하기 전에 옮겨 둠
+ for (slot, word) in BOOT_SEED.iter().zip([s0, s1, s2, s3]) {
+ slot.store(word, Ordering::Relaxed);
+ }
+ SEED_INFO.store(seed_info, Ordering::Relaxed);
+
// 출력에도 Console 케이퍼빌리티가 필요함. 고정 슬롯이라 바로 쓸 수 있지만
// 레이아웃 버전이 다르면 그 가정도 믿을 수 없으므로 출력 없이 끝냄
let hdr = bootinfo::VA as *const bootinfo::Header;
@@ -711,6 +743,13 @@ extern "C" fn _start() -> ! {
sys1(syscall::EXIT, 1);
}
put_str("root: hello from EL0\n");
+ // 시드 자체는 찍지 않고 재료만 알림
+ put_str("root: boot seed from rng-seed bytes ");
+ put_hex(seed_info & bootinfo::SEED_RNG_SEED_BYTES);
+ put_str(if seed_info & bootinfo::SEED_RNDR != 0 { " and rndr\n" } else { " without rndr\n" });
+ // 시드를 쓸 서비스가 없는 이미지에서는 보관하지 않고 바로 지움
+ #[cfg(not(feature = "vault"))]
+ let _ = take_boot_seed();
check(
"bootinfo frame size",
frame_size > 0 && frame_size.is_power_of_two(),
@@ -782,6 +821,8 @@ extern "C" fn _start() -> ! {
test_reuse(&b);
test_sched_ipc_fault(&b);
test_isolation(&b);
+ #[cfg(feature = "vault")]
+ oracle::test_oracle(&b);
test_reserve(&b);
put_str("root: sched tests pass\n");
diff --git a/userspace/root-task/src/oracle.rs b/userspace/root-task/src/oracle.rs
new file mode 100644
index 0000000..6f454e1
--- /dev/null
+++ b/userspace/root-task/src/oracle.rs
@@ -0,0 +1,404 @@
+//! 키 볼트(서명 오라클)를 띄우고 검증하는 모듈입니다.
+//!
+//! # Features
+//! 루트 태스크가 볼트 태스크 하나와 클라이언트 태스크들을 각자의 주소 공간에
+//! 만들고, 엔드포인트 하나와 클라이언트마다의 요청 프레임, 응답 프레임으로
+//! 잇습니다. 볼트와 클라이언트의 코드는 이 이미지 안에 있고 프로토콜과 암호
+//! 경계는 `k0-vault` 크레이트에 있습니다.
+//!
+//! 배선이 곧 정책입니다. 클라이언트의 CNode에는 볼트 엔드포인트의 송신 전용
+//! 복사본(배지 포함)과 보고용 엔드포인트만 들어갑니다. 프레임은 루트가 직접
+//! 매핑해 주고 프레임 케이퍼빌리티는 넘기지 않습니다. 요청 프레임은
+//! 클라이언트에 읽기/쓰기, 볼트에 읽기 전용으로, 응답 프레임은 그 반대로
+//! 매핑합니다. 볼트의 스택(키가 사는 곳)은 볼트의 주소 공간에만 있습니다.
+//! 루트 태스크는 이 모든 것을 만든 쪽이므로 격리의 바깥에 있습니다.
+//!
+//! 격리 태스크에는 이미지의 `.data`와 `.bss`가 매핑되지 않으므로, 볼트와
+//! 클라이언트의 진입점에서는 static을 쓰지 않습니다(출력과 `check`도 못 씀).
+//! 결과는 보고용 엔드포인트로 루트에 알립니다.
+
+use k0_vault::proto::{self, alg, request, state, status, MAX_MESSAGE, MAX_RESPONSE, RESPONSE_HEADER};
+use k0_vault::provider;
+use k0_vault::server::{fetch, publish, wipe, Vault};
+
+use super::{
+ call, cap_copy, cap_delete, cap_revoke, check, copy_here, desc, err, frames_in, ipc, make_aspace, map,
+ map_into, obj, perm, put_str, recv, reply_recv, retype, rights, send, take_boot_seed, tcb_configure,
+ tcb_resume, yield_now, Boot, TEST_VA,
+};
+
+/// 볼트와 클라이언트의 스택(각자의 주소 공간에서 같은 VA). 곡선 연산이 깊어
+/// 격리 검증의 한 장짜리 스택으로는 모자람
+const STACK_BASE: u64 = 0x52_0000;
+const STACK_SIZE: u64 = 0x8000;
+/// 볼트가 n번 호출자의 요청 프레임과 응답 프레임을 보는 VA(n = 0은 관리자)
+const VAULT_REQ: u64 = 0x54_0000;
+const VAULT_RESP: u64 = 0x58_0000;
+const FRAME_STEP: u64 = 0x8000;
+/// 클라이언트가 자기 요청 프레임과 응답 프레임을 보는 VA
+const CLIENT_REQ: u64 = VAULT_REQ;
+const CLIENT_RESP: u64 = VAULT_RESP;
+/// 루트가 관리자용 프레임과, 회수한 메모리를 다시 볼 때 쓰는 VA
+const ROOT_REQ: u64 = TEST_VA + 0x64 * 0x4000;
+const ROOT_RESP: u64 = ROOT_REQ + 0x4000;
+const ROOT_PEEK: u64 = ROOT_REQ + 0x8000;
+
+/// 클라이언트가 볼트를 기다리는 한도(틱)
+const WAIT: u64 = ipc::timeout(4);
+/// 클라이언트의 보고가 성공임을 뜻하는 값
+const REPORT_OK: u64 = 0x0C;
+const REPORT_TAG: u64 = 0x0AC1E;
+
+/// 클라이언트가 하는 일
+const MODE_SIGNER: u64 = 0;
+const MODE_READER: u64 = 1;
+const MODE_WRITE_RESPONSE: u64 = 2;
+const MODE_READ_FOREIGN: u64 = 3;
+const MODE_AFTER_ZEROIZE: u64 = 4;
+
+/// 볼트 태스크의 진입점입니다.
+///
+/// 자가 시험을 돌린 뒤 요청을 하나씩 처리합니다. 요청 본문은 호출자의 요청
+/// 프레임에서 한 번만 옮겨 오고, 응답 본문은 성공했을 때만 그 호출자의 응답
+/// 프레임에 씁니다. 응답 레지스터 네 개는 항상 전부 채웁니다.
+extern "C" fn vault_entry(_arg: u64) -> ! {
+ let mut vault = Vault::new();
+ let mut body = [0u8; MAX_MESSAGE];
+ let mut out = [0u8; MAX_RESPONSE];
+ let mut r = recv(1, 0);
+ loop {
+ if r.status != 0 {
+ // 엔드포인트가 사라졌으면 할 일이 없음
+ loop {
+ yield_now();
+ }
+ }
+ let reply = match proto::role_of(r.badge) {
+ Some((_, index)) => {
+ let req = (VAULT_REQ + index * FRAME_STEP) as *const u8;
+ // SAFETY: 루트가 이 호출자의 요청 프레임을 이 VA에 읽기 전용으로
+ // 매핑해 두었고 버퍼는 프레임보다 작음
+ let n = unsafe { fetch(req, r.mr[1], &mut body) };
+ let reply = vault.handle(r.badge, r.mr, &body[..n], &mut out);
+ wipe(&mut body[..n]);
+ if reply[0] == status::OK && r.mr[0] & 0xFF != request::STATUS {
+ let resp = (VAULT_RESP + index * FRAME_STEP) as *mut u8;
+ let len = (reply[1] as usize).min(MAX_RESPONSE);
+ // SAFETY: 루트가 이 호출자의 응답 프레임을 이 VA에 쓰기
+ // 가능으로 매핑해 두었고 프레임은 정렬돼 있음
+ unsafe { publish(resp, r.mr[2], &out[..len]) };
+ }
+ reply
+ }
+ None => vault.handle(r.badge, r.mr, &[], &mut out),
+ };
+ r = reply_recv(1, 0, reply);
+ }
+}
+
+/// 응답 프레임에서 본문을 읽는 함수입니다. 프레임의 일회용 번호가 자기
+/// 번호와 다르거나 길이가 맞지 않으면 `false`
+fn read_response(nonce: u64, want: &mut [u8]) -> bool {
+ let frame = CLIENT_RESP as *const u8;
+ // SAFETY: 루트가 이 VA에 응답 프레임을 읽기 전용으로 매핑해 두었음
+ unsafe {
+ if frame.cast::().read_volatile() != nonce
+ || frame.add(8).cast::().read_volatile() != want.len() as u64
+ {
+ return false;
+ }
+ for (i, b) in want.iter_mut().enumerate() {
+ *b = frame.add(RESPONSE_HEADER + i).read_volatile();
+ }
+ }
+ true
+}
+
+/// 요청 프레임에 메시지를 쓰는 함수입니다.
+fn write_request(msg: &[u8]) {
+ for (i, b) in msg.iter().enumerate() {
+ // SAFETY: 루트가 이 VA에 요청 프레임을 쓰기 가능으로 매핑해 두었음
+ unsafe { (CLIENT_REQ as *mut u8).add(i).write_volatile(*b) };
+ }
+}
+
+/// 볼트를 한 번 호출하는 함수입니다. 응답이 번호를 그대로 돌려주지 않으면
+/// 상태를 믿지 않습니다.
+fn ask(op: u64, algo: u64, len: u64, nonce: u64) -> (u64, u64, u64) {
+ let r = call(1, WAIT, [request::word(op, algo), len, nonce, 0]);
+ if r.status != 0 || r.mr[3] != nonce {
+ return (u64::MAX, 0, 0);
+ }
+ (r.mr[0], r.mr[1], r.mr[2])
+}
+
+/// 서명 클라이언트의 정상 경로 함수입니다. 실패한 단계의 번호를 주고 전부
+/// 통과하면 0
+fn signer_path() -> u64 {
+ let (st, vault_state, _) = ask(request::STATUS, alg::NONE, 0, 1);
+ if st != status::OK || vault_state != state::READY {
+ return 1;
+ }
+ let msg = b"k0 signing oracle self test message";
+ write_request(msg);
+ if !provider::HAS_ED25519 {
+ // 알고리즘 없이 빌드한 이미지: 서명과 공개키는 지원하지 않음으로 거부
+ let unsupported = ask(request::SIGN, alg::ED25519, msg.len() as u64, 2).0 == status::UNSUPPORTED
+ && ask(request::PUBLIC_KEY, alg::ED25519, 0, 3).0 == status::UNSUPPORTED;
+ return if unsupported { 0 } else { 2 };
+ }
+ let mut public = [0u8; provider::PUBLIC_KEY_LEN];
+ if ask(request::PUBLIC_KEY, alg::ED25519, 0, 2).0 != status::OK || !read_response(2, &mut public) {
+ return 3;
+ }
+ let mut sig = [0u8; provider::SIGNATURE_LEN];
+ if ask(request::SIGN, alg::ED25519, msg.len() as u64, 3).0 != status::OK || !read_response(3, &mut sig) {
+ return 4;
+ }
+ if !provider::verify(&public, msg, &sig) {
+ return 5;
+ }
+ // 한 글자 다른 메시지와 한 비트 다른 서명은 검증되지 않아야 함
+ let mut other = *msg;
+ other[0] ^= 1;
+ let mut bad = sig;
+ bad[10] ^= 4;
+ if provider::verify(&public, &other, &sig) || provider::verify(&public, msg, &bad) {
+ return 6;
+ }
+ // 길이를 프레임보다 크게 말하거나 모르는 알고리즘을 대면 거부됨
+ if ask(request::SIGN, alg::ED25519, MAX_MESSAGE as u64 + 1, 4).0 != status::BAD_REQUEST
+ || ask(request::SIGN, 9, 1, 5).0 != status::UNSUPPORTED
+ || ask(request::INIT, alg::NONE, 0, 6).0 != status::DENIED
+ || ask(request::ZEROIZE, alg::NONE, 0, 7).0 != status::DENIED
+ {
+ return 7;
+ }
+ 0
+}
+
+/// 클라이언트 태스크의 진입점입니다. 1번 슬롯이 볼트, 2번 슬롯이 보고용
+/// 엔드포인트입니다.
+///
+/// # Arguments
+/// `mode` - 할 일(`MODE_*`)
+extern "C" fn client_entry(mode: u64) -> ! {
+ let failed = match mode {
+ MODE_SIGNER => signer_path(),
+ MODE_READER => {
+ let key_ok = if provider::HAS_ED25519 {
+ let mut public = [0u8; provider::PUBLIC_KEY_LEN];
+ ask(request::PUBLIC_KEY, alg::ED25519, 0, 1).0 == status::OK && read_response(1, &mut public)
+ } else {
+ true
+ };
+ // 공개키는 받지만 서명은 이 배지에 허용되지 않음
+ let denied = ask(request::SIGN, alg::ED25519, 1, 2).0 == status::DENIED;
+ u64::from(!(key_ok && denied))
+ }
+ MODE_WRITE_RESPONSE => {
+ // 응답 프레임은 클라이언트에 읽기 전용이라 쓰면 이 태스크가 종료됨
+ // SAFETY: 의도된 위반
+ unsafe { (CLIENT_RESP as *mut u64).write_volatile(0xBAD) };
+ 9
+ }
+ MODE_READ_FOREIGN => {
+ // 볼트가 다른 호출자의 요청 프레임을 보는 자리는 이 주소 공간에
+ // 매핑돼 있지 않아 읽으면 이 태스크가 종료됨
+ // SAFETY: 의도된 위반
+ let leaked = unsafe { ((VAULT_REQ + FRAME_STEP) as *const u64).read_volatile() };
+ 9 + (leaked & 1)
+ }
+ _ => {
+ let gone = !provider::HAS_ED25519
+ || (ask(request::SIGN, alg::ED25519, 1, 1).0 == status::ZEROIZED
+ && ask(request::PUBLIC_KEY, alg::ED25519, 0, 2).0 == status::ZEROIZED);
+ u64::from(!gone)
+ }
+ };
+ let code = if failed == 0 { REPORT_OK } else { 0xF0 + failed };
+ send(2, 0, [code, REPORT_TAG, mode, 0]);
+ loop {
+ yield_now();
+ }
+}
+
+/// 이 검증이 쓸 untyped를 고르는 함수입니다. 다른 검증이 쓰지 않는 것 중 가장
+/// 큰 것이고, 그런 것이 없으면 0
+fn spare_untyped(b: &Boot) -> u64 {
+ // SAFETY: 커널이 이 VA에 bootinfo 페이지를 RO로 매핑하고 내용을 채웠음
+ let cap_count = unsafe { (*(super::bootinfo::VA as *const super::bootinfo::Header)).cap_count };
+ let (mut best, mut best_frames) = (0, 0);
+ for i in 0..cap_count {
+ let d = desc(i);
+ if d.kind != super::bootinfo::cap_kind::UNTYPED || i == b.ut_main || i == b.ut_small || i == b.ut_reuse {
+ continue;
+ }
+ let n = frames_in(d, b.frame_size);
+ if n >= 512 && n > best_frames {
+ best = i;
+ best_frames = n;
+ }
+ }
+ best
+}
+
+/// 주소 공간 하나와 그 안의 스택을 만드는 함수입니다. 주소 공간 슬롯을 줍니다.
+fn make_space(ut: u64, b: &Boot) -> i64 {
+ let (aspace, _) = make_aspace(ut, b);
+ let mut va = STACK_BASE;
+ while va < STACK_BASE + STACK_SIZE {
+ let f = retype(ut, obj::FRAME);
+ check("oracle stack", f > 0 && map_into(f, va, perm::RW, aspace) == 0);
+ va += b.frame_size;
+ }
+ aspace
+}
+
+/// 프레임 하나를 만들어 한쪽에는 쓰기 가능으로, 다른 쪽에는 읽기 전용으로
+/// 매핑하는 함수입니다. 읽기 쪽에는 권한을 줄인 복사본을 써서, 그 매핑을
+/// 쓰기 가능으로 바꿀 길이 없게 합니다.
+///
+/// # Arguments
+/// `rw` - (주소 공간 슬롯, VA). 주소 공간이 0이면 루트 자신
+/// `ro` - 읽기 전용으로 볼 쪽
+fn link(ut: u64, rw: (i64, u64), ro: (i64, u64)) {
+ let frame = retype(ut, obj::FRAME);
+ let view = copy_here(frame, rights::R, 0);
+ check("oracle frame", frame > 0 && view > 0);
+ let put = |cap: i64, (aspace, va): (i64, u64), p: u64| {
+ if aspace == 0 { map(cap, va, p) } else { map_into(cap, va, p, aspace) }
+ };
+ check("oracle frame rw", put(frame, rw, perm::RW) == 0);
+ check("oracle frame ro", put(view, ro, perm::RO) == 0);
+}
+
+/// 태스크 하나를 만들어 실행 대기 상태로 만드는 함수입니다. TCB 슬롯을 줍니다.
+fn spawn(ut: u64, aspace: i64, entry: u64, arg: u64, caps: &[(i64, u64, u64)]) -> i64 {
+ let cnode = retype(ut, obj::CNODE);
+ check("oracle cnode", cnode > 0);
+ for (i, &(src, mask, badge)) in caps.iter().enumerate() {
+ check("oracle grant", cap_copy(src, cnode, 1 + i as u64, mask, badge) == 0);
+ }
+ let tcb = retype(ut, obj::TCB);
+ check(
+ "oracle task",
+ tcb > 0
+ && tcb_configure(tcb, entry, STACK_BASE + STACK_SIZE, aspace, cnode, arg) == 0
+ && tcb_resume(tcb) == 0,
+ );
+ tcb
+}
+
+/// 클라이언트 태스크 하나를 클라이언트 주소 공간에 만드는 함수입니다. TCB
+/// 슬롯을 줍니다.
+///
+/// 루트 CNode의 슬롯을 아끼려고 클라이언트들은 주소 공간과 스택, 프레임 한
+/// 쌍을 차례로 물려 씁니다. 그래서 한 번에 하나만 살아 있어야 하고, 호출자는
+/// 다음 클라이언트를 만들기 전에 앞의 것을 삭제합니다. 여기서 보려는 것은
+/// 클라이언트와 볼트 사이의 격리입니다(클라이언트끼리의 격리는 격리 검증이
+/// 이미 다룸).
+fn client(ut: u64, space: i64, ep: i64, report: i64, badge: u64, mode: u64) -> i64 {
+ spawn(ut, space, client_entry as usize as u64, mode, &[(ep, rights::W, badge), (report, rights::W, 0)])
+}
+
+/// 서명 오라클을 띄우고 검증하는 함수입니다.
+pub fn test_oracle(b: &Boot) {
+ let spare = spare_untyped(b);
+ let ut = if spare != 0 { spare } else { b.ut_main };
+ let (ep, report) = (retype(ut, obj::ENDPOINT), retype(ut, obj::ENDPOINT));
+ check("oracle endpoints", ep > 0 && report > 0);
+
+ // 볼트: 자기 주소 공간, 스택, 수신 전용 엔드포인트. 관리자(루트)의 프레임 둘
+ let vault_space = make_space(ut, b);
+ link(ut, (0, ROOT_REQ), (vault_space, VAULT_REQ));
+ link(ut, (vault_space, VAULT_RESP), (0, ROOT_RESP));
+ let vault_tcb = spawn(ut, vault_space, vault_entry as usize as u64, 0, &[(ep, rights::R, 0)]);
+ let admin = copy_here(ep, rights::W, proto::ADMIN_BADGE);
+ check("oracle admin cap", admin > 0);
+ let ask = |cap: i64, op: u64, len: u64, nonce: u64| {
+ let r = call(cap, WAIT, [request::word(op, alg::NONE), len, nonce, 0]);
+ (if r.status == 0 && r.mr[3] == nonce { r.mr[0] } else { u64::MAX }, r.mr[1], r.mr[2])
+ };
+
+ // 자가 시험을 통과한 볼트는 아직 키가 없는 상태임. 배지 없는 호출은 거부됨
+ let (st, vault_state, ind) = ask(admin, request::STATUS, 0, 1);
+ check("vault self test", st == status::OK && vault_state == state::FRESH);
+ check("vault self test indicator", ind == proto::indicator::SELF_TEST_PASSED);
+ check("call without a badge refused", ask(ep, request::STATUS, 0, 2).0 == status::DENIED);
+
+ // 커널이 준 부트 시드를 관리자 프레임으로 넘겨 키를 만들게 하고, 루트 쪽
+ // 사본은 지움. 재료가 모자란 시드로는 볼트가 키를 만들지 않음
+ let (mut seed, info) = take_boot_seed();
+ for (i, byte) in seed.iter().chain(&info.to_le_bytes()).enumerate() {
+ // SAFETY: 방금 이 VA에 관리자 요청 프레임을 쓰기 가능으로 매핑했음
+ unsafe { (ROOT_REQ as *mut u8).add(i).write_volatile(*byte) };
+ }
+ wipe(&mut seed);
+ let init = ask(admin, request::INIT, proto::INIT_LEN as u64, 3).0;
+ for i in 0..proto::INIT_LEN {
+ // SAFETY: 위와 같음
+ unsafe { (ROOT_REQ as *mut u8).add(i).write_volatile(0) };
+ }
+ if init == status::NO_ENTROPY {
+ check("no key without entropy", ask(admin, request::STATUS, 0, 4).1 == state::FRESH);
+ check("cleanup", cap_delete(vault_tcb) == 0);
+ put_str("root: oracle made no key (boot seed has no entropy)\n");
+ return;
+ }
+ check("vault key made", init == status::OK);
+ check("second init refused", ask(admin, request::INIT, proto::INIT_LEN as u64, 5).0 == status::DENIED);
+ check("admin cannot sign", ask(admin, request::SIGN, 1, 6).0 == status::DENIED);
+
+ // 클라이언트들의 주소 공간과 1번 호출자의 프레임 한 쌍
+ let space = make_space(ut, b);
+ link(ut, (space, CLIENT_REQ), (vault_space, VAULT_REQ + FRAME_STEP));
+ link(ut, (vault_space, VAULT_RESP + FRAME_STEP), (space, CLIENT_RESP));
+ // 보고하는 클라이언트는 보고를 받은 뒤에, 위반하는 클라이언트는 보고 없이
+ // 종료된 것을 확인한 뒤에 삭제함
+ let reports = |mode: u64, badge: u64| {
+ let tcb = client(ut, space, ep, report, badge, mode);
+ let r = recv(report, ipc::timeout(8));
+ check("oracle client report", r.status == 0 && r.mr == [REPORT_OK, REPORT_TAG, mode, 0]);
+ check("oracle client delete", cap_delete(tcb) == 0);
+ };
+ let dies = |mode: u64| {
+ let tcb = client(ut, space, ep, report, proto::signer_badge(1), mode);
+ for _ in 0..8 {
+ yield_now();
+ }
+ check("violator stayed silent", recv(report, ipc::NONBLOCK).status == err::WOULD_BLOCK);
+ check("violator is dead", tcb_resume(tcb) == err::BAD_STATE);
+ check("oracle client delete", cap_delete(tcb) == 0);
+ };
+ reports(MODE_SIGNER, proto::signer_badge(1));
+ reports(MODE_READER, proto::reader_badge(1));
+ dies(MODE_WRITE_RESPONSE);
+ dies(MODE_READ_FOREIGN);
+
+ // 관리자가 키를 지우게 하면 볼트는 더는 서명하지 않음
+ check("zeroize", ask(admin, request::ZEROIZE, 0, 7).0 == status::OK);
+ check("vault zeroized", ask(admin, request::STATUS, 0, 8).1 == state::ZEROIZED);
+ reports(MODE_AFTER_ZEROIZE, proto::signer_badge(1));
+
+ // 볼트가 사라진 뒤의 호출은 영원히 기다리지 않고 기한에 끝남
+ check("delete vault", cap_delete(vault_tcb) == 0);
+ let r = call(admin, ipc::timeout(1), [request::word(request::STATUS, alg::NONE), 0, 9, 0]);
+ check("call to a dead vault ends", r.status == err::TIMEOUT);
+
+ // 볼트와 클라이언트가 쓰던 메모리를 통째로 회수해 다시 재분류하면 전부
+ // 0으로 읽힘. 다른 검증과 untyped를 나눠 쓰는 배치에서는 회수할 수 없음
+ if spare != 0 {
+ check("revoke oracle memory", cap_revoke(ut as i64) == 0);
+ for _ in 0..(4 * STACK_SIZE / b.frame_size) {
+ let f = retype(ut, obj::FRAME);
+ check("oracle memory again", f > 0 && map(f, ROOT_PEEK, perm::RO) == 0);
+ let words = (b.frame_size / 8) as usize;
+ // SAFETY: 방금 이 VA에 프레임 하나를 읽기 전용으로 매핑했음
+ let clean = (0..words).all(|i| unsafe { (ROOT_PEEK as *const u64).add(i).read_volatile() } == 0);
+ check("oracle memory zeroed", clean);
+ check("oracle peek unmap", super::unmap(f) == 0);
+ }
+ }
+ put_str("root: oracle tests pass\n");
+}
diff --git a/vendor/curve25519-dalek-derive/.cargo-checksum.json b/vendor/curve25519-dalek-derive/.cargo-checksum.json
new file mode 100644
index 0000000..d374d62
--- /dev/null
+++ b/vendor/curve25519-dalek-derive/.cargo-checksum.json
@@ -0,0 +1 @@
+{"files":{".cargo_vcs_info.json":"ab1c53ad220b9c6160b8be8873451d0994ec96a4bb56dadd67a203692a07c7c8","CHANGELOG.md":"2996880440a6a5bcad117d8beea9ae3508ae2707c9a040949d4264bdbe33ed6c","Cargo.toml":"60d2093fbabea9e72ad1350ae4a616ae56b2592742a64d2bd679a749f7a6bb4d","Cargo.toml.orig":"efa463b38c5cd2d4abd159ad29afdd39dca6f0531dd1dc1aca9d8632756f36c7","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"45733d1932bfa409c51cf7fd54cb830e2932a145bdaa50b8ef23d19080f907b9","src/lib.rs":"fb56c338b6294eb1cfc91c3561c2cb01a5a56305dbf0957d5c34fa8927f23895","tests/tests.rs":"af971f447f55e412bdd9de51eb37ec166141f1e49d42ffe2e1ba890a507d59be"},"package":"f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"}
\ No newline at end of file
diff --git a/vendor/curve25519-dalek-derive/.cargo_vcs_info.json b/vendor/curve25519-dalek-derive/.cargo_vcs_info.json
new file mode 100644
index 0000000..7c8f802
--- /dev/null
+++ b/vendor/curve25519-dalek-derive/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "72761ca6b4772af985f969db53faf7accbad9b36"
+ },
+ "path_in_vcs": "curve25519-dalek-derive"
+}
\ No newline at end of file
diff --git a/vendor/curve25519-dalek-derive/CHANGELOG.md b/vendor/curve25519-dalek-derive/CHANGELOG.md
new file mode 100644
index 0000000..8a0915b
--- /dev/null
+++ b/vendor/curve25519-dalek-derive/CHANGELOG.md
@@ -0,0 +1,8 @@
+# Changelog
+
+Entries are listed in reverse chronological order per undeprecated
+major series.
+
+### 0.1.1
+
+* Copied over license files from [original](https://github.com/koute/unsafe_target_feature/tree/389ae00d34cf0ff589cb8d9b38a85ae1b05ebfdc) repo
diff --git a/vendor/curve25519-dalek-derive/Cargo.toml b/vendor/curve25519-dalek-derive/Cargo.toml
new file mode 100644
index 0000000..b013ebb
--- /dev/null
+++ b/vendor/curve25519-dalek-derive/Cargo.toml
@@ -0,0 +1,34 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+name = "curve25519-dalek-derive"
+version = "0.1.1"
+description = "curve25519-dalek Derives"
+homepage = "https://github.com/dalek-cryptography/curve25519-dalek"
+documentation = "https://docs.rs/curve25519-dalek-derive"
+readme = "README.md"
+license = "MIT/Apache-2.0"
+repository = "https://github.com/dalek-cryptography/curve25519-dalek"
+
+[lib]
+proc-macro = true
+
+[dependencies.proc-macro2]
+version = "1.0.66"
+
+[dependencies.quote]
+version = "1.0.31"
+
+[dependencies.syn]
+version = "2.0.27"
+features = ["full"]
diff --git a/vendor/curve25519-dalek-derive/Cargo.toml.orig b/vendor/curve25519-dalek-derive/Cargo.toml.orig
new file mode 100644
index 0000000..938144a
--- /dev/null
+++ b/vendor/curve25519-dalek-derive/Cargo.toml.orig
@@ -0,0 +1,19 @@
+[package]
+name = "curve25519-dalek-derive"
+version = "0.1.1"
+edition = "2021"
+
+repository = "https://github.com/dalek-cryptography/curve25519-dalek"
+homepage = "https://github.com/dalek-cryptography/curve25519-dalek"
+documentation = "https://docs.rs/curve25519-dalek-derive"
+license = "MIT/Apache-2.0"
+readme = "README.md"
+description = "curve25519-dalek Derives"
+
+[lib]
+proc-macro = true
+
+[dependencies]
+proc-macro2 = "1.0.66"
+quote = "1.0.31"
+syn = { version = "2.0.27", features = ["full"] }
diff --git a/vendor/curve25519-dalek-derive/LICENSE-APACHE b/vendor/curve25519-dalek-derive/LICENSE-APACHE
new file mode 100644
index 0000000..16fe87b
--- /dev/null
+++ b/vendor/curve25519-dalek-derive/LICENSE-APACHE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/vendor/curve25519-dalek-derive/LICENSE-MIT b/vendor/curve25519-dalek-derive/LICENSE-MIT
new file mode 100644
index 0000000..31aa793
--- /dev/null
+++ b/vendor/curve25519-dalek-derive/LICENSE-MIT
@@ -0,0 +1,23 @@
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/vendor/curve25519-dalek-derive/README.md b/vendor/curve25519-dalek-derive/README.md
new file mode 100644
index 0000000..69bde71
--- /dev/null
+++ b/vendor/curve25519-dalek-derive/README.md
@@ -0,0 +1,198 @@
+# A more convenient `#[target_feature]` replacement
+
+To get good performance out of SIMD everything on the SIMD codepath must be inlined.
+With how SIMD is currently implemented in Rust one of two things have to be true for
+a function using SIMD to be inlinable: (and this includes the SIMD intrinsics themselves)
+
+ a) The whole program has to be compiled with the relevant `-C target-cpu` or `-C target-feature` flags.
+
+ b) SIMD support must be automatically detected at runtime, and every function on the SIMD codepath must be marked with `#[target_feature]`.
+
+Both have their downsides. Setting the `target-cpu` or `target-features` makes the resulting binary
+incompatible with older CPUs, while using `#[target_feature]` is incredibly inconvenient.
+
+This crate is meant to make `#[target_feature]` less painful to use.
+
+## Problems with `#[target_feature]`
+
+When we're not compiling with the relevant `target-cpu`/`target-feature` flags everything on
+the SIMD codepath must be marked with the `#[target_feature]` attribute. This is not a problem
+when all of your SIMD code is neatly encapsulated inside of a single function, but once you start
+to build out more elaborate abstractions it starts to become painful to use.
+
+ * It can only be used on `unsafe` functions, so everything on your SIMD codepath now has to be `unsafe`.
+
+ In theory this is nice - these functions require the relevant SIMD instructions to be present at runtime,
+ so calling them without checking is obviously unsafe! But in practice this is rarely what you want. When
+ you build an abstraction over SIMD code you usually want to assume that *internally* within your module
+ all of the necessary SIMD instructions are available, and you only want to check this at the boundaries
+ when you're first entering your module. You do *not* want to infect everything *inside* of the module with
+ `unsafe` since you've already checked this invariant at the module's API boundary.
+
+ * It cannot be used on non-`unsafe` trait methods.
+
+ If you're implementing a trait, say for example `std::ops::Add`, then you cannot mark the method `unsafe`
+ unless the original trait also has it marked as `unsafe`, and usually it doesn't.
+
+ * It makes it impossible to abstract over a given SIMD instruction set using a trait.
+
+ For example, let's assume you want to abstract over which SIMD instructions you use using a trait in the following way:
+
+ ```rust
+ trait Backend {
+ unsafe fn sum(input: &[u32]) -> u32;
+ }
+
+ struct AVX;
+ # #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
+ impl Backend for AVX {
+ #[target_feature(enable = "avx")]
+ unsafe fn sum(xs: &[u32]) -> u32 {
+ // ...
+ todo!();
+ }
+ }
+
+ struct AVX2;
+ # #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
+ impl Backend for AVX2 {
+ #[target_feature(enable = "avx2")]
+ unsafe fn sum(xs: &[u32]) -> u32 {
+ // ...
+ todo!();
+ }
+ }
+
+ // And now you want a have function which calls into that trait:
+ unsafe fn do_calculations(xs: &[u32]) -> u32 where B: Backend {
+ let value = B::sum(xs);
+ // ...do some more calculations here...
+ value
+ }
+ ```
+
+ We have a problem here. This has to be marked with `#[target_feature]`, and that has to specify the concrete
+ feature flag for a given SIMD instruction set, but this function is generic so we can't do that!
+
+## How does this crate make it better?
+
+### You can now mark safe functions with `#[target_feature]`
+
+This crate exposes an `#[unsafe_target_feature]` macro which works just like `#[target_feature]` except
+it moves the `unsafe` from the function prototype into the macro name, and can be used on safe functions.
+
+```rust,compile_fail
+// ERROR: `#[target_feature(..)]` can only be applied to `unsafe` functions
+#[target_feature(enable = "avx2")]
+fn func() {}
+```
+
+```rust
+// It works, but must be `unsafe`
+# #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
+#[target_feature(enable = "avx2")]
+unsafe fn func() {}
+```
+
+```rust
+use curve25519_dalek_derive::unsafe_target_feature;
+
+// No `unsafe` on the function itself!
+# #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
+#[unsafe_target_feature("avx2")]
+fn func() {}
+```
+
+It can also be used to mark functions inside of impls:
+
+```rust,compile_fail
+struct S;
+
+impl core::ops::Add for S {
+ type Output = S;
+ // ERROR: method `add` has an incompatible type for trait
+ #[target_feature(enable = "avx2")]
+ unsafe fn add(self, rhs: S) -> S {
+ S
+ }
+}
+```
+
+```rust
+use curve25519_dalek_derive::unsafe_target_feature;
+
+struct S;
+
+# #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
+#[unsafe_target_feature("avx2")]
+impl core::ops::Add for S {
+ type Output = S;
+ // No `unsafe` on the function itself!
+ fn add(self, rhs: S) -> S {
+ S
+ }
+}
+
+```
+
+### You can generate specialized copies of a module for each target feature
+
+```rust
+use curve25519_dalek_derive::unsafe_target_feature_specialize;
+
+# #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
+#[unsafe_target_feature_specialize("sse2", "avx2", conditional("avx512ifma", nightly))]
+mod simd {
+ #[for_target_feature("sse2")]
+ pub const CONSTANT: u32 = 1;
+
+ #[for_target_feature("avx2")]
+ pub const CONSTANT: u32 = 2;
+
+ #[for_target_feature("avx512ifma")]
+ pub const CONSTANT: u32 = 3;
+
+ pub fn func() { /* ... */ }
+}
+
+# #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
+fn entry_point() {
+ #[cfg(nightly)]
+ if std::is_x86_feature_detected!("avx512ifma") {
+ return simd_avx512ifma::func();
+ }
+
+ if std::is_x86_feature_detected!("avx2") {
+ return simd_avx2::func();
+ }
+
+ if std::is_x86_feature_detected!("sse2") {
+ return simd_sse2::func();
+ }
+
+ unimplemented!();
+}
+```
+
+## How to use `#[unsafe_target_feature]`?
+
+ - Can be used on `fn`s, `impl`s and `mod`s.
+ - When used on a function will only apply to that function; it won't apply to any nested functions, traits, mods, etc.
+ - When used on an `impl` will only apply to all of the functions directly defined inside of that `impl`.
+ - When used on a `mod` will only apply to all of the `fn`s and `impl`s directly defined inside of that `mod`.
+ - Cannot be used on methods which use `self` or `Self`; instead use it on the `impl` in which the method is defined.
+
+## License
+
+Licensed under either of
+
+ * Apache License, Version 2.0, [LICENSE-APACHE](LICENSE-APACHE)
+ * MIT license ([LICENSE-MIT](LICENSE-MIT))
+
+at your option.
+
+### Contribution
+
+Unless you explicitly state otherwise, any contribution intentionally submitted
+for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
+dual licensed as above, without any additional terms or conditions.
diff --git a/vendor/curve25519-dalek-derive/src/lib.rs b/vendor/curve25519-dalek-derive/src/lib.rs
new file mode 100644
index 0000000..6e5920b
--- /dev/null
+++ b/vendor/curve25519-dalek-derive/src/lib.rs
@@ -0,0 +1,466 @@
+#![doc = include_str!("../README.md")]
+
+use proc_macro::TokenStream;
+use proc_macro2::TokenStream as TokenStream2;
+use syn::spanned::Spanned;
+
+macro_rules! unsupported_if_some {
+ ($value:expr) => {
+ if let Some(value) = $value {
+ return syn::Error::new(value.span(), "unsupported by #[unsafe_target_feature(...)]")
+ .into_compile_error()
+ .into();
+ }
+ };
+}
+
+macro_rules! unsupported {
+ ($value: expr) => {
+ return syn::Error::new(
+ $value.span(),
+ "unsupported by #[unsafe_target_feature(...)]",
+ )
+ .into_compile_error()
+ .into()
+ };
+}
+
+mod kw {
+ syn::custom_keyword!(conditional);
+}
+
+enum SpecializeArg {
+ LitStr(syn::LitStr),
+ Conditional(Conditional),
+}
+
+impl SpecializeArg {
+ fn lit(&self) -> &syn::LitStr {
+ match self {
+ SpecializeArg::LitStr(lit) => lit,
+ SpecializeArg::Conditional(conditional) => &conditional.lit,
+ }
+ }
+
+ fn condition(&self) -> Option<&TokenStream2> {
+ match self {
+ SpecializeArg::LitStr(..) => None,
+ SpecializeArg::Conditional(conditional) => Some(&conditional.attr),
+ }
+ }
+}
+
+struct Conditional {
+ lit: syn::LitStr,
+ attr: TokenStream2,
+}
+
+impl syn::parse::Parse for Conditional {
+ fn parse(input: syn::parse::ParseStream) -> syn::Result {
+ let lit = input.parse()?;
+ input.parse::()?;
+ let attr = input.parse()?;
+
+ Ok(Conditional { lit, attr })
+ }
+}
+
+impl syn::parse::Parse for SpecializeArg {
+ fn parse(input: syn::parse::ParseStream) -> syn::Result {
+ let lookahead = input.lookahead1();
+ if lookahead.peek(kw::conditional) {
+ input.parse::()?;
+
+ let content;
+ syn::parenthesized!(content in input);
+
+ let conditional = content.parse()?;
+ Ok(SpecializeArg::Conditional(conditional))
+ } else {
+ Ok(SpecializeArg::LitStr(input.parse()?))
+ }
+ }
+}
+
+struct SpecializeArgs(syn::punctuated::Punctuated);
+
+impl syn::parse::Parse for SpecializeArgs {
+ fn parse(input: syn::parse::ParseStream) -> syn::Result {
+ Ok(Self(syn::punctuated::Punctuated::parse_terminated(input)?))
+ }
+}
+
+#[proc_macro_attribute]
+pub fn unsafe_target_feature(attributes: TokenStream, input: TokenStream) -> TokenStream {
+ let attributes = syn::parse_macro_input!(attributes as syn::LitStr);
+ let item = syn::parse_macro_input!(input as syn::Item);
+ process_item(&attributes, item, true)
+}
+
+#[proc_macro_attribute]
+pub fn unsafe_target_feature_specialize(
+ attributes: TokenStream,
+ input: TokenStream,
+) -> TokenStream {
+ let attributes = syn::parse_macro_input!(attributes as SpecializeArgs);
+ let item_mod = syn::parse_macro_input!(input as syn::ItemMod);
+
+ let mut out = Vec::new();
+ for attributes in attributes.0 {
+ let features: Vec<_> = attributes
+ .lit()
+ .value()
+ .split(',')
+ .map(|feature| feature.replace(' ', ""))
+ .collect();
+ let name = format!("{}_{}", item_mod.ident, features.join("_"));
+ let ident = syn::Ident::new(&name, item_mod.ident.span());
+ let mut attrs = item_mod.attrs.clone();
+ if let Some(condition) = attributes.condition() {
+ attrs.push(syn::Attribute {
+ pound_token: Default::default(),
+ style: syn::AttrStyle::Outer,
+ bracket_token: Default::default(),
+ meta: syn::Meta::List(syn::MetaList {
+ path: syn::Ident::new("cfg", attributes.lit().span()).into(),
+ delimiter: syn::MacroDelimiter::Paren(Default::default()),
+ tokens: condition.clone(),
+ }),
+ });
+ }
+
+ let item_mod = process_mod(
+ attributes.lit(),
+ syn::ItemMod {
+ attrs,
+ ident,
+ ..item_mod.clone()
+ },
+ Some(features),
+ );
+
+ out.push(item_mod);
+ }
+
+ quote::quote! {
+ #(#out)*
+ }
+ .into()
+}
+
+fn process_item(attributes: &syn::LitStr, item: syn::Item, strict: bool) -> TokenStream {
+ match item {
+ syn::Item::Fn(function) => process_function(attributes, function, None),
+ syn::Item::Impl(item_impl) => process_impl(attributes, item_impl),
+ syn::Item::Mod(item_mod) => process_mod(attributes, item_mod, None).into(),
+ item => {
+ if strict {
+ unsupported!(item)
+ } else {
+ quote::quote! { #item }.into()
+ }
+ }
+ }
+}
+
+fn process_mod(
+ attributes: &syn::LitStr,
+ mut item_mod: syn::ItemMod,
+ spec_features: Option>,
+) -> TokenStream2 {
+ if let Some((_, ref mut content)) = item_mod.content {
+ 'next_item: for item in content {
+ if let Some(ref spec_features) = spec_features {
+ match item {
+ syn::Item::Const(syn::ItemConst { ref mut attrs, .. })
+ | syn::Item::Enum(syn::ItemEnum { ref mut attrs, .. })
+ | syn::Item::ExternCrate(syn::ItemExternCrate { ref mut attrs, .. })
+ | syn::Item::Fn(syn::ItemFn { ref mut attrs, .. })
+ | syn::Item::ForeignMod(syn::ItemForeignMod { ref mut attrs, .. })
+ | syn::Item::Impl(syn::ItemImpl { ref mut attrs, .. })
+ | syn::Item::Macro(syn::ItemMacro { ref mut attrs, .. })
+ | syn::Item::Mod(syn::ItemMod { ref mut attrs, .. })
+ | syn::Item::Static(syn::ItemStatic { ref mut attrs, .. })
+ | syn::Item::Struct(syn::ItemStruct { ref mut attrs, .. })
+ | syn::Item::Trait(syn::ItemTrait { ref mut attrs, .. })
+ | syn::Item::TraitAlias(syn::ItemTraitAlias { ref mut attrs, .. })
+ | syn::Item::Type(syn::ItemType { ref mut attrs, .. })
+ | syn::Item::Union(syn::ItemUnion { ref mut attrs, .. })
+ | syn::Item::Use(syn::ItemUse { ref mut attrs, .. }) => {
+ let mut index = 0;
+ while index < attrs.len() {
+ let attr = &attrs[index];
+ if matches!(attr.style, syn::AttrStyle::Outer) {
+ match attr.meta {
+ syn::Meta::List(ref list)
+ if is_path_eq(&list.path, "for_target_feature") =>
+ {
+ let feature: syn::LitStr = match list.parse_args() {
+ Ok(feature) => feature,
+ Err(error) => {
+ return error.into_compile_error();
+ }
+ };
+
+ let feature = feature.value();
+ if !spec_features
+ .iter()
+ .any(|enabled_feature| feature == *enabled_feature)
+ {
+ *item = syn::Item::Verbatim(Default::default());
+ continue 'next_item;
+ }
+
+ attrs.remove(index);
+ continue;
+ }
+ _ => {}
+ }
+ }
+
+ index += 1;
+ continue;
+ }
+ }
+ _ => {
+ unsupported!(item_mod);
+ }
+ }
+ }
+
+ *item = syn::Item::Verbatim(
+ process_item(
+ attributes,
+ std::mem::replace(item, syn::Item::Verbatim(Default::default())),
+ false,
+ )
+ .into(),
+ );
+ }
+ }
+
+ quote::quote! {
+ #item_mod
+ }
+}
+
+fn process_impl(attributes: &syn::LitStr, mut item_impl: syn::ItemImpl) -> TokenStream {
+ unsupported_if_some!(item_impl.defaultness);
+ unsupported_if_some!(item_impl.unsafety);
+
+ let mut items = Vec::new();
+ for item in item_impl.items.drain(..) {
+ match item {
+ syn::ImplItem::Fn(function) => {
+ unsupported_if_some!(function.defaultness);
+ let function = syn::ItemFn {
+ attrs: function.attrs,
+ vis: function.vis,
+ sig: function.sig,
+ block: Box::new(function.block),
+ };
+ let output_item = process_function(
+ attributes,
+ function,
+ Some((item_impl.generics.clone(), item_impl.self_ty.clone())),
+ );
+ items.push(syn::ImplItem::Verbatim(output_item.into()));
+ }
+ item => items.push(item),
+ }
+ }
+
+ item_impl.items = items;
+ quote::quote! {
+ #item_impl
+ }
+ .into()
+}
+
+fn is_path_eq(path: &syn::Path, ident: &str) -> bool {
+ let segments: Vec<_> = ident.split("::").collect();
+ path.segments.len() == segments.len()
+ && path
+ .segments
+ .iter()
+ .zip(segments.iter())
+ .all(|(segment, expected)| segment.ident == expected && segment.arguments.is_none())
+}
+
+fn process_function(
+ attributes: &syn::LitStr,
+ function: syn::ItemFn,
+ outer: Option<(syn::Generics, Box)>,
+) -> TokenStream {
+ if function.sig.unsafety.is_some() {
+ return quote::quote! {
+ #[target_feature(enable = #attributes)]
+ #function
+ }
+ .into();
+ }
+
+ unsupported_if_some!(function.sig.constness);
+ unsupported_if_some!(function.sig.asyncness);
+ unsupported_if_some!(function.sig.abi);
+ unsupported_if_some!(function.sig.variadic);
+
+ let function_visibility = function.vis;
+ let function_name = function.sig.ident;
+ let function_return = function.sig.output;
+ let function_inner_name =
+ syn::Ident::new(&format!("_impl_{}", function_name), function_name.span());
+ let function_args = function.sig.inputs;
+ let function_body = function.block;
+ let mut function_call_args = Vec::new();
+ let mut function_args_outer = Vec::new();
+ let mut function_args_inner = Vec::new();
+ for (index, arg) in function_args.iter().enumerate() {
+ match arg {
+ syn::FnArg::Receiver(receiver) => {
+ unsupported_if_some!(receiver.attrs.first());
+ unsupported_if_some!(receiver.colon_token);
+
+ if outer.is_none() {
+ return syn::Error::new(receiver.span(), "unsupported by #[unsafe_target_feature(...)]; put the attribute on the outer `impl`").into_compile_error().into();
+ }
+
+ function_args_inner.push(syn::FnArg::Receiver(receiver.clone()));
+ function_args_outer.push(syn::FnArg::Receiver(receiver.clone()));
+ function_call_args.push(syn::Ident::new("self", receiver.self_token.span()));
+ }
+ syn::FnArg::Typed(ty) => {
+ unsupported_if_some!(ty.attrs.first());
+
+ match &*ty.pat {
+ syn::Pat::Ident(pat_ident) => {
+ unsupported_if_some!(pat_ident.attrs.first());
+
+ function_args_inner.push(arg.clone());
+ function_args_outer.push(syn::FnArg::Typed(syn::PatType {
+ attrs: Vec::new(),
+ pat: Box::new(syn::Pat::Ident(syn::PatIdent {
+ attrs: Vec::new(),
+ by_ref: None,
+ mutability: None,
+ ident: pat_ident.ident.clone(),
+ subpat: None,
+ })),
+ colon_token: ty.colon_token,
+ ty: ty.ty.clone(),
+ }));
+ function_call_args.push(pat_ident.ident.clone());
+ }
+ syn::Pat::Wild(pat_wild) => {
+ unsupported_if_some!(pat_wild.attrs.first());
+
+ let ident = syn::Ident::new(
+ &format!("__arg_{}__", index),
+ pat_wild.underscore_token.span(),
+ );
+ function_args_inner.push(arg.clone());
+ function_args_outer.push(syn::FnArg::Typed(syn::PatType {
+ attrs: Vec::new(),
+ pat: Box::new(syn::Pat::Ident(syn::PatIdent {
+ attrs: Vec::new(),
+ by_ref: None,
+ mutability: None,
+ ident: ident.clone(),
+ subpat: None,
+ })),
+ colon_token: ty.colon_token,
+ ty: ty.ty.clone(),
+ }));
+ function_call_args.push(ident);
+ }
+ _ => unsupported!(arg),
+ }
+ }
+ }
+ }
+
+ let mut maybe_inline = quote::quote! {};
+ let mut maybe_outer_attributes = Vec::new();
+ let mut maybe_cfg = quote::quote! {};
+ for attribute in function.attrs {
+ match &attribute.meta {
+ syn::Meta::Path(path) if is_path_eq(path, "inline") => {
+ maybe_inline = quote::quote! { #[inline] };
+ }
+ syn::Meta::Path(path) if is_path_eq(path, "test") => {
+ maybe_outer_attributes.push(attribute);
+ maybe_cfg = quote::quote! { #[cfg(target_feature = #attributes)] };
+ }
+ syn::Meta::List(syn::MetaList { path, tokens, .. })
+ if is_path_eq(path, "inline") && tokens.to_string() == "always" =>
+ {
+ maybe_inline = quote::quote! { #[inline] };
+ }
+ syn::Meta::NameValue(syn::MetaNameValue { path, .. }) if is_path_eq(path, "doc") => {
+ maybe_outer_attributes.push(attribute);
+ }
+ syn::Meta::List(syn::MetaList { path, .. })
+ if is_path_eq(path, "cfg")
+ || is_path_eq(path, "allow")
+ || is_path_eq(path, "deny") =>
+ {
+ maybe_outer_attributes.push(attribute);
+ }
+ syn::Meta::Path(path) if is_path_eq(path, "rustfmt::skip") => {
+ maybe_outer_attributes.push(attribute);
+ }
+ _ => unsupported!(attribute),
+ }
+ }
+
+ let (fn_impl_generics, fn_ty_generics, fn_where_clause) =
+ function.sig.generics.split_for_impl();
+ let fn_call_generics = fn_ty_generics.as_turbofish();
+
+ if let Some((generics, self_ty)) = outer {
+ let (outer_impl_generics, outer_ty_generics, outer_where_clause) =
+ generics.split_for_impl();
+ let trait_ident =
+ syn::Ident::new(&format!("__Impl_{}__", function_name), function_name.span());
+ let item_trait = quote::quote! {
+ #[allow(non_camel_case_types)]
+ trait #trait_ident #outer_impl_generics #outer_where_clause {
+ unsafe fn #function_inner_name #fn_impl_generics (#(#function_args_outer),*) #function_return #fn_where_clause;
+ }
+ };
+
+ let item_trait_impl = quote::quote! {
+ impl #outer_impl_generics #trait_ident #outer_ty_generics for #self_ty #outer_where_clause {
+ #[target_feature(enable = #attributes)]
+ #maybe_inline
+ unsafe fn #function_inner_name #fn_impl_generics (#(#function_args_inner),*) #function_return #fn_where_clause #function_body
+ }
+ };
+
+ quote::quote! {
+ #[inline(always)]
+ #(#maybe_outer_attributes)*
+ #function_visibility fn #function_name #fn_impl_generics (#(#function_args_outer),*) #function_return #fn_where_clause {
+ #item_trait
+ #item_trait_impl
+ unsafe {
+ ::#function_inner_name #fn_call_generics (#(#function_call_args),*)
+ }
+ }
+ }.into()
+ } else {
+ quote::quote! {
+ #[inline(always)]
+ #maybe_cfg
+ #(#maybe_outer_attributes)*
+ #function_visibility fn #function_name #fn_impl_generics (#(#function_args_outer),*) #function_return #fn_where_clause {
+ #[target_feature(enable = #attributes)]
+ #maybe_inline
+ unsafe fn #function_inner_name #fn_impl_generics (#(#function_args_inner),*) #function_return #fn_where_clause #function_body
+ unsafe {
+ #function_inner_name #fn_call_generics (#(#function_call_args),*)
+ }
+ }
+ }.into()
+ }
+}
diff --git a/vendor/curve25519-dalek-derive/tests/tests.rs b/vendor/curve25519-dalek-derive/tests/tests.rs
new file mode 100644
index 0000000..1516b35
--- /dev/null
+++ b/vendor/curve25519-dalek-derive/tests/tests.rs
@@ -0,0 +1,148 @@
+#![cfg(any(target_arch = "x86", target_arch = "x86_64"))]
+#![allow(dead_code)]
+#![allow(unused_imports)]
+
+use curve25519_dalek_derive::{unsafe_target_feature, unsafe_target_feature_specialize};
+
+#[unsafe_target_feature("sse2")]
+/// A doc comment.
+fn function(a: u32, b: u32) -> u32 {
+ a - b
+}
+
+#[unsafe_target_feature("sse2")]
+fn function_with_const_arg(b: u32) -> u32 {
+ N - b
+}
+
+#[unsafe_target_feature("sse2")]
+fn function_with_where_clause(a: T, b: T) -> T::Output
+where
+ T: Copy + core::ops::Sub,
+{
+ a - b
+}
+
+#[unsafe_target_feature("sse2")]
+#[cfg(feature = "dummy")]
+fn function_with_cfg() {}
+
+#[unsafe_target_feature("sse2")]
+#[rustfmt::skip]
+fn function_with_rustfmt_skip() {}
+
+struct Struct {
+ a: u32,
+}
+
+#[unsafe_target_feature("sse2")]
+impl Struct {
+ #[allow(unused_mut)]
+ fn member_function(&self, mut b: u32) -> u32 {
+ self.a - b
+ }
+
+ fn member_function_with_const_arg(self) -> u32 {
+ self.a - N
+ }
+
+ #[cfg(feature = "dummy")]
+ fn member_function_with_cfg() {}
+}
+
+struct StructWithGenerics
+where
+ T: Copy + core::ops::Sub,
+{
+ a: T,
+}
+
+#[unsafe_target_feature("sse2")]
+impl StructWithGenerics
+where
+ T: Copy + core::ops::Sub,
+{
+ #[inline]
+ fn member_function(&self, b: T) -> T::Output {
+ self.a - b
+ }
+}
+
+struct StructWithGenericsNoWhere {
+ a: T,
+}
+
+#[unsafe_target_feature("sse2")]
+impl StructWithGenericsNoWhere {
+ #[inline(always)]
+ fn member_function(&self, b: T) -> T::Output {
+ self.a - b
+ }
+}
+
+#[unsafe_target_feature("sse2")]
+#[allow(dead_code)]
+impl<'a> From<&'a Struct> for () {
+ fn from(_: &'a Struct) -> Self {}
+}
+
+#[unsafe_target_feature("sse2")]
+mod inner {
+ fn inner_function(a: u32, b: u32) -> u32 {
+ a - b
+ }
+}
+
+#[unsafe_target_feature_specialize("sse2", "avx2", conditional("avx512ifma", disabled))]
+mod inner_spec {
+ #[for_target_feature("sse2")]
+ const CONST: u32 = 1;
+
+ #[for_target_feature("avx2")]
+ const CONST: u32 = 2;
+
+ pub fn spec_function(a: u32, b: u32) -> u32 {
+ a - b - CONST
+ }
+
+ #[for_target_feature("sse2")]
+ const IS_AVX2: bool = false;
+
+ #[for_target_feature("avx2")]
+ const IS_AVX2: bool = true;
+
+ #[test]
+ fn test_specialized() {
+ assert!(!IS_AVX2);
+ }
+
+ #[cfg(test)]
+ mod tests {
+ #[test]
+ fn test_specialized_inner() {
+ assert!(!super::IS_AVX2);
+ }
+ }
+}
+
+#[unsafe_target_feature("sse2")]
+#[test]
+fn test_sse2_only() {}
+
+#[unsafe_target_feature("avx2")]
+#[test]
+fn test_avx2_only() {
+ compile_error!();
+}
+
+#[test]
+fn test_function() {
+ assert_eq!(function(10, 3), 7);
+ assert_eq!(function_with_where_clause(10, 3), 7);
+ assert_eq!(function_with_const_arg::<10>(3), 7);
+ assert_eq!(Struct { a: 10 }.member_function(3), 7);
+ assert_eq!(StructWithGenerics { a: 10 }.member_function(3), 7);
+ assert_eq!(StructWithGenericsNoWhere { a: 10 }.member_function(3), 7);
+ assert_eq!(inner_spec_sse2::spec_function(10, 3), 6);
+ assert_eq!(inner_spec_avx2::spec_function(10, 3), 5);
+}
diff --git a/vendor/curve25519-dalek/.cargo-checksum.json b/vendor/curve25519-dalek/.cargo-checksum.json
new file mode 100644
index 0000000..98f2f7d
--- /dev/null
+++ b/vendor/curve25519-dalek/.cargo-checksum.json
@@ -0,0 +1 @@
+{"files":{".cargo_vcs_info.json":"da154d5c75d8e058534e06edf8bea3404a22522d569877b7c249ba22f8dab66c","CHANGELOG.md":"c1b62cc204693d67a509c5dc89dab51cdc81d95c457e70c8a9e57332e0b81044","Cargo.toml":"ef9a2ca89de6eb3e09adf27478df06d246f27ee025150241e847aff26d78129d","Cargo.toml.orig":"7b2379b5faff3579525dcd8f676bfb6b2408364b7b3e3996d9f8e09eb8624381","LICENSE":"cca0bd3c4fcdba74145ef9d49c62337e2c9fbf9368288f11d0547f1b0273219f","Makefile":"077a0ab4ad06f7e041968c7673c265360ce60254506b10820edb48bd38a07d7f","README.md":"5905d6af2da3098f3a095ed09d65b1236bd998fc3be803a626a4024399b6390f","benches/dalek_benchmarks.rs":"0ee0e8cd50cf9621fe40008283078f90e771cdd62d84237b5893acee67e6447c","build.rs":"c479ea95fa9cac8b3374564261c15cfcb110738ddcaa5e0852644b6083bd9189","docs/assets/rustdoc-include-katex-header.html":"088c9bb27bdc5c240c00ff1c06d583d77995d53b76421116609a751ca4a54b59","docs/avx2-notes.md":"47e41778044529299f78906d99d6dfe9c0400acf5ad32e519fa54b6d6bea36dc","docs/ifma-notes.md":"e1fab7acb37c363d391659b2b8cae44844aa1121a074e3752f5ae6b49027d8ac","docs/parallel-formulas.md":"94d620c7fd8a0c9edba320c175cedb5458a37833f3fb5dbe989c540ab8eda4ff","src/backend/mod.rs":"0a9c9afa3e88ee691a344460b76078a884d7a3cc722223cc95e62f4de235379d","src/backend/serial/curve_models/mod.rs":"ac3a6e25659ee804e55064d87010ab69af80a78a149d05796fa3d9e5c5fb0b62","src/backend/serial/fiat_u32/field.rs":"cc4f923ab24efd5f3942133143d6f0fc9e5fff00774cc22b1049e61f48d6c112","src/backend/serial/fiat_u32/mod.rs":"6e36a757f0f804caaebb5a2f0c04754589740279160890d592287edc7d65efcf","src/backend/serial/fiat_u64/field.rs":"1182ecb1321c597ac2f69ad25bce084a689913d0e43d41739783964f2b74d8e0","src/backend/serial/fiat_u64/mod.rs":"6e6f773aa9669a740519d2256421734ddfee60cd6ad7f45156b6b5201c10487d","src/backend/serial/mod.rs":"8c92cec992cf112c0683ed328ecfdfcc08d4732de92a76c882b3062e4549f39c","src/backend/serial/scalar_mul/mod.rs":"a6a4185075faebf984f365b6dcc28c3da6c087d18d811257cd2c0245b41d113e","src/backend/serial/scalar_mul/pippenger.rs":"d9bf40f8a31987a917f8e5b984443b60eb358cc0586c5b46ea6459446684cc64","src/backend/serial/scalar_mul/precomputed_straus.rs":"d26f11fc80a9ca95410007290746d04eaa7c8a85d7b3c686c856560847a6f3b3","src/backend/serial/scalar_mul/straus.rs":"92040d722c6771c3f90c8c86621f5ef9239e1bec237750d2f39c311d5cb7463b","src/backend/serial/scalar_mul/variable_base.rs":"b9bc69189d5a9339a4c05882b736ac65176b6e98eb93008bc5e200b090e386b6","src/backend/serial/scalar_mul/vartime_double_base.rs":"528db8b24adf9a3b50fbe89fe917b0ae9dace30bbcae9f40c0ba3583f1d80ac8","src/backend/serial/u32/constants.rs":"1e62a0897ecca3e4bec3512236160e3b9fc3b089ceccd9d0e2215c9e9765a986","src/backend/serial/u32/field.rs":"1aaefdbf121a7f9787ff6b2e5c370eca97d5a45f1c76df627f5cd430f7b7323d","src/backend/serial/u32/mod.rs":"14fabb2034c68094df508c19517db14e5e3b956b5dac93bd0dd3c125f47f396e","src/backend/serial/u32/scalar.rs":"0ccf76feb3452624f6716b7c8b906d7e0c9eeb3e9e4ad096acac3f1ecc16d416","src/backend/serial/u64/constants.rs":"fa72dc113456cfbe5d34f144e89e1bbe2976b1016b09a278fe1e4b3fda57ab6f","src/backend/serial/u64/field.rs":"a4e90b018c235852da117db1bb87e62a2bbe75725e52c16462705a9c0a25e977","src/backend/serial/u64/mod.rs":"b4aab9c62cf39bafc976b2e03bea503f120b125c30eb0e9e5d5f257b08a3eda4","src/backend/serial/u64/scalar.rs":"0926d7e50c7477ceb300f66c49f44c53c56597fcbd7083ba36f965b6e7a2301d","src/backend/vector/avx2/constants.rs":"95f19d41ad1796d892734ba9125f6442dcb049f6392d31c1ec61d5b4a011102b","src/backend/vector/avx2/edwards.rs":"6734cadeec567675b94b7278c9f4d21f53120a1a6c79b61261cc18b2fbb1d624","src/backend/vector/avx2/field.rs":"9c904f61332c605850dc3a60808dc2981777facdf60ebf5f3bc8a325dea66fff","src/backend/vector/avx2/mod.rs":"e8933b6f1e11255c701eda08bdcbf3593c0c2e169006c13aab26e1c92ebe24d8","src/backend/vector/ifma/constants.rs":"69f06bb74de041842b8780bb13da4f636d2876ae0bb871889a192313f10d3511","src/backend/vector/ifma/edwards.rs":"84ca8c236dafe186599294dfbd5fc00f3961b7a631e4add1946c9b1d97aee3cb","src/backend/vector/ifma/field.rs":"e78789524cad9bdb4be2da87970da0a7852eb823c18a08df54f68683e69e4c0f","src/backend/vector/ifma/mod.rs":"5feec145182a460e856afe37d9aacac0124e59600e46727752e956ee908dec1e","src/backend/vector/mod.rs":"3fce1ede5a2705640aaa9e509c3c38614cbb5b8882d943fc112b91d00cfdccbf","src/backend/vector/packed_simd.rs":"295f734a1e4d752b6df0b8b0255315e6e6f9947c0abdcb98e0b346ded559f4d1","src/backend/vector/scalar_mul/mod.rs":"c2ae669727ba81a486b447f98561273cd62f76b1c546c55dafdc86c85674e8e7","src/backend/vector/scalar_mul/pippenger.rs":"55db1d720f2cc073352927d3517495b8faf6b368828d50eb1d91a45dfd288e81","src/backend/vector/scalar_mul/precomputed_straus.rs":"4adbab25fe3a26867548cd3fd788bbecab1c7c35270b9adbd59c466f09ecffed","src/backend/vector/scalar_mul/straus.rs":"3dea20f3f30aab82d06fa1416268015d20402c9d3211612549d89199182de810","src/backend/vector/scalar_mul/variable_base.rs":"6506efaf0c50dab542d8a4dcec0c94683296e02866367e777d1c259c41dbfc9b","src/backend/vector/scalar_mul/vartime_double_base.rs":"d1330c64e64343d2e3a79f01fa2b3ba6c004bc270f9796eee3117364cc726ee5","src/constants.rs":"f2de2d3e6c0cedc301475cc6043e0baa1418c677998ebce8863fa04a6e14a6b0","src/diagnostics.rs":"737e956565a9fac8b9b7245c259a3d776227812b4c735eea49abdf5f4b44ff63","src/edwards.rs":"28014a3b0d1b4a4502eea90e812653a6cb6c01b77a9921719a422f808b7a9bbb","src/field.rs":"75fa7d6055d1f19aa9e4a2d231c6f2d4a74dfa62f0eb7e49a40b45462f709a01","src/lib.rs":"d8041dbc74e84df6a01cc0186a80501e5642d421734222950d8e0d5a50fc9701","src/macros.rs":"2d848f7d36d69108f1ff0d641537c726bcefb40721f42ca2180176af14d081f3","src/montgomery.rs":"49a75524b05076d053c67b49f9e9f082fb0c5ec9c723acc8e73611f3c955a812","src/ristretto.rs":"ea4f8f8c3785a8ccf17013610582a8c73d59c60693cf5a6298030a10c142c352","src/scalar.rs":"d60cd7ef2ef08072f9e073a43b3485a631dc732daf22054cceff00f96afaa4af","src/traits.rs":"67dc6e016c53c69225200a8cd2e76f152783d23149a11b7306f5de7cff37d92c","src/window.rs":"2124ce6436f9c9b753605c406de00443002a9f2c81cf2a24cbd0df0f7885f219","tests/build_tests.sh":"3eb54238d60cbe438f9fd0848aa9ce36eab6ea9de8ef655eba2118bf6ffeef3f","vendor/ristretto.sage":"a2f4309ada0afa4156f5a660be4384a0f1f332c12f836199124f48e89310344d"},"package":"97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"}
\ No newline at end of file
diff --git a/vendor/curve25519-dalek/.cargo_vcs_info.json b/vendor/curve25519-dalek/.cargo_vcs_info.json
new file mode 100644
index 0000000..7688f4a
--- /dev/null
+++ b/vendor/curve25519-dalek/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "5312a0311ec40df95be953eacfa8a11b9a34bc54"
+ },
+ "path_in_vcs": "curve25519-dalek"
+}
\ No newline at end of file
diff --git a/vendor/curve25519-dalek/CHANGELOG.md b/vendor/curve25519-dalek/CHANGELOG.md
new file mode 100644
index 0000000..939d3bf
--- /dev/null
+++ b/vendor/curve25519-dalek/CHANGELOG.md
@@ -0,0 +1,268 @@
+# Changelog
+
+Entries are listed in reverse chronological order per undeprecated
+major series.
+
+## 4.x series
+
+### 4.1.3
+
+* Security: Fix timing leak in Scalar subtraction on u32, u64, fiat_u32, and fiat_u64 backends
+* Fix assorted new warnings and lints from rustc and clippy
+
+### 4.1.2
+
+* Fix nightly SIMD build
+
+### 4.1.1
+
+* Mark `constants::BASEPOINT_ORDER` deprecated from pub API
+* Add implementation for `PrimeFieldBits`, behind the `group-bits` feature flag.
+
+### 4.1.0
+
+* Add arbitrary integer multiplication with `MontgomeryPoint::mul_bits_be`
+* Add implementations of the `ff` and `group` traits, behind the `group` feature flag
+* Adapt to new types introduced in `fiat-crypto` 0.2 in `fiat` backend
+* Fix `no_std` for `fiat` backend
+* Mark `Scalar::clamp_integer` as `#[must_use]`
+* Various documentation fixes
+
+### 4.0.0
+
+#### Breaking changes
+
+* Update the MSRV from 1.41 to 1.60
+* Provide SemVer policy
+* Make `digest` an optional feature
+* Make `rand_core` an optional feature
+* Remove `std` feature flag
+* Remove `nightly` feature flag
+* Automatic serial backend selection between `u32` and `u64` over the default `u32`
+* Backend `simd` is now automatically selected over `serial` when a supported CPU is detected
+* Backend override is now via cfg(curve25519_dalek_backend) over additive features
+* Provide override to select `u32` or `u64` backend via cfg(curve25519_dalek_bits)
+* Replace methods `Scalar::{zero, one}` with constants `Scalar::{ZERO, ONE}`
+* Deprecate `EdwardsPoint::hash_from_bytes` and rename it `EdwardsPoint::nonspec_map_to_curve`
+* Require including a new trait, `use curve25519_dalek::traits::BasepointTable`
+ whenever using `EdwardsBasepointTable` or `RistrettoBasepointTable`
+* `Scalar::from_canonical_bytes` now returns `CtOption`
+* `Scalar::is_canonical` now returns `Choice`
+* Remove `Scalar::from_bytes_clamped` and `Scalar::reduce`
+* Deprecate and feature-gate `Scalar::from_bits` behind `legacy_compatibility`
+
+#### Other changes
+
+* Add `EdwardsPoint::{mul_base, mul_base_clamped}`, `MontgomeryPoint::{mul_base, mul_base_clamped}`, and `BasepointTable::mul_base_clamped`
+* Add `precomputed-tables` feature
+* Update Maintenance Policies for SemVer
+* Migrate documentation to docs.rs hosted
+* Fix backend documentation generation
+* Fix panic when `Ristretto::double_and_compress_batch` receives the identity point
+* Remove `byteorder` dependency
+* Update the `criterion` dependency to 0.4.0
+* Include README.md into crate Documentation
+* Update the `rand_core` dependency version and the `rand` dev-dependency
+ version.
+* Relax the `zeroize` dependency to `^1`
+* Update the edition from 2015 to 2021
+
+## 3.x series
+
+### 3.2.0
+
+* Add support for getting the identity element for the Montgomery
+ form of curve25519, which is useful in certain protocols for
+ checking contributory behaviour in derivation of shared secrets.
+
+### 3.1.2
+
+* Revert a commit which mistakenly removed support for `zeroize` traits
+ for some point types, as well as elligator2 support for Edwards points.
+
+### 3.1.1
+
+* Fix documentation builds on nightly due to syntax changes to
+ `#![cfg_attr(feature = "nightly", doc = include_str!("../README.md"))]`.
+
+### 3.1.0
+
+* Add support for the Elligator2 encoding for Edwards points.
+* Add two optional formally-verified field arithmetic backends which
+ use the Fiat Crypto project's Rust code, which is generated from
+ proofs of functional correctness checked by the Coq theorem proving
+ system.
+* Add support for additional sizes of precomputed tables for basepoint
+ scalar multiplication.
+* Fix an unused import.
+* Add support for using the `zeroize` traits with all point types.
+ Note that points are not automatically zeroized on Drop, but that
+ consumers of `curve25519-dalek` should call these methods manually
+ when needed.
+
+### 3.0.3
+
+* Fix documentation builds on nightly due to syntax changes to
+ `#![cfg_attr(feature = "nightly", doc = include_str!("../README.md"))]`.
+
+### 3.0.2
+
+* Multiple documentation typo fixes.
+* Fixes to make using `alloc`+`no_std` possible for stable Rust.
+
+### 3.0.1
+
+* Update the optional `packed-simd` dependency to rely on a newer,
+ maintained version of the `packed-simd-2` crate.
+
+### 3.0.0
+
+#### Breaking changes
+
+* Update the `digest` dependency to `0.9`. This requires a major version
+ because the `digest` traits are part of the public API, but there are
+ otherwise no changes to the API.
+
+## 2.x series
+
+### 2.1.3
+
+* Fix documentation builds on nightly due to syntax changes to
+ `#![fg_attr(feature = "nightly", doc = include_str!("../README.md"))]`.
+
+### 2.1.2
+
+* Multiple documentation typo fixes.
+* Fix `alloc` feature working with stable rust.
+
+### 2.1.1
+
+* Update the optional `packed-simd` dependency to rely on a newer,
+ maintained version of the `packed-simd-2` crate.
+
+### 2.1.0
+
+* Make `Scalar::from_bits` a `const fn`, allowing its use in `const` contexts.
+
+### 2.0.0
+
+The only significant change is the data model change to the `serde` feature;
+besides the `rand_core` version bump, there are no other user-visible changes.
+
+#### Breaking changes
+
+* Fix a data modeling error in the `serde` feature pointed out by Trevor Perrin
+ which caused points and scalars to be serialized with length fields rather
+ than as fixed-size 32-byte arrays. This is a breaking change, but it fixes
+ compatibility with `serde-json` and ensures that the `serde-bincode` encoding
+ matches the conventional encoding for X/Ed25519.
+* Update `rand_core` to `0.5`, allowing use with new `rand` versions.
+
+#### Other changes
+
+* Switch from `clear_on_drop` to `zeroize` (by Tony Arcieri).
+* Require `subtle = ^2.2.1` and remove the note advising nightly Rust, which is
+ no longer required as of that version of `subtle`. See the `subtle`
+ changelog for more details.
+* Update `README.md` for `2.x` series.
+* Remove the `build.rs` hack which loaded the entire crate into its own
+ `build.rs` to generate constants, and keep the constants in the source code.
+
+## 1.x series
+
+### 1.2.6
+
+* Fixes to make using alloc+no_std possible for stable Rust.
+
+### 1.2.5
+
+* Update the optional `packed-simd` dependency to rely on a newer,
+ maintained version of the `packed-simd-2` crate.
+
+### 1.2.4
+
+* Specify a semver bound for `clear_on_drop` rather than an exact version,
+ addressing an issue where changes to inline assembly in rustc prevented
+ `clear_on_drop` from working without an update.
+
+### 1.2.3
+
+* Fix an issue identified by a Quarkslab audit (and Jack Grigg), where manually
+ constructing unreduced `Scalar` values, as needed for X/Ed25519, and then
+ performing scalar/scalar arithmetic could compute incorrect results.
+* Switch to upstream Rust intrinsics for the IFMA backend now that they exist in
+ Rust and don't need to be defined locally.
+* Ensure that the NAF computation works correctly, even for parameters never
+ used elsewhere in the codebase.
+* Minor refactoring to EdwardsPoint decompression.
+* Fix broken links in documentation.
+* Fix compilation on nightly broken due to changes to the `#[doc(include)]` path
+ root (not quite correctly done in 1.2.2).
+
+### 1.2.2
+
+* Fix a typo in an internal doc-comment.
+* Add the "crypto" tag to crate metadata.
+* Fix compilation on nightly broken due to changes to the `#[doc(include)]` path
+ root.
+
+### 1.2.1
+
+* Fix a bug in bucket index calculations in the Pippenger multiscalar algorithm
+ for very large input sizes.
+* Add a more extensive randomized multiscalar multiplication consistency check
+ to the test suite to prevent regressions.
+* Ensure that that multiscalar and NAF computations work correctly on extremal
+ `Scalar` values constructed via `from_bits`.
+
+### 1.2.0
+
+* New multiscalar multiplication algorithm with better performance for
+ large problem sizes. The backend algorithm is selected
+ transparently using the size hints of the input iterators, so no
+ changes are required for client crates to start using it.
+* Equality of Edwards points is now checked in projective coordinates.
+* Serde can now be used with `no_std`.
+
+### 1.1.4
+
+* Fix typos in documentation comments.
+* Remove unnecessary `Default` bound on `Scalar::from_hash`.
+
+### 1.1.3
+
+* Reverts the change in 1.1.0 to allow owned and borrowed RNGs, which caused a breakage due to a subtle interaction with ownership rules. (The `RngCore` change is retained).
+
+### 1.1.2
+
+* Disabled KaTeX on `docs.rs` pending proper [support upstream](https://github.com/rust-lang/docs.rs/issues/302).
+
+## 1.1.1
+
+* Fixed an issue related to `#[cfg(rustdoc)]` which prevented documenting multiple backends.
+
+### 1.1.0
+
+* Adds support for precomputation for multiscalar multiplication.
+* Restructures the internal source tree into `serial` and `vector` backends (no change to external API).
+* Adds a new IFMA backend which sets speed records.
+* The `avx2_backend` feature is now an alias for the `simd_backend` feature, which autoselects an appropriate vector backend (currently AVX2 or IFMA).
+* Replaces the `rand` dependency with `rand_core`.
+* Generalizes trait bounds on `RistrettoPoint::random()` and `Scalar::random()` to allow owned and borrowed RNGs and to allow `RngCore` instead of `Rng`.
+
+### 1.0.3
+
+* Adds `ConstantTimeEq` implementation for compressed points.
+
+### 1.0.2
+
+* Fixes a typo in the naming of variables in Ristretto formulas (no change to functionality).
+
+### 1.0.1
+
+* Depends on the stable `2.0` version of `subtle` instead of `2.0.0-pre.0`.
+
+### 1.0.0
+
+Initial stable release. Yanked due to a dependency mistake (see above).
+
diff --git a/vendor/curve25519-dalek/Cargo.toml b/vendor/curve25519-dalek/Cargo.toml
new file mode 100644
index 0000000..c3ea85d
--- /dev/null
+++ b/vendor/curve25519-dalek/Cargo.toml
@@ -0,0 +1,155 @@
+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
+#
+# When uploading crates to the registry Cargo will automatically
+# "normalize" Cargo.toml files for maximal compatibility
+# with all versions of Cargo and also rewrite `path` dependencies
+# to registry (e.g., crates.io) dependencies.
+#
+# If you are reading this file be aware that the original Cargo.toml
+# will likely look very different (and much more reasonable).
+# See Cargo.toml.orig for the original contents.
+
+[package]
+edition = "2021"
+rust-version = "1.60.0"
+name = "curve25519-dalek"
+version = "4.1.3"
+authors = [
+ "Isis Lovecruft ",
+ "Henry de Valence ",
+]
+exclude = [
+ "**/.gitignore",
+ ".gitignore",
+]
+description = "A pure-Rust implementation of group operations on ristretto255 and Curve25519"
+homepage = "https://github.com/dalek-cryptography/curve25519-dalek"
+documentation = "https://docs.rs/curve25519-dalek"
+readme = "README.md"
+keywords = [
+ "cryptography",
+ "crypto",
+ "ristretto",
+ "curve25519",
+ "ristretto255",
+]
+categories = [
+ "cryptography",
+ "no-std",
+]
+license = "BSD-3-Clause"
+repository = "https://github.com/dalek-cryptography/curve25519-dalek/tree/main/curve25519-dalek"
+
+[package.metadata.docs.rs]
+features = [
+ "serde",
+ "rand_core",
+ "digest",
+ "legacy_compatibility",
+ "group-bits",
+]
+rustdoc-args = [
+ "--html-in-header",
+ "docs/assets/rustdoc-include-katex-header.html",
+ "--cfg",
+ "docsrs",
+]
+
+[[bench]]
+name = "dalek_benchmarks"
+harness = false
+required-features = [
+ "alloc",
+ "rand_core",
+]
+
+[dependencies.cfg-if]
+version = "1"
+
+[dependencies.digest]
+version = "0.10"
+optional = true
+default-features = false
+
+[dependencies.ff]
+version = "0.13"
+optional = true
+default-features = false
+
+[dependencies.group]
+version = "0.13"
+optional = true
+default-features = false
+
+[dependencies.rand_core]
+version = "0.6.4"
+optional = true
+default-features = false
+
+[dependencies.serde]
+version = "1.0"
+features = ["derive"]
+optional = true
+default-features = false
+
+[dependencies.subtle]
+version = "2.3.0"
+default-features = false
+
+[dependencies.zeroize]
+version = "1"
+optional = true
+default-features = false
+
+[dev-dependencies.bincode]
+version = "1"
+
+[dev-dependencies.criterion]
+version = "0.5"
+features = ["html_reports"]
+
+[dev-dependencies.hex]
+version = "0.4.2"
+
+[dev-dependencies.rand]
+version = "0.8"
+
+[dev-dependencies.rand_core]
+version = "0.6"
+features = ["getrandom"]
+default-features = false
+
+[dev-dependencies.sha2]
+version = "0.10"
+default-features = false
+
+[build-dependencies.rustc_version]
+version = "0.4.0"
+
+[features]
+alloc = ["zeroize?/alloc"]
+default = [
+ "alloc",
+ "precomputed-tables",
+ "zeroize",
+]
+group = [
+ "dep:group",
+ "rand_core",
+]
+group-bits = [
+ "group",
+ "ff/bits",
+]
+legacy_compatibility = []
+precomputed-tables = []
+
+[target."cfg(all(not(curve25519_dalek_backend = \"fiat\"), not(curve25519_dalek_backend = \"serial\"), target_arch = \"x86_64\"))".dependencies.curve25519-dalek-derive]
+version = "0.1"
+
+[target."cfg(curve25519_dalek_backend = \"fiat\")".dependencies.fiat-crypto]
+version = "0.2.1"
+default-features = false
+
+[target."cfg(target_arch = \"x86_64\")".dependencies.cpufeatures]
+version = "0.2.6"
diff --git a/vendor/curve25519-dalek/Cargo.toml.orig b/vendor/curve25519-dalek/Cargo.toml.orig
new file mode 100644
index 0000000..8e480ad
--- /dev/null
+++ b/vendor/curve25519-dalek/Cargo.toml.orig
@@ -0,0 +1,73 @@
+[package]
+name = "curve25519-dalek"
+# Before incrementing:
+# - update CHANGELOG
+# - update README if required by semver
+# - if README was updated, also update module documentation in src/lib.rs
+version = "4.1.3"
+edition = "2021"
+rust-version = "1.60.0"
+authors = ["Isis Lovecruft ",
+ "Henry de Valence "]
+readme = "README.md"
+license = "BSD-3-Clause"
+repository = "https://github.com/dalek-cryptography/curve25519-dalek/tree/main/curve25519-dalek"
+homepage = "https://github.com/dalek-cryptography/curve25519-dalek"
+documentation = "https://docs.rs/curve25519-dalek"
+categories = ["cryptography", "no-std"]
+keywords = ["cryptography", "crypto", "ristretto", "curve25519", "ristretto255"]
+description = "A pure-Rust implementation of group operations on ristretto255 and Curve25519"
+exclude = [
+ "**/.gitignore",
+ ".gitignore",
+]
+
+[package.metadata.docs.rs]
+rustdoc-args = [
+ "--html-in-header", "docs/assets/rustdoc-include-katex-header.html",
+ "--cfg", "docsrs",
+]
+features = ["serde", "rand_core", "digest", "legacy_compatibility", "group-bits"]
+
+[dev-dependencies]
+sha2 = { version = "0.10", default-features = false }
+bincode = "1"
+criterion = { version = "0.5", features = ["html_reports"] }
+hex = "0.4.2"
+rand = "0.8"
+rand_core = { version = "0.6", default-features = false, features = ["getrandom"] }
+
+[build-dependencies]
+rustc_version = "0.4.0"
+
+[[bench]]
+name = "dalek_benchmarks"
+harness = false
+required-features = ["alloc", "rand_core"]
+
+[dependencies]
+cfg-if = "1"
+ff = { version = "0.13", default-features = false, optional = true }
+group = { version = "0.13", default-features = false, optional = true }
+rand_core = { version = "0.6.4", default-features = false, optional = true }
+digest = { version = "0.10", default-features = false, optional = true }
+subtle = { version = "2.3.0", default-features = false }
+serde = { version = "1.0", default-features = false, optional = true, features = ["derive"] }
+zeroize = { version = "1", default-features = false, optional = true }
+
+[target.'cfg(target_arch = "x86_64")'.dependencies]
+cpufeatures = "0.2.6"
+
+[target.'cfg(curve25519_dalek_backend = "fiat")'.dependencies]
+fiat-crypto = { version = "0.2.1", default-features = false }
+
+[features]
+default = ["alloc", "precomputed-tables", "zeroize"]
+alloc = ["zeroize?/alloc"]
+precomputed-tables = []
+legacy_compatibility = []
+group = ["dep:group", "rand_core"]
+group-bits = ["group", "ff/bits"]
+
+[target.'cfg(all(not(curve25519_dalek_backend = "fiat"), not(curve25519_dalek_backend = "serial"), target_arch = "x86_64"))'.dependencies]
+curve25519-dalek-derive = { version = "0.1", path = "../curve25519-dalek-derive" }
diff --git a/vendor/curve25519-dalek/LICENSE b/vendor/curve25519-dalek/LICENSE
new file mode 100644
index 0000000..ff34757
--- /dev/null
+++ b/vendor/curve25519-dalek/LICENSE
@@ -0,0 +1,65 @@
+Copyright (c) 2016-2021 isis agora lovecruft. All rights reserved.
+Copyright (c) 2016-2021 Henry de Valence. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+1. Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer in the
+documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holder nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+========================================================================
+
+Portions of curve25519-dalek were originally derived from Adam Langley's
+Go ed25519 implementation, found at ,
+under the following licence:
+
+========================================================================
+
+Copyright (c) 2012 The Go Authors. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+ * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+ * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
+TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/curve25519-dalek/Makefile b/vendor/curve25519-dalek/Makefile
new file mode 100644
index 0000000..bb61cc8
--- /dev/null
+++ b/vendor/curve25519-dalek/Makefile
@@ -0,0 +1,11 @@
+FEATURES := serde rand_core digest legacy_compatibility
+
+export RUSTDOCFLAGS := \
+ --cfg docsrs \
+ --html-in-header docs/assets/rustdoc-include-katex-header.html
+
+doc:
+ cargo +nightly rustdoc --features "$(FEATURES)"
+
+doc-internal:
+ cargo +nightly rustdoc --features "$(FEATURES)" -- --document-private-items
diff --git a/vendor/curve25519-dalek/README.md b/vendor/curve25519-dalek/README.md
new file mode 100644
index 0000000..c918d69
--- /dev/null
+++ b/vendor/curve25519-dalek/README.md
@@ -0,0 +1,323 @@
+
+# curve25519-dalek [](https://crates.io/crates/curve25519-dalek) [](https://docs.rs/curve25519-dalek) [](https://github.com/dalek-cryptography/curve25519-dalek/actions/workflows/curve25519-dalek.yml)
+
+
+
+
+
+**A pure-Rust implementation of group operations on Ristretto and Curve25519.**
+
+`curve25519-dalek` is a library providing group operations on the Edwards and
+Montgomery forms of Curve25519, and on the prime-order Ristretto group.
+
+`curve25519-dalek` is not intended to provide implementations of any particular
+crypto protocol. Rather, implementations of those protocols (such as
+[`x25519-dalek`][x25519-dalek] and [`ed25519-dalek`][ed25519-dalek]) should use
+`curve25519-dalek` as a library.
+
+`curve25519-dalek` is intended to provide a clean and safe _mid-level_ API for use
+implementing a wide range of ECC-based crypto protocols, such as key agreement,
+signatures, anonymous credentials, rangeproofs, and zero-knowledge proof
+systems.
+
+In particular, `curve25519-dalek` implements Ristretto, which constructs a
+prime-order group from a non-prime-order Edwards curve. This provides the
+speed and safety benefits of Edwards curve arithmetic, without the pitfalls of
+cofactor-related abstraction mismatches.
+
+# Use
+
+## Stable
+
+To import `curve25519-dalek`, add the following to the dependencies section of
+your project's `Cargo.toml`:
+```toml
+curve25519-dalek = "4"
+```
+
+If opting into [SemVer-exempted features](#public-api-semver-exemptions) a range
+can be used to scope the tested compatible version range e.g.:
+```toml
+curve25519-dalek = ">= 4.0, < 4.2"
+```
+
+## Feature Flags
+
+| Feature | Default? | Description |
+| :--- | :---: | :--- |
+| `alloc` | ✓ | Enables Edwards and Ristretto multiscalar multiplication, batch scalar inversion, and batch Ristretto double-and-compress. Also enables `zeroize`. |
+| `zeroize` | ✓ | Enables [`Zeroize`][zeroize-trait] for all scalar and curve point types. |
+| `precomputed-tables` | ✓ | Includes precomputed basepoint multiplication tables. This speeds up `EdwardsPoint::mul_base` and `RistrettoPoint::mul_base` by ~4x, at the cost of ~30KB added to the code size. |
+| `rand_core` | | Enables `Scalar::random` and `RistrettoPoint::random`. This is an optional dependency whose version is not subject to SemVer. See [below](#public-api-semver-exemptions) for more details. |
+| `digest` | | Enables `RistrettoPoint::{from_hash, hash_from_bytes}` and `Scalar::{from_hash, hash_from_bytes}`. This is an optional dependency whose version is not subject to SemVer. See [below](#public-api-semver-exemptions) for more details. |
+| `serde` | | Enables `serde` serialization/deserialization for all the point and scalar types. |
+| `legacy_compatibility`| | Enables `Scalar::from_bits`, which allows the user to build unreduced scalars whose arithmetic is broken. Do not use this unless you know what you're doing. |
+| `group` | | Enables external `group` and `ff` crate traits |
+
+To disable the default features when using `curve25519-dalek` as a dependency,
+add `default-features = false` to the dependency in your `Cargo.toml`. To
+disable it when running `cargo`, add the `--no-default-features` CLI flag.
+
+## Major Version API Changes
+
+Breaking changes for each major version release can be found in
+[`CHANGELOG.md`](CHANGELOG.md), under the "Breaking changes" subheader. The
+latest breaking changes in high level are below:
+
+### Breaking changes in 4.0.0
+
+* Update the MSRV from 1.41 to 1.60
+* Provide SemVer policy
+* Make `digest` and `rand_core` optional features
+* Remove `std` and `nightly` features
+* Replace backend selection - See [CHANGELOG.md](CHANGELOG.md) and [backends](#backends)
+* Replace methods `Scalar::{zero, one}` with constants `Scalar::{ZERO, ONE}`
+* `Scalar::from_canonical_bytes` now returns `CtOption`
+* `Scalar::is_canonical` now returns `Choice`
+* Remove `Scalar::from_bytes_clamped` and `Scalar::reduce`
+* Deprecate and feature-gate `Scalar::from_bits` behind `legacy_compatibility`
+* Deprecate `EdwardsPoint::hash_from_bytes` and rename it
+ `EdwardsPoint::nonspec_map_to_curve`
+* Require including a new trait, `use curve25519_dalek::traits::BasepointTable`
+ whenever using `EdwardsBasepointTable` or `RistrettoBasepointTable`
+
+This release also does a lot of dependency updates and relaxations to unblock upstream build issues.
+
+# Backends
+
+Curve arithmetic is implemented and used by one of the following backends:
+
+| Backend | Selection | Implementation | Bits / Word sizes |
+| :--- | :--- | :--- | :--- |
+| `serial` | Automatic | An optimized, non-parllel implementation | `32` and `64` |
+| `fiat` | Manual | Formally verified field arithmetic from [fiat-crypto] | `32` and `64` |
+| `simd` | Automatic | Intel AVX2 / AVX512 IFMA accelerated backend | `64` only |
+
+At runtime, `curve25519-dalek` selects an arithmetic backend from the set of backends it was compiled to support. For Intel x86-64 targets, unless otherwise specified, it will build itself with `simd` support, and default to `serial` at runtime if the appropriate CPU features aren't detected. See [SIMD backend] for more details.
+
+In the future, `simd` backend may be extended to cover more instruction sets. This change will be non-breaking as this is considered as implementation detail.
+
+## Manual Backend Override
+
+You can force the crate to compile with specific backend support, e.g., `serial` for x86-64 targets to save code size, or `fiat` to force the runtime to use verified code. To do this, set the environment variable:
+```sh
+RUSTFLAGS='--cfg curve25519_dalek_backend="BACKEND"'
+```
+Equivalently, you can write to
+`~/.cargo/config`:
+```toml
+[build]
+rustflags = ['--cfg=curve25519_dalek_backend="BACKEND"']
+```
+More info [here](https://doc.rust-lang.org/cargo/reference/config.html#buildrustflags).
+
+Note for contributors: The target backends are not entirely independent of each
+other. The [SIMD backend] directly depends on parts of the serial backend to
+function.
+
+## Bits / Word size
+
+`curve25519-dalek` will automatically choose the word size for the `fiat` and
+`serial` backends, based on the build target.
+For example, building for a 64-bit machine, the default 64 bit word size is
+automatically chosen when either the `serial` or `fiat` backend is selected.
+
+In some targets it might be required to override the word size for better
+performance.
+Backend word size can be overridden for `serial` and `fiat` by setting the
+environment variable:
+```sh
+RUSTFLAGS='--cfg curve25519_dalek_bits="SIZE"'
+```
+`SIZE` is `32` or `64`. As in the above section, this can also be placed
+in `~/.cargo/config`.
+
+Note: The [SIMD backend] requires a word size of 64 bits. Attempting to set bits=32 and backend=`simd` will yield a compile error.
+
+### Cross-compilation
+
+Because backend selection is done by target, cross-compiling will select the correct word size automatically. For example, if a x86-64 Linux machine runs the following commands, `curve25519-dalek` will be compiled with the 32-bit `serial` backend.
+```console
+$ sudo apt install gcc-multilib # (or whatever package manager you use)
+$ rustup target add i686-unknown-linux-gnu
+$ cargo build --target i686-unknown-linux-gnu
+```
+
+## SIMD backend
+
+The specific SIMD backend (AVX512 / AVX2 / `serial` default) is selected automatically at runtime, depending on the currently available CPU features, and whether Rust nightly is being used for compilation. The precise conditions are specified below.
+
+For a given CPU feature, you can also specify an appropriate `-C target_feature` to build a binary which assumes the required SIMD instructions are always available. Don't do this if you don't have a good reason.
+
+| Backend | `RUSTFLAGS` | Requires nightly? |
+| :--- | :--- | :--- |
+| avx2 | `-C target_feature=+avx2` | no |
+| avx512 | `-C target_feature=+avx512ifma,+avx512vl` | yes |
+
+If compiled on a non-nightly compiler, `curve25519-dalek` will not include AVX512 code, and therefore will never select it at runtime.
+
+# Documentation
+
+The semver-stable, public-facing `curve25519-dalek` API is documented [here][docs].
+
+## Building Docs Locally
+
+The `curve25519-dalek` documentation requires a custom HTML header to include
+KaTeX for math support. Unfortunately `cargo doc` does not currently support
+this, but docs can be built using
+```sh
+make doc
+```
+for regular docs, and
+```sh
+make doc-internal
+```
+for docs that include private items.
+
+# Maintenance Policies
+
+All on-by-default features of this library are covered by
+[semantic versioning][semver] (SemVer). SemVer exemptions are outlined below
+for MSRV and public API.
+
+## Minimum Supported Rust Version
+
+| Releases | MSRV |
+| :--- |:-------|
+| 4.x | 1.60.0 |
+| 3.x | 1.41.0 |
+
+From 4.x and on, MSRV changes will be accompanied by a minor version bump.
+
+## Public API SemVer Exemptions
+
+Breaking changes to SemVer-exempted components affecting the public API will be accompanied by
+_some_ version bump. Below are the specific policies:
+
+| Releases | Public API Component(s) | Policy |
+| :--- | :--- | :--- |
+| 4.x | Dependencies `group`, `digest` and `rand_core` | Minor SemVer bump |
+
+# Safety
+
+The `curve25519-dalek` types are designed to make illegal states
+unrepresentable. For example, any instance of an `EdwardsPoint` is
+guaranteed to hold a point on the Edwards curve, and any instance of a
+`RistrettoPoint` is guaranteed to hold a valid point in the Ristretto
+group.
+
+All operations are implemented using constant-time logic (no
+secret-dependent branches, no secret-dependent memory accesses),
+unless specifically marked as being variable-time code.
+We believe that our constant-time logic is lowered to constant-time
+assembly, at least on `x86_64` targets.
+
+As an additional guard against possible future compiler optimizations,
+the `subtle` crate places an optimization barrier before every
+conditional move or assignment. More details can be found in [the
+documentation for the `subtle` crate][subtle_doc].
+
+Some functionality (e.g., multiscalar multiplication or batch
+inversion) requires heap allocation for temporary buffers. All
+heap-allocated buffers of potentially secret data are explicitly
+zeroed before release.
+
+However, we do not attempt to zero stack data, for two reasons.
+First, it's not possible to do so correctly: we don't have control
+over stack allocations, so there's no way to know how much data to
+wipe. Second, because `curve25519-dalek` provides a mid-level API,
+the correct place to start zeroing stack data is likely not at the
+entrypoints of `curve25519-dalek` functions, but at the entrypoints of
+functions in other crates.
+
+The implementation is memory-safe, and contains no significant
+`unsafe` code. The SIMD backend uses `unsafe` internally to call SIMD
+intrinsics. These are marked `unsafe` only because invoking them on an
+inappropriate CPU would cause `SIGILL`, but the entire backend is only
+invoked when the appropriate CPU features are detected at runtime, or
+when the whole program is compiled with the appropriate `target_feature`s.
+
+# Performance
+
+Benchmarks are run using [`criterion.rs`][criterion]:
+
+```sh
+cargo bench --features "rand_core"
+export RUSTFLAGS='-C target_cpu=native'
+cargo +nightly bench --features "rand_core"
+```
+
+Performance is a secondary goal behind correctness, safety, and
+clarity, but we aim to be competitive with other implementations.
+
+# FFI
+
+Unfortunately, we have no plans to add FFI to `curve25519-dalek` directly. The
+reason is that we use Rust features to provide an API that maintains safety
+invariants, which are not possible to maintain across an FFI boundary. For
+instance, as described in the _Safety_ section above, invalid points are
+impossible to construct, and this would not be the case if we exposed point
+operations over FFI.
+
+However, `curve25519-dalek` is designed as a *mid-level* API, aimed at
+implementing other, higher-level primitives. Instead of providing FFI at the
+mid-level, our suggestion is to implement the higher-level primitive (a
+signature, PAKE, ZKP, etc) in Rust, using `curve25519-dalek` as a dependency,
+and have that crate provide a minimal, byte-buffer-oriented FFI specific to
+that primitive.
+
+# Contributing
+
+Please see [CONTRIBUTING.md][contributing].
+
+# About
+
+**SPOILER ALERT:** *The Twelfth Doctor's first encounter with the Daleks is in
+his second full episode, "Into the Dalek". A beleaguered ship of the "Combined
+Galactic Resistance" has discovered a broken Dalek that has turned "good",
+desiring to kill all other Daleks. The Doctor, Clara and a team of soldiers
+are miniaturized and enter the Dalek, which the Doctor names Rusty. They
+repair the damage, but accidentally restore it to its original nature, causing
+it to go on the rampage and alert the Dalek fleet to the whereabouts of the
+rebel ship. However, the Doctor manages to return Rusty to its previous state
+by linking his mind with the Dalek's: Rusty shares the Doctor's view of the
+universe's beauty, but also his deep hatred of the Daleks. Rusty destroys the
+other Daleks and departs the ship, determined to track down and bring an end
+to the Dalek race.*
+
+`curve25519-dalek` is authored by Isis Agora Lovecruft and Henry de Valence.
+
+Portions of this library were originally a port of [Adam Langley's
+Golang ed25519 library](https://github.com/agl/ed25519), which was in
+turn a port of the reference `ref10` implementation. Most of this code,
+including the 32-bit field arithmetic, has since been rewritten.
+
+The fast `u32` and `u64` scalar arithmetic was implemented by Andrew Moon, and
+the addition chain for scalar inversion was provided by Brian Smith. The
+optimised batch inversion was contributed by Sean Bowe and Daira Hopwood.
+
+The `no_std` and `zeroize` support was contributed by Tony Arcieri.
+
+The formally verified `fiat_backend` integrates Rust code generated by the
+[Fiat Crypto project](https://github.com/mit-plv/fiat-crypto) and was
+contributed by François Garillot.
+
+Thanks also to Ashley Hauck, Lucas Salibian, Manish Goregaokar, Jack Grigg,
+Pratyush Mishra, Michael Rosenberg, @pinkforest, and countless others for their
+contributions.
+
+[ed25519-dalek]: https://github.com/dalek-cryptography/curve25519-dalek/tree/main/ed25519-dalek
+[x25519-dalek]: https://github.com/dalek-cryptography/curve25519-dalek/tree/main/x25519-dalek
+[docs]: https://docs.rs/curve25519-dalek/
+[contributing]: https://github.com/dalek-cryptography/curve25519-dalek/blob/master/CONTRIBUTING.md
+[criterion]: https://github.com/japaric/criterion.rs
+[parallel_doc]: https://docs.rs/curve25519-dalek/latest/curve25519_dalek/backend/vector/index.html
+[subtle_doc]: https://docs.rs/subtle
+[fiat-crypto]: https://github.com/mit-plv/fiat-crypto
+[semver]: https://semver.org/spec/v2.0.0.html
+[rngcorestd]: https://github.com/rust-random/rand/tree/7aa25d577e2df84a5156f824077bb7f6bdf28d97/rand_core#crate-features
+[zeroize-trait]: https://docs.rs/zeroize/latest/zeroize/trait.Zeroize.html
+[SIMD backend]: #simd-backend
diff --git a/vendor/curve25519-dalek/benches/dalek_benchmarks.rs b/vendor/curve25519-dalek/benches/dalek_benchmarks.rs
new file mode 100644
index 0000000..62a6280
--- /dev/null
+++ b/vendor/curve25519-dalek/benches/dalek_benchmarks.rs
@@ -0,0 +1,366 @@
+#![allow(non_snake_case)]
+
+use rand::{rngs::OsRng, thread_rng};
+
+use criterion::{
+ criterion_main, measurement::Measurement, BatchSize, BenchmarkGroup, BenchmarkId, Criterion,
+};
+
+use curve25519_dalek::constants;
+use curve25519_dalek::scalar::Scalar;
+
+static BATCH_SIZES: [usize; 5] = [1, 2, 4, 8, 16];
+static MULTISCALAR_SIZES: [usize; 13] = [1, 2, 4, 8, 16, 32, 64, 128, 256, 384, 512, 768, 1024];
+
+mod edwards_benches {
+ use super::*;
+
+ use curve25519_dalek::edwards::EdwardsPoint;
+
+ fn compress(c: &mut BenchmarkGroup) {
+ let B = &constants::ED25519_BASEPOINT_POINT;
+ c.bench_function("EdwardsPoint compression", move |b| b.iter(|| B.compress()));
+ }
+
+ fn decompress(c: &mut BenchmarkGroup) {
+ let B_comp = &constants::ED25519_BASEPOINT_COMPRESSED;
+ c.bench_function("EdwardsPoint decompression", move |b| {
+ b.iter(|| B_comp.decompress().unwrap())
+ });
+ }
+
+ fn consttime_fixed_base_scalar_mul(c: &mut BenchmarkGroup) {
+ let s = Scalar::from(897987897u64).invert();
+ c.bench_function("Constant-time fixed-base scalar mul", move |b| {
+ b.iter(|| EdwardsPoint::mul_base(&s))
+ });
+ }
+
+ fn consttime_variable_base_scalar_mul(c: &mut BenchmarkGroup) {
+ let B = &constants::ED25519_BASEPOINT_POINT;
+ let s = Scalar::from(897987897u64).invert();
+ c.bench_function("Constant-time variable-base scalar mul", move |b| {
+ b.iter(|| B * s)
+ });
+ }
+
+ fn vartime_double_base_scalar_mul(c: &mut BenchmarkGroup) {
+ c.bench_function("Variable-time aA+bB, A variable, B fixed", |bench| {
+ let mut rng = thread_rng();
+ let A = EdwardsPoint::mul_base(&Scalar::random(&mut rng));
+ bench.iter_batched(
+ || (Scalar::random(&mut rng), Scalar::random(&mut rng)),
+ |(a, b)| EdwardsPoint::vartime_double_scalar_mul_basepoint(&a, &A, &b),
+ BatchSize::SmallInput,
+ );
+ });
+ }
+
+ pub(crate) fn edwards_benches() {
+ let mut c = Criterion::default();
+ let mut g = c.benchmark_group("edwards benches");
+
+ compress(&mut g);
+ decompress(&mut g);
+ consttime_fixed_base_scalar_mul(&mut g);
+ consttime_variable_base_scalar_mul(&mut g);
+ vartime_double_base_scalar_mul(&mut g);
+ }
+}
+
+mod multiscalar_benches {
+ use super::*;
+
+ use curve25519_dalek::edwards::EdwardsPoint;
+ use curve25519_dalek::edwards::VartimeEdwardsPrecomputation;
+ use curve25519_dalek::traits::MultiscalarMul;
+ use curve25519_dalek::traits::VartimeMultiscalarMul;
+ use curve25519_dalek::traits::VartimePrecomputedMultiscalarMul;
+
+ fn construct_scalars(n: usize) -> Vec {
+ let mut rng = thread_rng();
+ (0..n).map(|_| Scalar::random(&mut rng)).collect()
+ }
+
+ fn construct_points(n: usize) -> Vec {
+ let mut rng = thread_rng();
+ (0..n)
+ .map(|_| EdwardsPoint::mul_base(&Scalar::random(&mut rng)))
+ .collect()
+ }
+
+ fn consttime_multiscalar_mul(c: &mut BenchmarkGroup) {
+ for multiscalar_size in &MULTISCALAR_SIZES {
+ c.bench_with_input(
+ BenchmarkId::new(
+ "Constant-time variable-base multiscalar multiplication",
+ *multiscalar_size,
+ ),
+ &multiscalar_size,
+ |b, &&size| {
+ let points = construct_points(size);
+ // This is supposed to be constant-time, but we might as well
+ // rerandomize the scalars for every call just in case.
+ b.iter_batched(
+ || construct_scalars(size),
+ |scalars| EdwardsPoint::multiscalar_mul(&scalars, &points),
+ BatchSize::SmallInput,
+ );
+ },
+ );
+ }
+ }
+
+ fn vartime_multiscalar_mul(c: &mut BenchmarkGroup) {
+ for multiscalar_size in &MULTISCALAR_SIZES {
+ c.bench_with_input(
+ BenchmarkId::new(
+ "Variable-time variable-base multiscalar multiplication",
+ *multiscalar_size,
+ ),
+ &multiscalar_size,
+ |b, &&size| {
+ let points = construct_points(size);
+ // Rerandomize the scalars for every call to prevent
+ // false timings from better caching (e.g., the CPU
+ // cache lifts exactly the right table entries for the
+ // benchmark into the highest cache levels).
+ b.iter_batched(
+ || construct_scalars(size),
+ |scalars| EdwardsPoint::vartime_multiscalar_mul(&scalars, &points),
+ BatchSize::SmallInput,
+ );
+ },
+ );
+ }
+ }
+
+ fn vartime_precomputed_pure_static(c: &mut BenchmarkGroup) {
+ for multiscalar_size in &MULTISCALAR_SIZES {
+ c.bench_with_input(
+ BenchmarkId::new(
+ "Variable-time fixed-base multiscalar multiplication",
+ multiscalar_size,
+ ),
+ &multiscalar_size,
+ move |b, &&total_size| {
+ let static_size = total_size;
+
+ let static_points = construct_points(static_size);
+ let precomp = VartimeEdwardsPrecomputation::new(static_points);
+ // Rerandomize the scalars for every call to prevent
+ // false timings from better caching (e.g., the CPU
+ // cache lifts exactly the right table entries for the
+ // benchmark into the highest cache levels).
+ b.iter_batched(
+ || construct_scalars(static_size),
+ |scalars| precomp.vartime_multiscalar_mul(scalars),
+ BatchSize::SmallInput,
+ );
+ },
+ );
+ }
+ }
+
+ fn vartime_precomputed_helper(
+ c: &mut BenchmarkGroup,
+ dynamic_fraction: f64,
+ ) {
+ for multiscalar_size in &MULTISCALAR_SIZES {
+ let bench_id = BenchmarkId::new(
+ "Variable-time mixed-base",
+ format!(
+ "(size: {:?}), ({:.0}pct dyn)",
+ multiscalar_size,
+ 100.0 * dynamic_fraction
+ ),
+ );
+
+ c.bench_with_input(bench_id, &multiscalar_size, move |b, &&total_size| {
+ let dynamic_size = ((total_size as f64) * dynamic_fraction) as usize;
+ let static_size = total_size - dynamic_size;
+
+ let static_points = construct_points(static_size);
+ let dynamic_points = construct_points(dynamic_size);
+ let precomp = VartimeEdwardsPrecomputation::new(static_points);
+ // Rerandomize the scalars for every call to prevent
+ // false timings from better caching (e.g., the CPU
+ // cache lifts exactly the right table entries for the
+ // benchmark into the highest cache levels). Timings
+ // should be independent of points so we don't
+ // randomize them.
+ b.iter_batched(
+ || {
+ (
+ construct_scalars(static_size),
+ construct_scalars(dynamic_size),
+ )
+ },
+ |(static_scalars, dynamic_scalars)| {
+ precomp.vartime_mixed_multiscalar_mul(
+ &static_scalars,
+ &dynamic_scalars,
+ &dynamic_points,
+ )
+ },
+ BatchSize::SmallInput,
+ );
+ });
+ }
+ }
+
+ pub(crate) fn multiscalar_benches() {
+ let mut c = Criterion::default();
+ let mut g = c.benchmark_group("multiscalar benches");
+
+ consttime_multiscalar_mul(&mut g);
+ vartime_multiscalar_mul(&mut g);
+ vartime_precomputed_pure_static(&mut g);
+
+ let dynamic_fracs = [0.0, 0.2, 0.5];
+
+ for frac in dynamic_fracs.iter() {
+ vartime_precomputed_helper(&mut g, *frac);
+ }
+ }
+}
+
+mod ristretto_benches {
+ use super::*;
+ use curve25519_dalek::ristretto::RistrettoPoint;
+
+ fn compress(c: &mut BenchmarkGroup) {
+ c.bench_function("RistrettoPoint compression", |b| {
+ let B = &constants::RISTRETTO_BASEPOINT_POINT;
+ b.iter(|| B.compress())
+ });
+ }
+
+ fn decompress(c: &mut BenchmarkGroup) {
+ c.bench_function("RistrettoPoint decompression", |b| {
+ let B_comp = &constants::RISTRETTO_BASEPOINT_COMPRESSED;
+ b.iter(|| B_comp.decompress().unwrap())
+ });
+ }
+
+ fn double_and_compress_batch(c: &mut BenchmarkGroup) {
+ for batch_size in &BATCH_SIZES {
+ c.bench_with_input(
+ BenchmarkId::new("Batch Ristretto double-and-encode", *batch_size),
+ &batch_size,
+ |b, &&size| {
+ let mut rng = OsRng;
+ let points: Vec = (0..size)
+ .map(|_| RistrettoPoint::random(&mut rng))
+ .collect();
+ b.iter(|| RistrettoPoint::double_and_compress_batch(&points));
+ },
+ );
+ }
+ }
+
+ pub(crate) fn ristretto_benches() {
+ let mut c = Criterion::default();
+ let mut g = c.benchmark_group("ristretto benches");
+
+ compress(&mut g);
+ decompress(&mut g);
+ double_and_compress_batch(&mut g);
+ }
+}
+
+mod montgomery_benches {
+ use super::*;
+ use curve25519_dalek::montgomery::MontgomeryPoint;
+
+ fn montgomery_ladder(c: &mut BenchmarkGroup) {
+ c.bench_function("Montgomery pseudomultiplication", |b| {
+ let B = constants::X25519_BASEPOINT;
+ let s = Scalar::from(897987897u64).invert();
+ b.iter(|| B * s);
+ });
+ }
+
+ fn consttime_fixed_base_scalar_mul(c: &mut BenchmarkGroup) {
+ let s = Scalar::from(897987897u64).invert();
+ c.bench_function("Constant-time fixed-base scalar mul", move |b| {
+ b.iter(|| MontgomeryPoint::mul_base(&s))
+ });
+ }
+
+ pub(crate) fn montgomery_benches() {
+ let mut c = Criterion::default();
+ let mut g = c.benchmark_group("montgomery benches");
+
+ montgomery_ladder(&mut g);
+ consttime_fixed_base_scalar_mul(&mut g);
+ }
+}
+
+mod scalar_benches {
+ use super::*;
+
+ fn scalar_arith(c: &mut BenchmarkGroup) {
+ let mut rng = thread_rng();
+
+ c.bench_function("Scalar inversion", |b| {
+ let s = Scalar::from(897987897u64).invert();
+ b.iter(|| s.invert());
+ });
+ c.bench_function("Scalar addition", |b| {
+ b.iter_batched(
+ || (Scalar::random(&mut rng), Scalar::random(&mut rng)),
+ |(a, b)| a + b,
+ BatchSize::SmallInput,
+ );
+ });
+ c.bench_function("Scalar subtraction", |b| {
+ b.iter_batched(
+ || (Scalar::random(&mut rng), Scalar::random(&mut rng)),
+ |(a, b)| a - b,
+ BatchSize::SmallInput,
+ );
+ });
+ c.bench_function("Scalar multiplication", |b| {
+ b.iter_batched(
+ || (Scalar::random(&mut rng), Scalar::random(&mut rng)),
+ |(a, b)| a * b,
+ BatchSize::SmallInput,
+ );
+ });
+ }
+
+ fn batch_scalar_inversion(c: &mut BenchmarkGroup) {
+ for batch_size in &BATCH_SIZES {
+ c.bench_with_input(
+ BenchmarkId::new("Batch scalar inversion", *batch_size),
+ &batch_size,
+ |b, &&size| {
+ let mut rng = OsRng;
+ let scalars: Vec =
+ (0..size).map(|_| Scalar::random(&mut rng)).collect();
+ b.iter(|| {
+ let mut s = scalars.clone();
+ Scalar::batch_invert(&mut s);
+ });
+ },
+ );
+ }
+ }
+
+ pub(crate) fn scalar_benches() {
+ let mut c = Criterion::default();
+ let mut g = c.benchmark_group("scalar benches");
+
+ scalar_arith(&mut g);
+ batch_scalar_inversion(&mut g);
+ }
+}
+
+criterion_main!(
+ scalar_benches::scalar_benches,
+ montgomery_benches::montgomery_benches,
+ ristretto_benches::ristretto_benches,
+ edwards_benches::edwards_benches,
+ multiscalar_benches::multiscalar_benches,
+);
diff --git a/vendor/curve25519-dalek/build.rs b/vendor/curve25519-dalek/build.rs
new file mode 100644
index 0000000..97fa285
--- /dev/null
+++ b/vendor/curve25519-dalek/build.rs
@@ -0,0 +1,126 @@
+//! This selects the curve25519_dalek_bits either by default from target_pointer_width or explicitly set
+
+#![deny(clippy::unwrap_used, dead_code)]
+
+#[allow(non_camel_case_types)]
+#[derive(PartialEq, Debug)]
+enum DalekBits {
+ Dalek32,
+ Dalek64,
+}
+
+use std::fmt::Formatter;
+
+impl std::fmt::Display for DalekBits {
+ fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
+ let w_bits = match self {
+ DalekBits::Dalek32 => "32",
+ DalekBits::Dalek64 => "64",
+ };
+ write!(f, "{}", w_bits)
+ }
+}
+
+fn main() {
+ let target_arch = match std::env::var("CARGO_CFG_TARGET_ARCH") {
+ Ok(arch) => arch,
+ _ => "".to_string(),
+ };
+
+ let curve25519_dalek_bits = match std::env::var("CARGO_CFG_CURVE25519_DALEK_BITS").as_deref() {
+ Ok("32") => DalekBits::Dalek32,
+ Ok("64") => DalekBits::Dalek64,
+ _ => deterministic::determine_curve25519_dalek_bits(&target_arch),
+ };
+
+ println!("cargo:rustc-cfg=curve25519_dalek_bits=\"{curve25519_dalek_bits}\"");
+
+ if rustc_version::version_meta()
+ .expect("failed to detect rustc version")
+ .channel
+ == rustc_version::Channel::Nightly
+ {
+ println!("cargo:rustc-cfg=nightly");
+ }
+
+ let rustc_version = rustc_version::version().expect("failed to detect rustc version");
+ if rustc_version.major == 1 && rustc_version.minor <= 64 {
+ // Old versions of Rust complain when you have an `unsafe fn` and you use `unsafe {}` inside,
+ // so for those we want to apply the `#[allow(unused_unsafe)]` attribute to get rid of that warning.
+ println!("cargo:rustc-cfg=allow_unused_unsafe");
+ }
+
+ // Backend overrides / defaults
+ let curve25519_dalek_backend =
+ match std::env::var("CARGO_CFG_CURVE25519_DALEK_BACKEND").as_deref() {
+ Ok("fiat") => "fiat",
+ Ok("serial") => "serial",
+ Ok("simd") => {
+ // simd can only be enabled on x86_64 & 64bit target_pointer_width
+ match is_capable_simd(&target_arch, curve25519_dalek_bits) {
+ true => "simd",
+ // If override is not possible this must result to compile error
+ // See: issues/532
+ false => panic!("Could not override curve25519_dalek_backend to simd"),
+ }
+ }
+ // default between serial / simd (if potentially capable)
+ _ => match is_capable_simd(&target_arch, curve25519_dalek_bits) {
+ true => "simd",
+ false => "serial",
+ },
+ };
+ println!("cargo:rustc-cfg=curve25519_dalek_backend=\"{curve25519_dalek_backend}\"");
+}
+
+// Is the target arch & curve25519_dalek_bits potentially simd capable ?
+fn is_capable_simd(arch: &str, bits: DalekBits) -> bool {
+ arch == "x86_64" && bits == DalekBits::Dalek64
+}
+
+// Deterministic cfg(curve25519_dalek_bits) when this is not explicitly set.
+mod deterministic {
+
+ use super::*;
+
+ // Custom Rust non-cargo build tooling needs to set CARGO_CFG_TARGET_POINTER_WIDTH
+ static ERR_MSG_NO_POINTER_WIDTH: &str =
+ "Standard Cargo TARGET_POINTER_WIDTH environment variable is not set.";
+
+ // When either non-32 or 64 TARGET_POINTER_WIDTH detected
+ static ERR_MSG_UNKNOWN_POINTER_WIDTH: &str = "Unknown TARGET_POINTER_WIDTH detected.";
+
+ // Warning when the curve25519_dalek_bits cannot be determined
+ fn determine_curve25519_dalek_bits_warning(cause: &str) {
+ println!("cargo:warning=\"Defaulting to curve25519_dalek_bits=32: {cause}\"");
+ }
+
+ // Determine the curve25519_dalek_bits based on Rust standard TARGET triplet
+ pub(super) fn determine_curve25519_dalek_bits(target_arch: &String) -> DalekBits {
+ let target_pointer_width = match std::env::var("CARGO_CFG_TARGET_POINTER_WIDTH") {
+ Ok(pw) => pw,
+ Err(_) => {
+ determine_curve25519_dalek_bits_warning(ERR_MSG_NO_POINTER_WIDTH);
+ return DalekBits::Dalek32;
+ }
+ };
+
+ #[allow(clippy::match_single_binding)]
+ match &target_arch {
+ //Issues: 449 and 456
+ //TODO: When adding arch defaults use proper types not String match
+ //TODO(Arm): Needs tests + benchmarks to back this up
+ //TODO(Wasm32): Needs tests + benchmarks to back this up
+ _ => match target_pointer_width.as_ref() {
+ "64" => DalekBits::Dalek64,
+ "32" => DalekBits::Dalek32,
+ // Intended default solely for non-32/64 target pointer widths
+ // Otherwise known target platforms only.
+ _ => {
+ determine_curve25519_dalek_bits_warning(ERR_MSG_UNKNOWN_POINTER_WIDTH);
+ DalekBits::Dalek32
+ }
+ },
+ }
+ }
+}
diff --git a/vendor/curve25519-dalek/docs/assets/rustdoc-include-katex-header.html b/vendor/curve25519-dalek/docs/assets/rustdoc-include-katex-header.html
new file mode 100644
index 0000000..d240432
--- /dev/null
+++ b/vendor/curve25519-dalek/docs/assets/rustdoc-include-katex-header.html
@@ -0,0 +1,12 @@
+
+
+
+
+
+
+
+
+
diff --git a/vendor/curve25519-dalek/docs/avx2-notes.md b/vendor/curve25519-dalek/docs/avx2-notes.md
new file mode 100644
index 0000000..ccb5022
--- /dev/null
+++ b/vendor/curve25519-dalek/docs/avx2-notes.md
@@ -0,0 +1,140 @@
+An AVX2 implementation of the vectorized point operation strategy.
+
+# Field element representation
+
+Our strategy is to implement 4-wide multiplication and squaring by
+wordslicing, using one 64-bit AVX2 lane for each field element. Field
+elements are represented in the usual way as 10 `u32` limbs in radix
+\\(25.5\\) (i.e., alternating between \\(2\^{26}\\) for even limbs and
+\\(2\^{25}\\) for odd limbs). This has the effect that passing between
+the parallel 32-bit AVX2 representation and the serial 64-bit
+representation (which uses radix \\(2^{51}\\)) amounts to regrouping
+digits.
+
+The field element representation is oriented around the AVX2
+`vpmuludq` instruction, which multiplies the low 32 bits of each
+64-bit lane of each operand to produce a 64-bit result.
+
+```text,no_run
+(a1 ?? b1 ?? c1 ?? d1 ??)
+(a2 ?? b2 ?? c2 ?? d2 ??)
+
+(a1*a2 b1*b2 c1*c2 d1*d2)
+```
+
+To unpack 32-bit values into 64-bit lanes for use in multiplication
+it would be convenient to use the `vpunpck[lh]dq` instructions,
+which unpack and interleave the low and high 32-bit lanes of two
+source vectors.
+However, the AVX2 versions of these instructions are designed to
+operate only within 128-bit lanes of the 256-bit vectors, so that
+interleaving the low lanes of `(a0 b0 c0 d0 a1 b1 c1 d1)` with zero
+gives `(a0 00 b0 00 a1 00 b1 00)`. Instead, we pre-shuffle the data
+layout as `(a0 b0 a1 b1 c0 d0 c1 d1)` so that we can unpack the
+"low" and "high" parts as
+
+```text,no_run
+(a0 00 b0 00 c0 00 d0 00)
+(a1 00 b1 00 c1 00 d1 00)
+```
+
+The data layout for a vector of four field elements \\( (a,b,c,d)
+\\) with limbs \\( a_0, a_1, \ldots, a_9 \\) is as `[u32x8; 5]` in
+the form
+
+```text,no_run
+(a0 b0 a1 b1 c0 d0 c1 d1)
+(a2 b2 a3 b3 c2 d2 c3 d3)
+(a4 b4 a5 b5 c4 d4 c5 d5)
+(a6 b6 a7 b7 c6 d6 c7 d7)
+(a8 b8 a9 b9 c8 d8 c9 d9)
+```
+
+Since this breaks cleanly into two 128-bit lanes, it may be possible
+to adapt it to 128-bit vector instructions such as NEON without too
+much difficulty.
+
+# Avoiding Overflow in Doubling
+
+To analyze the size of the field element coefficients during the
+computations, we can parameterize the bounds on the limbs of each
+field element by \\( b \in \mathbb R \\) representing the excess bits
+above that limb's radix, so that each limb is bounded by either
+\\(2\^{25+b} \\) or \\( 2\^{26+b} \\), as appropriate.
+
+The multiplication routine requires that its inputs are bounded with
+\\( b < 1.75 \\), in order to fit a multiplication by \\( 19 \\)
+into 32 bits. Since \\( \lg 19 < 4.25 \\), \\( 19x < 2\^{32} \\)
+when \\( x < 2\^{27.75} = 2\^{26 + 1.75} \\). However, this is only
+required for one of the inputs; the other can grow up to \\( b < 2.5
+\\).
+
+In addition, the multiplication and squaring routines do not
+canonically reduce their outputs, but can leave some small uncarried
+excesses, so that their reduced outputs are bounded with
+\\( b < 0.007 \\).
+
+The non-parallel portion of the doubling formulas is
+$$
+\begin{aligned}
+(S\_5 &&,&& S\_6 &&,&& S\_8 &&,&& S\_9 )
+&\gets
+(S\_1 + S\_2 &&,&& S\_1 - S\_2 &&,&& S\_1 + 2S\_3 - S\_2 &&,&& S\_1 + S\_2 - S\_4)
+\end{aligned}
+$$
+
+Computing \\( (S\_5, S\_6, S\_8, S\_9 ) \\) as
+$$
+\begin{matrix}
+ & S\_1 & S\_1 & S\_1 & S\_1 \\\\
++& S\_2 & & & S\_2 \\\\
++& & & S\_3 & \\\\
++& & & S\_3 & \\\\
++& & 2p & 2p & 2p \\\\
+-& & S\_2 & S\_2 & \\\\
+-& & & & S\_4 \\\\
+=& S\_5 & S\_6 & S\_8 & S\_9
+\end{matrix}
+$$
+results in bit-excesses \\( < (1.01, 1.60, 2.33, 2.01)\\) for
+\\( (S\_5, S\_6, S\_8, S\_9 ) \\). The products we want to compute
+are then
+$$
+\begin{aligned}
+X\_3 &\gets S\_8 S\_9 \leftrightarrow (2.33, 2.01) \\\\
+Y\_3 &\gets S\_5 S\_6 \leftrightarrow (1.01, 1.60) \\\\
+Z\_3 &\gets S\_8 S\_6 \leftrightarrow (2.33, 1.60) \\\\
+T\_3 &\gets S\_5 S\_9 \leftrightarrow (1.01, 2.01)
+\end{aligned}
+$$
+which are too large: it's not possible to arrange the multiplicands so
+that one vector has \\(b < 2.5\\) and the other has \\( b < 1.75 \\).
+However, if we flip the sign of \\( S\_4 = S\_0\^2 \\) during
+squaring, so that we output \\(S\_4' = -S\_4 \pmod p\\), then we can
+compute
+$$
+\begin{matrix}
+ & S\_1 & S\_1 & S\_1 & S\_1 \\\\
++& S\_2 & & & S\_2 \\\\
++& & & S\_3 & \\\\
++& & & S\_3 & \\\\
++& & & & S\_4' \\\\
++& & 2p & 2p & \\\\
+-& & S\_2 & S\_2 & \\\\
+=& S\_5 & S\_6 & S\_8 & S\_9
+\end{matrix}
+$$
+resulting in bit-excesses \\( < (1.01, 1.60, 2.33, 1.60)\\) for
+\\( (S\_5, S\_6, S\_8, S\_9 ) \\). The products we want to compute
+are then
+$$
+\begin{aligned}
+X\_3 &\gets S\_8 S\_9 \leftrightarrow (2.33, 1.60) \\\\
+Y\_3 &\gets S\_5 S\_6 \leftrightarrow (1.01, 1.60) \\\\
+Z\_3 &\gets S\_8 S\_6 \leftrightarrow (2.33, 1.60) \\\\
+T\_3 &\gets S\_5 S\_9 \leftrightarrow (1.01, 1.60)
+\end{aligned}
+$$
+whose right-hand sides are all bounded with \\( b < 1.75 \\) and
+whose left-hand sides are all bounded with \\( b < 2.5 \\),
+so that we can avoid any intermediate reductions.
diff --git a/vendor/curve25519-dalek/docs/ifma-notes.md b/vendor/curve25519-dalek/docs/ifma-notes.md
new file mode 100644
index 0000000..faf8928
--- /dev/null
+++ b/vendor/curve25519-dalek/docs/ifma-notes.md
@@ -0,0 +1,580 @@
+An AVX512-IFMA implementation of the vectorized point operation
+strategy.
+
+# IFMA instructions
+
+AVX512-IFMA is an extension to AVX-512 consisting of two instructions:
+
+* `vpmadd52luq`: packed multiply of unsigned 52-bit integers and add
+ the low 52 product bits to 64-bit accumulators;
+* `vpmadd52huq`: packed multiply of unsigned 52-bit integers and add
+ the high 52 product bits to 64-bit accumulators;
+
+These operate on 64-bit lanes of their source vectors, taking the low
+52 bits of each lane of each source vector, computing the 104-bit
+products of each pair, and then adding either the high or low 52 bits
+of the 104-bit products to the 64-bit lanes of the destination vector.
+The multiplication is performed internally by reusing circuitry for
+floating-point arithmetic. Although these instructions are part of
+AVX512, the AVX512VL (vector length) extension (present whenever IFMA
+is) allows using them with 512, 256, or 128-bit operands.
+
+This provides a major advantage to vectorized integer operations:
+previously, vector operations could only use a \\(32 \times 32
+\rightarrow 64\\)-bit multiplier, while serial code could use a
+\\(64\times 64 \rightarrow 128\\)-bit multiplier.
+
+## IFMA for big-integer multiplications
+
+A detailed example of the intended use of the IFMA instructions can be
+found in a 2016 paper by Gueron and Krasnov, [_Accelerating Big
+Integer Arithmetic Using Intel IFMA Extensions_][2016_gueron_krasnov].
+The basic idea is that multiplication of large integers (such as 1024,
+2048, or more bits) can be performed as follows.
+
+First, convert a “packed” 64-bit representation
+\\[
+\begin{aligned}
+x &= x'_0 + x'_1 2^{64} + x'_2 2^{128} + \cdots \\\\
+y &= y'_0 + y'_1 2^{64} + y'_2 2^{128} + \cdots
+\end{aligned}
+\\]
+into a “redundant” 52-bit representation
+\\[
+\begin{aligned}
+x &= x_0 + x_1 2^{52} + x_2 2^{104} + \cdots \\\\
+y &= y_0 + y_1 2^{52} + y_2 2^{104} + \cdots
+\end{aligned}
+\\]
+with each \\(x_i, y_j\\) in a 64-bit lane.
+
+Writing the product as \\(z = z_0 + z_1 2^{52} + z_2 2^{104} + \cdots\\),
+the “schoolbook” multiplication strategy gives
+\\[
+\begin{aligned}
+&z_0 &&=& x_0 & y_0 & & & & & & & & \\\\
+&z_1 &&=& x_1 & y_0 &+ x_0 & y_1 & & & & & & \\\\
+&z_2 &&=& x_2 & y_0 &+ x_1 & y_1 &+ x_0 & y_2 & & & & \\\\
+&z_3 &&=& x_3 & y_0 &+ x_2 & y_1 &+ x_1 & y_2 &+ x_0 & y_3 & & \\\\
+&z_4 &&=& \vdots\\;&\\;\vdots &+ x_3 & y_1 &+ x_2 & y_2 &+ x_1 & y_3 &+ \cdots& \\\\
+&z_5 &&=& & & \vdots\\;&\\;\vdots &+ x_3 & y_2 &+ x_2 & y_3 &+ \cdots& \\\\
+&z_6 &&=& & & & & \vdots\\;&\\;\vdots &+ x_3 & y_3 &+ \cdots& \\\\
+&z_7 &&=& & & & & & & \vdots\\;&\\;\vdots &+ \cdots& \\\\
+&\vdots&&=& & & & & & & & & \ddots& \\\\
+\end{aligned}
+\\]
+Notice that the product coefficient \\(z_k\\), representing the value
+\\(z_k 2^{52k}\\), is the sum of all product terms
+\\(
+(x_i 2^{52 i}) (y_j 2^{52 j})
+\\)
+with \\(k = i + j\\).
+Write the IFMA operators \\(\mathrm{lo}(a,b)\\), denoting the low
+\\(52\\) bits of \\(ab\\), and
+\\(\mathrm{hi}(a,b)\\), denoting the high \\(52\\) bits of
+\\(ab\\).
+Now we can rewrite the product terms as
+\\[
+\begin{aligned}
+(x_i 2^{52 i}) (y_j 2^{52 j})
+&=
+2^{52 (i+j)}(
+\mathrm{lo}(x_i, y_j) +
+\mathrm{hi}(x_i, y_j) 2^{52}
+)
+\\\\
+&=
+\mathrm{lo}(x_i, y_j) 2^{52 (i+j)} +
+\mathrm{hi}(x_i, y_j) 2^{52 (i+j+1)}.
+\end{aligned}
+\\]
+This means that the low half of \\(x_i y_j\\) can be accumulated onto
+the product limb \\(z_{i+j}\\) and the high half can be directly
+accumulated onto the next-higher product limb \\(z_{i+j+1}\\) with no
+additional operations. This allows rewriting the schoolbook
+multiplication into the form
+\\[
+\begin{aligned}
+&z_0 &&=& \mathrm{lo}(x_0,&y_0) & & & & & & & & & & \\\\
+&z_1 &&=& \mathrm{lo}(x_1,&y_0) &+\mathrm{hi}(x_0,&y_0) &+\mathrm{lo}(x_0,&y_1) & & & & & & \\\\
+&z_2 &&=& \mathrm{lo}(x_2,&y_0) &+\mathrm{hi}(x_1,&y_0) &+\mathrm{lo}(x_1,&y_1) &+\mathrm{hi}(x_0,&y_1) &+\mathrm{lo}(x_0,&y_2) & & \\\\
+&z_3 &&=& \mathrm{lo}(x_3,&y_0) &+\mathrm{hi}(x_2,&y_0) &+\mathrm{lo}(x_2,&y_1) &+\mathrm{hi}(x_1,&y_1) &+\mathrm{lo}(x_1,&y_2) &+ \cdots& \\\\
+&z_4 &&=& \vdots\\;&\\;\vdots &+\mathrm{hi}(x_3,&y_0) &+\mathrm{lo}(x_3,&y_1) &+\mathrm{hi}(x_2,&y_1) &+\mathrm{lo}(x_2,&y_2) &+ \cdots& \\\\
+&z_5 &&=& & & \vdots\\;&\\;\vdots & \vdots\\;&\\;\vdots &+\mathrm{hi}(x_3,&y_1) &+\mathrm{lo}(x_3,&y_2) &+ \cdots& \\\\
+&z_6 &&=& & & & & & & \vdots\\;&\\;\vdots & \vdots\\;&\\;\vdots &+ \cdots& \\\\
+&\vdots&&=& & & & & & & & & & & \ddots& \\\\
+\end{aligned}
+\\]
+Gueron and Krasnov implement multiplication by constructing vectors
+out of the columns of this diagram, so that the source operands for
+the IFMA instructions are of the form \\((x_0, x_1, x_2, \ldots)\\)
+and \\((y_i, y_i, y_i, \ldots)\\).
+After performing the multiplication,
+the product terms \\(z_i\\) are then repacked into a 64-bit representation.
+
+## An alternative strategy
+
+The strategy described above is aimed at big-integer multiplications,
+such as 1024, 2048, or 4096 bits, which would be used for applications
+like RSA. However, elliptic curve cryptography uses much smaller field
+sizes, such as 256 or 384 bits, so a different strategy is needed.
+
+The parallel Edwards formulas provide parallelism at the level of the
+formulas for curve operations. This means that instead of scanning
+through the terms of the source operands and parallelizing *within* a
+field element (as described above), we can arrange the computation in
+product-scanning form and parallelize *across* field elements (as
+described below).
+
+The parallel Edwards
+formulas provide 4-way parallelism, so they can be implemented using
+256-bit vectors using a single 64-bit lane for each element, or using
+512-bit vectors using two 64-bit lanes.
+The only available CPU supporting IFMA (the
+i3-8121U) executes 512-bit IFMA instructions at half rate compared to
+256-bit instructions, so for now there's no throughput advantage to
+using 512-bit IFMA instructions, and this implementation uses 256-bit
+vectors.
+
+To extend this to 512-bit vectors, it's only only necessary to achieve
+2-way parallelism, and it's possible (with a small amount of overhead)
+to create a hybrid strategy that operates entirely within 128-bit
+lanes. This means that cross-lane operations can use the faster
+`vpshufd` (1c latency) instead of a general shuffle instruction (3c
+latency).
+
+# Choice of radix
+
+The inputs to IFMA instructions are 52 bits wide, so the radix \\(r\\)
+used to represent a multiprecision integer must be \\( r \leq 52 \\).
+The obvious choice is the "native" radix \\(r = 52\\).
+
+As described above, this choice
+has the advantage that for \\(x_i, y_j \in [0,2^{52})\\), the product term
+\\[
+\begin{aligned}
+(x_i 2^{52 i}) (y_j 2^{52 j})
+&=
+2^{52 (i+j)}(
+\mathrm{lo}(x_i, y_j) +
+\mathrm{hi}(x_i, y_j) 2^{52}
+)
+\\\\
+&=
+\mathrm{lo}(x_i, y_j) 2^{52 (i+j)} +
+\mathrm{hi}(x_i, y_j) 2^{52 (i+j+1)},
+\end{aligned}
+\\]
+so that the low and high halves of the product can be directly accumulated
+onto the product limbs.
+In contrast, when using a smaller radix \\(r = 52 - k\\),
+the product term has the form
+\\[
+\begin{aligned}
+(x_i 2^{r i}) (y_j 2^{r j})
+&=
+2^{r (i+j)}(
+\mathrm{lo}(x_i, y_j) +
+\mathrm{hi}(x_i, y_j) 2^{52}
+)
+\\\\
+&=
+\mathrm{lo}(x_i, y_j) 2^{r (i+j)} +
+(
+\mathrm{hi}(x_i, y_j) 2^k
+)
+2^{r (i+j+1)}.
+\end{aligned}
+\\]
+What's happening is that the product \\(x_i y_j\\) of size \\(2r\\)
+bits is split not at \\(r\\) but at \\(52\\), so \\(k\\) product bits
+are placed into the low half instead of the high half. This means
+that the high half of the product cannot be directly accumulated onto
+\\(z_{i+j+1}\\), but must first be multiplied by \\(2^k\\) (i.e., left
+shifted by \\(k\\)). In addition, the low half of the product is
+\\(52\\) bits large instead of \\(r\\) bits.
+
+## Handling offset product terms
+
+[Drucker and Gueron][2018_drucker_gueron] analyze the choice of radix
+in the context of big-integer squaring, outlining three ways to handle
+the offset product terms, before concluding that all of them are
+suboptimal:
+
+1. Shift the results after accumulation;
+2. Shift the input operands before multiplication;
+3. Split the MAC operation, accumulating into a zeroed register,
+ shifting the result, and then adding.
+
+The first option is rejected because it could double-shift some
+previously accumulated terms, the second doesn't work because the
+inputs could become larger than \\(52\\) bits, and the third requires
+additional instructions to handle the shifting and adding.
+
+Based on an analysis of total number of instructions, they suggest an
+addition to the instruction set, which they call `FMSA` (fused
+multiply-shift-add). This would shift the result according to an 8-bit
+immediate value before accumulating it into the destination register.
+
+However, this change to the instruction set doesn't seem to be
+necessary. Instead, the product terms can be grouped according to
+their coefficients, accumulated together, then shifted once before
+adding them to the final sum. This uses an extra register, shift, and
+add, but only once per product term (accumulation target), not once
+per source term (as in the Drucker-Gueron paper).
+
+Moreover, because IFMA instructions execute only on two ports
+(presumably 0 and 1), while adds and shifts can execute on three ports
+(0, 1, and 5), the adds and shifts can execute independently of the
+IFMA operations, as long as there is not too much pressure on port 5.
+This means that, although the total number of instructions increases,
+the shifts and adds do not necessarily increase the execution time, as
+long as throughput is limited by IFMA operations.
+
+Finally, because IFMA instructions have 4 cycle latency and 0.5/1
+cycle throughput (for 256/512 bit vectors), maximizing IFMA throughput
+requires either 8 (for 256) or 4 (for 512) independent operations. So
+accumulating groups of terms independently before adding them at the
+end may be necessary anyways, in order to prevent long chains of
+dependent instructions.
+
+## Advantages of a smaller radix
+
+Using a smaller radix has other advantages. Although radix \\(52\\)
+is an unsaturated representation from the point of view of the
+\\(64\\)-bit accumulators (because up to 4096 product terms can be
+accumulated without carries), it's a saturated representation from the
+point of view of the multiplier (since \\(52\\)-bit values are the
+maximum input size).
+
+Because the inputs to a multiplication must have all of their limbs
+bounded by \\(2^{52}\\), limbs in excess of \\(2^{52}\\) must be
+reduced before they can be used as an input. The
+[Gueron-Krasnov][2016_gueron_krasnov] paper suggests normalizing
+values using a standard, sequential carry chain: for each limb, add
+the carryin from reducing the previous limb, compute the carryout and
+reduce the current limb, then move to the next limb.
+
+However, when using a smaller radix, such as \\(51\\), each limb can
+store a carry bit and still be used as the input to a multiplication.
+This means that the inputs do not need to be normalized, and instead
+of using a sequential carry chain, we can compute all carryouts in
+parallel, reduce all limbs in parallel, and then add the carryins in
+parallel (possibly growing the limb values by one bit).
+
+Because the output of this partial reduction is an acceptable
+multiplication input, we can "close the loop" using partial reductions
+and never have to normalize to a canonical representation through the
+entire computation, in contrast to the Gueron-Krasnov approach, which
+converts back to a packed representation after every operation. (This
+idea seems to trace back to at least as early as [this 1999
+paper][1999_walter]).
+
+Using \\(r = 51\\) is enough to keep a carry bit in each limb and
+avoid normalizations. What about an even smaller radix? One reason
+to choose a smaller radix would be to align the limb boundaries with
+an inline reduction (for instance, choosing \\(r = 43\\) for the
+Mersenne field \\(p = 2^{127} - 1\\)), but for \\(p = 2^{255 - 19}\\),
+\\(r = 51 = 255/5\\) is the natural choice.
+
+# Multiplication
+
+The inputs to a multiplication are two field elements
+\\[
+\begin{aligned}
+x &= x_0 + x_1 2^{51} + x_2 2^{102} + x_3 2^{153} + x_4 2^{204} \\\\
+y &= y_0 + y_1 2^{51} + y_2 2^{102} + y_3 2^{153} + y_4 2^{204},
+\end{aligned}
+\\]
+with limbs in range \\([0,2^{52})\\).
+
+Writing the product terms as
+\\[
+\begin{aligned}
+z &= z_0 + z_1 2^{51} + z_2 2^{102} + z_3 2^{153} + z_4 2^{204} \\\\
+ &+ z_5 2^{255} + z_6 2^{306} + z_7 2^{357} + z_8 2^{408} + z_9 2^{459},
+\end{aligned}
+\\]
+a schoolbook multiplication in product scanning form takes the form
+\\[
+\begin{aligned}
+z_0 &= x_0 y_0 \\\\
+z_1 &= x_1 y_0 + x_0 y_1 \\\\
+z_2 &= x_2 y_0 + x_1 y_1 + x_0 y_2 \\\\
+z_3 &= x_3 y_0 + x_2 y_1 + x_1 y_2 + x_0 y_3 \\\\
+z_4 &= x_4 y_0 + x_3 y_1 + x_2 y_2 + x_1 y_3 + x_0 y_4 \\\\
+z_5 &= x_4 y_1 + x_3 y_2 + x_2 y_3 + x_1 y_4 \\\\
+z_6 &= x_4 y_2 + x_3 y_3 + x_2 y_4 \\\\
+z_7 &= x_4 y_3 + x_3 y_4 \\\\
+z_8 &= x_4 y_4 \\\\
+z_9 &= 0 \\\\
+\end{aligned}
+\\]
+Each term \\(x_i y_j\\) can be written in terms of IFMA operations as
+\\[
+x_i y_j = \mathrm{lo}(x_i,y_j) + 2\mathrm{hi}(x_i,y_j)2^{51}.
+\\]
+Substituting this equation into the schoolbook multiplication, then
+moving terms to eliminate the \\(2^{51}\\) factors gives
+\\[
+\begin{aligned}
+z_0 &= \mathrm{lo}(x_0, y_0) \\\\
+ &+ \qquad 0 \\\\
+z_1 &= \mathrm{lo}(x_1, y_0) + \mathrm{lo}(x_0, y_1) \\\\
+ &+ \qquad 2( \mathrm{hi}(x_0, y_0) )\\\\
+z_2 &= \mathrm{lo}(x_2, y_0) + \mathrm{lo}(x_1, y_1) + \mathrm{lo}(x_0, y_2) \\\\
+ &+ \qquad 2( \mathrm{hi}(x_1, y_0) + \mathrm{hi}(x_0, y_1) )\\\\
+z_3 &= \mathrm{lo}(x_3, y_0) + \mathrm{lo}(x_2, y_1) + \mathrm{lo}(x_1, y_2) + \mathrm{lo}(x_0, y_3) \\\\
+ &+ \qquad 2( \mathrm{hi}(x_2, y_0) + \mathrm{hi}(x_1, y_1) + \mathrm{hi}(x_0, y_2) )\\\\
+z_4 &= \mathrm{lo}(x_4, y_0) + \mathrm{lo}(x_3, y_1) + \mathrm{lo}(x_2, y_2) + \mathrm{lo}(x_1, y_3) + \mathrm{lo}(x_0, y_4) \\\\
+ &+ \qquad 2( \mathrm{hi}(x_3, y_0) + \mathrm{hi}(x_2, y_1) + \mathrm{hi}(x_1, y_2) + \mathrm{hi}(x_0, y_3) )\\\\
+z_5 &= \mathrm{lo}(x_4, y_1) + \mathrm{lo}(x_3, y_2) + \mathrm{lo}(x_2, y_3) + \mathrm{lo}(x_1, y_4) \\\\
+ &+ \qquad 2( \mathrm{hi}(x_4, y_0) + \mathrm{hi}(x_3, y_1) + \mathrm{hi}(x_2, y_2) + \mathrm{hi}(x_1, y_3) + \mathrm{hi}(x_0, y_4) )\\\\
+z_6 &= \mathrm{lo}(x_4, y_2) + \mathrm{lo}(x_3, y_3) + \mathrm{lo}(x_2, y_4) \\\\
+ &+ \qquad 2( \mathrm{hi}(x_4, y_1) + \mathrm{hi}(x_3, y_2) + \mathrm{hi}(x_2, y_3) + \mathrm{hi}(x_1, y_4) )\\\\
+z_7 &= \mathrm{lo}(x_4, y_3) + \mathrm{lo}(x_3, y_4) \\\\
+ &+ \qquad 2( \mathrm{hi}(x_4, y_2) + \mathrm{hi}(x_3, y_3) + \mathrm{hi}(x_2, y_4) )\\\\
+z_8 &= \mathrm{lo}(x_4, y_4) \\\\
+ &+ \qquad 2( \mathrm{hi}(x_4, y_3) + \mathrm{hi}(x_3, y_4) )\\\\
+z_9 &= 0 \\\\
+ &+ \qquad 2( \mathrm{hi}(x_4, y_4) )\\\\
+\end{aligned}
+\\]
+As noted above, our strategy will be to multiply and accumulate the
+terms with coefficient \\(2\\) separately from those with coefficient
+\\(1\\), before combining them at the end. This can alternately be
+thought of as accumulating product terms into a *doubly-redundant*
+representation, with two limbs for each digit, before collapsing
+the doubly-redundant representation by shifts and adds.
+
+This computation requires 25 `vpmadd52luq` and 25 `vpmadd52huq`
+operations. For 256-bit vectors, IFMA operations execute on an
+i3-8121U with latency 4 cycles, throughput 0.5 cycles, so executing 50
+instructions requires 25 cycles' worth of throughput. Accumulating
+terms with coefficient \\(1\\) and \\(2\\) separately means that the
+longest dependency chain has length 5, so the critical path has length
+20 cycles and the bottleneck is throughput.
+
+# Reduction modulo \\(p\\)
+
+The next question is how to handle the reduction modulo \\(p\\).
+Because \\(p = 2^{255} - 19\\), \\(2^{255} = 19 \pmod p\\), so we can
+alternately write
+\\[
+\begin{aligned}
+z &= z_0 + z_1 2^{51} + z_2 2^{102} + z_3 2^{153} + z_4 2^{204} \\\\
+ &+ z_5 2^{255} + z_6 2^{306} + z_7 2^{357} + z_8 2^{408} + z_9 2^{459}
+\end{aligned}
+\\]
+as
+\\[
+\begin{aligned}
+z &= (z_0 + 19z_5) + (z_1 + 19z_6) 2^{51} + (z_2 + 19z_7) 2^{102} + (z_3 + 19z_8) 2^{153} + (z_4 + 19z_9) 2^{204}.
+\end{aligned}
+\\]
+When using a \\(64 \times 64 \rightarrow 128\\)-bit multiplier, this
+can be handled (as in [Ed25519][ed25519_paper]) by premultiplying
+source terms by \\(19\\). Since \\(\lg(19) < 4.25\\), this increases
+their size by less than \\(4.25\\) bits, and the rest of the
+multiplication can be shown to work out.
+
+Here, we have at most \\(1\\) bit of headroom. In order to allow
+premultiplication, we would need to use radix \\(2^{47}\\), which
+would require six limbs instead of five. Instead, we compute the high
+terms \\(z_5, \ldots, z_9\\), each using two chains of IFMA
+operations, then multiply by \\(19\\) and combine with the lower terms
+\\(z_0, \ldots, z_4\\). There are two ways to perform the
+multiplication by \\(19\\): using more IFMA operations, or using the
+`vpmullq` instruction, which computes the low \\(64\\) bits of a \\(64
+\times 64\\)-bit product. However, `vpmullq` has 15c/1.5c
+latency/throughput, in contrast to the 4c/0.5c latency/throughput of
+IFMA operations, so it seems like a worse choice.
+
+The high terms \\(z_5, \ldots, z_9\\) are sums of \\(52\\)-bit terms,
+so they are larger than \\(52\\) bits. Write these terms in radix \\(52\\) as
+\\[
+z_{5+i} = z_{5+i}' + z_{5+i}'' 2^{52}, \qquad z_{5+i}' < 2^{52}.
+\\]
+Then the contribution of \\(z_{5+i}\\), taken modulo \\(p\\), is
+\\[
+\begin{aligned}
+z_{5+i} 2^{255} 2^{51 i}
+&=
+19 (z_{5+i}' + z_{5+i}'' 2^{52}) 2^{51 i}
+\\\\
+&=
+19 z_{5+i}' 2^{51 i} + 2 \cdot 19 z_{5+i}'' 2^{51 (i+1)}
+\\\\
+\end{aligned}
+\\]
+The products \\(19 z_{5+i}', 19 z_{5+i}''\\) can be written in terms of IFMA operations as
+\\[
+\begin{aligned}
+19 z_{5+i}' &= \mathrm{lo}(19, z_{5+i}') + 2 \mathrm{hi}(19, z_{5+i}') 2^{51}, \\\\
+19 z_{5+i}'' &= \mathrm{lo}(19, z_{5+i}'') + 2 \mathrm{hi}(19, z_{5+i}'') 2^{51}. \\\\
+\end{aligned}
+\\]
+Because \\(z_{5+i} < 2^{64}\\), \\(z_{5+i}'' < 2^{12} \\), so \\(19
+z_{5+i}'' < 2^{17} < 2^{52} \\) and \\(\mathrm{hi}(19, z_{5+i}'') = 0\\).
+Because IFMA operations ignore the high bits of their source
+operands, we do not need to compute \\(z\_{5+i}'\\) explicitly:
+the high bits will be ignored.
+Combining these observations, we can write
+\\[
+\begin{aligned}
+z_{5+i} 2^{255} 2^{51 i}
+&=
+19 z_{5+i}' 2^{51 i} + 2 \cdot 19 z_{5+i}'' 2^{51 (i+1)}
+\\\\
+&=
+\mathrm{lo}(19, z_{5+i}) 2^{51 i}
+\+ 2 \mathrm{hi}(19, z_{5+i}) 2^{51 (i+1)}
+\+ 2 \mathrm{lo}(19, z_{5+i}/2^{52}) 2^{51 (i+1)}.
+\end{aligned}
+\\]
+
+For \\(i = 0,1,2,3\\), this allows reducing \\(z_{5+i}\\) onto
+\\(z_{i}, z_{i+1}\\), and if the low terms are computed using a
+doubly-redundant representation, no additional shifts are needed to
+handle the \\(2\\) coefficients. For \\(i = 4\\), there's a
+complication: the contribution becomes
+\\[
+\begin{aligned}
+z_{9} 2^{255} 2^{204}
+&=
+\mathrm{lo}(19, z_{9}) 2^{204}
+\+ 2 \mathrm{hi}(19, z_{9}) 2^{255}
+\+ 2 \mathrm{lo}(19, z_{9}/2^{52}) 2^{255}
+\\\\
+&=
+\mathrm{lo}(19, z_{9}) 2^{204}
+\+ 2 \mathrm{hi}(19, z_{9}) 19
+\+ 2 \mathrm{lo}(19, z_{9}/2^{52}) 19
+\\\\
+&=
+\mathrm{lo}(19, z_{9}) 2^{204}
+\+ 2
+\mathrm{lo}(19, \mathrm{hi}(19, z_{9}) + \mathrm{lo}(19, z_{9}/2^{52})).
+\\\\
+\end{aligned}
+\\]
+
+It would be possible to cut the number of multiplications from 3 to 2
+by carrying the high part of each \\(z_i\\) onto \\(z_{i+1}\\). This
+would eliminate 5 multiplications, clearing 2.5 cycles of port
+pressure, at the cost of 5 additions, adding 1.66 cycles of port
+pressure. But doing this would create a dependency between terms
+(e.g., \\(z_{5}\\) must be computed before the reduction of
+\\(z_{6}\\) can begin), whereas with the approach above, all
+contributions to all terms are computed independently, to maximize ILP
+and flexibility for the processor to schedule instructions.
+
+This strategy performs 16 IFMA operations, adding two IFMA operations
+to each of the \\(2\\)-coefficient terms and one to each of the
+\\(1\\)-coefficient terms. Considering the multiplication and
+reduction together, we use 66 IFMA operations, requiring 33 cycles'
+throughput, while the longest chain of IFMA operations is in the
+reduction of \\(z_5\\) onto \\(z_1\\), of length 7 (so 28 cycles, plus
+2 cycles to combine the two parts of \\(z_5\\), and the bottleneck is
+again throughput.
+
+Once this is done, we have computed the product terms
+\\[
+z = z_0 + z_1 2^{51} + z_2 2^{102} + z_3 2^{153} + z_4 2^{204},
+\\]
+without reducing the \\(z_i\\) to fit in \\(52\\) bits. Because the
+overall flow of operations alternates multiplications and additions or
+subtractions, we would have to perform a reduction after an addition
+but before the next multiplication anyways, so there's no benefit to
+fully reducing the limbs at the end of a multiplication. Instead, we
+leave them unreduced, and track the reduction state using the type
+system to ensure that unreduced limbs are not accidentally used as an
+input to a multiplication.
+
+# Squaring
+
+Squaring operates similarly to multiplication, but with the
+possibility to combine identical terms.
+As before, we write the input as
+\\[
+\begin{aligned}
+x &= x_0 + x_1 2^{51} + x_2 2^{102} + x_3 2^{153} + x_4 2^{204}
+\end{aligned}
+\\]
+with limbs in range \\([0,2^{52})\\).
+Writing the product terms as
+\\[
+\begin{aligned}
+z &= z_0 + z_1 2^{51} + z_2 2^{102} + z_3 2^{153} + z_4 2^{204} \\\\
+ &+ z_5 2^{255} + z_6 2^{306} + z_7 2^{357} + z_8 2^{408} + z_9 2^{459},
+\end{aligned}
+\\]
+a schoolbook squaring in product scanning form takes the form
+\\[
+\begin{aligned}
+z_0 &= x_0 x_0 \\\\
+z_1 &= 2 x_1 x_0 \\\\
+z_2 &= 2 x_2 x_0 + x_1 x_1 \\\\
+z_3 &= 2 x_3 x_0 + 2 x_2 x_1 \\\\
+z_4 &= 2 x_4 x_0 + 2 x_3 x_1 + x_2 x_2 \\\\
+z_5 &= 2 x_4 x_1 + 2 x_3 x_2 \\\\
+z_6 &= 2 x_4 x_2 + x_3 x_3 \\\\
+z_7 &= 2 x_4 x_3 \\\\
+z_8 &= x_4 x_4 \\\\
+z_9 &= 0 \\\\
+\end{aligned}
+\\]
+As before, we write \\(x_i x_j\\) as
+\\[
+x_i x_j = \mathrm{lo}(x_i,x_j) + 2\mathrm{hi}(x_i,x_j)2^{51},
+\\]
+and substitute to obtain
+\\[
+\begin{aligned}
+z_0 &= \mathrm{lo}(x_0, x_0) + 0 \\\\
+z_1 &= 2 \mathrm{lo}(x_1, x_0) + 2 \mathrm{hi}(x_0, x_0) \\\\
+z_2 &= 2 \mathrm{lo}(x_2, x_0) + \mathrm{lo}(x_1, x_1) + 4 \mathrm{hi}(x_1, x_0) \\\\
+z_3 &= 2 \mathrm{lo}(x_3, x_0) + 2 \mathrm{lo}(x_2, x_1) + 4 \mathrm{hi}(x_2, x_0) + 2 \mathrm{hi}(x_1, x_1) \\\\
+z_4 &= 2 \mathrm{lo}(x_4, x_0) + 2 \mathrm{lo}(x_3, x_1) + \mathrm{lo}(x_2, x_2) + 4 \mathrm{hi}(x_3, x_0) + 4 \mathrm{hi}(x_2, x_1) \\\\
+z_5 &= 2 \mathrm{lo}(x_4, x_1) + 2 \mathrm{lo}(x_3, x_2) + 4 \mathrm{hi}(x_4, x_0) + 4 \mathrm{hi}(x_3, x_1) + 2 \mathrm{hi}(x_2, x_2) \\\\
+z_6 &= 2 \mathrm{lo}(x_4, x_2) + \mathrm{lo}(x_3, x_3) + 4 \mathrm{hi}(x_4, x_1) + 4 \mathrm{hi}(x_3, x_2) \\\\
+z_7 &= 2 \mathrm{lo}(x_4, x_3) + 4 \mathrm{hi}(x_4, x_2) + 2 \mathrm{hi}(x_3, x_3) \\\\
+z_8 &= \mathrm{lo}(x_4, x_4) + 4 \mathrm{hi}(x_4, x_3) \\\\
+z_9 &= 0 + 2 \mathrm{hi}(x_4, x_4) \\\\
+\end{aligned}
+\\]
+To implement these, we group terms by their coefficient, computing
+those with coefficient \\(2\\) on set of IFMA chains, and on another
+set of chains, we begin with coefficient-\\(4\\) terms, then shift
+left before continuing with the coefficient-\\(1\\) terms.
+The reduction strategy is the same as for multiplication.
+
+# Future improvements
+
+LLVM won't use blend operations on [256-bit vectors yet][llvm_blend],
+so there's a bunch of blend instructions that could be omitted.
+
+Although the multiplications and squarings are much faster, there's no
+speedup to the additions and subtractions, so there are diminishing
+returns. In fact, the complications in the doubling formulas mean
+that doubling is actually slower than readdition. This also suggests
+that moving to 512-bit vectors won't be much help for a strategy aimed
+at parallelism within a group operation, so to extract performance
+gains from 512-bit vectors it will probably be necessary to create a
+parallel-friendly multiscalar multiplication algorithm. This could
+also help with reducing shuffle pressure.
+
+The squaring implementation could probably be optimized, but without
+`perf` support on Cannonlake it's difficult to make actual
+measurements.
+
+Another improvement would be to implement vectorized square root
+computations, which would allow creating an iterator adaptor for point
+decompression that bunched decompression operations and executed them
+in parallel. This would accelerate batch verification.
+
+[2016_gueron_krasnov]: https://ieeexplore.ieee.org/document/7563269
+[2018_drucker_gueron]: https://eprint.iacr.org/2018/335
+[1999_walter]: https://pdfs.semanticscholar.org/0e6a/3e8f30b63b556679f5dff2cbfdfe9523f4fa.pdf
+[ed25519_paper]: https://ed25519.cr.yp.to/ed25519-20110926.pdf
+[llvm_blend]: https://bugs.llvm.org/show_bug.cgi?id=38343
diff --git a/vendor/curve25519-dalek/docs/parallel-formulas.md b/vendor/curve25519-dalek/docs/parallel-formulas.md
new file mode 100644
index 0000000..70aadc3
--- /dev/null
+++ b/vendor/curve25519-dalek/docs/parallel-formulas.md
@@ -0,0 +1,333 @@
+Vectorized implementations of field and point operations, using a
+modification of the 4-way parallel formulas of Hisil, Wong, Carter,
+and Dawson.
+
+These notes explain the parallel formulas and our strategy for using
+them with SIMD operations. There are two backend implementations: one
+using AVX2, and the other using AVX512-IFMA.
+
+# Overview
+
+The 2008 paper [_Twisted Edwards Curves Revisited_][hwcd08] by Hisil,
+Wong, Carter, and Dawson (HWCD) introduced the “extended coordinates”
+and mixed-model representations which are used by most Edwards curve
+implementations.
+
+However, they also describe 4-way parallel formulas for point addition
+and doubling: a unified addition algorithm taking an effective
+\\(2\mathbf M + 1\mathbf D\\), a doubling algorithm taking an
+effective \\(1\mathbf M + 1\mathbf S\\), and a dedicated (i.e., for
+distinct points) addition algorithm taking an effective \\(2 \mathbf M
+\\). They compare these formulas with a 2-way parallel variant of the
+Montgomery ladder.
+
+Unlike their serial formulas, which are used widely, their parallel
+formulas do not seem to have been implemented in software before. The
+2-way parallel Montgomery ladder was used in 2015 by Tung Chou's
+`sandy2x` implementation. Curiously, however, although the [`sandy2x`
+paper][sandy2x] also implements Edwards arithmetic, and cites HWCD08,
+it doesn't mention their parallel Edwards formulas.
+A 2015 paper by Hernández and López describes an AVX2 implementation
+of X25519. Neither the paper nor the code are publicly available, but
+it apparently gives only a [slight speedup][avx2trac], suggesting that
+it uses a 4-way parallel Montgomery ladder rather than parallel
+Edwards formulas.
+
+The reason may be that HWCD08 describe their formulas as operating on
+four independent processors, which would make a software
+implementation impractical: all of the operations are too low-latency
+to effectively synchronize. But a closer inspection reveals that the
+(more expensive) multiplication and squaring steps are uniform, while
+the instruction divergence occurs in the (much cheaper) addition and
+subtraction steps. This means that a SIMD implementation can perform
+the expensive steps uniformly, and handle divergence in the
+inexpensive steps using masking.
+
+These notes describe modifications to the original parallel formulas
+to allow a SIMD implementation, and this module contains
+implementations of the modified formulas targeting either AVX2 or
+AVX512-IFMA.
+
+# Parallel formulas in HWCD'08
+
+The doubling formula is presented in the HWCD paper as follows:
+
+| Cost | Processor 1 | Processor 2 | Processor 3 | Processor 4 |
+|------------------|--------------------------------|--------------------------------|--------------------------------|--------------------------------|
+| | idle | idle | idle | \\( R\_1 \gets X\_1 + Y\_1 \\) |
+| \\(1\mathbf S\\) | \\( R\_2 \gets X\_1\^2 \\) | \\( R\_3 \gets Y\_1\^2 \\) | \\( R\_4 \gets Z\_1\^2 \\) | \\( R\_5 \gets R\_1\^2 \\) |
+| | \\( R\_6 \gets R\_2 + R\_3 \\) | \\( R\_7 \gets R\_2 - R\_3 \\) | \\( R\_4 \gets 2 R\_4 \\) | idle |
+| | idle | \\( R\_1 \gets R\_4 + R\_7 \\) | idle | \\( R\_2 \gets R\_6 - R\_5 \\) |
+| \\(1\mathbf M\\) | \\( X\_3 \gets R\_1 R\_2 \\) | \\( Y\_3 \gets R\_6 R\_7 \\) | \\( T\_3 \gets R\_2 R\_6 \\) | \\( Z\_3 \gets R\_1 R\_7 \\) |
+
+and the unified addition algorithm is presented as follows:
+
+| Cost | Processor 1 | Processor 2 | Processor 3 | Processor 4 |
+|------------------|--------------------------------|--------------------------------|--------------------------------|--------------------------------|
+| | \\( R\_1 \gets Y\_1 - X\_1 \\) | \\( R\_2 \gets Y\_2 - X\_2 \\) | \\( R\_3 \gets Y\_1 + X\_1 \\) | \\( R\_4 \gets Y\_2 + X\_2 \\) |
+| \\(1\mathbf M\\) | \\( R\_5 \gets R\_1 R\_2 \\) | \\( R\_6 \gets R\_3 R\_4 \\) | \\( R\_7 \gets T\_1 T\_2 \\) | \\( R\_8 \gets Z\_1 Z\_2 \\) |
+| \\(1\mathbf D\\) | idle | idle | \\( R\_7 \gets k R\_7 \\) | \\( R\_8 \gets 2 R\_8 \\) |
+| | \\( R\_1 \gets R\_6 - R\_5 \\) | \\( R\_2 \gets R\_8 - R\_7 \\) | \\( R\_3 \gets R\_8 + R\_7 \\) | \\( R\_4 \gets R\_6 + R\_5 \\) |
+| \\(1\mathbf M\\) | \\( X\_3 \gets R\_1 R\_2 \\) | \\( Y\_3 \gets R\_3 R\_4 \\) | \\( T\_3 \gets R\_1 R\_4 \\) | \\( Z\_3 \gets R\_2 R\_3 \\) |
+
+Here \\(\mathbf M\\) and \\(\mathbf S\\) represent the cost of
+multiplication and squaring of generic field elements, \\(\mathbf D\\)
+represents the cost of multiplication by a curve constant (in this
+case \\( k = 2d \\)).
+
+Notice that the \\(1\mathbf M\\) and \\(1\mathbf S\\) steps are
+uniform. The non-uniform steps are all inexpensive additions or
+subtractions, with the exception of the multiplication by the curve
+constant \\(k = 2d\\):
+$$
+R\_7 \gets 2 d R\_7.
+$$
+
+HWCD suggest parallelising this step by breaking \\(k = 2d\\) into four
+parts as \\(k = k_0 + 2\^n k_1 + 2\^{2n} k_2 + 2\^{3n} k_3 \\) and
+computing \\(k_i R_7 \\) in parallel. This is quite awkward, but if
+the curve constant is a ratio \\( d = d\_1/d\_2 \\), then projective
+coordinates allow us to instead compute
+$$
+(R\_5, R\_6, R\_7, R\_8) \gets (d\_2 R\_5, d\_2 R\_6, 2d\_1 R\_7, d\_2 R\_8).
+$$
+This can be performed as a uniform multiplication by a vector of
+constants, and if \\(d\_1, d\_2\\) are small, it is relatively
+inexpensive. (This trick was suggested by Mike Hamburg).
+In the Curve25519 case, we have
+$$
+d = \frac{d\_1}{d\_2} = \frac{-121665}{121666};
+$$
+Since \\(2 \cdot 121666 < 2\^{18}\\), all the constants above fit (up
+to sign) in 32 bits, so this can be done in parallel as four
+multiplications by small constants \\( (121666, 121666, 2\cdot 121665,
+2\cdot 121666) \\), followed by a negation to compute \\( - 2\cdot 121665\\).
+
+# Modified parallel formulas
+
+Using the modifications sketched above, we can write SIMD-friendly
+versions of the parallel formulas as follows. To avoid confusion with
+the original formulas, temporary variables are named \\(S\\) instead
+of \\(R\\) and are in static single-assignment form.
+
+## Addition
+
+To add points
+\\(P_1 = (X_1 : Y_1 : Z_1 : T_1) \\)
+and
+\\(P_2 = (X_2 : Y_2 : Z_2 : T_2 ) \\),
+we compute
+$$
+\begin{aligned}
+(S\_0 &&,&& S\_1 &&,&& S\_2 &&,&& S\_3 )
+&\gets
+(Y\_1 - X\_1&&,&& Y\_1 + X\_1&&,&& Y\_2 - X\_2&&,&& Y\_2 + X\_2)
+\\\\
+(S\_4 &&,&& S\_5 &&,&& S\_6 &&,&& S\_7 )
+&\gets
+(S\_0 \cdot S\_2&&,&& S\_1 \cdot S\_3&&,&& Z\_1 \cdot Z\_2&&,&& T\_1 \cdot T\_2)
+\\\\
+(S\_8 &&,&& S\_9 &&,&& S\_{10} &&,&& S\_{11} )
+&\gets
+(d\_2 \cdot S\_4 &&,&& d\_2 \cdot S\_5 &&,&& 2 d\_2 \cdot S\_6 &&,&& 2 d\_1 \cdot S\_7 )
+\\\\
+(S\_{12} &&,&& S\_{13} &&,&& S\_{14} &&,&& S\_{15})
+&\gets
+(S\_9 - S\_8&&,&& S\_9 + S\_8&&,&& S\_{10} - S\_{11}&&,&& S\_{10} + S\_{11})
+\\\\
+(X\_3&&,&& Y\_3&&,&& Z\_3&&,&& T\_3)
+&\gets
+(S\_{12} \cdot S\_{14}&&,&& S\_{15} \cdot S\_{13}&&,&& S\_{15} \cdot S\_{14}&&,&& S\_{12} \cdot S\_{13})
+\end{aligned}
+$$
+to obtain \\( P\_3 = (X\_3 : Y\_3 : Z\_3 : T\_3) = P\_1 + P\_2 \\).
+This costs \\( 2\mathbf M + 1 \mathbf D\\).
+
+## Readdition
+
+If the point \\( P\_2 = (X\_2 : Y\_2 : Z\_2 : T\_2) \\) is fixed, we
+can cache the multiplication of the curve constants by computing
+$$
+\begin{aligned}
+(S\_2\' &&,&& S\_3\' &&,&& Z\_2\' &&,&& T\_2\' )
+&\gets
+(d\_2 \cdot (Y\_2 - X\_2)&&,&& d\_2 \cdot (Y\_1 + X\_1)&&,&& 2d\_2 \cdot Z\_2 &&,&& 2d\_1 \cdot T\_2).
+\end{aligned}
+$$
+This costs \\( 1\mathbf D\\); with \\( (S\_2\', S\_3\', Z\_2\', T\_2\')\\)
+in hand, the addition formulas above become
+$$
+\begin{aligned}
+(S\_0 &&,&& S\_1 &&,&& Z\_1 &&,&& T\_1 )
+&\gets
+(Y\_1 - X\_1&&,&& Y\_1 + X\_1&&,&& Z\_1 &&,&& T\_1)
+\\\\
+(S\_8 &&,&& S\_9 &&,&& S\_{10} &&,&& S\_{11} )
+&\gets
+(S\_0 \cdot S\_2\' &&,&& S\_1 \cdot S\_3\'&&,&& Z\_1 \cdot Z\_2\' &&,&& T\_1 \cdot T\_2\')
+\\\\
+(S\_{12} &&,&& S\_{13} &&,&& S\_{14} &&,&& S\_{15})
+&\gets
+(S\_9 - S\_8&&,&& S\_9 + S\_8&&,&& S\_{10} - S\_{11}&&,&& S\_{10} + S\_{11})
+\\\\
+(X\_3&&,&& Y\_3&&,&& Z\_3&&,&& T\_3)
+&\gets
+(S\_{12} \cdot S\_{14}&&,&& S\_{15} \cdot S\_{13}&&,&& S\_{15} \cdot S\_{14}&&,&& S\_{12} \cdot S\_{13})
+\end{aligned}
+$$
+which costs only \\( 2\mathbf M \\). This precomputation is
+essentially similar to the precomputation that HWCD suggest for their
+serial formulas. Because the cost of precomputation and then
+readdition is the same as addition, it's sufficient to only
+implement caching and readdition.
+
+## Doubling
+
+The non-uniform portions of the (re)addition formulas have a fairly
+regular structure. Unfortunately, this is not the case for the
+doubling formulas, which are much less nice.
+
+To double a point \\( P = (X\_1 : Y\_1 : Z\_1 : T\_1) \\), we compute
+$$
+\begin{aligned}
+(X\_1 &&,&& Y\_1 &&,&& Z\_1 &&,&& S\_0)
+&\gets
+(X\_1 &&,&& Y\_1 &&,&& Z\_1 &&,&& X\_1 + Y\_1)
+\\\\
+(S\_1 &&,&& S\_2 &&,&& S\_3 &&,&& S\_4 )
+&\gets
+(X\_1\^2 &&,&& Y\_1\^2&&,&& Z\_1\^2 &&,&& S\_0\^2)
+\\\\
+(S\_5 &&,&& S\_6 &&,&& S\_8 &&,&& S\_9 )
+&\gets
+(S\_1 + S\_2 &&,&& S\_1 - S\_2 &&,&& S\_1 + 2S\_3 - S\_2 &&,&& S\_1 + S\_2 - S\_4)
+\\\\
+(X\_3 &&,&& Y\_3 &&,&& Z\_3 &&,&& T\_3 )
+&\gets
+(S\_8 \cdot S\_9 &&,&& S\_5 \cdot S\_6 &&,&& S\_8 \cdot S\_6 &&,&& S\_5 \cdot S\_9)
+\end{aligned}
+$$
+to obtain \\( P\_3 = (X\_3 : Y\_3 : Z\_3 : T\_3) = \[2\]P\_1 \\).
+
+The intermediate step between the squaring and multiplication requires
+a long chain of additions. For the IFMA-based implementation, this is not a problem; for the AVX2-based implementation, it is, but with some care and finesse, it's possible to arrange the computation without requiring an intermediate reduction.
+
+# Implementation
+
+These formulas aren't specific to a particular representation of field
+element vectors, whose optimum choice is determined by the details of
+the instruction set. However, it's not possible to perfectly separate
+the implementation of the field element vectors from the
+implementation of the point operations. Instead, the [`avx2`] and
+[`ifma`] backends provide `ExtendedPoint` and `CachedPoint` types, and
+the [`scalar_mul`] code uses one of the backend types by a type alias.
+
+# Comparison to non-vectorized formulas
+
+In theory, the parallel Edwards formulas seem to allow a \\(4\\)-way
+speedup from parallelism. However, an actual vectorized
+implementation has several slowdowns that cut into this speedup.
+
+First, the parallel formulas can only use the available vector
+multiplier. For AVX2, this is a \\( 32 \times 32 \rightarrow 64
+\\)-bit integer multiplier, so the speedup from vectorization must
+overcome the disadvantage of losing the \\( 64 \times 64 \rightarrow
+128\\)-bit (serial) integer multiplier. The effect of this slowdown
+is microarchitecture-dependent, since it requires accounting for the
+total number of multiplications and additions and their relative
+costs. IFMA allows using a \\( 52 \times 52 \rightarrow 104 \\)-bit
+multiplier, but the high and low halves need to be computed
+separately, and the reduction requires extra work because it's not
+possible to pre-multiply by \\(19\\).
+
+Second, the parallel doubling formulas incur both a theoretical and
+practical slowdown. The parallel formulas described above work on the
+\\( \mathbb P\^3 \\) “extended” coordinates. The \\( \mathbb P\^2 \\)
+model introduced earlier by [Bernstein, Birkner, Joye, Lange, and
+Peters][bbjlp08] allows slightly faster doublings, so HWCD suggest
+mixing coordinate systems while performing scalar multiplication
+(attributing the idea to [a 1998 paper][cmo98] by Cohen, Miyagi, and
+Ono). The \\( T \\) coordinate is not required for doublings, so when
+doublings are followed by doublings, its computation can be skipped.
+More details on this approach and the different coordinate systems can
+be found in the [`curve_models` module documentation][curve_models].
+
+Unfortunately, this optimization is not compatible with the parallel
+formulas, which cannot save time by skipping a single variable, so the
+parallel doubling formulas do slightly more work when counting the
+total number of field multiplications and squarings.
+
+In addition, the parallel doubling formulas have a less regular
+pattern of additions and subtractions than the parallel addition
+formulas, so the vectorization overhead is proportionately greater.
+Both the parallel addition and parallel doubling formulas also require
+some shuffling to rearrange data within the vectors, which places more
+pressure on the shuffle unit than is desirable.
+
+This means that the speedup from using a vectorized implementation of
+parallel Edwards formulas is likely to be greatest in applications
+that do fewer doublings and more additions (like a large multiscalar
+multiplication) rather than applications that do fewer additions and
+more doublings (like a double-base scalar multiplication).
+
+Third, Amdahl's law says that the speedup is limited to the portion
+which can be parallelized. Normally, the field multiplications
+dominate the cost of point operations, but with the IFMA backend, the
+multiplications are so fast that the non-parallel additions end up as
+a significant portion of the total time.
+
+Fourth, current Intel CPUs perform thermal throttling when using wide
+vector instructions. A detailed description can be found in §15.26 of
+[the Intel Optimization Manual][intel], but using wide vector
+instructions prevents the core from operating at higher frequencies.
+The core can return to the higher-frequency state after 2
+milliseconds, but this timer is reset every time high-power
+instructions are used.
+
+Any speedup from vectorization therefore has to be weighed against a
+slowdown for the next few million instructions. For a mixed workload,
+where point operations are interspersed with other tasks, this can
+reduce overall performance. This implementation is therefore probably
+not suitable for basic applications, like signatures, but is
+worthwhile for complex applications, like zero-knowledge proofs, which
+do sustained work.
+
+# Future work
+
+There are several directions for future improvement:
+
+* Using the vectorized field arithmetic code to parallelize across
+ point operations rather than within a single point operation. This
+ is less flexible, but would give a speedup both from allowing use of
+ the faster mixed-model arithmetic and from reducing shuffle
+ pressure. One approach in this direction would be to implement
+ batched scalar-point operations using vectors of points (AoSoA
+ layout). This less generally useful but would give a speedup for
+ Bulletproofs.
+
+* Extending the IFMA implementation to use the full width of AVX512,
+ either handling the extra parallelism internally to a single point
+ operation (by using a 2-way parallel implementation of field
+ arithmetic instead of a wordsliced one), or externally,
+ parallelizing across point operations. Internal parallelism would
+ be preferable but might require too much shuffle pressure. For now,
+ the only available CPU which runs IFMA operations executes them at
+ 256-bits wide anyways, so this isn't yet important.
+
+* Generalizing the implementation to NEON instructions. The current
+ point arithmetic code is written in terms of field element vectors,
+ which are in turn implemented using platform SIMD vectors. It
+ should be possible to write an alternate implementation of the
+ `FieldElement2625x4` using NEON without changing the point
+ arithmetic. NEON has 128-bit vectors rather than 256-bit vectors,
+ but this may still be worthwhile compared to a serial
+ implementation.
+
+
+[sandy2x]: https://eprint.iacr.org/2015/943.pdf
+[avx2trac]: https://trac.torproject.org/projects/tor/ticket/8897#comment:28
+[hwcd08]: https://www.iacr.org/archive/asiacrypt2008/53500329/53500329.pdf
+[curve_models]: https://docs.rs/curve25519-dalek/latest/curve25519-dalek/backend/serial/curve_models/index.html
+[bbjlp08]: https://eprint.iacr.org/2008/013
+[cmo98]: https://link.springer.com/content/pdf/10.1007%2F3-540-49649-1_6.pdf
+[intel]: https://software.intel.com/sites/default/files/managed/9e/bc/64-ia-32-architectures-optimization-manual.pdf
diff --git a/vendor/curve25519-dalek/src/backend/mod.rs b/vendor/curve25519-dalek/src/backend/mod.rs
new file mode 100644
index 0000000..9ad1dd3
--- /dev/null
+++ b/vendor/curve25519-dalek/src/backend/mod.rs
@@ -0,0 +1,251 @@
+// -*- mode: rust; -*-
+//
+// This file is part of curve25519-dalek.
+// Copyright (c) 2016-2021 isis lovecruft
+// Copyright (c) 2016-2019 Henry de Valence
+// See LICENSE for licensing information.
+//
+// Authors:
+// - isis agora lovecruft
+// - Henry de Valence
+
+//! **INTERNALS:** Pluggable implementations for different architectures.
+//!
+//! The backend code is split into two parts: a serial backend,
+//! and a vector backend.
+//!
+//! The [`serial`] backend contains 32- and 64-bit implementations of
+//! field arithmetic and scalar arithmetic, as well as implementations
+//! of point operations using the mixed-model strategy (passing
+//! between different curve models depending on the operation).
+//!
+//! The [`vector`] backend contains implementations of vectorized
+//! field arithmetic, used to implement point operations using a novel
+//! implementation strategy derived from parallel formulas of Hisil,
+//! Wong, Carter, and Dawson.
+//!
+//! Because the two strategies give rise to different curve models,
+//! it's not possible to reuse exactly the same scalar multiplication
+//! code (or to write it generically), so both serial and vector
+//! backends contain matching implementations of scalar multiplication
+//! algorithms. These are intended to be selected by a `#[cfg]`-based
+//! type alias.
+//!
+//! The [`vector`] backend is selected by the `simd_backend` cargo
+//! feature; it uses the [`serial`] backend for non-vectorized operations.
+
+use crate::EdwardsPoint;
+use crate::Scalar;
+
+pub mod serial;
+
+#[cfg(curve25519_dalek_backend = "simd")]
+pub mod vector;
+
+#[derive(Copy, Clone)]
+enum BackendKind {
+ #[cfg(curve25519_dalek_backend = "simd")]
+ Avx2,
+ #[cfg(all(curve25519_dalek_backend = "simd", nightly))]
+ Avx512,
+ Serial,
+}
+
+#[inline]
+fn get_selected_backend() -> BackendKind {
+ #[cfg(all(curve25519_dalek_backend = "simd", nightly))]
+ {
+ cpufeatures::new!(cpuid_avx512, "avx512ifma", "avx512vl");
+ let token_avx512: cpuid_avx512::InitToken = cpuid_avx512::init();
+ if token_avx512.get() {
+ return BackendKind::Avx512;
+ }
+ }
+
+ #[cfg(curve25519_dalek_backend = "simd")]
+ {
+ cpufeatures::new!(cpuid_avx2, "avx2");
+ let token_avx2: cpuid_avx2::InitToken = cpuid_avx2::init();
+ if token_avx2.get() {
+ return BackendKind::Avx2;
+ }
+ }
+
+ BackendKind::Serial
+}
+
+#[allow(missing_docs)]
+#[cfg(feature = "alloc")]
+pub fn pippenger_optional_multiscalar_mul(scalars: I, points: J) -> Option
+where
+ I: IntoIterator,
+ I::Item: core::borrow::Borrow,
+ J: IntoIterator>,
+{
+ use crate::traits::VartimeMultiscalarMul;
+
+ match get_selected_backend() {
+ #[cfg(curve25519_dalek_backend = "simd")]
+ BackendKind::Avx2 =>
+ vector::scalar_mul::pippenger::spec_avx2::Pippenger::optional_multiscalar_mul::(scalars, points),
+ #[cfg(all(curve25519_dalek_backend = "simd", nightly))]
+ BackendKind::Avx512 =>
+ vector::scalar_mul::pippenger::spec_avx512ifma_avx512vl::Pippenger::optional_multiscalar_mul::(scalars, points),
+ BackendKind::Serial =>
+ serial::scalar_mul::pippenger::Pippenger::optional_multiscalar_mul::(scalars, points),
+ }
+}
+
+#[cfg(feature = "alloc")]
+pub(crate) enum VartimePrecomputedStraus {
+ #[cfg(curve25519_dalek_backend = "simd")]
+ Avx2(vector::scalar_mul::precomputed_straus::spec_avx2::VartimePrecomputedStraus),
+ #[cfg(all(curve25519_dalek_backend = "simd", nightly))]
+ Avx512ifma(
+ vector::scalar_mul::precomputed_straus::spec_avx512ifma_avx512vl::VartimePrecomputedStraus,
+ ),
+ Scalar(serial::scalar_mul::precomputed_straus::VartimePrecomputedStraus),
+}
+
+#[cfg(feature = "alloc")]
+impl VartimePrecomputedStraus {
+ pub fn new(static_points: I) -> Self
+ where
+ I: IntoIterator,
+ I::Item: core::borrow::Borrow,
+ {
+ use crate::traits::VartimePrecomputedMultiscalarMul;
+
+ match get_selected_backend() {
+ #[cfg(curve25519_dalek_backend = "simd")]
+ BackendKind::Avx2 =>
+ VartimePrecomputedStraus::Avx2(vector::scalar_mul::precomputed_straus::spec_avx2::VartimePrecomputedStraus::new(static_points)),
+ #[cfg(all(curve25519_dalek_backend = "simd", nightly))]
+ BackendKind::Avx512 =>
+ VartimePrecomputedStraus::Avx512ifma(vector::scalar_mul::precomputed_straus::spec_avx512ifma_avx512vl::VartimePrecomputedStraus::new(static_points)),
+ BackendKind::Serial =>
+ VartimePrecomputedStraus::Scalar(serial::scalar_mul::precomputed_straus::VartimePrecomputedStraus::new(static_points))
+ }
+ }
+
+ pub fn optional_mixed_multiscalar_mul(
+ &self,
+ static_scalars: I,
+ dynamic_scalars: J,
+ dynamic_points: K,
+ ) -> Option
+ where
+ I: IntoIterator,
+ I::Item: core::borrow::Borrow,
+ J: IntoIterator,
+ J::Item: core::borrow::Borrow,
+ K: IntoIterator>,
+ {
+ use crate::traits::VartimePrecomputedMultiscalarMul;
+
+ match self {
+ #[cfg(curve25519_dalek_backend = "simd")]
+ VartimePrecomputedStraus::Avx2(inner) => inner.optional_mixed_multiscalar_mul(
+ static_scalars,
+ dynamic_scalars,
+ dynamic_points,
+ ),
+ #[cfg(all(curve25519_dalek_backend = "simd", nightly))]
+ VartimePrecomputedStraus::Avx512ifma(inner) => inner.optional_mixed_multiscalar_mul(
+ static_scalars,
+ dynamic_scalars,
+ dynamic_points,
+ ),
+ VartimePrecomputedStraus::Scalar(inner) => inner.optional_mixed_multiscalar_mul(
+ static_scalars,
+ dynamic_scalars,
+ dynamic_points,
+ ),
+ }
+ }
+}
+
+#[allow(missing_docs)]
+#[cfg(feature = "alloc")]
+pub fn straus_multiscalar_mul(scalars: I, points: J) -> EdwardsPoint
+where
+ I: IntoIterator,
+ I::Item: core::borrow::Borrow,
+ J: IntoIterator,
+ J::Item: core::borrow::Borrow,
+{
+ use crate::traits::MultiscalarMul;
+
+ match get_selected_backend() {
+ #[cfg(curve25519_dalek_backend = "simd")]
+ BackendKind::Avx2 => {
+ vector::scalar_mul::straus::spec_avx2::Straus::multiscalar_mul::(scalars, points)
+ }
+ #[cfg(all(curve25519_dalek_backend = "simd", nightly))]
+ BackendKind::Avx512 => {
+ vector::scalar_mul::straus::spec_avx512ifma_avx512vl::Straus::multiscalar_mul::(
+ scalars, points,
+ )
+ }
+ BackendKind::Serial => {
+ serial::scalar_mul::straus::Straus::multiscalar_mul::(scalars, points)
+ }
+ }
+}
+
+#[allow(missing_docs)]
+#[cfg(feature = "alloc")]
+pub fn straus_optional_multiscalar_mul(scalars: I, points: J) -> Option
+where
+ I: IntoIterator,
+ I::Item: core::borrow::Borrow,
+ J: IntoIterator>,
+{
+ use crate::traits::VartimeMultiscalarMul;
+
+ match get_selected_backend() {
+ #[cfg(curve25519_dalek_backend = "simd")]
+ BackendKind::Avx2 => {
+ vector::scalar_mul::straus::spec_avx2::Straus::optional_multiscalar_mul::(
+ scalars, points,
+ )
+ }
+ #[cfg(all(curve25519_dalek_backend = "simd", nightly))]
+ BackendKind::Avx512 => {
+ vector::scalar_mul::straus::spec_avx512ifma_avx512vl::Straus::optional_multiscalar_mul::<
+ I,
+ J,
+ >(scalars, points)
+ }
+ BackendKind::Serial => {
+ serial::scalar_mul::straus::Straus::optional_multiscalar_mul::(scalars, points)
+ }
+ }
+}
+
+/// Perform constant-time, variable-base scalar multiplication.
+pub fn variable_base_mul(point: &EdwardsPoint, scalar: &Scalar) -> EdwardsPoint {
+ match get_selected_backend() {
+ #[cfg(curve25519_dalek_backend = "simd")]
+ BackendKind::Avx2 => vector::scalar_mul::variable_base::spec_avx2::mul(point, scalar),
+ #[cfg(all(curve25519_dalek_backend = "simd", nightly))]
+ BackendKind::Avx512 => {
+ vector::scalar_mul::variable_base::spec_avx512ifma_avx512vl::mul(point, scalar)
+ }
+ BackendKind::Serial => serial::scalar_mul::variable_base::mul(point, scalar),
+ }
+}
+
+/// Compute \\(aA + bB\\) in variable time, where \\(B\\) is the Ed25519 basepoint.
+#[allow(non_snake_case)]
+pub fn vartime_double_base_mul(a: &Scalar, A: &EdwardsPoint, b: &Scalar) -> EdwardsPoint {
+ match get_selected_backend() {
+ #[cfg(curve25519_dalek_backend = "simd")]
+ BackendKind::Avx2 => vector::scalar_mul::vartime_double_base::spec_avx2::mul(a, A, b),
+ #[cfg(all(curve25519_dalek_backend = "simd", nightly))]
+ BackendKind::Avx512 => {
+ vector::scalar_mul::vartime_double_base::spec_avx512ifma_avx512vl::mul(a, A, b)
+ }
+ BackendKind::Serial => serial::scalar_mul::vartime_double_base::mul(a, A, b),
+ }
+}
diff --git a/vendor/curve25519-dalek/src/backend/serial/curve_models/mod.rs b/vendor/curve25519-dalek/src/backend/serial/curve_models/mod.rs
new file mode 100644
index 0000000..1343d37
--- /dev/null
+++ b/vendor/curve25519-dalek/src/backend/serial/curve_models/mod.rs
@@ -0,0 +1,564 @@
+// -*- mode: rust; -*-
+//
+// This file is part of curve25519-dalek.
+// Copyright (c) 2016-2021 isis lovecruft
+// Copyright (c) 2016-2019 Henry de Valence
+// See LICENSE for licensing information.
+//
+// Authors:
+// - isis agora lovecruft
+// - Henry de Valence
+
+//! Internal curve representations which are not part of the public API.
+//!
+//! # Curve representations
+//!
+//! Internally, we use several different models for the curve. Here
+//! is a sketch of the relationship between the models, following [a
+//! post][smith-moderncrypto]
+//! by Ben Smith on the `moderncrypto` mailing list. This is also briefly
+//! discussed in section 2.5 of [_Montgomery curves and their
+//! arithmetic_][costello-smith-2017] by Costello and Smith.
+//!
+//! Begin with the affine equation for the curve,
+//! $$
+//! -x\^2 + y\^2 = 1 + dx\^2y\^2.
+//! $$
+//! Next, pass to the projective closure \\(\mathbb P\^1 \times \mathbb
+//! P\^1 \\) by setting \\(x=X/Z\\), \\(y=Y/T.\\) Clearing denominators
+//! gives the model
+//! $$
+//! -X\^2T\^2 + Y\^2Z\^2 = Z\^2T\^2 + dX\^2Y\^2.
+//! $$
+//! In `curve25519-dalek`, this is represented as the `CompletedPoint`
+//! struct.
+//! To map from \\(\mathbb P\^1 \times \mathbb P\^1 \\), a product of
+//! two lines, to \\(\mathbb P\^3\\), we use the [Segre
+//! embedding](https://en.wikipedia.org/wiki/Segre_embedding)
+//! $$
+//! \sigma : ((X:Z),(Y:T)) \mapsto (XY:XT:ZY:ZT).
+//! $$
+//! Using coordinates \\( (W_0:W_1:W_2:W_3) \\) for \\(\mathbb P\^3\\),
+//! the image \\(\sigma (\mathbb P\^1 \times \mathbb P\^1) \\) is the
+//! surface defined by \\( W_0 W_3 = W_1 W_2 \\), and under \\(
+//! \sigma\\), the equation above becomes
+//! $$
+//! -W\_1\^2 + W\_2\^2 = W\_3\^2 + dW\_0\^2,
+//! $$
+//! so that the curve is given by the pair of equations
+//! $$
+//! \begin{aligned}
+//! -W\_1\^2 + W\_2\^2 &= W\_3\^2 + dW\_0\^2, \\\\ W_0 W_3 &= W_1 W_2.
+//! \end{aligned}
+//! $$
+//! Up to variable naming, this is exactly the "extended" curve model
+//! introduced in [_Twisted Edwards Curves
+//! Revisited_][hisil-wong-carter-dawson-2008] by Hisil, Wong, Carter,
+//! and Dawson. In `curve25519-dalek`, it is represented as the
+//! `EdwardsPoint` struct. We can map from \\(\mathbb P\^3 \\) to
+//! \\(\mathbb P\^2 \\) by sending \\( (W\_0:W\_1:W\_2:W\_3) \\) to \\(
+//! (W\_1:W\_2:W\_3) \\). Notice that
+//! $$
+//! \frac {W\_1} {W\_3} = \frac {XT} {ZT} = \frac X Z = x,
+//! $$
+//! and
+//! $$
+//! \frac {W\_2} {W\_3} = \frac {YZ} {ZT} = \frac Y T = y,
+//! $$
+//! so this is the same as if we had started with the affine model
+//! and passed to \\( \mathbb P\^2 \\) by setting \\( x = W\_1 / W\_3
+//! \\), \\(y = W\_2 / W\_3 \\).
+//! Up to variable naming, this is the projective representation
+//! introduced in in [_Twisted Edwards
+//! Curves_][bernstein-birkner-joye-lange-peters-2008] by Bernstein,
+//! Birkner, Joye, Lange, and Peters. In `curve25519-dalek`, it is
+//! represented by the `ProjectivePoint` struct.
+//!
+//! # Passing between curve models
+//!
+//! Although the \\( \mathbb P\^3 \\) model provides faster addition
+//! formulas, the \\( \mathbb P\^2 \\) model provides faster doubling
+//! formulas. Hisil, Wong, Carter, and Dawson therefore suggest mixing
+//! coordinate systems for scalar multiplication, attributing the idea
+//! to [a 1998 paper][cohen-miyaji-ono-1998] of Cohen, Miyagi, and Ono.
+//!
+//! Their suggestion is to vary the formulas used by context, using a
+//! \\( \mathbb P\^2 \rightarrow \mathbb P\^2 \\) doubling formula when
+//! a doubling is followed
+//! by another doubling, a \\( \mathbb P\^2 \rightarrow \mathbb P\^3 \\)
+//! doubling formula when a doubling is followed by an addition, and
+//! computing point additions using a \\( \mathbb P\^3 \times \mathbb P\^3
+//! \rightarrow \mathbb P\^2 \\) formula.
+//!
+//! The `ref10` reference implementation of [Ed25519][ed25519], by
+//! Bernstein, Duif, Lange, Schwabe, and Yang, tweaks
+//! this strategy, factoring the addition formulas through the
+//! completion \\( \mathbb P\^1 \times \mathbb P\^1 \\), so that the
+//! output of an addition or doubling always lies in \\( \mathbb P\^1 \times
+//! \mathbb P\^1\\), and the choice of which formula to use is replaced
+//! by a choice of whether to convert the result to \\( \mathbb P\^2 \\)
+//! or \\(\mathbb P\^3 \\). However, this tweak is not described in
+//! their paper, only in their software.
+//!
+//! Our naming for the `CompletedPoint` (\\(\mathbb P\^1 \times \mathbb
+//! P\^1 \\)), `ProjectivePoint` (\\(\mathbb P\^2 \\)), and
+//! `EdwardsPoint` (\\(\mathbb P\^3 \\)) structs follows the naming in
+//! Adam Langley's [Golang ed25519][agl-ed25519] implementation, which
+//! `curve25519-dalek` was originally derived from.
+//!
+//! Finally, to accelerate readditions, we use two cached point formats
+//! in "Niels coordinates", named for Niels Duif,
+//! one for the affine model and one for the \\( \mathbb P\^3 \\) model:
+//!
+//! * `AffineNielsPoint`: \\( (y+x, y-x, 2dxy) \\)
+//! * `ProjectiveNielsPoint`: \\( (Y+X, Y-X, Z, 2dXY) \\)
+//!
+//! [smith-moderncrypto]: https://moderncrypto.org/mail-archive/curves/2016/000807.html
+//! [costello-smith-2017]: https://eprint.iacr.org/2017/212
+//! [hisil-wong-carter-dawson-2008]: https://www.iacr.org/archive/asiacrypt2008/53500329/53500329.pdf
+//! [bernstein-birkner-joye-lange-peters-2008]: https://eprint.iacr.org/2008/013
+//! [cohen-miyaji-ono-1998]: https://link.springer.com/content/pdf/10.1007%2F3-540-49649-1_6.pdf
+//! [ed25519]: https://eprint.iacr.org/2011/368
+//! [agl-ed25519]: https://github.com/agl/ed25519
+
+#![allow(non_snake_case)]
+
+use core::fmt::Debug;
+use core::ops::{Add, Neg, Sub};
+
+use subtle::Choice;
+use subtle::ConditionallySelectable;
+
+#[cfg(feature = "zeroize")]
+use zeroize::Zeroize;
+
+use crate::constants;
+
+use crate::edwards::EdwardsPoint;
+use crate::field::FieldElement;
+use crate::traits::ValidityCheck;
+
+// ------------------------------------------------------------------------
+// Internal point representations
+// ------------------------------------------------------------------------
+
+/// A `ProjectivePoint` is a point \\((X:Y:Z)\\) on the \\(\mathbb
+/// P\^2\\) model of the curve.
+/// A point \\((x,y)\\) in the affine model corresponds to
+/// \\((x:y:1)\\).
+///
+/// More details on the relationships between the different curve models
+/// can be found in the module-level documentation.
+#[allow(missing_docs)]
+#[derive(Copy, Clone)]
+pub struct ProjectivePoint {
+ pub X: FieldElement,
+ pub Y: FieldElement,
+ pub Z: FieldElement,
+}
+
+/// A `CompletedPoint` is a point \\(((X:Z), (Y:T))\\) on the \\(\mathbb
+/// P\^1 \times \mathbb P\^1 \\) model of the curve.
+/// A point (x,y) in the affine model corresponds to \\( ((x:1),(y:1))
+/// \\).
+///
+/// More details on the relationships between the different curve models
+/// can be found in the module-level documentation.
+#[derive(Copy, Clone)]
+#[allow(missing_docs)]
+pub struct CompletedPoint {
+ pub X: FieldElement,
+ pub Y: FieldElement,
+ pub Z: FieldElement,
+ pub T: FieldElement,
+}
+
+/// A pre-computed point in the affine model for the curve, represented as
+/// \\((y+x, y-x, 2dxy)\\) in "Niels coordinates".
+///
+/// More details on the relationships between the different curve models
+/// can be found in the module-level documentation.
+// Safe to derive Eq because affine coordinates.
+#[derive(Copy, Clone, Eq, PartialEq)]
+#[allow(missing_docs)]
+pub struct AffineNielsPoint {
+ pub y_plus_x: FieldElement,
+ pub y_minus_x: FieldElement,
+ pub xy2d: FieldElement,
+}
+
+#[cfg(feature = "zeroize")]
+impl Zeroize for AffineNielsPoint {
+ fn zeroize(&mut self) {
+ self.y_plus_x.zeroize();
+ self.y_minus_x.zeroize();
+ self.xy2d.zeroize();
+ }
+}
+
+/// A pre-computed point on the \\( \mathbb P\^3 \\) model for the
+/// curve, represented as \\((Y+X, Y-X, Z, 2dXY)\\) in "Niels coordinates".
+///
+/// More details on the relationships between the different curve models
+/// can be found in the module-level documentation.
+#[derive(Copy, Clone)]
+#[allow(missing_docs)]
+pub struct ProjectiveNielsPoint {
+ pub Y_plus_X: FieldElement,
+ pub Y_minus_X: FieldElement,
+ pub Z: FieldElement,
+ pub T2d: FieldElement,
+}
+
+#[cfg(feature = "zeroize")]
+impl Zeroize for ProjectiveNielsPoint {
+ fn zeroize(&mut self) {
+ self.Y_plus_X.zeroize();
+ self.Y_minus_X.zeroize();
+ self.Z.zeroize();
+ self.T2d.zeroize();
+ }
+}
+
+// ------------------------------------------------------------------------
+// Constructors
+// ------------------------------------------------------------------------
+
+use crate::traits::Identity;
+
+impl Identity for ProjectivePoint {
+ fn identity() -> ProjectivePoint {
+ ProjectivePoint {
+ X: FieldElement::ZERO,
+ Y: FieldElement::ONE,
+ Z: FieldElement::ONE,
+ }
+ }
+}
+
+impl Identity for ProjectiveNielsPoint {
+ fn identity() -> ProjectiveNielsPoint {
+ ProjectiveNielsPoint {
+ Y_plus_X: FieldElement::ONE,
+ Y_minus_X: FieldElement::ONE,
+ Z: FieldElement::ONE,
+ T2d: FieldElement::ZERO,
+ }
+ }
+}
+
+impl Default for ProjectiveNielsPoint {
+ fn default() -> ProjectiveNielsPoint {
+ ProjectiveNielsPoint::identity()
+ }
+}
+
+impl Identity for AffineNielsPoint {
+ fn identity() -> AffineNielsPoint {
+ AffineNielsPoint {
+ y_plus_x: FieldElement::ONE,
+ y_minus_x: FieldElement::ONE,
+ xy2d: FieldElement::ZERO,
+ }
+ }
+}
+
+impl Default for AffineNielsPoint {
+ fn default() -> AffineNielsPoint {
+ AffineNielsPoint::identity()
+ }
+}
+
+// ------------------------------------------------------------------------
+// Validity checks (for debugging, not CT)
+// ------------------------------------------------------------------------
+
+impl ValidityCheck for ProjectivePoint {
+ fn is_valid(&self) -> bool {
+ // Curve equation is -x^2 + y^2 = 1 + d*x^2*y^2,
+ // homogenized as (-X^2 + Y^2)*Z^2 = Z^4 + d*X^2*Y^2
+ let XX = self.X.square();
+ let YY = self.Y.square();
+ let ZZ = self.Z.square();
+ let ZZZZ = ZZ.square();
+ let lhs = &(&YY - &XX) * &ZZ;
+ let rhs = &ZZZZ + &(&constants::EDWARDS_D * &(&XX * &YY));
+
+ lhs == rhs
+ }
+}
+
+// ------------------------------------------------------------------------
+// Constant-time assignment
+// ------------------------------------------------------------------------
+
+impl ConditionallySelectable for ProjectiveNielsPoint {
+ fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
+ ProjectiveNielsPoint {
+ Y_plus_X: FieldElement::conditional_select(&a.Y_plus_X, &b.Y_plus_X, choice),
+ Y_minus_X: FieldElement::conditional_select(&a.Y_minus_X, &b.Y_minus_X, choice),
+ Z: FieldElement::conditional_select(&a.Z, &b.Z, choice),
+ T2d: FieldElement::conditional_select(&a.T2d, &b.T2d, choice),
+ }
+ }
+
+ fn conditional_assign(&mut self, other: &Self, choice: Choice) {
+ self.Y_plus_X.conditional_assign(&other.Y_plus_X, choice);
+ self.Y_minus_X.conditional_assign(&other.Y_minus_X, choice);
+ self.Z.conditional_assign(&other.Z, choice);
+ self.T2d.conditional_assign(&other.T2d, choice);
+ }
+}
+
+impl ConditionallySelectable for AffineNielsPoint {
+ fn conditional_select(a: &Self, b: &Self, choice: Choice) -> Self {
+ AffineNielsPoint {
+ y_plus_x: FieldElement::conditional_select(&a.y_plus_x, &b.y_plus_x, choice),
+ y_minus_x: FieldElement::conditional_select(&a.y_minus_x, &b.y_minus_x, choice),
+ xy2d: FieldElement::conditional_select(&a.xy2d, &b.xy2d, choice),
+ }
+ }
+
+ fn conditional_assign(&mut self, other: &Self, choice: Choice) {
+ self.y_plus_x.conditional_assign(&other.y_plus_x, choice);
+ self.y_minus_x.conditional_assign(&other.y_minus_x, choice);
+ self.xy2d.conditional_assign(&other.xy2d, choice);
+ }
+}
+
+// ------------------------------------------------------------------------
+// Point conversions
+// ------------------------------------------------------------------------
+
+impl ProjectivePoint {
+ /// Convert this point from the \\( \mathbb P\^2 \\) model to the
+ /// \\( \mathbb P\^3 \\) model.
+ ///
+ /// This costs \\(3 \mathrm M + 1 \mathrm S\\).
+ pub fn as_extended(&self) -> EdwardsPoint {
+ EdwardsPoint {
+ X: &self.X * &self.Z,
+ Y: &self.Y * &self.Z,
+ Z: self.Z.square(),
+ T: &self.X * &self.Y,
+ }
+ }
+}
+
+impl CompletedPoint {
+ /// Convert this point from the \\( \mathbb P\^1 \times \mathbb P\^1
+ /// \\) model to the \\( \mathbb P\^2 \\) model.
+ ///
+ /// This costs \\(3 \mathrm M \\).
+ pub fn as_projective(&self) -> ProjectivePoint {
+ ProjectivePoint {
+ X: &self.X * &self.T,
+ Y: &self.Y * &self.Z,
+ Z: &self.Z * &self.T,
+ }
+ }
+
+ /// Convert this point from the \\( \mathbb P\^1 \times \mathbb P\^1
+ /// \\) model to the \\( \mathbb P\^3 \\) model.
+ ///
+ /// This costs \\(4 \mathrm M \\).
+ pub fn as_extended(&self) -> EdwardsPoint {
+ EdwardsPoint {
+ X: &self.X * &self.T,
+ Y: &self.Y * &self.Z,
+ Z: &self.Z * &self.T,
+ T: &self.X * &self.Y,
+ }
+ }
+}
+
+// ------------------------------------------------------------------------
+// Doubling
+// ------------------------------------------------------------------------
+
+impl ProjectivePoint {
+ /// Double this point: return self + self
+ pub fn double(&self) -> CompletedPoint {
+ // Double()
+ let XX = self.X.square();
+ let YY = self.Y.square();
+ let ZZ2 = self.Z.square2();
+ let X_plus_Y = &self.X + &self.Y;
+ let X_plus_Y_sq = X_plus_Y.square();
+ let YY_plus_XX = &YY + &XX;
+ let YY_minus_XX = &YY - &XX;
+
+ CompletedPoint {
+ X: &X_plus_Y_sq - &YY_plus_XX,
+ Y: YY_plus_XX,
+ Z: YY_minus_XX,
+ T: &ZZ2 - &YY_minus_XX,
+ }
+ }
+}
+
+// ------------------------------------------------------------------------
+// Addition and Subtraction
+// ------------------------------------------------------------------------
+
+// XXX(hdevalence) These were doc(hidden) so they don't appear in the
+// public API docs.
+// However, that prevents them being used with --document-private-items,
+// so comment out the doc(hidden) for now until this is resolved
+//
+// upstream rust issue: https://github.com/rust-lang/rust/issues/46380
+//#[doc(hidden)]
+impl<'a, 'b> Add<&'b ProjectiveNielsPoint> for &'a EdwardsPoint {
+ type Output = CompletedPoint;
+
+ fn add(self, other: &'b ProjectiveNielsPoint) -> CompletedPoint {
+ let Y_plus_X = &self.Y + &self.X;
+ let Y_minus_X = &self.Y - &self.X;
+ let PP = &Y_plus_X * &other.Y_plus_X;
+ let MM = &Y_minus_X * &other.Y_minus_X;
+ let TT2d = &self.T * &other.T2d;
+ let ZZ = &self.Z * &other.Z;
+ let ZZ2 = &ZZ + &ZZ;
+
+ CompletedPoint {
+ X: &PP - &MM,
+ Y: &PP + &MM,
+ Z: &ZZ2 + &TT2d,
+ T: &ZZ2 - &TT2d,
+ }
+ }
+}
+
+//#[doc(hidden)]
+impl<'a, 'b> Sub<&'b ProjectiveNielsPoint> for &'a EdwardsPoint {
+ type Output = CompletedPoint;
+
+ fn sub(self, other: &'b ProjectiveNielsPoint) -> CompletedPoint {
+ let Y_plus_X = &self.Y + &self.X;
+ let Y_minus_X = &self.Y - &self.X;
+ let PM = &Y_plus_X * &other.Y_minus_X;
+ let MP = &Y_minus_X * &other.Y_plus_X;
+ let TT2d = &self.T * &other.T2d;
+ let ZZ = &self.Z * &other.Z;
+ let ZZ2 = &ZZ + &ZZ;
+
+ CompletedPoint {
+ X: &PM - &MP,
+ Y: &PM + &MP,
+ Z: &ZZ2 - &TT2d,
+ T: &ZZ2 + &TT2d,
+ }
+ }
+}
+
+//#[doc(hidden)]
+impl<'a, 'b> Add<&'b AffineNielsPoint> for &'a EdwardsPoint {
+ type Output = CompletedPoint;
+
+ fn add(self, other: &'b AffineNielsPoint) -> CompletedPoint {
+ let Y_plus_X = &self.Y + &self.X;
+ let Y_minus_X = &self.Y - &self.X;
+ let PP = &Y_plus_X * &other.y_plus_x;
+ let MM = &Y_minus_X * &other.y_minus_x;
+ let Txy2d = &self.T * &other.xy2d;
+ let Z2 = &self.Z + &self.Z;
+
+ CompletedPoint {
+ X: &PP - &MM,
+ Y: &PP + &MM,
+ Z: &Z2 + &Txy2d,
+ T: &Z2 - &Txy2d,
+ }
+ }
+}
+
+//#[doc(hidden)]
+impl<'a, 'b> Sub<&'b AffineNielsPoint> for &'a EdwardsPoint {
+ type Output = CompletedPoint;
+
+ fn sub(self, other: &'b AffineNielsPoint) -> CompletedPoint {
+ let Y_plus_X = &self.Y + &self.X;
+ let Y_minus_X = &self.Y - &self.X;
+ let PM = &Y_plus_X * &other.y_minus_x;
+ let MP = &Y_minus_X * &other.y_plus_x;
+ let Txy2d = &self.T * &other.xy2d;
+ let Z2 = &self.Z + &self.Z;
+
+ CompletedPoint {
+ X: &PM - &MP,
+ Y: &PM + &MP,
+ Z: &Z2 - &Txy2d,
+ T: &Z2 + &Txy2d,
+ }
+ }
+}
+
+// ------------------------------------------------------------------------
+// Negation
+// ------------------------------------------------------------------------
+
+impl<'a> Neg for &'a ProjectiveNielsPoint {
+ type Output = ProjectiveNielsPoint;
+
+ fn neg(self) -> ProjectiveNielsPoint {
+ ProjectiveNielsPoint {
+ Y_plus_X: self.Y_minus_X,
+ Y_minus_X: self.Y_plus_X,
+ Z: self.Z,
+ T2d: -(&self.T2d),
+ }
+ }
+}
+
+impl<'a> Neg for &'a AffineNielsPoint {
+ type Output = AffineNielsPoint;
+
+ fn neg(self) -> AffineNielsPoint {
+ AffineNielsPoint {
+ y_plus_x: self.y_minus_x,
+ y_minus_x: self.y_plus_x,
+ xy2d: -(&self.xy2d),
+ }
+ }
+}
+
+// ------------------------------------------------------------------------
+// Debug traits
+// ------------------------------------------------------------------------
+
+impl Debug for ProjectivePoint {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ write!(
+ f,
+ "ProjectivePoint{{\n\tX: {:?},\n\tY: {:?},\n\tZ: {:?}\n}}",
+ &self.X, &self.Y, &self.Z
+ )
+ }
+}
+
+impl Debug for CompletedPoint {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ write!(
+ f,
+ "CompletedPoint{{\n\tX: {:?},\n\tY: {:?},\n\tZ: {:?},\n\tT: {:?}\n}}",
+ &self.X, &self.Y, &self.Z, &self.T
+ )
+ }
+}
+
+impl Debug for AffineNielsPoint {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ write!(
+ f,
+ "AffineNielsPoint{{\n\ty_plus_x: {:?},\n\ty_minus_x: {:?},\n\txy2d: {:?}\n}}",
+ &self.y_plus_x, &self.y_minus_x, &self.xy2d
+ )
+ }
+}
+
+impl Debug for ProjectiveNielsPoint {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ write!(f, "ProjectiveNielsPoint{{\n\tY_plus_X: {:?},\n\tY_minus_X: {:?},\n\tZ: {:?},\n\tT2d: {:?}\n}}",
+ &self.Y_plus_X, &self.Y_minus_X, &self.Z, &self.T2d)
+ }
+}
diff --git a/vendor/curve25519-dalek/src/backend/serial/fiat_u32/field.rs b/vendor/curve25519-dalek/src/backend/serial/fiat_u32/field.rs
new file mode 100644
index 0000000..97695c3
--- /dev/null
+++ b/vendor/curve25519-dalek/src/backend/serial/fiat_u32/field.rs
@@ -0,0 +1,271 @@
+// -*- mode: rust; coding: utf-8; -*-
+//
+// This file is part of curve25519-dalek.
+// Copyright (c) 2016-2018 Isis Lovecruft, Henry de Valence
+// See LICENSE for licensing information.
+//
+// Authors:
+// - Isis Agora Lovecruft
+// - Henry de Valence
+
+//! Field arithmetic modulo \\(p = 2\^{255} - 19\\), using \\(32\\)-bit
+//! limbs with \\(64\\)-bit products.
+//!
+//! This code was originally derived from Adam Langley's Golang ed25519
+//! implementation, and was then rewritten to use unsigned limbs instead
+//! of signed limbs.
+//!
+//! This uses the formally-verified field arithmetic generated by the
+//! [fiat-crypto project](https://github.com/mit-plv/fiat-crypto)
+
+use core::fmt::Debug;
+use core::ops::Neg;
+use core::ops::{Add, AddAssign};
+use core::ops::{Mul, MulAssign};
+use core::ops::{Sub, SubAssign};
+
+use subtle::Choice;
+use subtle::ConditionallySelectable;
+
+#[cfg(feature = "zeroize")]
+use zeroize::Zeroize;
+
+use fiat_crypto::curve25519_32::*;
+
+/// A `FieldElement2625` represents an element of the field
+/// \\( \mathbb Z / (2\^{255} - 19)\\).
+///
+/// In the 32-bit implementation, a `FieldElement` is represented in
+/// radix \\(2\^{25.5}\\) as ten `u32`s. This means that a field
+/// element \\(x\\) is represented as
+/// $$
+/// x = \sum\_{i=0}\^9 x\_i 2\^{\lceil i \frac {51} 2 \rceil}
+/// = x\_0 + x\_1 2\^{26} + x\_2 2\^{51} + x\_3 2\^{77} + \cdots + x\_9 2\^{230};
+/// $$
+/// the coefficients are alternately bounded by \\(2\^{25}\\) and
+/// \\(2\^{26}\\). The limbs are allowed to grow between reductions up
+/// to \\(2\^{25+b}\\) or \\(2\^{26+b}\\), where \\(b = 1.75\\).
+///
+/// # Note
+///
+/// The `curve25519_dalek::field` module provides a type alias
+/// `curve25519_dalek::field::FieldElement` to either `FieldElement51`
+/// or `FieldElement2625`.
+///
+/// The backend-specific type `FieldElement2625` should not be used
+/// outside of the `curve25519_dalek::field` module.
+#[derive(Copy, Clone)]
+pub struct FieldElement2625(pub(crate) fiat_25519_tight_field_element);
+
+impl Debug for FieldElement2625 {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ write!(f, "FieldElement2625({:?})", &(self.0).0[..])
+ }
+}
+
+#[cfg(feature = "zeroize")]
+impl Zeroize for FieldElement2625 {
+ fn zeroize(&mut self) {
+ (self.0).0.zeroize();
+ }
+}
+
+impl<'b> AddAssign<&'b FieldElement2625> for FieldElement2625 {
+ fn add_assign(&mut self, rhs: &'b FieldElement2625) {
+ let mut result_loose = fiat_25519_loose_field_element([0; 10]);
+ fiat_25519_add(&mut result_loose, &self.0, &rhs.0);
+ fiat_25519_carry(&mut self.0, &result_loose);
+ }
+}
+
+impl<'a, 'b> Add<&'b FieldElement2625> for &'a FieldElement2625 {
+ type Output = FieldElement2625;
+ fn add(self, rhs: &'b FieldElement2625) -> FieldElement2625 {
+ let mut result_loose = fiat_25519_loose_field_element([0; 10]);
+ fiat_25519_add(&mut result_loose, &self.0, &rhs.0);
+ let mut output = FieldElement2625::ZERO;
+ fiat_25519_carry(&mut output.0, &result_loose);
+ output
+ }
+}
+
+impl<'b> SubAssign<&'b FieldElement2625> for FieldElement2625 {
+ fn sub_assign(&mut self, rhs: &'b FieldElement2625) {
+ let mut result_loose = fiat_25519_loose_field_element([0; 10]);
+ fiat_25519_sub(&mut result_loose, &self.0, &rhs.0);
+ fiat_25519_carry(&mut self.0, &result_loose);
+ }
+}
+
+impl<'a, 'b> Sub<&'b FieldElement2625> for &'a FieldElement2625 {
+ type Output = FieldElement2625;
+ fn sub(self, rhs: &'b FieldElement2625) -> FieldElement2625 {
+ let mut result_loose = fiat_25519_loose_field_element([0; 10]);
+ fiat_25519_sub(&mut result_loose, &self.0, &rhs.0);
+ let mut output = FieldElement2625::ZERO;
+ fiat_25519_carry(&mut output.0, &result_loose);
+ output
+ }
+}
+
+impl<'b> MulAssign<&'b FieldElement2625> for FieldElement2625 {
+ fn mul_assign(&mut self, rhs: &'b FieldElement2625) {
+ let mut self_loose = fiat_25519_loose_field_element([0; 10]);
+ fiat_25519_relax(&mut self_loose, &self.0);
+ let mut rhs_loose = fiat_25519_loose_field_element([0; 10]);
+ fiat_25519_relax(&mut rhs_loose, &rhs.0);
+ fiat_25519_carry_mul(&mut self.0, &self_loose, &rhs_loose);
+ }
+}
+
+impl<'a, 'b> Mul<&'b FieldElement2625> for &'a FieldElement2625 {
+ type Output = FieldElement2625;
+ fn mul(self, rhs: &'b FieldElement2625) -> FieldElement2625 {
+ let mut self_loose = fiat_25519_loose_field_element([0; 10]);
+ fiat_25519_relax(&mut self_loose, &self.0);
+ let mut rhs_loose = fiat_25519_loose_field_element([0; 10]);
+ fiat_25519_relax(&mut rhs_loose, &rhs.0);
+ let mut output = FieldElement2625::ZERO;
+ fiat_25519_carry_mul(&mut output.0, &self_loose, &rhs_loose);
+ output
+ }
+}
+
+impl<'a> Neg for &'a FieldElement2625 {
+ type Output = FieldElement2625;
+ fn neg(self) -> FieldElement2625 {
+ let mut output_loose = fiat_25519_loose_field_element([0; 10]);
+ fiat_25519_opp(&mut output_loose, &self.0);
+ let mut output = FieldElement2625::ZERO;
+ fiat_25519_carry(&mut output.0, &output_loose);
+ output
+ }
+}
+
+impl ConditionallySelectable for FieldElement2625 {
+ fn conditional_select(
+ a: &FieldElement2625,
+ b: &FieldElement2625,
+ choice: Choice,
+ ) -> FieldElement2625 {
+ let mut output = fiat_25519_tight_field_element([0u32; 10]);
+ fiat_25519_selectznz(
+ &mut output.0,
+ choice.unwrap_u8() as fiat_25519_u1,
+ &(a.0).0,
+ &(b.0).0,
+ );
+ FieldElement2625(output)
+ }
+
+ fn conditional_assign(&mut self, other: &FieldElement2625, choice: Choice) {
+ let mut output = [0u32; 10];
+ let choicebit = choice.unwrap_u8() as fiat_25519_u1;
+ fiat_25519_cmovznz_u32(&mut output[0], choicebit, self.0[0], other.0[0]);
+ fiat_25519_cmovznz_u32(&mut output[1], choicebit, self.0[1], other.0[1]);
+ fiat_25519_cmovznz_u32(&mut output[2], choicebit, self.0[2], other.0[2]);
+ fiat_25519_cmovznz_u32(&mut output[3], choicebit, self.0[3], other.0[3]);
+ fiat_25519_cmovznz_u32(&mut output[4], choicebit, self.0[4], other.0[4]);
+ fiat_25519_cmovznz_u32(&mut output[5], choicebit, self.0[5], other.0[5]);
+ fiat_25519_cmovznz_u32(&mut output[6], choicebit, self.0[6], other.0[6]);
+ fiat_25519_cmovznz_u32(&mut output[7], choicebit, self.0[7], other.0[7]);
+ fiat_25519_cmovznz_u32(&mut output[8], choicebit, self.0[8], other.0[8]);
+ fiat_25519_cmovznz_u32(&mut output[9], choicebit, self.0[9], other.0[9]);
+ *self = FieldElement2625::from_limbs(output);
+ }
+
+ fn conditional_swap(a: &mut FieldElement2625, b: &mut FieldElement2625, choice: Choice) {
+ u32::conditional_swap(&mut a.0[0], &mut b.0[0], choice);
+ u32::conditional_swap(&mut a.0[1], &mut b.0[1], choice);
+ u32::conditional_swap(&mut a.0[2], &mut b.0[2], choice);
+ u32::conditional_swap(&mut a.0[3], &mut b.0[3], choice);
+ u32::conditional_swap(&mut a.0[4], &mut b.0[4], choice);
+ u32::conditional_swap(&mut a.0[5], &mut b.0[5], choice);
+ u32::conditional_swap(&mut a.0[6], &mut b.0[6], choice);
+ u32::conditional_swap(&mut a.0[7], &mut b.0[7], choice);
+ u32::conditional_swap(&mut a.0[8], &mut b.0[8], choice);
+ u32::conditional_swap(&mut a.0[9], &mut b.0[9], choice);
+ }
+}
+
+impl FieldElement2625 {
+ pub(crate) const fn from_limbs(limbs: [u32; 10]) -> FieldElement2625 {
+ FieldElement2625(fiat_25519_tight_field_element(limbs))
+ }
+
+ /// The scalar \\( 0 \\).
+ pub const ZERO: FieldElement2625 = FieldElement2625::from_limbs([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+ /// The scalar \\( 1 \\).
+ pub const ONE: FieldElement2625 = FieldElement2625::from_limbs([1, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
+ /// The scalar \\( -1 \\).
+ pub const MINUS_ONE: FieldElement2625 = FieldElement2625::from_limbs([
+ 0x3ffffec, 0x1ffffff, 0x3ffffff, 0x1ffffff, 0x3ffffff, 0x1ffffff, 0x3ffffff, 0x1ffffff,
+ 0x3ffffff, 0x1ffffff,
+ ]);
+
+ /// Invert the sign of this field element
+ pub fn negate(&mut self) {
+ let neg = self.neg();
+ self.0 = neg.0;
+ }
+
+ /// Given `k > 0`, return `self^(2^k)`.
+ pub fn pow2k(&self, k: u32) -> FieldElement2625 {
+ debug_assert!(k > 0);
+ let mut z = self.square();
+ for _ in 1..k {
+ z = z.square();
+ }
+ z
+ }
+
+ /// Load a `FieldElement2625` from the low 255 bits of a 256-bit
+ /// input.
+ ///
+ /// # Warning
+ ///
+ /// This function does not check that the input used the canonical
+ /// representative. It masks the high bit, but it will happily
+ /// decode 2^255 - 18 to 1. Applications that require a canonical
+ /// encoding of every field element should decode, re-encode to
+ /// the canonical encoding, and check that the input was
+ /// canonical.
+ pub fn from_bytes(data: &[u8; 32]) -> FieldElement2625 {
+ let mut temp = [0u8; 32];
+ temp.copy_from_slice(data);
+ temp[31] &= 127u8;
+ let mut output = fiat_25519_tight_field_element([0u32; 10]);
+ fiat_25519_from_bytes(&mut output, &temp);
+ FieldElement2625(output)
+ }
+
+ /// Serialize this `FieldElement51` to a 32-byte array. The
+ /// encoding is canonical.
+ pub fn as_bytes(&self) -> [u8; 32] {
+ let mut bytes = [0u8; 32];
+ fiat_25519_to_bytes(&mut bytes, &self.0);
+ bytes
+ }
+
+ /// Compute `self^2`.
+ pub fn square(&self) -> FieldElement2625 {
+ let mut self_loose = fiat_25519_loose_field_element([0; 10]);
+ fiat_25519_relax(&mut self_loose, &self.0);
+ let mut output = FieldElement2625::ZERO;
+ fiat_25519_carry_square(&mut output.0, &self_loose);
+ output
+ }
+
+ /// Compute `2*self^2`.
+ pub fn square2(&self) -> FieldElement2625 {
+ let mut self_loose = fiat_25519_loose_field_element([0; 10]);
+ fiat_25519_relax(&mut self_loose, &self.0);
+ let mut square = fiat_25519_tight_field_element([0; 10]);
+ fiat_25519_carry_square(&mut square, &self_loose);
+ let mut output_loose = fiat_25519_loose_field_element([0; 10]);
+ fiat_25519_add(&mut output_loose, &square, &square);
+ let mut output = FieldElement2625::ZERO;
+ fiat_25519_carry(&mut output.0, &output_loose);
+ output
+ }
+}
diff --git a/vendor/curve25519-dalek/src/backend/serial/fiat_u32/mod.rs b/vendor/curve25519-dalek/src/backend/serial/fiat_u32/mod.rs
new file mode 100644
index 0000000..974316e
--- /dev/null
+++ b/vendor/curve25519-dalek/src/backend/serial/fiat_u32/mod.rs
@@ -0,0 +1,26 @@
+// -*- mode: rust; -*-
+//
+// This file is part of curve25519-dalek.
+// Copyright (c) 2016-2018 Isis Lovecruft, Henry de Valence
+// See LICENSE for licensing information.
+//
+// Authors:
+// - Isis Agora Lovecruft
+// - Henry de Valence
+
+//! The `u32` backend uses `u32`s and a `(u32, u32) -> u64` multiplier.
+//!
+//! This code is intended to be portable, but it requires that
+//! multiplication of two \\(32\\)-bit values to a \\(64\\)-bit result
+//! is constant-time on the target platform.
+//!
+//! This uses the formally-verified field arithmetic generated by the
+//! [fiat-crypto project](https://github.com/mit-plv/fiat-crypto)
+
+#[path = "../u32/scalar.rs"]
+pub mod scalar;
+
+pub mod field;
+
+#[path = "../u32/constants.rs"]
+pub mod constants;
diff --git a/vendor/curve25519-dalek/src/backend/serial/fiat_u64/field.rs b/vendor/curve25519-dalek/src/backend/serial/fiat_u64/field.rs
new file mode 100644
index 0000000..2a022e2
--- /dev/null
+++ b/vendor/curve25519-dalek/src/backend/serial/fiat_u64/field.rs
@@ -0,0 +1,262 @@
+// -*- mode: rust; coding: utf-8; -*-
+//
+// This file is part of curve25519-dalek.
+// Copyright (c) 2016-2018 Isis Lovecruft, Henry de Valence
+// See LICENSE for licensing information.
+//
+// Authors:
+// - Isis Agora Lovecruft
+// - Henry de Valence
+
+//! Field arithmetic modulo \\(p = 2\^{255} - 19\\), using \\(64\\)-bit
+//! limbs with \\(128\\)-bit products.
+//!
+//! This uses the formally-verified field arithmetic generated by the
+//! [fiat-crypto project](https://github.com/mit-plv/fiat-crypto)
+
+use core::fmt::Debug;
+use core::ops::Neg;
+use core::ops::{Add, AddAssign};
+use core::ops::{Mul, MulAssign};
+use core::ops::{Sub, SubAssign};
+
+use subtle::Choice;
+use subtle::ConditionallySelectable;
+
+#[cfg(feature = "zeroize")]
+use zeroize::Zeroize;
+
+use fiat_crypto::curve25519_64::*;
+
+/// A `FieldElement51` represents an element of the field
+/// \\( \mathbb Z / (2\^{255} - 19)\\).
+///
+/// In the 64-bit implementation, a `FieldElement` is represented in
+/// radix \\(2\^{51}\\) as five `u64`s; the coefficients are allowed to
+/// grow up to \\(2\^{54}\\) between reductions modulo \\(p\\).
+///
+/// # Note
+///
+/// The `curve25519_dalek::field` module provides a type alias
+/// `curve25519_dalek::field::FieldElement` to either `FieldElement51`
+/// or `FieldElement2625`.
+///
+/// The backend-specific type `FieldElement51` should not be used
+/// outside of the `curve25519_dalek::field` module.
+#[derive(Copy, Clone)]
+pub struct FieldElement51(pub(crate) fiat_25519_tight_field_element);
+
+impl Debug for FieldElement51 {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ write!(f, "FieldElement51({:?})", &(self.0).0[..])
+ }
+}
+
+#[cfg(feature = "zeroize")]
+impl Zeroize for FieldElement51 {
+ fn zeroize(&mut self) {
+ (self.0).0.zeroize();
+ }
+}
+
+impl<'b> AddAssign<&'b FieldElement51> for FieldElement51 {
+ fn add_assign(&mut self, rhs: &'b FieldElement51) {
+ let mut result_loose = fiat_25519_loose_field_element([0; 5]);
+ fiat_25519_add(&mut result_loose, &self.0, &rhs.0);
+ fiat_25519_carry(&mut self.0, &result_loose);
+ }
+}
+
+impl<'a, 'b> Add<&'b FieldElement51> for &'a FieldElement51 {
+ type Output = FieldElement51;
+ fn add(self, rhs: &'b FieldElement51) -> FieldElement51 {
+ let mut result_loose = fiat_25519_loose_field_element([0; 5]);
+ fiat_25519_add(&mut result_loose, &self.0, &rhs.0);
+ let mut output = FieldElement51::ZERO;
+ fiat_25519_carry(&mut output.0, &result_loose);
+ output
+ }
+}
+
+impl<'b> SubAssign<&'b FieldElement51> for FieldElement51 {
+ fn sub_assign(&mut self, rhs: &'b FieldElement51) {
+ let mut result_loose = fiat_25519_loose_field_element([0; 5]);
+ fiat_25519_sub(&mut result_loose, &self.0, &rhs.0);
+ fiat_25519_carry(&mut self.0, &result_loose);
+ }
+}
+
+impl<'a, 'b> Sub<&'b FieldElement51> for &'a FieldElement51 {
+ type Output = FieldElement51;
+ fn sub(self, rhs: &'b FieldElement51) -> FieldElement51 {
+ let mut result_loose = fiat_25519_loose_field_element([0; 5]);
+ fiat_25519_sub(&mut result_loose, &self.0, &rhs.0);
+ let mut output = FieldElement51::ZERO;
+ fiat_25519_carry(&mut output.0, &result_loose);
+ output
+ }
+}
+
+impl<'b> MulAssign<&'b FieldElement51> for FieldElement51 {
+ fn mul_assign(&mut self, rhs: &'b FieldElement51) {
+ let mut self_loose = fiat_25519_loose_field_element([0; 5]);
+ fiat_25519_relax(&mut self_loose, &self.0);
+ let mut rhs_loose = fiat_25519_loose_field_element([0; 5]);
+ fiat_25519_relax(&mut rhs_loose, &rhs.0);
+ fiat_25519_carry_mul(&mut self.0, &self_loose, &rhs_loose);
+ }
+}
+
+impl<'a, 'b> Mul<&'b FieldElement51> for &'a FieldElement51 {
+ type Output = FieldElement51;
+ fn mul(self, rhs: &'b FieldElement51) -> FieldElement51 {
+ let mut self_loose = fiat_25519_loose_field_element([0; 5]);
+ fiat_25519_relax(&mut self_loose, &self.0);
+ let mut rhs_loose = fiat_25519_loose_field_element([0; 5]);
+ fiat_25519_relax(&mut rhs_loose, &rhs.0);
+ let mut output = FieldElement51::ZERO;
+ fiat_25519_carry_mul(&mut output.0, &self_loose, &rhs_loose);
+ output
+ }
+}
+
+impl<'a> Neg for &'a FieldElement51 {
+ type Output = FieldElement51;
+ fn neg(self) -> FieldElement51 {
+ let mut output_loose = fiat_25519_loose_field_element([0; 5]);
+ fiat_25519_opp(&mut output_loose, &self.0);
+ let mut output = FieldElement51::ZERO;
+ fiat_25519_carry(&mut output.0, &output_loose);
+ output
+ }
+}
+
+impl ConditionallySelectable for FieldElement51 {
+ fn conditional_select(
+ a: &FieldElement51,
+ b: &FieldElement51,
+ choice: Choice,
+ ) -> FieldElement51 {
+ let mut output = fiat_25519_tight_field_element([0u64; 5]);
+ fiat_25519_selectznz(
+ &mut output.0,
+ choice.unwrap_u8() as fiat_25519_u1,
+ &(a.0).0,
+ &(b.0).0,
+ );
+ FieldElement51(output)
+ }
+
+ fn conditional_swap(a: &mut FieldElement51, b: &mut FieldElement51, choice: Choice) {
+ u64::conditional_swap(&mut a.0[0], &mut b.0[0], choice);
+ u64::conditional_swap(&mut a.0[1], &mut b.0[1], choice);
+ u64::conditional_swap(&mut a.0[2], &mut b.0[2], choice);
+ u64::conditional_swap(&mut a.0[3], &mut b.0[3], choice);
+ u64::conditional_swap(&mut a.0[4], &mut b.0[4], choice);
+ }
+
+ fn conditional_assign(&mut self, rhs: &FieldElement51, choice: Choice) {
+ let mut output = [0u64; 5];
+ let choicebit = choice.unwrap_u8() as fiat_25519_u1;
+ fiat_25519_cmovznz_u64(&mut output[0], choicebit, self.0[0], rhs.0[0]);
+ fiat_25519_cmovznz_u64(&mut output[1], choicebit, self.0[1], rhs.0[1]);
+ fiat_25519_cmovznz_u64(&mut output[2], choicebit, self.0[2], rhs.0[2]);
+ fiat_25519_cmovznz_u64(&mut output[3], choicebit, self.0[3], rhs.0[3]);
+ fiat_25519_cmovznz_u64(&mut output[4], choicebit, self.0[4], rhs.0[4]);
+ *self = FieldElement51::from_limbs(output);
+ }
+}
+
+impl FieldElement51 {
+ pub(crate) const fn from_limbs(limbs: [u64; 5]) -> FieldElement51 {
+ FieldElement51(fiat_25519_tight_field_element(limbs))
+ }
+
+ /// The scalar \\( 0 \\).
+ pub const ZERO: FieldElement51 = FieldElement51::from_limbs([0, 0, 0, 0, 0]);
+ /// The scalar \\( 1 \\).
+ pub const ONE: FieldElement51 = FieldElement51::from_limbs([1, 0, 0, 0, 0]);
+ /// The scalar \\( -1 \\).
+ pub const MINUS_ONE: FieldElement51 = FieldElement51::from_limbs([
+ 2251799813685228,
+ 2251799813685247,
+ 2251799813685247,
+ 2251799813685247,
+ 2251799813685247,
+ ]);
+
+ /// Given 64-bit input limbs, reduce to enforce the bound 2^(51 + epsilon).
+ #[inline(always)]
+ #[allow(dead_code)] // Need this to not complain about reduce not being used
+ fn reduce(limbs: [u64; 5]) -> FieldElement51 {
+ let input = fiat_25519_loose_field_element(limbs);
+ let mut output = fiat_25519_tight_field_element([0; 5]);
+ fiat_25519_carry(&mut output, &input);
+ FieldElement51(output)
+ }
+
+ /// Load a `FieldElement51` from the low 255 bits of a 256-bit
+ /// input.
+ ///
+ /// # Warning
+ ///
+ /// This function does not check that the input used the canonical
+ /// representative. It masks the high bit, but it will happily
+ /// decode 2^255 - 18 to 1. Applications that require a canonical
+ /// encoding of every field element should decode, re-encode to
+ /// the canonical encoding, and check that the input was
+ /// canonical.
+ ///
+ pub fn from_bytes(bytes: &[u8; 32]) -> FieldElement51 {
+ let mut temp = [0u8; 32];
+ temp.copy_from_slice(bytes);
+ temp[31] &= 127u8;
+ let mut output = fiat_25519_tight_field_element([0u64; 5]);
+ fiat_25519_from_bytes(&mut output, &temp);
+ FieldElement51(output)
+ }
+
+ /// Serialize this `FieldElement51` to a 32-byte array. The
+ /// encoding is canonical.
+ pub fn as_bytes(&self) -> [u8; 32] {
+ let mut bytes = [0u8; 32];
+ fiat_25519_to_bytes(&mut bytes, &self.0);
+ bytes
+ }
+
+ /// Given `k > 0`, return `self^(2^k)`.
+ pub fn pow2k(&self, mut k: u32) -> FieldElement51 {
+ let mut output = *self;
+ loop {
+ let mut input = fiat_25519_loose_field_element([0; 5]);
+ fiat_25519_relax(&mut input, &output.0);
+ fiat_25519_carry_square(&mut output.0, &input);
+ k -= 1;
+ if k == 0 {
+ return output;
+ }
+ }
+ }
+
+ /// Returns the square of this field element.
+ pub fn square(&self) -> FieldElement51 {
+ let mut self_loose = fiat_25519_loose_field_element([0; 5]);
+ fiat_25519_relax(&mut self_loose, &self.0);
+ let mut output = FieldElement51::ZERO;
+ fiat_25519_carry_square(&mut output.0, &self_loose);
+ output
+ }
+
+ /// Returns 2 times the square of this field element.
+ pub fn square2(&self) -> FieldElement51 {
+ let mut self_loose = fiat_25519_loose_field_element([0; 5]);
+ fiat_25519_relax(&mut self_loose, &self.0);
+ let mut square = fiat_25519_tight_field_element([0; 5]);
+ fiat_25519_carry_square(&mut square, &self_loose);
+ let mut output_loose = fiat_25519_loose_field_element([0; 5]);
+ fiat_25519_add(&mut output_loose, &square, &square);
+ let mut output = FieldElement51::ZERO;
+ fiat_25519_carry(&mut output.0, &output_loose);
+ output
+ }
+}
diff --git a/vendor/curve25519-dalek/src/backend/serial/fiat_u64/mod.rs b/vendor/curve25519-dalek/src/backend/serial/fiat_u64/mod.rs
new file mode 100644
index 0000000..8c83062
--- /dev/null
+++ b/vendor/curve25519-dalek/src/backend/serial/fiat_u64/mod.rs
@@ -0,0 +1,28 @@
+// -*- mode: rust; -*-
+//
+// This file is part of curve25519-dalek.
+// Copyright (c) 2016-2018 Isis Lovecruft, Henry de Valence
+// See LICENSE for licensing information.
+//
+// Authors:
+// - Isis Agora Lovecruft
+// - Henry de Valence
+
+//! The `u64` backend uses `u64`s and a `(u64, u64) -> u128` multiplier.
+//!
+//! On x86_64, the idiom `(x as u128) * (y as u128)` lowers to `MUL`
+//! instructions taking 64-bit inputs and producing 128-bit outputs. On
+//! other platforms, this implementation is not recommended.
+//!
+//! On Haswell and newer, the BMI2 extension provides `MULX`, and on
+//! Broadwell and newer, the ADX extension provides `ADCX` and `ADOX`
+//! (allowing the CPU to compute two carry chains in parallel). These
+//! will be used if available.
+
+#[path = "../u64/scalar.rs"]
+pub mod scalar;
+
+pub mod field;
+
+#[path = "../u64/constants.rs"]
+pub mod constants;
diff --git a/vendor/curve25519-dalek/src/backend/serial/mod.rs b/vendor/curve25519-dalek/src/backend/serial/mod.rs
new file mode 100644
index 0000000..4baec83
--- /dev/null
+++ b/vendor/curve25519-dalek/src/backend/serial/mod.rs
@@ -0,0 +1,49 @@
+// -*- mode: rust; -*-
+//
+// This file is part of curve25519-dalek.
+// Copyright (c) 2016-2021 isis lovecruft
+// Copyright (c) 2016-2019 Henry de Valence
+// See LICENSE for licensing information.
+//
+// Authors:
+// - isis agora lovecruft
+// - Henry de Valence
+
+//! Serial implementations of field, scalar, point arithmetic.
+//!
+//! When the vector backend is disabled, the crate uses the mixed-model strategy
+//! for implementing point operations and scalar multiplication; see the
+//! [`curve_models`] and [`scalar_mul`] documentation for more information.
+//!
+//! When the vector backend is enabled, the field and scalar
+//! implementations are still used for non-vectorized operations.
+
+use cfg_if::cfg_if;
+
+cfg_if! {
+ if #[cfg(curve25519_dalek_backend = "fiat")] {
+
+ #[cfg(curve25519_dalek_bits = "32")]
+ #[doc(hidden)]
+ pub mod fiat_u32;
+
+ #[cfg(curve25519_dalek_bits = "64")]
+ #[doc(hidden)]
+ pub mod fiat_u64;
+
+ } else {
+
+ #[cfg(curve25519_dalek_bits = "32")]
+ #[doc(hidden)]
+ pub mod u32;
+
+ #[cfg(curve25519_dalek_bits = "64")]
+ #[doc(hidden)]
+ pub mod u64;
+
+ }
+}
+
+pub mod curve_models;
+
+pub mod scalar_mul;
diff --git a/vendor/curve25519-dalek/src/backend/serial/scalar_mul/mod.rs b/vendor/curve25519-dalek/src/backend/serial/scalar_mul/mod.rs
new file mode 100644
index 0000000..7747dec
--- /dev/null
+++ b/vendor/curve25519-dalek/src/backend/serial/scalar_mul/mod.rs
@@ -0,0 +1,33 @@
+// -*- mode: rust; -*-
+//
+// This file is part of curve25519-dalek.
+// Copyright (c) 2016-2021 isis lovecruft
+// Copyright (c) 2016-2019 Henry de Valence
+// See LICENSE for licensing information.
+//
+// Authors:
+// - isis agora lovecruft
+// - Henry de Valence
+
+//! Implementations of various scalar multiplication algorithms.
+//!
+//! Note that all of these implementations use serial code for field
+//! arithmetic with the multi-model strategy described in the
+//! `curve_models` module. The vectorized AVX2 backend has its own
+//! scalar multiplication implementations, since it only uses one
+//! curve model.
+
+#[allow(missing_docs)]
+pub mod variable_base;
+
+#[allow(missing_docs)]
+pub mod vartime_double_base;
+
+#[cfg(feature = "alloc")]
+pub mod straus;
+
+#[cfg(feature = "alloc")]
+pub mod precomputed_straus;
+
+#[cfg(feature = "alloc")]
+pub mod pippenger;
diff --git a/vendor/curve25519-dalek/src/backend/serial/scalar_mul/pippenger.rs b/vendor/curve25519-dalek/src/backend/serial/scalar_mul/pippenger.rs
new file mode 100644
index 0000000..f60d9b9
--- /dev/null
+++ b/vendor/curve25519-dalek/src/backend/serial/scalar_mul/pippenger.rs
@@ -0,0 +1,199 @@
+// -*- mode: rust; -*-
+//
+// This file is part of curve25519-dalek.
+// Copyright (c) 2019 Oleg Andreev
+// See LICENSE for licensing information.
+//
+// Authors:
+// - Oleg Andreev
+
+//! Implementation of a variant of Pippenger's algorithm.
+
+#![allow(non_snake_case)]
+
+use alloc::vec::Vec;
+
+use core::borrow::Borrow;
+use core::cmp::Ordering;
+
+use crate::edwards::EdwardsPoint;
+use crate::scalar::Scalar;
+use crate::traits::VartimeMultiscalarMul;
+
+/// Implements a version of Pippenger's algorithm.
+///
+/// The algorithm works as follows:
+///
+/// Let `n` be a number of point-scalar pairs.
+/// Let `w` be a window of bits (6..8, chosen based on `n`, see cost factor).
+///
+/// 1. Prepare `2^(w-1) - 1` buckets with indices `[1..2^(w-1))` initialized with identity points.
+/// Bucket 0 is not needed as it would contain points multiplied by 0.
+/// 2. Convert scalars to a radix-`2^w` representation with signed digits in `[-2^w/2, 2^w/2]`.
+/// Note: only the last digit may equal `2^w/2`.
+/// 3. Starting with the last window, for each point `i=[0..n)` add it to a a bucket indexed by
+/// the point's scalar's value in the window.
+/// 4. Once all points in a window are sorted into buckets, add buckets by multiplying each
+/// by their index. Efficient way of doing it is to start with the last bucket and compute two sums:
+/// intermediate sum from the last to the first, and the full sum made of all intermediate sums.
+/// 5. Shift the resulting sum of buckets by `w` bits by using `w` doublings.
+/// 6. Add to the return value.
+/// 7. Repeat the loop.
+///
+/// Approximate cost w/o wNAF optimizations (A = addition, D = doubling):
+///
+/// ```ascii
+/// cost = (n*A + 2*(2^w/2)*A + w*D + A)*256/w
+/// | | | | |
+/// | | | | looping over 256/w windows
+/// | | | adding to the result
+/// sorting points | shifting the sum by w bits (to the next window, starting from last window)
+/// one by one |
+/// into buckets adding/subtracting all buckets
+/// multiplied by their indexes
+/// using a sum of intermediate sums
+/// ```
+///
+/// For large `n`, dominant factor is (n*256/w) additions.
+/// However, if `w` is too big and `n` is not too big, then `(2^w/2)*A` could dominate.
+/// Therefore, the optimal choice of `w` grows slowly as `n` grows.
+///
+/// This algorithm is adapted from section 4 of .
+pub struct Pippenger;
+
+impl VartimeMultiscalarMul for Pippenger {
+ type Point = EdwardsPoint;
+
+ fn optional_multiscalar_mul(scalars: I, points: J) -> Option
+ where
+ I: IntoIterator,
+ I::Item: Borrow,
+ J: IntoIterator>,
+ {
+ use crate::traits::Identity;
+
+ let mut scalars = scalars.into_iter();
+ let size = scalars.by_ref().size_hint().0;
+
+ // Digit width in bits. As digit width grows,
+ // number of point additions goes down, but amount of
+ // buckets and bucket additions grows exponentially.
+ let w = if size < 500 {
+ 6
+ } else if size < 800 {
+ 7
+ } else {
+ 8
+ };
+
+ let max_digit: usize = 1 << w;
+ let digits_count: usize = Scalar::to_radix_2w_size_hint(w);
+ let buckets_count: usize = max_digit / 2; // digits are signed+centered hence 2^w/2, excluding 0-th bucket
+
+ // Collect optimized scalars and points in buffers for repeated access
+ // (scanning the whole set per digit position).
+ let scalars = scalars.map(|s| s.borrow().as_radix_2w(w));
+
+ let points = points
+ .into_iter()
+ .map(|p| p.map(|P| P.as_projective_niels()));
+
+ let scalars_points = scalars
+ .zip(points)
+ .map(|(s, maybe_p)| maybe_p.map(|p| (s, p)))
+ .collect::