Compare commits
23 Commits
feature/arcanum
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| e950660ca3 | |||
| 7f7b2b641a | |||
| 5529560a72 | |||
| dafcebdef0 | |||
| cbde0650a4 | |||
| fc96614fce | |||
| 1e7e0bb16c | |||
| 0b2480bf83 | |||
| 9f9318664f | |||
| 002371445b | |||
| 274cf37d69 | |||
| 413dbaa279 | |||
| abcc375741 | |||
| 2329eb0719 | |||
| 99db18af16 | |||
| d56ee10f0d | |||
| b245e1054c | |||
| ddda8415eb | |||
| 5a52854ccc | |||
| 2a432f5d86 | |||
| 5b9e3ee8fb | |||
| c7294612ae | |||
| 2fae9ad3eb |
@@ -0,0 +1,23 @@
|
||||
# Arcanum: the whole suite once on Linux, on the server's NixOS runner (Mark, 2026-11-26: "Fabrica server runner").
|
||||
# By hand (Artifex → arcanum → linux, or the hub's POST /api/runs with pipeline linux and a ref), or on a push to
|
||||
# ci/linux. Every run line starts with `nix` and has no `&&`, `;` or `|`: Fabrica's preflight reads the first
|
||||
# word of each such part as a tool the runner must have, even inside quotes. It builds and switches nothing on the server. The toolchain is the flake's `ci` shell (nixos-26.05).
|
||||
name: linux
|
||||
on:
|
||||
push: [ci/linux]
|
||||
manual: true
|
||||
runner: nixos
|
||||
env:
|
||||
CARGO_TERM_COLOR: "never"
|
||||
steps:
|
||||
- id: toolchain
|
||||
run: nix --extra-experimental-features "nix-command flakes" develop .#ci -c cargo --version
|
||||
- id: test-debug
|
||||
needs: [toolchain]
|
||||
run: nix --extra-experimental-features "nix-command flakes" develop .#ci -c cargo test --no-fail-fast
|
||||
- id: test-release
|
||||
needs: [test-debug]
|
||||
run: nix --extra-experimental-features "nix-command flakes" develop .#ci -c cargo test --release --no-fail-fast
|
||||
- id: zeroize-probe
|
||||
needs: [test-release]
|
||||
run: nix --extra-experimental-features "nix-command flakes" develop .#ci -c cargo test --release --manifest-path zeroize-probe/Cargo.toml -- --test-threads=1
|
||||
@@ -16,3 +16,13 @@ Read HANDOVER.md and the day's docs/NN_*.md before writing code.
|
||||
## Workflow
|
||||
(D)TDD doc → tests → code. Branch, PR with critical self-review, merge --no-ff, push, verify.
|
||||
No AI attribution in commits. No binaries in git. Say which build you are describing.
|
||||
|
||||
## This PC
|
||||
- **No build or test while this PC is too busy** (Mark, 2026-11-25; drive limit raised 2026-11-29). Never start a
|
||||
build or a test run (cargo, npm/pnpm, Playwright, fuzz, e2e, Fabrica runs on this PC) while the CPU or the RAM is
|
||||
more than 90 % used, or any drive the run writes to (D:, E:, F:) is more than 95 % used. Check first; if one is
|
||||
over, don't start, wait and check again. A run already going may finish. Never stop other sessions' work to make
|
||||
room. Merging, pushing and editing files are not builds. In PowerShell: CPU
|
||||
`(Get-CimInstance Win32_Processor | Measure-Object LoadPercentage -Average).Average`; RAM
|
||||
`$o=Get-CimInstance Win32_OperatingSystem; (1-$o.FreePhysicalMemory/$o.TotalVisibleMemorySize)*100`; drives
|
||||
`Get-PSDrive D,E,F`, used / (used + free).
|
||||
|
||||
Generated
+96
-1
@@ -14,14 +14,18 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "arcanum"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"arcanum",
|
||||
"base64",
|
||||
"chacha20",
|
||||
"chacha20poly1305",
|
||||
"curve25519-dalek",
|
||||
"ed25519-dalek",
|
||||
"hex",
|
||||
"hkdf",
|
||||
"hmac",
|
||||
"ml-dsa",
|
||||
"ml-kem",
|
||||
"rand_core",
|
||||
"serde",
|
||||
@@ -40,6 +44,18 @@ version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "base64"
|
||||
version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.1"
|
||||
@@ -142,6 +158,7 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"curve25519-dalek-derive",
|
||||
"digest",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
@@ -159,6 +176,16 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.11.3"
|
||||
@@ -172,6 +199,28 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
|
||||
dependencies = [
|
||||
"signature",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-dalek"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"ed25519",
|
||||
"sha2",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.3.0"
|
||||
@@ -260,6 +309,22 @@ version = "2.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||
|
||||
[[package]]
|
||||
name = "ml-dsa"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f6d49c3f3f0e10e18ca975ffda66f8da0ec36521c1d911adcbc521bf0743f5c"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"ctutils",
|
||||
"hybrid-array",
|
||||
"module-lattice",
|
||||
"pkcs8",
|
||||
"shake",
|
||||
"signature",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ml-kem"
|
||||
version = "0.3.4"
|
||||
@@ -296,6 +361,16 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
|
||||
dependencies = [
|
||||
"der",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "poly1305"
|
||||
version = "0.9.1"
|
||||
@@ -421,6 +496,26 @@ dependencies = [
|
||||
"sponge-cursor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"der",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sponge-cursor"
|
||||
version = "0.1.0"
|
||||
|
||||
+12
-3
@@ -1,10 +1,10 @@
|
||||
[package]
|
||||
name = "arcanum"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
license = "CPAL-1.0"
|
||||
description = "Hybrid post-quantum key exchange (X-Wing: ML-KEM-768 + X25519), key schedule, WireGuard PSK derivation and sealing for the Domi ecosystem"
|
||||
description = "Hybrid post-quantum key exchange (X-Wing: ML-KEM-768 + X25519), key schedule, WireGuard PSK derivation, sealing and hybrid signatures (ML-DSA-65 + Ed25519, RFC 10073) for the Domi ecosystem"
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/arcanum"
|
||||
readme = "README.md"
|
||||
publish = false
|
||||
@@ -21,9 +21,14 @@ hmac = { version = "0.13", default-features = false, features = ["zeroize"] }
|
||||
chacha20poly1305 = { version = "0.11", default-features = false, features = ["alloc", "zeroize"] }
|
||||
rand_core = { version = "0.10", default-features = false }
|
||||
zeroize = { version = "1.8", default-features = false, features = ["alloc", "zeroize_derive"] }
|
||||
# v0.2.0 signatures (docs/02_signatures.md): ML-DSA-65 (FIPS 204) and Ed25519 (RFC 8032), combined as
|
||||
# RFC 10073 id-MLDSA65-Ed25519-SHA512. Pinned exactly; `zeroize` is opt-in in ml-dsa and must stay on.
|
||||
ml-dsa = { version = "=0.1.2", default-features = false, features = ["alloc", "rand_core", "zeroize"] }
|
||||
ed25519-dalek = { version = "=3.0.0", default-features = false, features = ["zeroize"] }
|
||||
|
||||
[features]
|
||||
# Deterministic entry points (`_derand`, `from_seed`) for the known-answer tests. Off by default;
|
||||
# Deterministic entry points (`_derand`, `from_seed`) and the bare RFC 10073 signature interface
|
||||
# (`sign_composite_raw`, `verify_composite_raw`) for the known-answer tests. Off by default;
|
||||
# never enable it in a release build (tests/feature_hygiene.rs checks the normal dependency graph).
|
||||
hazmat = []
|
||||
|
||||
@@ -37,6 +42,10 @@ serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
hex = "0.4"
|
||||
sha2 = "0.11"
|
||||
# The RFC 10073 vectors are base64.
|
||||
base64 = "0.22"
|
||||
# Ed25519 scalar arithmetic, for the small-order-R half (QA S-01). Already in the lock via ed25519-dalek.
|
||||
curve25519-dalek = { version = "=5.0.0", default-features = false }
|
||||
|
||||
# ML-KEM in a debug build is slow; the byte-flip tests run thousands of exchanges.
|
||||
[profile.dev.package."*"]
|
||||
|
||||
+122
@@ -2,6 +2,128 @@
|
||||
|
||||
Newest entry first. Where this file and the code disagree, the code wins and the next entry says so.
|
||||
|
||||
## 2026-11-26 — v0.2.0, QA review answered (builder), still on `feature/signatures`, not merged, not tagged
|
||||
|
||||
QA's review (`Via/qa/review-arcanum-pr2.md`, head `d56ee10`): no blocker, no major, 12 minors (S-01 to
|
||||
S-12). Answered in `99db18a..` this entry; QA's proof tests (`qa_sig_review.rs`) ported where they pin
|
||||
something, into the existing test files.
|
||||
|
||||
**Fixed:**
|
||||
- S-01, S-02, S-03: tests pin `verify_strict` (a small-order R in the Ed25519 half is refused), the order
|
||||
of checks in `verify_binding` (a forged window outside `now` is `InvalidSignature`, never
|
||||
`OutsideValidity`) and two independent seeds in `generate` (exactly 64 bytes drawn, in order). QA's
|
||||
mutations now fail: Q1 `verify_strict` → `verify` fails `a_small_order_r_in_the_ed25519_half_is_refused`;
|
||||
Q3 `now` checked first fails `a_forged_window_that_excludes_now_is_invalid_signature_not_outside_validity`;
|
||||
Q4 the Ed25519 seed copied from the ML-DSA seed fails `generate_draws_two_independent_seeds`.
|
||||
- S-05: an ML-DSA-65 key with t1 = 0 is refused as `InvalidVerifyingKey`; removing the check fails
|
||||
`an_ml_dsa_key_with_zero_t1_is_refused`.
|
||||
- S-09: `AppContext::new` is a `const fn` taking `&'static [u8]`, the only constructor; a consumer passing a
|
||||
runtime `Vec` does not compile (`sig_hygiene`, E0597/E0716). **API change** from `d56ee10`.
|
||||
- S-10: `deny.toml` bans `legacy_compatibility` on `ed25519-dalek` and `curve25519-dalek`, and
|
||||
`ed25519-dalek/hazmat`; enabling either in `Cargo.toml` fails `cargo deny --offline check bans` (checked,
|
||||
reverted).
|
||||
- S-06: the docs no longer claim timing hides which half failed; it does not, harmlessly (public data only).
|
||||
`&` became `&&`; no behaviour change.
|
||||
- S-04: the zeroize probe also watches the canary key's expanded ML-DSA K and a window of encoded s1; QA's
|
||||
Q15 (an unwiped `to_expanded()` copy in `SigningKey`) now fails the probe.
|
||||
- S-11: stack need documented on `SigningKey`, measured with `tests/sig_stack.rs`: release overflows at
|
||||
128 KiB and fits in 256 KiB; Arcanum's debug profile overflows at 256 KiB and fits in 512 KiB. A thread
|
||||
that is too small aborts the process. **Consumers that sign on small threads (worker pools, async
|
||||
blocking pools, JNI): give them at least 512 KiB.** The release figure is pinned by a test (ignored in
|
||||
debug).
|
||||
- The expanded key moves about 35 kB (34,992 B) through the stack when a key is built, not 64 kB.
|
||||
|
||||
**Recorded as gaps** (docs/02_signatures.md, and THREAT_MODEL for S-04): S-04's `rnd`/ρ''/y stack residue
|
||||
inside `ml-dsa`; S-07, the composite is a **separate** identity, never a wrapped Tessera Ed25519 seed
|
||||
(recommendation under open question 1; `from_bytes` cannot detect reuse); S-08, a binding does not tie
|
||||
`id` to `vk` and has no serial (Day 3's replay design with QA E-07; also on `verify_binding`'s docs);
|
||||
S-12, none of the 9 ML-DSA-65 "modified z" sigVer cases at `a7f283cd` reaches the ‖z‖∞ bound (largest
|
||||
|z| 524,077 < 524,092, decoded by script from the original file), so no ACVP case could be added; only
|
||||
Wycheproof tests the bound.
|
||||
|
||||
**Counts, run by the builder** at `0b2480b` (this entry only adds docs), Windows 10, `cargo 1.99.0`:
|
||||
|
||||
| Run | Result |
|
||||
|:--|:--|
|
||||
| `cargo test` (debug) | **126 passed, 0 failed, 5 ignored** (the release-only stack test and four stack measurements) |
|
||||
| `cargo test --release` | **127 passed, 0 failed, 4 ignored** (the four measurements) |
|
||||
| `cargo clippy --all-targets --all-features -- -D warnings` | clean |
|
||||
| `cargo fmt --check` (crate, probe, fuzz) | clean |
|
||||
| `zeroize-probe` (`--test-threads=1`) | 1 passed (now also K and s1 of the expanded key) |
|
||||
| `cargo deny --offline check` | advisories ok, bans ok, licenses ok, sources ok |
|
||||
| fuzz `signatures` (rebuilt: `src/` and the target changed) | **601 s, 181,113 executions, 0 crashes, 0 artifacts** (301 exec/s, coverage 3,564), on `0b2480b` |
|
||||
|
||||
`cargo audit` was not re-run (no dependency changed except the `curve25519-dalek` dev-dependency,
|
||||
already in the lock). New since `d56ee10`: 3 tests (S-01 to S-03), 1 (S-05), 1 doctest (the `const`
|
||||
`AppContext`), `sig_stack.rs` (1 + 4 ignored).
|
||||
|
||||
**For consumers, added:** ban `ed25519-dalek/legacy_compatibility` and `curve25519-dalek/legacy_compatibility`
|
||||
in `deny.toml`, next to `ed25519-dalek/hazmat`; build `AppContext`s as `const`s; check that `vk` is the
|
||||
right key for `id` before trusting `verify_binding`, and refuse bindings older than the newest per `id`.
|
||||
|
||||
## 2026-11-25 — v0.2.0 built (builder), on `feature/signatures` (PR #2), not merged, not tagged
|
||||
|
||||
**What it adds:** `arcanum::sign`, hybrid signatures ML-DSA-65 + Ed25519, exactly RFC 10073
|
||||
`id-MLDSA65-Ed25519-SHA512` (design: `docs/02_signatures.md`, which now has an "As built" section).
|
||||
Public key 1984 B, signature 3373 B, private key 64 B (ML-DSA seed || Ed25519 seed). The ML-DSA half is
|
||||
`ExpandedSigningKey::sign_randomized(M', ctx = Label, rng)`, hedged; the Ed25519 half is pure Ed25519 over
|
||||
M', checked with `verify_strict`; one `InvalidSignature` whichever half fails. `AppContext` (only
|
||||
`domi/arcanum/v2/sig/app/` + a 1–231-byte label), `bind_kem_key` / `verify_binding` for X-Wing keys under
|
||||
`domi/arcanum/v2/sig/kem-key`. The bare RFC interface (`sign_composite_raw`, `verify_composite_raw`, any
|
||||
ctx) is `hazmat` only and still hedged. Stricter than the RFC: a non-canonical or small-order Ed25519 key
|
||||
is refused at parse. `ml-dsa =0.1.2` (alloc, rand_core, zeroize) and `ed25519-dalek =3.0.0` (zeroize),
|
||||
default features off. v0.1.0's bytes are unchanged (`tests/golden_v1.rs` untouched, passing).
|
||||
|
||||
**Vectors** (`tests/vectors/SOURCES.md`, sha256 of every original and subset): ACVP ML-DSA keyGen (whole)
|
||||
and sigGen at `2972def2`, sigVer at `a7f283cd`; Wycheproof `ed25519_test` and `mldsa_65_sign_seed` (whole)
|
||||
and `mldsa_65_verify` (subset) at `20b25694`; the composite-sigs `testvectors.json` at `f0627ab` (the
|
||||
`id-MLDSA65-Ed25519-SHA512` entry); RFC 8032 §7.1. Subsets made by `tests/vectors/make_subsets.py`.
|
||||
|
||||
**Counts, run by the builder** on `feature/signatures`, Windows 10, `cargo 1.99.0` stable MSVC,
|
||||
`--target-dir D:/cargo-target/arcanum-v2` (intermediates in `D:/cargo-build/`, the machine's `build-dir`):
|
||||
|
||||
| Run | Result |
|
||||
|:--|:--|
|
||||
| `cargo test` (debug) | **121 passed, 0 failed, 0 ignored** (82 from v0.1.0 + 39 new) |
|
||||
| `cargo test --release` | **121 passed, 0 failed, 0 ignored** |
|
||||
| `cargo clippy --all-targets --all-features -- -D warnings` | clean |
|
||||
| `cargo fmt --check` | clean |
|
||||
| `zeroize-probe` (`--test-threads=1`) | 1 passed (now also covers the signing key, `to_bytes`, signing and binding) |
|
||||
| `cargo deny check` | advisories ok, bans ok, licenses ok, sources ok |
|
||||
| `cargo audit` | 64 crates, 0 vulnerabilities, 0 warnings (advisory db of 2026-11-25, 1,568 advisories) |
|
||||
| fuzz `signatures` (new) | **605 s, 38,609 executions, 0 crashes, 0 artifacts** (libFuzzer + ASan, nightly `1.102.0` 2026-11-24, MSVC 14.44 asan runtime; coverage 3,549; 63 exec/s; corpus and artifacts on D:), on `5a52854` + the target |
|
||||
|
||||
New tests: `kat_mldsa65` 6, `kat_ed25519` 3, `sig_composite` 6, `sig_halves` 5, `sig_every_byte` 7,
|
||||
`sig_malformed` 5, `sig_hygiene` 6, `feature_hygiene` +1.
|
||||
|
||||
**Answers to the doc's open gap:** `verify_strict` accepts both RFC 10073 vectors (`s`, `sWithContext`),
|
||||
and agrees with all 151 Wycheproof Ed25519 verdicts.
|
||||
|
||||
**Mutation checks by the builder** (each reintroduced with `src/sign.rs` edited, seen to fail, reverted;
|
||||
`git diff` clean after):
|
||||
- M1, test 4: verify checks only the ML-DSA half (`if ml_ok`): fails `a_zeroed_or_missing_half_is_refused`
|
||||
and `a_half_from_another_signature_is_refused`.
|
||||
- M2, test 3/4: the ML-DSA half signs and verifies with an empty ctx instead of Label: fails
|
||||
`rfc_signatures_verify`, `own_signatures_verify_under_an_independent_rebuild_of_m_prime`,
|
||||
`ml_dsa_half_uses_the_label_as_its_context` (cargo stopped there; `sig_halves` not reached).
|
||||
- M3, test 5: ctx left out of M' (its length kept): fails `flipping_any_byte_of_the_context_fails`.
|
||||
- M4, test 5: `not_after` left out of the binding hash: fails `every_field_of_a_key_binding_matters` and
|
||||
`a_key_binding_never_verifies_as_an_app_message_and_back` (the documented encoding no longer matches).
|
||||
- M5, hygiene: `verify_composite_raw` ungated: fails `the_raw_interface_is_not_reachable_without_hazmat`.
|
||||
- M6, hygiene: `#[derive(Clone)]` on `SigningKey`: fails `ml_dsa_internals_are_not_reachable`.
|
||||
- M7, test 6: `is_weak()` dropped from the key check: fails `weak_and_non_canonical_ed25519_keys_are_refused`.
|
||||
|
||||
**Not verified:** constant time (dudect, Day 7); anything on Linux; interop with a non-Rust RFC 10073
|
||||
implementation beyond the RFC's own vector (one key, two signatures); a byte-exact composite signing KAT
|
||||
(the RFC's vectors are hedged; byte-exact checks exist per half); the ACVP and Wycheproof cases dropped by
|
||||
the subsets; HashML-DSA (not used). The fuzz run is one 10-minute run at 63 exec/s (ASan and ML-DSA are
|
||||
slow), far fewer executions than v0.1.0's target. The first test commit (`2a432f5`) failed by not compiling
|
||||
(the module did not exist); it also had one test bug, fixed in `5a52854`. Not audited.
|
||||
|
||||
**For consumers:** as for v0.1.0, and also ban a direct `ml-dsa` dependency in `deny.toml` (its
|
||||
`sign_internal`, `sign_mu_deterministic` and empty-ctx `Signer` are public) and `ed25519-dalek/hazmat`;
|
||||
never use a composite signature as an identifier (not SUF-CMA, RFC 10073 §9.2, pinned by `sig_halves`).
|
||||
|
||||
## 2026-11-25 — v0.1.0 (owner session)
|
||||
|
||||
**Who owns this:** the Via owner session. Mark's decisions go through the orchestrator session.
|
||||
|
||||
@@ -4,11 +4,15 @@ Arcanum is the shared post-quantum crypto core of the Domi ecosystem. It is one
|
||||
crate that gives every Domi product a hybrid key exchange: ML-KEM-768 (FIPS 203) combined
|
||||
with X25519, so a shared secret stays safe as long as either of the two holds.
|
||||
|
||||
Since v0.2.0 it also signs: a hybrid ML-DSA-65 + Ed25519 signature, exactly RFC 10073
|
||||
`id-MLDSA65-Ed25519-SHA512`, which stays unforgeable while either half holds, and a helper that
|
||||
binds an X-Wing public key to its owner.
|
||||
|
||||
Via Domi uses it first, to derive and rotate the WireGuard pre-shared key. Canalis, Custos
|
||||
sealing and Tabellarius are expected to adopt it later.
|
||||
|
||||
- No primitive is written here. ML-KEM, X25519, SHA-3, HKDF and ChaCha20-Poly1305 come from
|
||||
vetted RustCrypto and dalek crates.
|
||||
- No primitive is written here. ML-KEM, X25519, ML-DSA, Ed25519, SHA-2, SHA-3, HKDF and
|
||||
ChaCha20-Poly1305 come from vetted RustCrypto and dalek crates.
|
||||
- No I/O, no network, no clock. Randomness is passed in by the caller.
|
||||
- No `unsafe` code.
|
||||
|
||||
@@ -21,6 +25,13 @@ let session = init.finish(&ct_ri)?;
|
||||
let psk = session.wireguard_psk(arcanum::epoch_at(unix_seconds)); // one exchange per 120 s epoch
|
||||
```
|
||||
|
||||
```rust
|
||||
let ctx = arcanum::sign::AppContext::new(b"plans")?;
|
||||
let sig = signing_key.sign(plan_bytes, &ctx, &mut rng)?; // 3373 bytes
|
||||
signing_key.verifying_key().verify(plan_bytes, &ctx, &sig)?; // 1984-byte public key
|
||||
let binding = arcanum::sign::bind_kem_key(&signing_key, device_id, xwing_sk.public_key(), (from, until), &mut rng)?;
|
||||
```
|
||||
|
||||
## Checks
|
||||
|
||||
```
|
||||
@@ -28,6 +39,7 @@ cargo test # KATs, binding, epochs, malformed input, golden vect
|
||||
cargo deny check
|
||||
cargo audit
|
||||
cargo +nightly fuzz run --release untrusted_input -- -max_total_time=600
|
||||
cargo +nightly fuzz run --release signatures -- -max_total_time=600
|
||||
```
|
||||
|
||||
**Not audited.** Nothing here is called secure before an external audit.
|
||||
|
||||
@@ -29,6 +29,17 @@ multiple-versions = "deny"
|
||||
wildcards = "deny"
|
||||
highlight = "all"
|
||||
|
||||
# QA S-10: `legacy_compatibility` makes ed25519-dalek accept a non-reduced S (S + l), a second
|
||||
# encoding of every Ed25519 half, and is enabled for the whole binary by any crate that asks for it.
|
||||
# `hazmat` exposes raw ExpandedSecretKey signing. Neither may reach Arcanum's graph.
|
||||
[[bans.features]]
|
||||
crate = "ed25519-dalek"
|
||||
deny = ["legacy_compatibility", "hazmat"]
|
||||
|
||||
[[bans.features]]
|
||||
crate = "curve25519-dalek"
|
||||
deny = ["legacy_compatibility"]
|
||||
|
||||
[sources]
|
||||
unknown-registry = "deny"
|
||||
unknown-git = "deny"
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
# Arcanum v0.2.0: hybrid post-quantum signatures
|
||||
|
||||
> (D)TDD document, written before the tests and the code. Mark decided on 2026-11-25: "Yes, before Day 3".
|
||||
> Research behind every fact here, with URLs and dates: `F:\Akce\Via\research\ml-dsa-2026-11-25.md`.
|
||||
> The crate facts below were also read from the local cargo registry (`ml-dsa-0.1.2`, `ed25519-dalek-3.0.0`).
|
||||
|
||||
## Why
|
||||
|
||||
Arcanum v0.1.0 makes the key exchange post-quantum, but its threat model says that everything rests on each
|
||||
peer holding the **real** hybrid public key of the other. Today that key would be vouched for by Tessera's
|
||||
Ed25519 signatures, which a quantum attacker can forge, and then substitute keys. v0.2.0 adds a signature
|
||||
that stays secure while either ML-DSA or Ed25519 does, so Day 3 can authenticate exchanged X-Wing public
|
||||
keys, and signed plans, post-quantum.
|
||||
|
||||
## What
|
||||
|
||||
- A **composite signature, ML-DSA-65 + Ed25519**, exactly RFC 10073 (November 2026) `id-MLDSA65-Ed25519-SHA512`
|
||||
(OID `1.3.6.1.5.5.7.6.48`). No combiner of our own.
|
||||
- **Key binding:** a helper that signs an X-Wing public key (and a key id and a validity) under a fixed
|
||||
Arcanum context, so Day 3 can check "this X-Wing key belongs to that device" with one call.
|
||||
- Same rules as v0.1.0: `#![no_std]`, `#![forbid(unsafe_code)]`, no I/O, no clock, randomness as a parameter,
|
||||
secrets zeroised on drop, typed errors, deterministic entry points only under `hazmat`.
|
||||
|
||||
Out of scope: certificates and X.509 (we use the RFC's construction, not its ASN.1); SLH-DSA; HashML-DSA;
|
||||
changing v0.1.0's KEM, exchange or seal bytes (they stay frozen by `tests/golden_v1.rs`).
|
||||
|
||||
## How
|
||||
|
||||
### Primitives (vetted crates, none written here)
|
||||
|
||||
| Crate | Version | Features | Why |
|
||||
|:--|:--|:--|:--|
|
||||
| `ml-dsa` (RustCrypto) | `=0.1.2` (2026-10-31) | `default-features = false`, `rand_core`, `zeroize`, `alloc` | FIPS 204; pure Rust, `forbid(unsafe_code)`, `no_std`; hedged signing with a context; same ecosystem as `ml-kem` (rand_core 0.10, signature 3, module-lattice 0.2.4, keccak 0.2) |
|
||||
| `ed25519-dalek` | `=3.0.0` (2026-07-06) | `default-features = false`, `zeroize` | RFC 8032; shares `curve25519-dalek 5.0.0` with `x25519-dalek`; `verify_strict` |
|
||||
| `sha2` | `0.11` (already a dependency) | — | PH = SHA-512 |
|
||||
|
||||
Alternatives looked at and refused: `fips204` (no RustSec history, deterministic signing only behind a test
|
||||
feature), `libcrux-ml-dsa` (SIMD `unsafe`, four advisories in 2026), `aws-lc-rs` (needs std, empty context
|
||||
only), `pqcrypto-mldsa` (archived).
|
||||
|
||||
**Parameter set: ML-DSA-65**, NIST category 3, matching ML-KEM-768 in X-Wing. It is RFC 10073's
|
||||
recommendation for the Ed25519 composite and RustCrypto's default. Cost: public key 1984 B, signature
|
||||
3373 B, private key 64 B (two seeds). ML-DSA-44 (OpenSSH 10.6's choice, signature 2484 B) is the fallback if
|
||||
size ever matters more than a matched level; it would be a new label, never a silent switch.
|
||||
|
||||
### The construction (RFC 10073 §2.2, §3.2, §3.3, §4, §6)
|
||||
|
||||
```
|
||||
Prefix = "CompositeAlgorithmSignatures2025" (32 ASCII bytes)
|
||||
Label = "COMPSIG-MLDSA65-Ed25519-SHA512" (ASCII, fixed)
|
||||
M' = Prefix || Label || u8(len(ctx)) || ctx || SHA-512(M) ctx: 0..=255 bytes
|
||||
|
||||
Sign: mldsaSig = ML-DSA-65.Sign(mldsaSK, M', ctx = Label) hedged (fresh rnd from the caller's RNG)
|
||||
edSig = Ed25519.Sign(edSK, M') pure Ed25519, no Ed25519ctx
|
||||
sig = mldsaSig (3309 B) || edSig (64 B)
|
||||
Verify: split by fixed lengths (wrong length: invalid); rebuild M';
|
||||
valid only if ML-DSA-65.Verify(mldsaPK, M', mldsaSig, ctx = Label)
|
||||
and Ed25519.verify_strict(edPK, M', edSig)
|
||||
Keys: public = mldsaPK (1952 B) || edPK (32 B)
|
||||
private = mldsaSeed (32 B) || edSeed (32 B), both generated fresh and never used outside the composite
|
||||
```
|
||||
|
||||
Crate calls, chosen because the convenient traits are wrong for this: `ml-dsa`'s `Signer`/`Verifier` impls
|
||||
sign **deterministically** with an **empty** context, which is not RFC 10073. Arcanum calls the inherent
|
||||
`ExpandedSigningKey::sign_randomized(M', Label, rng)` and `VerifyingKey::verify_with_context(M', Label, sig)`,
|
||||
and builds the expanded key with `ExpandedSigningKey::from_seed`. `SigningKey::sign_internal` (public in 0.1.2,
|
||||
caller-chosen randomness) is never called outside `hazmat` tests, and via must ban a direct `ml-dsa`
|
||||
dependency the way it bans `ml-kem`.
|
||||
|
||||
### Arcanum's contexts
|
||||
|
||||
The RFC's `ctx` is the application's domain separator. Arcanum fixes one per purpose, versioned like the KDF
|
||||
labels, so a signature made for one purpose never verifies for another:
|
||||
|
||||
| Purpose | ctx |
|
||||
|:--|:--|
|
||||
| Binding an X-Wing public key to its owner | `domi/arcanum/v2/sig/kem-key` |
|
||||
| A caller's own messages (Day 3: plans) | `domi/arcanum/v2/sig/app/` + the caller's label (total ≤ 255 B) |
|
||||
|
||||
The key-binding message is `u8(version=1) || u64be(not_before) || u64be(not_after) || u16be(len(id)) || id ||
|
||||
xwing_pk (1216 B)`: fixed widths and one length prefix, so it is injective. Arcanum has no clock: the caller
|
||||
passes `now` to `verify_binding`.
|
||||
|
||||
### Shape of the API
|
||||
|
||||
```rust
|
||||
pub mod sign {
|
||||
pub struct SigningKey; // two 32-byte seeds; ZeroizeOnDrop; no Clone/Copy/PartialEq/Display; Debug redacted
|
||||
pub struct VerifyingKey; // 1984 bytes; from_bytes checks lengths and the Ed25519 point (not weak)
|
||||
pub struct Signature; // 3373 bytes
|
||||
impl SigningKey {
|
||||
pub fn generate<R: CryptoRng + ?Sized>(rng: &mut R) -> Self;
|
||||
pub fn from_bytes(&[u8]) -> Result<Self, Error>; pub fn to_bytes(&self) -> Zeroizing<[u8; 64]>;
|
||||
pub fn verifying_key(&self) -> &VerifyingKey;
|
||||
pub fn sign<R: CryptoRng + ?Sized>(&self, msg: &[u8], ctx: &AppContext, rng: &mut R) -> Result<Signature, Error>;
|
||||
}
|
||||
impl VerifyingKey { pub fn verify(&self, msg: &[u8], ctx: &AppContext, sig: &Signature) -> Result<(), Error>; }
|
||||
pub fn bind_kem_key<R>(sk: &SigningKey, id: &[u8], kem: &xwing::PublicKey, valid: (u64, u64), rng: &mut R) -> Result<Signature, Error>;
|
||||
pub fn verify_binding(vk: &VerifyingKey, id: &[u8], kem: &xwing::PublicKey, valid: (u64, u64), now: u64, sig: &Signature) -> Result<(), Error>;
|
||||
#[cfg(feature = "hazmat")] pub fn sign_composite_raw(...); // the bare RFC ctx, for the RFC's own vectors
|
||||
}
|
||||
```
|
||||
|
||||
`AppContext` is a newtype that can only be built with the `domi/arcanum/v2/sig/app/` prefix, so a caller can
|
||||
never pass an empty or foreign context by accident. The bare RFC interface (any ctx, deterministic ML-DSA)
|
||||
exists only under `hazmat`, for the known-answer tests. Verification returns one error,
|
||||
`Error::InvalidSignature`, whichever half failed. **Correction (QA S-06):** the timing *does* tell which half
|
||||
failed: a malformed ML-DSA half is refused at decode without being verified, and `verify_strict` returns early
|
||||
on an undecodable or small-order R (QA measured 59 µs, 187 µs and 217 µs against 225 µs for a valid signature).
|
||||
That is harmless: verification handles only public data (the message, the public key, the signature), so its
|
||||
timing leaks nothing secret, and RFC 10073 §3.3 allows failing early. No dummy work is added.
|
||||
|
||||
## Tests (written first)
|
||||
|
||||
| # | Mandatory test | Source of truth |
|
||||
|:--|:--|:--|
|
||||
| 1 | ML-DSA-65 KATs: keyGen, sigGen (deterministic groups, byte for byte), sigVer (accept and reject) | NIST ACVP-Server `gen-val/json-files/ML-DSA-*-FIPS204/`, keyGen/sigGen at `2972def2` (2026-07-20), **sigVer at `a7f283cd` (2026-07-31, the ModifyZ correction)**; sha256 pinned in `tests/vectors/SOURCES.md` |
|
||||
| 2 | Ed25519 KATs and edge cases, with `verify_strict` | RFC 8032 §7.1; Wycheproof `ed25519_test.json` |
|
||||
| 3 | The composite: verify the RFC's `s` and `sWithContext` for `id-MLDSA65-Ed25519-SHA512`; our own signatures verify under an independent rebuild of M′ in the test | RFC 10073 Appendix E (`lamps-wg/draft-composite-sigs` `testvectors.json` at `f0627ab`) |
|
||||
| 4 | Both halves are bound: a signature with either half replaced by a valid half from another signature, a zeroed half, or the halves swapped, is refused; an empty-ctx ML-DSA verifier refuses the ML-DSA half alone | constructed |
|
||||
| 5 | Every byte matters: flipping any byte of the message, ctx, public key or signature fails verification; contexts are prefix-free and a key-binding signature never verifies as an app message, or the other way round | constructed |
|
||||
| 6 | Malformed input (wrong lengths, a weak Ed25519 key, a 256-byte ctx) gives typed errors, never a panic; a fuzz target, 10 minutes | `cargo fuzz` |
|
||||
| 7 | Hygiene: `hazmat` and `ml-dsa`'s own randomness-taking internals are not reachable from a default-features consumer (compile-fail, like v0.1.0's A-33/A-34); the feature graph has no `hazmat`; secret types are ZeroizeOnDrop and freed wiped (the allocator probe) | v0.1.0's `feature_hygiene.rs`, `qa_consumer_api.rs`, `zeroize-probe` |
|
||||
| 8 | v0.1.0 is unchanged: `tests/golden_v1.rs` still passes | v0.1.0 |
|
||||
|
||||
Also Wycheproof `mldsa_65_sign_seed_test.json` and `mldsa_65_verify_test.json` (`20b25694`, 2026-10-12).
|
||||
RustCrypto's own ACVP copies predate the sigVer correction, so Arcanum runs the current files itself.
|
||||
|
||||
## Risks
|
||||
|
||||
| Risk | Consequence | Mitigation |
|
||||
|:--|:--|:--|
|
||||
| `ml-dsa` is unaudited and 0.1.x; three advisories in 2026 (a timing side channel, signature malleability, a `use_hint` bug), constant-time fixes in 0.1.2 | a forgery or a key leak in the PQ half | the hybrid: Ed25519 still holds; version pinned; ACVP + Wycheproof + RFC vectors; `cargo audit` in every run |
|
||||
| Using the crate's `Signer`/`Verifier` traits | signatures that are not RFC 10073 (empty ctx, deterministic) | never called; the RFC vectors fail if they are |
|
||||
| `zeroize` is opt-in in `ml-dsa` | secret keys left in memory | the feature is set, a hygiene test asserts it in the feature graph, the allocator probe covers signing |
|
||||
| The composite is **not SUF-CMA** and only weakly non-separable (RFC 10073 §9.2) | two valid signatures for one message; an Ed25519 half could be lifted out | Arcanum never uses a signature as an identifier; component keys never exist outside the composite; the Ed25519 half signs M′, which starts with the RFC Prefix (§9.4) |
|
||||
| Signing can fail (rejection sampling bound) | a panic in a release build | 0.1.2 returns an error from the hedged path; Arcanum surfaces it as `Error::SigningFailed`; the deterministic `sign_mu_deterministic` (documented to panic) is never called |
|
||||
| A 1984-byte key and a 3373-byte signature | larger control messages | fine over the control channel; noted for Day 5's QR import (classic keys only there) |
|
||||
|
||||
## As built (v0.2.0, `src/sign.rs`)
|
||||
|
||||
Where the code differs from, or adds to, the design above (the code wins):
|
||||
|
||||
- **The raw interface stays hedged.** `sign_composite_raw(sk, msg, ctx, rng)` and
|
||||
`verify_composite_raw(vk, msg, ctx, sig)` take any `ctx` of 0 to 255 bytes but still sign through
|
||||
`sign_randomized` with the caller's RNG; there is no deterministic ML-DSA path in Arcanum at all.
|
||||
A test that needs repeatable bytes passes a seeded RNG. Both are `hazmat` only.
|
||||
- **A stricter Ed25519 key check.** `ed25519-dalek`'s `VerifyingKey::from_bytes` accepts y >= p and
|
||||
a set sign bit on x = 0. Arcanum re-encodes the point and refuses any encoding that is not the
|
||||
canonical one, as well as small-order points (`Error::InvalidVerifyingKey`). Invisible to honest
|
||||
keys and to the RFC's vectors.
|
||||
- **And a weak ML-DSA key check** (QA S-05): an ML-DSA-65 half whose t1 is all zero is refused as
|
||||
`InvalidVerifyingKey`. With t1 = 0 a signature needs no secret (Wycheproof's `ZeroPublicKey`), so such a
|
||||
composite would silently be no stronger than Ed25519. ρ may be anything.
|
||||
- **App labels are 1 to 231 bytes** (`MAX_APP_LABEL_LEN` = 255 minus the 24-byte prefix); an empty
|
||||
label is `TooShort`, a longer one `TooLong`. **And `&'static`** (QA S-09): `AppContext::new` is a
|
||||
`const fn` taking `&'static [u8]`, so a label is written in the source, not derived from a peer
|
||||
name, file name or message field at run time (a consumer would have to leak memory on purpose to
|
||||
get around it). A consumer builds its contexts as `const`s, which also moves the length check to
|
||||
its compile time. There is no runtime constructor.
|
||||
- **Key bindings** are hashed field by field (no allocation); the window is inclusive at both ends;
|
||||
`verify_binding` checks, in this order, the window's shape and the id length
|
||||
(`InvalidValidity`, `TooLong`), the signature (`InvalidSignature`), then `now`
|
||||
(`OutsideValidity`), so `OutsideValidity` always means an authentic but expired binding.
|
||||
- `ml-dsa` gets `alloc` (its large vectors are boxed), `rand_core` and `zeroize`, default features
|
||||
off; `ed25519-dalek` gets only `zeroize` (not `fast`: no precomputed tables).
|
||||
|
||||
## Gaps
|
||||
|
||||
- **Not audited**, like v0.1.0; the Day 7 audit pack covers both versions.
|
||||
- No constant-time measurement (dudect) of our own; inherited from the crates.
|
||||
- No HashML-DSA and no X.509: not needed.
|
||||
- The RFC's signing vectors are hedged, so the composite has no byte-exact signing KAT; byte-exact checks exist
|
||||
for the ML-DSA half (ACVP deterministic groups) and Ed25519.
|
||||
- ~~Whether `verify_strict` refuses any RFC 10073 vector~~: **it does not.** Test 3 (2026-11-25) verifies
|
||||
both the RFC's `s` (empty ctx) and `sWithContext` with `verify_strict`, through Arcanum and through the
|
||||
independent rebuild of M'. `verify_strict` also agrees with all 151 Wycheproof `ed25519_test.json` verdicts
|
||||
(test 2: no disagreement to list).
|
||||
- ACVP sigGen, sigVer and Wycheproof `mldsa_65_verify` run as subsets (`tests/vectors/SOURCES.md`): 18 of
|
||||
the sigGen cases, 15 sigVer cases, 70 of 210 Wycheproof verify cases. The full files' sha256 are pinned,
|
||||
so the subsets can be rechecked against them by rerunning `make_subsets.py`.
|
||||
- Stack copies: building a `SigningKey` moves the expanded ML-DSA key through the stack before it is boxed:
|
||||
**about 35 kB** (34,992 B, QA's measurement; `A_hat`'s rows are boxed inside `ml-dsa`), and those bytes are
|
||||
exactly the secret part (s1, s2, t0 and their NTT forms). The allocator probe sees only the heap.
|
||||
- **Stack residue inside `ml-dsa`** (QA S-04): every signature leaves `rnd`, ρ'' and the mask y on the stack,
|
||||
unwiped, in `try_raw_sign_mu`; with the public z, a leaked y gives c·s1 and so s1. Arcanum cannot reach
|
||||
it; it is in `docs/THREAT_MODEL.md`. The allocator probe now watches the expanded key's K and s1 bytes on
|
||||
the heap as well as the seed canary, but no heap probe can see the stack.
|
||||
- **Stack size** (QA S-11): building a key and signing need more than 128 KiB of stack in release (fit in
|
||||
256 KiB) and more than 256 KiB in Arcanum's debug profile (fit in 512 KiB); a smaller thread aborts the
|
||||
process. Documented on `SigningKey`; pinned for release by `tests/sig_stack.rs`.
|
||||
- **ACVP never reaches the ‖z‖∞ bound** (QA S-12). The sigVer file at `a7f283cd` has 9 "modified signature - z"
|
||||
cases in its ML-DSA-65 non-preHash groups (3 kept in the subset); decoded with a script on 2026-11-26, the
|
||||
largest |z| coefficient among them is 524,077, below γ1 − β = 524,092, so all 9 decode and are refused only
|
||||
by the c̃ comparison. No ACVP case could be added for the bound; only Wycheproof's `InfinityNormViolation`
|
||||
cases (6 kept) test `ml-dsa`'s norm check at decode. Which of the 9 the ModifyZ correction changed was not
|
||||
checked (that needs the `2972def2` sigVer file).
|
||||
- **Key bindings have no serial and do not tie `id` to `vk`** (QA S-08). `verify_binding` checks that the
|
||||
holder of `vk` bound `kem` to `id` within the window; that `vk` is the right key for `id`, and that a newer
|
||||
binding has not replaced this one, are the caller's. For Day 3 (with the plan-replay rule, QA E-07): short
|
||||
windows, and keep only the binding with the newest `not_before` per `id` (no format change needed).
|
||||
- **Feature unification** (QA S-10): `ed25519-dalek/legacy_compatibility` in any crate of a consumer's binary
|
||||
would accept a non-reduced S (a second encoding of the Ed25519 half). Arcanum's `deny.toml` bans it (and
|
||||
`ed25519-dalek/hazmat`); consumers must ban it in theirs.
|
||||
|
||||
## Questions (none blocks the work)
|
||||
|
||||
1. Should Tessera's device identity itself move to this composite key, or should Tessera keep Ed25519 and
|
||||
this key be a separate Via identity signed by it? Day 3's `docs/03_engine.md` must decide; Arcanum works
|
||||
either way. **Recommendation (QA S-07):** the composite key is a **separate, freshly generated** identity
|
||||
(`SigningKey::generate`), optionally certified once by the old Ed25519 key. Never build it as
|
||||
`SigningKey::from_bytes(new_mldsa_seed || tessera_ed25519_seed)`: RFC 10073 §3.1 forbids reusing a component
|
||||
key, and with only weak non-separability (§9.2) any Tessera path that signs caller-influenced bytes
|
||||
beginning with the RFC Prefix would become a forgery oracle for the composite once ML-DSA falls. If the two
|
||||
keys ever coexist on one device, Tessera's Ed25519 signer should refuse messages that begin with
|
||||
`CompositeAlgorithmSignatures2025` (§9.4). `from_bytes` cannot detect reuse: any 64 bytes are a key.
|
||||
2. Validity windows on key bindings: the default the engine should use (proposal: 30 days, renewed by the
|
||||
control service).
|
||||
@@ -61,3 +61,9 @@ Moves in Rust copy stack bytes, and `zeroize` cannot reach those copies; hash an
|
||||
wiped only as far as the crates' `zeroize` features go. A process memory dump taken while Arcanum
|
||||
runs may contain key material. That is accepted for v1 and is one more reason keys at rest live in
|
||||
Custos or Tessera, not in Arcanum's callers.
|
||||
|
||||
v0.2.0 adds two stack exposures in signing, both accepted on the same terms: building a `SigningKey`
|
||||
moves the 35 kB expanded ML-DSA key (s1, s2, t0 and their NTT forms) through the stack before it is
|
||||
boxed, and `ml-dsa`'s signing loop (`try_raw_sign_mu`) leaves `rnd`, ρ'' and the mask y on the stack
|
||||
unwiped after every signature. A leaked y, with the public z, gives c·s1 and so s1. Neither is
|
||||
reachable from Arcanum, and neither is visible to the heap allocator probe (QA S-04, PR #2).
|
||||
|
||||
Generated
+27
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"nodes": {
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1793865203,
|
||||
"narHash": "sha256-/cpdPHaySDIyCgZI6EWngiM6jK3YLUNzv1b7lTzy6Bk=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "c56a87d8e41ce69bd2af57eb35dcc117a9dfca33",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixos-26.05",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
description = "The Linux test shell for Fabrica's NixOS runner (.fabrica/artifex/linux.yaml)";
|
||||
|
||||
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-26.05";
|
||||
|
||||
outputs =
|
||||
{ self, nixpkgs }:
|
||||
let
|
||||
pkgs = nixpkgs.legacyPackages.x86_64-linux;
|
||||
in
|
||||
{
|
||||
# nix develop .#ci -c cargo test : the toolchain only; the tests fetch crates from crates.io.
|
||||
devShells.x86_64-linux.ci = pkgs.mkShell {
|
||||
packages = with pkgs; [ cargo rustc clippy rustfmt git ];
|
||||
};
|
||||
};
|
||||
}
|
||||
Generated
+97
-1
@@ -20,11 +20,13 @@ checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
|
||||
|
||||
[[package]]
|
||||
name = "arcanum"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"chacha20poly1305",
|
||||
"ed25519-dalek",
|
||||
"hkdf",
|
||||
"hmac",
|
||||
"ml-dsa",
|
||||
"ml-kem",
|
||||
"rand_core",
|
||||
"sha2",
|
||||
@@ -39,7 +41,9 @@ name = "arcanum-fuzz"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"arcanum",
|
||||
"chacha20",
|
||||
"libfuzzer-sys",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -48,6 +52,12 @@ version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.1"
|
||||
@@ -85,6 +95,7 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cpufeatures",
|
||||
"rand_core",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
@@ -118,6 +129,12 @@ version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.1"
|
||||
@@ -155,6 +172,7 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"curve25519-dalek-derive",
|
||||
"digest",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
@@ -172,6 +190,16 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.11.3"
|
||||
@@ -184,6 +212,28 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
|
||||
dependencies = [
|
||||
"signature",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-dalek"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"ed25519",
|
||||
"sha2",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.3.0"
|
||||
@@ -291,6 +341,22 @@ dependencies = [
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ml-dsa"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f6d49c3f3f0e10e18ca975ffda66f8da0ec36521c1d911adcbc521bf0743f5c"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"ctutils",
|
||||
"hybrid-array",
|
||||
"module-lattice",
|
||||
"pkcs8",
|
||||
"shake",
|
||||
"signature",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ml-kem"
|
||||
version = "0.3.4"
|
||||
@@ -327,6 +393,16 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
|
||||
dependencies = [
|
||||
"der",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "poly1305"
|
||||
version = "0.9.1"
|
||||
@@ -421,6 +497,26 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"der",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sponge-cursor"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -11,6 +11,9 @@ cargo-fuzz = true
|
||||
[dependencies]
|
||||
libfuzzer-sys = "0.4"
|
||||
arcanum = { path = "..", features = ["hazmat"] }
|
||||
# A seeded RNG for the signing fixture (fuzz input never chooses randomness).
|
||||
chacha20 = { version = "0.10", default-features = false, features = ["rng"] }
|
||||
rand_core = { version = "0.10", default-features = false }
|
||||
|
||||
# Keep the fuzz crate out of the library's own dependency graph and checks.
|
||||
[workspace]
|
||||
@@ -22,3 +25,10 @@ path = "fuzz_targets/untrusted_input.rs"
|
||||
test = false
|
||||
doc = false
|
||||
bench = false
|
||||
|
||||
[[bin]]
|
||||
name = "signatures"
|
||||
path = "fuzz_targets/signatures.rs"
|
||||
test = false
|
||||
doc = false
|
||||
bench = false
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! v0.2.0 mandatory test 6, fuzzed: every signature entry point that takes bytes from the network
|
||||
//! returns a typed result for any input and never panics, and only the exact bytes that were
|
||||
//! signed verify (one key, one message, one context: the hedged ML-DSA half is not re-signed).
|
||||
//!
|
||||
//! The first byte picks the mode. Modes 0-1 parse raw bytes. Modes 2-7 XOR the input into a valid
|
||||
//! verifying key, signature, message, context or key binding, so the fuzzer reaches ML-DSA's hint
|
||||
//! and norm checks and Ed25519's point decoding instead of stopping at the length checks.
|
||||
#![no_main]
|
||||
|
||||
use arcanum::sign::{self, AppContext, Signature, SigningKey, VerifyingKey};
|
||||
use arcanum::xwing;
|
||||
use chacha20::ChaCha20Rng;
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
use rand_core::SeedableRng;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
const MSG: &[u8] = b"fuzz message";
|
||||
const LABEL: &[u8] = b"fuzz";
|
||||
const ID: &[u8] = b"fuzz-device";
|
||||
const VALID: (u64, u64) = (100, 200);
|
||||
|
||||
struct Fixture {
|
||||
sk: SigningKey,
|
||||
ctx: AppContext,
|
||||
sig: Signature,
|
||||
kem: xwing::SecretKey,
|
||||
binding: Signature,
|
||||
}
|
||||
|
||||
fn xor_into(base: &[u8], data: &[u8]) -> Vec<u8> {
|
||||
let mut out = base.to_vec();
|
||||
for (i, b) in data.iter().enumerate() {
|
||||
if i < out.len() {
|
||||
out[i] ^= b;
|
||||
} else {
|
||||
out.push(*b);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn be_u64(data: &[u8], at: usize) -> u64 {
|
||||
let mut b = [0u8; 8];
|
||||
for (i, x) in b.iter_mut().enumerate() {
|
||||
*x = data.get(at + i).copied().unwrap_or(0);
|
||||
}
|
||||
u64::from_be_bytes(b)
|
||||
}
|
||||
|
||||
fuzz_target!(|input: &[u8]| {
|
||||
let Some((&mode, data)) = input.split_first() else { return };
|
||||
// Key generation and signing are built once; redoing them per input would dominate the time.
|
||||
static FIX: OnceLock<Fixture> = OnceLock::new();
|
||||
let f = FIX.get_or_init(|| {
|
||||
let mut rng = ChaCha20Rng::from_seed([0x5a; 32]);
|
||||
let sk = SigningKey::from_bytes(&[0x42; 64]).unwrap();
|
||||
let ctx = AppContext::new(LABEL).unwrap();
|
||||
let sig = sk.sign(MSG, &ctx, &mut rng).unwrap();
|
||||
let kem = xwing::SecretKey::from_bytes(&[0x43; 32]).unwrap();
|
||||
let binding = sign::bind_kem_key(&sk, ID, kem.public_key(), VALID, &mut rng).unwrap();
|
||||
Fixture { sk, ctx, sig, kem, binding }
|
||||
});
|
||||
let vk = f.sk.verifying_key();
|
||||
match mode % 8 {
|
||||
0 => {
|
||||
if let Ok(k) = VerifyingKey::from_bytes(data) {
|
||||
assert!(k.verify(MSG, &f.ctx, &f.sig).is_err() || &k == vk);
|
||||
}
|
||||
}
|
||||
1 => {
|
||||
if let Ok(s) = Signature::from_bytes(data) {
|
||||
assert!(vk.verify(MSG, &f.ctx, &s).is_err() || s == f.sig);
|
||||
}
|
||||
let _ = SigningKey::from_bytes(data).map(|k| k.verifying_key().as_bytes()[0]);
|
||||
}
|
||||
2 => {
|
||||
let bad = xor_into(f.sig.as_bytes(), data);
|
||||
if let Ok(s) = Signature::from_bytes(&bad) {
|
||||
if vk.verify(MSG, &f.ctx, &s).is_ok() {
|
||||
assert_eq!(s, f.sig, "a changed signature verified");
|
||||
}
|
||||
}
|
||||
}
|
||||
3 => {
|
||||
let bad = xor_into(vk.as_bytes(), data);
|
||||
if let Ok(k) = VerifyingKey::from_bytes(&bad) {
|
||||
if k.verify(MSG, &f.ctx, &f.sig).is_ok() {
|
||||
assert_eq!(&k, vk, "a signature verified under a changed key");
|
||||
}
|
||||
}
|
||||
}
|
||||
4 => {
|
||||
let m = xor_into(MSG, data);
|
||||
if vk.verify(&m, &f.ctx, &f.sig).is_ok() {
|
||||
assert_eq!(m, MSG, "a changed message verified");
|
||||
}
|
||||
}
|
||||
5 => {
|
||||
// Any raw ctx (0..=255 bytes, or a typed error for longer). `AppContext` labels are
|
||||
// `&'static` and fixed at compile time, so there is no runtime label to fuzz.
|
||||
let raw = xor_into(f.ctx.as_bytes(), data);
|
||||
match sign::verify_composite_raw(vk, MSG, &raw, &f.sig) {
|
||||
Ok(()) => assert_eq!(raw, f.ctx.as_bytes()),
|
||||
Err(e) => assert!(raw.len() <= 255 || matches!(e, arcanum::Error::TooLong { .. })),
|
||||
}
|
||||
}
|
||||
6 => {
|
||||
// A key binding with a changed id, window and time.
|
||||
let id = xor_into(ID, data.get(17..).unwrap_or(&[]));
|
||||
let valid = (VALID.0 ^ be_u64(data, 0), VALID.1 ^ be_u64(data, 8));
|
||||
let now = 150 ^ u64::from(data.first().copied().unwrap_or(0));
|
||||
if sign::verify_binding(vk, &id, f.kem.public_key(), valid, now, &f.binding).is_ok() {
|
||||
assert_eq!((id.as_slice(), valid), (ID, VALID), "a changed binding verified");
|
||||
assert!((VALID.0..=VALID.1).contains(&now));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// A changed X-Wing key in a binding, and a changed binding signature.
|
||||
let kem = xor_into(f.kem.public_key().as_bytes(), data);
|
||||
if let Ok(k) = xwing::PublicKey::from_bytes(&kem) {
|
||||
if sign::verify_binding(vk, ID, &k, VALID, 150, &f.binding).is_ok() {
|
||||
assert_eq!(&k, f.kem.public_key(), "a binding verified for another X-Wing key");
|
||||
}
|
||||
}
|
||||
let bad = xor_into(f.binding.as_bytes(), data);
|
||||
if let Ok(s) = Signature::from_bytes(&bad) {
|
||||
if sign::verify_binding(vk, ID, f.kem.public_key(), VALID, 150, &s).is_ok() {
|
||||
assert_eq!(s, f.binding, "a changed binding signature verified");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -14,6 +14,16 @@ pub enum Input {
|
||||
Ciphertext,
|
||||
/// A sealed box.
|
||||
SealedBox,
|
||||
/// A composite signing key (ML-DSA-65 seed || Ed25519 seed).
|
||||
SigningKey,
|
||||
/// A composite verifying key (ML-DSA-65 public key || Ed25519 public key).
|
||||
VerifyingKey,
|
||||
/// A composite signature (ML-DSA-65 signature || Ed25519 signature).
|
||||
Signature,
|
||||
/// A signature context, or the caller's label inside one.
|
||||
Context,
|
||||
/// The key id in a key binding.
|
||||
KeyId,
|
||||
}
|
||||
|
||||
impl fmt::Display for Input {
|
||||
@@ -23,6 +33,11 @@ impl fmt::Display for Input {
|
||||
Input::SecretKey => "secret key",
|
||||
Input::Ciphertext => "ciphertext",
|
||||
Input::SealedBox => "sealed box",
|
||||
Input::SigningKey => "signing key",
|
||||
Input::VerifyingKey => "verifying key",
|
||||
Input::Signature => "signature",
|
||||
Input::Context => "signature context",
|
||||
Input::KeyId => "key id",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -49,6 +64,15 @@ pub enum Error {
|
||||
/// The length that was given.
|
||||
actual: usize,
|
||||
},
|
||||
/// The input is longer than the largest valid value.
|
||||
TooLong {
|
||||
/// What was being parsed.
|
||||
input: Input,
|
||||
/// The maximum length in bytes.
|
||||
maximum: usize,
|
||||
/// The length that was given.
|
||||
actual: usize,
|
||||
},
|
||||
/// The ML-KEM-768 part of a public key fails the FIPS 203 §7.2 encapsulation key check.
|
||||
InvalidPublicKey,
|
||||
/// An X25519 value is a low-order point, so the classical half would contribute nothing.
|
||||
@@ -59,6 +83,19 @@ pub enum Error {
|
||||
DecryptionFailed,
|
||||
/// The plaintext is longer than ChaCha20-Poly1305 allows (about 256 GiB).
|
||||
MessageTooLong,
|
||||
/// The Ed25519 half of a verifying key is not a canonically encoded point, or is a point of
|
||||
/// small order (a weak key).
|
||||
InvalidVerifyingKey,
|
||||
/// A signature does not verify: one half, the other, or both. The error does not say which; the
|
||||
/// verification time may, which is harmless because verification uses only public data.
|
||||
InvalidSignature,
|
||||
/// ML-DSA signing failed (the randomness source or the rejection-sampling bound). Retry with
|
||||
/// fresh randomness.
|
||||
SigningFailed,
|
||||
/// A key binding's validity window ends before it starts (`not_before > not_after`).
|
||||
InvalidValidity,
|
||||
/// A key binding is authentic, but `now` lies outside its validity window.
|
||||
OutsideValidity,
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
@@ -70,11 +107,19 @@ impl fmt::Display for Error {
|
||||
Error::TooShort { input, minimum, actual } => {
|
||||
write!(f, "{input} is too short: at least {minimum} bytes, got {actual}")
|
||||
}
|
||||
Error::TooLong { input, maximum, actual } => {
|
||||
write!(f, "{input} is too long: at most {maximum} bytes, got {actual}")
|
||||
}
|
||||
Error::InvalidPublicKey => f.write_str("public key fails the ML-KEM-768 encapsulation key check"),
|
||||
Error::NonContributory => f.write_str("X25519 value is a low-order point"),
|
||||
Error::UnsupportedVersion(v) => write!(f, "sealed box version {v} is not supported"),
|
||||
Error::DecryptionFailed => f.write_str("sealed box could not be opened"),
|
||||
Error::MessageTooLong => f.write_str("message is too long to seal"),
|
||||
Error::InvalidVerifyingKey => f.write_str("verifying key has a weak or non-canonical Ed25519 point"),
|
||||
Error::InvalidSignature => f.write_str("signature does not verify"),
|
||||
Error::SigningFailed => f.write_str("signing failed; retry with fresh randomness"),
|
||||
Error::InvalidValidity => f.write_str("key binding validity ends before it starts"),
|
||||
Error::OutsideValidity => f.write_str("key binding is not valid at this time"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-5
@@ -6,13 +6,16 @@
|
||||
//! - [`exchange`]: a mutual exchange between two peers (each encapsulates to the other), bound to
|
||||
//! the full transcript and a context, and the WireGuard pre-shared key it yields per epoch.
|
||||
//! - [`seal`]: a one-shot sealed box to a recipient's hybrid public key.
|
||||
//! - [`sign`] (v0.2.0): hybrid signatures ML-DSA-65 + Ed25519, exactly RFC 10073
|
||||
//! `id-MLDSA65-Ed25519-SHA512`, and a helper that binds an X-Wing public key to its owner.
|
||||
//!
|
||||
//! No primitive is implemented here; they come from `ml-kem`, `x25519-dalek`, `sha3`, `shake`,
|
||||
//! `sha2`, `hkdf` and `chacha20poly1305`. No I/O, no clock: randomness and time are parameters.
|
||||
//! Design, sources and risks: `docs/01_arcanum.md` and `docs/THREAT_MODEL.md`.
|
||||
//! No primitive is implemented here; they come from `ml-kem`, `x25519-dalek`, `ml-dsa`,
|
||||
//! `ed25519-dalek`, `sha3`, `shake`, `sha2`, `hkdf` and `chacha20poly1305`. No I/O, no clock: randomness and time are parameters.
|
||||
//! Design, sources and risks: `docs/01_arcanum.md`, `docs/02_signatures.md` and `docs/THREAT_MODEL.md`.
|
||||
//!
|
||||
//! The `hazmat` feature exposes the deterministic (`_derand`, `from_seed`) entry points used by
|
||||
//! the known-answer tests. It is off by default and must never be enabled in a release build.
|
||||
//! The `hazmat` feature exposes the deterministic (`_derand`, `from_seed`) entry points and the
|
||||
//! bare RFC 10073 signature interface (`sign_composite_raw`, `verify_composite_raw`) used by the
|
||||
//! known-answer tests. It is off by default and must never be enabled in a release build.
|
||||
#![no_std]
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(missing_docs)]
|
||||
@@ -23,6 +26,7 @@ mod error;
|
||||
pub mod exchange;
|
||||
mod schedule;
|
||||
pub mod seal;
|
||||
pub mod sign;
|
||||
pub mod xwing;
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
+484
@@ -0,0 +1,484 @@
|
||||
//! Hybrid post-quantum signatures: ML-DSA-65 + Ed25519, exactly RFC 10073
|
||||
//! `id-MLDSA65-Ed25519-SHA512` (OID 1.3.6.1.5.5.7.6.48). A signature stays unforgeable while
|
||||
//! either ML-DSA-65 or Ed25519 does.
|
||||
//!
|
||||
//! ```text
|
||||
//! Prefix = "CompositeAlgorithmSignatures2025" Label = "COMPSIG-MLDSA65-Ed25519-SHA512"
|
||||
//! M' = Prefix || Label || u8(len(ctx)) || ctx || SHA-512(M) (RFC 10073 §3.2)
|
||||
//! sig = ML-DSA-65.Sign(sk_ml, M', ctx = Label) hedged, 3309 bytes
|
||||
//! || Ed25519.Sign(sk_ed, M') pure Ed25519, 64 bytes
|
||||
//! valid iff ML-DSA-65.Verify(pk_ml, M', sig_ml, ctx = Label) and Ed25519 verify_strict(pk_ed, M', sig_ed)
|
||||
//! public key = pk_ml (1952 bytes) || pk_ed (32 bytes)
|
||||
//! private key = ML-DSA seed (32 bytes) || Ed25519 seed (32 bytes)
|
||||
//! ```
|
||||
//!
|
||||
//! This module is glue: ML-DSA-65 from `ml-dsa` (FIPS 204), Ed25519 from `ed25519-dalek` (RFC 8032),
|
||||
//! SHA-512 from `sha2`. It never uses `ml-dsa`'s `Signer`/`Verifier` traits (deterministic, empty
|
||||
//! ctx), only `ExpandedSigningKey::sign_randomized` and `VerifyingKey::verify_with_context`.
|
||||
//!
|
||||
//! **Contexts.** The RFC's `ctx` is a domain separator. Arcanum fixes it per purpose:
|
||||
//! [`KEM_KEY_CONTEXT`] for [`bind_kem_key`], and [`APP_CONTEXT_PREFIX`] + the caller's label for
|
||||
//! [`SigningKey::sign`], through [`AppContext`]. A signature made for one context never verifies
|
||||
//! under another: `ctx` and its length are inside M'.
|
||||
//!
|
||||
//! **Stricter than the RFC**, invisible to honest signers: a verifying key whose Ed25519 half is a
|
||||
//! small-order point or not the canonical encoding of its point, or whose ML-DSA-65 half has
|
||||
//! t1 = 0, is refused when parsed ([`Error::InvalidVerifyingKey`]), and Ed25519 is checked with
|
||||
//! `verify_strict`. Both refused shapes are "weak keys": with t1 = 0 an ML-DSA signature needs no
|
||||
//! secret at all (QA S-05), as a small-order Ed25519 key lets signatures verify for many messages.
|
||||
//!
|
||||
//! **Not SUF-CMA** (RFC 10073 §9.2): two signatures of one message under one key can trade their
|
||||
//! hedged ML-DSA halves. Never use a signature as an identifier.
|
||||
//!
|
||||
//! The bare RFC interface (any `ctx`, including empty) is `hazmat` only, for the RFC's vectors.
|
||||
|
||||
use alloc::boxed::Box;
|
||||
use core::{array, fmt};
|
||||
|
||||
use ed25519_dalek::Signer as _;
|
||||
use ml_dsa::{EncodedSignature, EncodedVerifyingKey, ExpandedSigningKey, MlDsa65, Seed};
|
||||
use rand_core::CryptoRng;
|
||||
use sha2::{Digest, Sha512};
|
||||
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
|
||||
|
||||
use crate::error::{Error, Input, exact};
|
||||
use crate::xwing;
|
||||
|
||||
/// RFC 10073 §2.2: the prefix of every composite M'.
|
||||
pub const PREFIX: &[u8] = b"CompositeAlgorithmSignatures2025";
|
||||
/// RFC 10073 §6: the label of `id-MLDSA65-Ed25519-SHA512`, also ML-DSA's own `ctx`.
|
||||
pub const LABEL: &[u8] = b"COMPSIG-MLDSA65-Ed25519-SHA512";
|
||||
|
||||
/// The context of a key binding ([`bind_kem_key`]).
|
||||
pub const KEM_KEY_CONTEXT: &[u8] = b"domi/arcanum/v2/sig/kem-key";
|
||||
/// The prefix of every application context ([`AppContext`]).
|
||||
pub const APP_CONTEXT_PREFIX: &[u8] = b"domi/arcanum/v2/sig/app/";
|
||||
/// The longest `ctx` RFC 10073 allows (it is encoded as one byte in M').
|
||||
pub const MAX_CONTEXT_LEN: usize = 255;
|
||||
/// The longest label an [`AppContext`] can take: 255 minus the 24-byte prefix.
|
||||
pub const MAX_APP_LABEL_LEN: usize = MAX_CONTEXT_LEN - APP_CONTEXT_PREFIX.len();
|
||||
/// The longest key id in a key binding (its length is a big-endian `u16`).
|
||||
pub const MAX_KEY_ID_LEN: usize = u16::MAX as usize;
|
||||
/// The version byte at the start of every key-binding message.
|
||||
pub const KEY_BINDING_VERSION: u8 = 1;
|
||||
|
||||
/// Length of a composite verifying key: ML-DSA-65 public key (1952) + Ed25519 public key (32).
|
||||
pub const VERIFYING_KEY_LEN: usize = 1984;
|
||||
/// Length of a stored composite signing key: two 32-byte seeds.
|
||||
pub const SIGNING_KEY_LEN: usize = 64;
|
||||
/// Length of a composite signature: ML-DSA-65 signature (3309) + Ed25519 signature (64).
|
||||
pub const SIGNATURE_LEN: usize = 3373;
|
||||
|
||||
const ML_DSA_PUBLIC_KEY_LEN: usize = 1952;
|
||||
const ML_DSA_SIGNATURE_LEN: usize = 3309;
|
||||
const ML_DSA_RHO_LEN: usize = 32;
|
||||
const SEED_LEN: usize = 32;
|
||||
const M_PRIME_MAX_LEN: usize = 32 + 30 + 1 + MAX_CONTEXT_LEN + 64;
|
||||
|
||||
// The fixed lengths above are the crates' own; a crate update that changed one fails to compile.
|
||||
const _: () = assert!(PREFIX.len() == 32 && LABEL.len() == 30);
|
||||
const _: () = assert!(core::mem::size_of::<EncodedVerifyingKey<MlDsa65>>() == ML_DSA_PUBLIC_KEY_LEN);
|
||||
const _: () = assert!(core::mem::size_of::<EncodedSignature<MlDsa65>>() == ML_DSA_SIGNATURE_LEN);
|
||||
const _: () = assert!(VERIFYING_KEY_LEN == ML_DSA_PUBLIC_KEY_LEN + ed25519_dalek::PUBLIC_KEY_LENGTH);
|
||||
const _: () = assert!(SIGNATURE_LEN == ML_DSA_SIGNATURE_LEN + ed25519_dalek::SIGNATURE_LENGTH);
|
||||
|
||||
/// An application context: [`APP_CONTEXT_PREFIX`] followed by the caller's label, 25 to 255 bytes
|
||||
/// in all. It can only be built with that prefix, so a caller cannot pass an empty context, the
|
||||
/// key-binding context or a foreign one by accident.
|
||||
///
|
||||
/// The label is `&'static` (QA S-09): one fixed label per purpose, written in the source, never
|
||||
/// derived from a peer name, a file name or a message field (two purposes whose labels came from
|
||||
/// data could collide). Build it once, at compile time:
|
||||
///
|
||||
/// ```
|
||||
/// use arcanum::sign::AppContext;
|
||||
/// const PLANS: AppContext = match AppContext::new(b"plans") {
|
||||
/// Ok(ctx) => ctx,
|
||||
/// Err(_) => panic!("label is 1 to 231 bytes"),
|
||||
/// };
|
||||
/// assert_eq!(PLANS.as_bytes(), b"domi/arcanum/v2/sig/app/plans");
|
||||
/// ```
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct AppContext {
|
||||
bytes: [u8; MAX_CONTEXT_LEN],
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl AppContext {
|
||||
/// `domi/arcanum/v2/sig/app/` + `label`, for a fixed, compile-time label (Day 3: `plans`).
|
||||
/// A `const fn`, so a `const` context is checked when the consumer compiles.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::TooShort`] for an empty label; [`Error::TooLong`] for one over
|
||||
/// [`MAX_APP_LABEL_LEN`] (231) bytes.
|
||||
pub const fn new(label: &'static [u8]) -> Result<Self, Error> {
|
||||
if label.is_empty() {
|
||||
return Err(Error::TooShort { input: Input::Context, minimum: 1, actual: 0 });
|
||||
}
|
||||
if label.len() > MAX_APP_LABEL_LEN {
|
||||
return Err(Error::TooLong { input: Input::Context, maximum: MAX_APP_LABEL_LEN, actual: label.len() });
|
||||
}
|
||||
let mut bytes = [0u8; MAX_CONTEXT_LEN];
|
||||
let p = APP_CONTEXT_PREFIX.len();
|
||||
let mut i = 0;
|
||||
while i < p {
|
||||
bytes[i] = APP_CONTEXT_PREFIX[i];
|
||||
i += 1;
|
||||
}
|
||||
let mut j = 0;
|
||||
while j < label.len() {
|
||||
bytes[p + j] = label[j];
|
||||
j += 1;
|
||||
}
|
||||
Ok(Self { bytes, len: p + label.len() })
|
||||
}
|
||||
|
||||
/// The whole context, prefix included: the RFC's `ctx`.
|
||||
#[must_use]
|
||||
pub fn as_bytes(&self) -> &[u8] {
|
||||
&self.bytes[..self.len]
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for AppContext {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_tuple("AppContext").field(&self.as_bytes().escape_ascii()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// M' (RFC 10073 §3.2), built on the stack: at most 382 bytes.
|
||||
struct MPrime {
|
||||
bytes: [u8; M_PRIME_MAX_LEN],
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl MPrime {
|
||||
/// M' from the message's SHA-512, which the caller computed (all at once, or field by field).
|
||||
fn new(ph: &[u8; 64], ctx: &[u8]) -> Result<Self, Error> {
|
||||
let ctx_len = u8::try_from(ctx.len()).map_err(|_| Error::TooLong {
|
||||
input: Input::Context,
|
||||
maximum: MAX_CONTEXT_LEN,
|
||||
actual: ctx.len(),
|
||||
})?;
|
||||
let mut m = Self { bytes: [0u8; M_PRIME_MAX_LEN], len: 0 };
|
||||
for part in [PREFIX, LABEL, &[ctx_len], ctx, ph] {
|
||||
m.bytes[m.len..m.len + part.len()].copy_from_slice(part);
|
||||
m.len += part.len();
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
fn of_message(msg: &[u8], ctx: &[u8]) -> Result<Self, Error> {
|
||||
Self::new(&Sha512::digest(msg).into(), ctx)
|
||||
}
|
||||
|
||||
fn as_bytes(&self) -> &[u8] {
|
||||
&self.bytes[..self.len]
|
||||
}
|
||||
}
|
||||
|
||||
/// A composite verifying key (`pk_ml || pk_ed`), validated on parse.
|
||||
#[derive(Clone)]
|
||||
pub struct VerifyingKey {
|
||||
bytes: [u8; VERIFYING_KEY_LEN],
|
||||
ml: ml_dsa::VerifyingKey<MlDsa65>,
|
||||
ed: ed25519_dalek::VerifyingKey,
|
||||
}
|
||||
|
||||
impl VerifyingKey {
|
||||
/// Parse a composite verifying key received from somewhere else.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::InvalidLength`] if it is not 1984 bytes; [`Error::InvalidVerifyingKey`] if the
|
||||
/// Ed25519 half is not a point, is not the canonical encoding of its point, or has small order,
|
||||
/// or if the ML-DSA-65 half's t1 (its bytes 32..1952) is all zero. Every other 1952-byte
|
||||
/// ML-DSA-65 public key is well formed (FIPS 204 `pkDecode` cannot fail).
|
||||
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
|
||||
let bytes: &[u8; VERIFYING_KEY_LEN] = exact(Input::VerifyingKey, bytes)?;
|
||||
let ed_bytes: [u8; 32] = array::from_fn(|i| bytes[ML_DSA_PUBLIC_KEY_LEN + i]);
|
||||
let ed = ed25519_dalek::VerifyingKey::from_bytes(&ed_bytes).map_err(|_| Error::InvalidVerifyingKey)?;
|
||||
// `from_bytes` accepts y >= p and a set sign bit on x = 0 (RFC 8032 §5.1.3 says to refuse
|
||||
// them); re-encoding the point and comparing refuses every non-canonical encoding.
|
||||
if ed.is_weak() || ed.to_edwards().compress().to_bytes() != ed_bytes {
|
||||
return Err(Error::InvalidVerifyingKey);
|
||||
}
|
||||
// t1 = 0 (Wycheproof's `ZeroPublicKey`): ML-DSA verification then checks only
|
||||
// c~ = H(mu || w1(A·z)), which anyone can satisfy with s1 = s2 = t0 = 0. An honest key has
|
||||
// t1 = 0 with negligible probability.
|
||||
if bytes[ML_DSA_RHO_LEN..ML_DSA_PUBLIC_KEY_LEN].iter().all(|&b| b == 0) {
|
||||
return Err(Error::InvalidVerifyingKey);
|
||||
}
|
||||
let enc = EncodedVerifyingKey::<MlDsa65>::try_from(&bytes[..ML_DSA_PUBLIC_KEY_LEN])
|
||||
.map_err(|_| Error::InvalidVerifyingKey)?;
|
||||
let ml = ml_dsa::VerifyingKey::<MlDsa65>::decode(&enc);
|
||||
Ok(Self { bytes: *bytes, ml, ed })
|
||||
}
|
||||
|
||||
/// The 1984-byte encoding.
|
||||
#[must_use]
|
||||
pub fn as_bytes(&self) -> &[u8; VERIFYING_KEY_LEN] {
|
||||
&self.bytes
|
||||
}
|
||||
|
||||
/// Verify a signature over `msg` made with [`SigningKey::sign`] under the same context.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::InvalidSignature`] if either half (or both) fails. The error does not say which
|
||||
/// half failed; the time taken may (a malformed ML-DSA half is refused at decode, and
|
||||
/// `verify_strict` stops early on a bad R). That is fine: verification handles only public data,
|
||||
/// so its timing reveals nothing secret (RFC 10073 §3.3 allows failing early; QA S-06).
|
||||
pub fn verify(&self, msg: &[u8], ctx: &AppContext, sig: &Signature) -> Result<(), Error> {
|
||||
self.verify_m_prime(&MPrime::of_message(msg, ctx.as_bytes())?, sig)
|
||||
}
|
||||
|
||||
fn verify_m_prime(&self, mp: &MPrime, sig: &Signature) -> Result<(), Error> {
|
||||
let mp = mp.as_bytes();
|
||||
// A malformed ML-DSA half (bad hint encoding, z out of range) is refused at decode, without
|
||||
// the verification step: quicker, and visible in the timing, but everything here is public.
|
||||
let ml_ok = ml_dsa::Signature::<MlDsa65>::try_from(&sig.0[..ML_DSA_SIGNATURE_LEN])
|
||||
.is_ok_and(|s| self.ml.verify_with_context(mp, LABEL, &s));
|
||||
let ed_sig = ed25519_dalek::Signature::from_bytes(&array::from_fn(|i| sig.0[ML_DSA_SIGNATURE_LEN + i]));
|
||||
let ed_ok = self.ed.verify_strict(mp, &ed_sig).is_ok();
|
||||
if ml_ok && ed_ok { Ok(()) } else { Err(Error::InvalidSignature) }
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for VerifyingKey {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.bytes == other.bytes
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for VerifyingKey {}
|
||||
|
||||
impl fmt::Debug for VerifyingKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("VerifyingKey").field("len", &VERIFYING_KEY_LEN).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// A composite signature (`sig_ml || sig_ed`). Any 3373 bytes parse; verification decides.
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
pub struct Signature([u8; SIGNATURE_LEN]);
|
||||
|
||||
impl Signature {
|
||||
/// Parse a signature.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::InvalidLength`] if it is not 3373 bytes.
|
||||
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
|
||||
exact(Input::Signature, bytes).map(|b| Self(*b))
|
||||
}
|
||||
|
||||
/// The 3373-byte encoding.
|
||||
#[must_use]
|
||||
pub fn as_bytes(&self) -> &[u8; SIGNATURE_LEN] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Signature {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Signature").field("len", &SIGNATURE_LEN).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// A composite signing key: two independent 32-byte seeds and the keys expanded from them, all
|
||||
/// zeroised on drop. Not `Clone`; `Debug` prints nothing secret.
|
||||
///
|
||||
/// **Stack** (QA S-11): building a key ([`SigningKey::generate`], [`SigningKey::from_bytes`]) and
|
||||
/// signing keep ML-DSA-65's polynomial vectors on the stack. Measured on Windows x86-64
|
||||
/// (`tests/sig_stack.rs`): a release build needs more than 128 KiB and fits in 256 KiB; a debug
|
||||
/// build (with dependencies at `opt-level = 2`, as in Arcanum's own profile) needs more than
|
||||
/// 256 KiB and fits in 512 KiB. Too small a thread **aborts the process** with a stack overflow;
|
||||
/// it is not an error that can be caught. Default threads (1–2 MiB) are fine; give worker,
|
||||
/// blocking-pool or JNI threads that sign at least 512 KiB, and measure unoptimised debug builds.
|
||||
pub struct SigningKey {
|
||||
seeds: Zeroizing<[u8; SIGNING_KEY_LEN]>,
|
||||
// Boxed: the expanded ML-DSA-65 key is 34,992 bytes on the stack (its A_hat rows are already
|
||||
// boxed inside ml-dsa); those bytes are the secret part, s1, s2, t0 and their NTT forms.
|
||||
ml: Box<ExpandedSigningKey<MlDsa65>>,
|
||||
ed: ed25519_dalek::SigningKey,
|
||||
public: VerifyingKey,
|
||||
}
|
||||
|
||||
impl SigningKey {
|
||||
/// Generate a new key pair from the caller's RNG: 64 fresh bytes, both seeds at once.
|
||||
///
|
||||
/// **`rng` must be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it
|
||||
/// once per process; never a fixed, derived or configured seed (QA R2-04).
|
||||
pub fn generate<R: CryptoRng + ?Sized>(rng: &mut R) -> Self {
|
||||
let mut seeds = Zeroizing::new([0u8; SIGNING_KEY_LEN]);
|
||||
rng.fill_bytes(seeds.as_mut_slice());
|
||||
Self::expand(seeds)
|
||||
}
|
||||
|
||||
/// Parse a stored signing key: the ML-DSA-65 seed, then the Ed25519 seed (RFC 10073's
|
||||
/// private key format).
|
||||
///
|
||||
/// **The 64 bytes must come from [`SigningKey::generate`]** (or from another RFC 10073 composite
|
||||
/// key), never from component seeds used anywhere else: RFC 10073 §3.1 forbids reusing a
|
||||
/// component key, and an existing Ed25519 seed (Tessera's, say) wrapped in here would make
|
||||
/// every classic signer of that key a potential forgery oracle for the composite if ML-DSA
|
||||
/// ever falls (QA S-07). This function cannot tell: any 64 bytes are a valid key.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::InvalidLength`] if it is not 64 bytes. Every 64-byte value is a valid key.
|
||||
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
|
||||
let seeds: &[u8; SIGNING_KEY_LEN] = exact(Input::SigningKey, bytes)?;
|
||||
Ok(Self::expand(Zeroizing::new(*seeds)))
|
||||
}
|
||||
|
||||
/// The 64 bytes to store in Custos or Tessera. Handle with care.
|
||||
#[must_use]
|
||||
pub fn to_bytes(&self) -> Zeroizing<[u8; SIGNING_KEY_LEN]> {
|
||||
Zeroizing::new(*self.seeds)
|
||||
}
|
||||
|
||||
/// The matching verifying key.
|
||||
#[must_use]
|
||||
pub fn verifying_key(&self) -> &VerifyingKey {
|
||||
&self.public
|
||||
}
|
||||
|
||||
/// Sign `msg` under an application context. The ML-DSA half is hedged: 32 fresh bytes come
|
||||
/// from `rng`, which must be the OS RNG or a CSPRNG seeded from it (see [`SigningKey::generate`]).
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::SigningFailed`] if the RNG fails or ML-DSA's rejection sampling gives up (it is
|
||||
/// bounded; with a working RNG this does not happen in practice). Retry with fresh randomness.
|
||||
pub fn sign<R: CryptoRng + ?Sized>(&self, msg: &[u8], ctx: &AppContext, rng: &mut R) -> Result<Signature, Error> {
|
||||
self.sign_m_prime(&MPrime::of_message(msg, ctx.as_bytes())?, rng)
|
||||
}
|
||||
|
||||
fn sign_m_prime<R: CryptoRng + ?Sized>(&self, mp: &MPrime, rng: &mut R) -> Result<Signature, Error> {
|
||||
let mp = mp.as_bytes();
|
||||
let ml = self.ml.sign_randomized(mp, LABEL, rng).map_err(|_| Error::SigningFailed)?;
|
||||
let ed = self.ed.try_sign(mp).map_err(|_| Error::SigningFailed)?;
|
||||
let mut out = [0u8; SIGNATURE_LEN];
|
||||
out[..ML_DSA_SIGNATURE_LEN].copy_from_slice(ml.encode().as_slice());
|
||||
out[ML_DSA_SIGNATURE_LEN..].copy_from_slice(&ed.to_bytes());
|
||||
Ok(Signature(out))
|
||||
}
|
||||
|
||||
fn expand(seeds: Zeroizing<[u8; SIGNING_KEY_LEN]>) -> Self {
|
||||
let mut ml_seed = Seed::default();
|
||||
ml_seed.as_mut_slice().copy_from_slice(&seeds[..SEED_LEN]);
|
||||
let ml = Box::new(ExpandedSigningKey::<MlDsa65>::from_seed(&ml_seed));
|
||||
ml_seed.as_mut_slice().zeroize();
|
||||
|
||||
let mut ed_seed = Zeroizing::new([0u8; SEED_LEN]);
|
||||
ed_seed.copy_from_slice(&seeds[SEED_LEN..]);
|
||||
let ed = ed25519_dalek::SigningKey::from_bytes(&ed_seed);
|
||||
|
||||
let ml_pk = ml.verifying_key();
|
||||
let ed_pk = ed.verifying_key();
|
||||
let mut bytes = [0u8; VERIFYING_KEY_LEN];
|
||||
bytes[..ML_DSA_PUBLIC_KEY_LEN].copy_from_slice(ml_pk.encode().as_slice());
|
||||
bytes[ML_DSA_PUBLIC_KEY_LEN..].copy_from_slice(ed_pk.as_bytes());
|
||||
Self { seeds, ml, ed, public: VerifyingKey { bytes, ml: ml_pk, ed: ed_pk } }
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for SigningKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("SigningKey([redacted])")
|
||||
}
|
||||
}
|
||||
|
||||
// `seeds` is `Zeroizing`; `ml-dsa`'s `ExpandedSigningKey` and `ed25519-dalek`'s `SigningKey` wipe
|
||||
// themselves on drop (their `zeroize` features are enabled in Cargo.toml, and
|
||||
// tests/sig_hygiene.rs asserts the bounds).
|
||||
impl ZeroizeOnDrop for SigningKey {}
|
||||
|
||||
/// SHA-512 of the key-binding message
|
||||
/// `u8(1) || u64be(not_before) || u64be(not_after) || u16be(len(id)) || id || xwing_pk (1216 bytes)`,
|
||||
/// fed field by field. Fixed widths and one length prefix: the encoding is injective.
|
||||
fn binding_digest(id: &[u8], kem: &xwing::PublicKey, (not_before, not_after): (u64, u64)) -> Result<[u8; 64], Error> {
|
||||
if not_before > not_after {
|
||||
return Err(Error::InvalidValidity);
|
||||
}
|
||||
let id_len = u16::try_from(id.len()).map_err(|_| Error::TooLong {
|
||||
input: Input::KeyId,
|
||||
maximum: MAX_KEY_ID_LEN,
|
||||
actual: id.len(),
|
||||
})?;
|
||||
let mut h = Sha512::new();
|
||||
h.update([KEY_BINDING_VERSION]);
|
||||
h.update(not_before.to_be_bytes());
|
||||
h.update(not_after.to_be_bytes());
|
||||
h.update(id_len.to_be_bytes());
|
||||
h.update(id);
|
||||
h.update(kem.as_bytes());
|
||||
Ok(h.finalize().into())
|
||||
}
|
||||
|
||||
/// Sign "this X-Wing public key belongs to `id` from `valid.0` to `valid.1` (inclusive, the
|
||||
/// caller's clock, usually Unix seconds)", under [`KEM_KEY_CONTEXT`].
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::InvalidValidity`] if `valid.0 > valid.1`; [`Error::TooLong`] for an id over 65,535
|
||||
/// bytes; [`Error::SigningFailed`] as for [`SigningKey::sign`].
|
||||
pub fn bind_kem_key<R: CryptoRng + ?Sized>(
|
||||
sk: &SigningKey,
|
||||
id: &[u8],
|
||||
kem: &xwing::PublicKey,
|
||||
valid: (u64, u64),
|
||||
rng: &mut R,
|
||||
) -> Result<Signature, Error> {
|
||||
sk.sign_m_prime(&MPrime::new(&binding_digest(id, kem, valid)?, KEM_KEY_CONTEXT)?, rng)
|
||||
}
|
||||
|
||||
/// Check a key binding made by [`bind_kem_key`], at time `now` (Arcanum has no clock).
|
||||
///
|
||||
/// **Two checks stay with the caller** (QA S-08): (1) that `vk` is *the* verifying key of `id`,
|
||||
/// from a trusted source: a binding only says "the holder of `vk` says `kem` is `id`'s"; and
|
||||
/// (2) freshness: there is no serial, so after a rotation the previous binding still verifies
|
||||
/// until its `valid.1`. Keep windows short and keep only the binding with the newest `valid.0`
|
||||
/// per `id`, refusing older ones (Day 3's replay design, QA E-07). `(0, u64::MAX)` is an
|
||||
/// eternal binding; avoid it.
|
||||
///
|
||||
/// # Errors
|
||||
/// In this order: [`Error::InvalidValidity`] or [`Error::TooLong`] for a malformed window or id;
|
||||
/// [`Error::InvalidSignature`] if the binding is not authentic; [`Error::OutsideValidity`] if it is
|
||||
/// authentic but `now` is before `valid.0` or after `valid.1`.
|
||||
pub fn verify_binding(
|
||||
vk: &VerifyingKey,
|
||||
id: &[u8],
|
||||
kem: &xwing::PublicKey,
|
||||
valid: (u64, u64),
|
||||
now: u64,
|
||||
sig: &Signature,
|
||||
) -> Result<(), Error> {
|
||||
vk.verify_m_prime(&MPrime::new(&binding_digest(id, kem, valid)?, KEM_KEY_CONTEXT)?, sig)?;
|
||||
if !(valid.0..=valid.1).contains(&now) {
|
||||
return Err(Error::OutsideValidity);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// RFC 10073 composite signing with the bare `ctx` (0 to 255 bytes, empty allowed), for the RFC's
|
||||
/// own vectors. **Hazmat** (feature `hazmat`): release code signs through [`AppContext`] or
|
||||
/// [`bind_kem_key`], so its contexts can never collide. The ML-DSA half is still hedged; a test
|
||||
/// that needs repeatable bytes passes a seeded RNG.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::TooLong`] for a `ctx` over 255 bytes; [`Error::SigningFailed`].
|
||||
#[cfg(feature = "hazmat")]
|
||||
pub fn sign_composite_raw<R: CryptoRng + ?Sized>(
|
||||
sk: &SigningKey,
|
||||
msg: &[u8],
|
||||
ctx: &[u8],
|
||||
rng: &mut R,
|
||||
) -> Result<Signature, Error> {
|
||||
sk.sign_m_prime(&MPrime::of_message(msg, ctx)?, rng)
|
||||
}
|
||||
|
||||
/// RFC 10073 composite verification with the bare `ctx`. **Hazmat** (feature `hazmat`).
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::TooLong`] for a `ctx` over 255 bytes; [`Error::InvalidSignature`].
|
||||
#[cfg(feature = "hazmat")]
|
||||
pub fn verify_composite_raw(vk: &VerifyingKey, msg: &[u8], ctx: &[u8], sig: &Signature) -> Result<(), Error> {
|
||||
vk.verify_m_prime(&MPrime::of_message(msg, ctx)?, sig)
|
||||
}
|
||||
@@ -23,3 +23,50 @@ pub fn assert_sha256(bytes: &[u8], expected_hex: &str, name: &str) {
|
||||
let got = hex::encode(Sha256::digest(bytes));
|
||||
assert_eq!(got, expected_hex, "{name} is not the pinned file (see tests/vectors/SOURCES.md)");
|
||||
}
|
||||
|
||||
/// Standard base64 (RFC 4648 §4, with padding), as the RFC 10073 vectors use.
|
||||
pub fn b64(s: &str) -> Vec<u8> {
|
||||
use base64::Engine;
|
||||
base64::engine::general_purpose::STANDARD.decode(s).expect("vector base64")
|
||||
}
|
||||
|
||||
/// An "RNG" that returns exactly the given bytes, then panics. It lets a known-answer test feed a
|
||||
/// vector's `rnd` to the hedged signing path that Arcanum uses (`sign_randomized`), and proves
|
||||
/// that path draws exactly 32 bytes. Claims `TryCryptoRng` only so the signing API accepts it.
|
||||
pub struct FixedRng {
|
||||
bytes: Vec<u8>,
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl FixedRng {
|
||||
pub fn new(bytes: &[u8]) -> Self {
|
||||
Self { bytes: bytes.to_vec(), pos: 0 }
|
||||
}
|
||||
|
||||
pub fn used(&self) -> usize {
|
||||
self.pos
|
||||
}
|
||||
}
|
||||
|
||||
impl rand_core::TryRng for FixedRng {
|
||||
type Error = core::convert::Infallible;
|
||||
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
|
||||
let mut b = [0u8; 4];
|
||||
self.try_fill_bytes(&mut b)?;
|
||||
Ok(u32::from_le_bytes(b))
|
||||
}
|
||||
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
|
||||
let mut b = [0u8; 8];
|
||||
self.try_fill_bytes(&mut b)?;
|
||||
Ok(u64::from_le_bytes(b))
|
||||
}
|
||||
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
|
||||
let end = self.pos + dst.len();
|
||||
assert!(end <= self.bytes.len(), "FixedRng: asked for more bytes than the vector gives");
|
||||
dst.copy_from_slice(&self.bytes[self.pos..end]);
|
||||
self.pos = end;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl rand_core::TryCryptoRng for FixedRng {}
|
||||
|
||||
@@ -49,3 +49,22 @@ fn no_os_rng_in_the_normal_graph() {
|
||||
assert!(t.contains("rand_core"), "the tree must include rand_core:\n{t}");
|
||||
assert!(!t.contains("getrandom"), "getrandom reached a normal build:\n{t}");
|
||||
}
|
||||
|
||||
/// v0.2.0, mandatory test 7: the signature crates enter the normal graph with `zeroize` on and
|
||||
/// no `hazmat`. `ed25519-dalek` has a `hazmat` feature of its own (raw `ExpandedSecretKey`
|
||||
/// signing, `verify_stream`); `ml-dsa`'s `default` would pull `getrandom` and `pkcs8`.
|
||||
#[test]
|
||||
fn signature_crates_have_zeroize_and_no_hazmat() {
|
||||
let t = tree(&["-i", "ml-dsa"]);
|
||||
assert!(t.contains("ml-dsa feature \"zeroize\""), "ml-dsa must have zeroize:\n{t}");
|
||||
assert!(t.contains("ml-dsa feature \"rand_core\""), "the tree must list ml-dsa's features:\n{t}");
|
||||
assert!(!t.contains("ml-dsa feature \"default\""), "ml-dsa's default features reached a normal build:\n{t}");
|
||||
assert!(!t.contains("ml-dsa feature \"getrandom\""), "ml-dsa's getrandom reached a normal build:\n{t}");
|
||||
assert_no_hazmat(&t, "ml-dsa");
|
||||
|
||||
let t = tree(&["-i", "ed25519-dalek"]);
|
||||
assert!(t.contains("ed25519-dalek feature \"zeroize\""), "ed25519-dalek must have zeroize:\n{t}");
|
||||
assert!(!t.contains("ed25519-dalek feature \"default\""), "ed25519-dalek's defaults reached a normal build:\n{t}");
|
||||
assert_no_hazmat(&t, "ed25519-dalek");
|
||||
// (That the check can see a `hazmat` feature at all is proved for arcanum's own, above.)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
//! Mandatory test 2 (v0.2.0): Ed25519 known answers and edge cases, verified with `verify_strict`,
|
||||
//! the check Arcanum's composite uses.
|
||||
//!
|
||||
//! RFC 8032 §7.1 (all five vectors, signing byte for byte) and Wycheproof `ed25519_test.json`
|
||||
//! (`20b25694`). Provenance and sha256: tests/vectors/SOURCES.md. Pure Ed25519 signing is
|
||||
//! deterministic by definition (RFC 8032 §5.1.6); `ed25519_dalek::Signer::sign` is that algorithm.
|
||||
|
||||
mod common;
|
||||
|
||||
use common::{assert_sha256, hex};
|
||||
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
|
||||
use serde_json::Value;
|
||||
|
||||
const RFC8032: &[u8] = include_bytes!("vectors/rfc8032-7.1-ed25519.json");
|
||||
const RFC8032_SHA256: &str = "fad8e499cdc3e0324a5b4a93cdbabb33f8aed1df73ecacfdb364f433b0fdf12b";
|
||||
const WYCHEPROOF: &[u8] = include_bytes!("vectors/wycheproof-ed25519_test.json");
|
||||
const WYCHEPROOF_SHA256: &str = "752d2ea7d7c6cf4736381b6cbacb61f8182b126ab7cd9b058f00c50084975536";
|
||||
|
||||
/// Wycheproof cases where `verify_strict` disagrees with the file's verdict, with the reason.
|
||||
/// Empty unless a run shows otherwise; each entry must be explained in docs/02_signatures.md.
|
||||
const KNOWN_DISAGREEMENTS: &[(u64, &str)] = &[];
|
||||
|
||||
fn json(file: &[u8]) -> Value {
|
||||
serde_json::from_slice(file).expect("vector json")
|
||||
}
|
||||
|
||||
fn arr<const N: usize>(v: &Value) -> [u8; N] {
|
||||
hex(v.as_str().expect("hex field")).try_into().expect("field length")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_files_are_the_pinned_ones() {
|
||||
assert_sha256(RFC8032, RFC8032_SHA256, "RFC 8032 section 7.1 extraction");
|
||||
assert_sha256(WYCHEPROOF, WYCHEPROOF_SHA256, "Wycheproof ed25519_test");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rfc8032_section_7_1() {
|
||||
let tests = json(RFC8032)["tests"].as_array().unwrap().clone();
|
||||
assert_eq!(tests.len(), 5);
|
||||
for t in &tests {
|
||||
let name = t["name"].as_str().unwrap();
|
||||
let sk = SigningKey::from_bytes(&arr(&t["secret_key"]));
|
||||
let pk: [u8; 32] = arr(&t["public_key"]);
|
||||
let msg = hex(t["message"].as_str().unwrap());
|
||||
let want: [u8; 64] = arr(&t["signature"]);
|
||||
assert_eq!(sk.verifying_key().to_bytes(), pk, "TEST {name}: public key");
|
||||
let sig = sk.sign(&msg);
|
||||
assert_eq!(sig.to_bytes(), want, "TEST {name}: signature");
|
||||
let vk = VerifyingKey::from_bytes(&pk).unwrap();
|
||||
assert!(vk.verify_strict(&msg, &sig).is_ok(), "TEST {name}: verify_strict");
|
||||
let mut other = msg.clone();
|
||||
other.push(0);
|
||||
assert!(vk.verify_strict(&other, &sig).is_err(), "TEST {name}: an extended message must fail");
|
||||
let mut bad = want;
|
||||
bad[0] ^= 1;
|
||||
assert!(vk.verify_strict(&msg, &Signature::from_bytes(&bad)).is_err(), "TEST {name}: flipped R");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wycheproof_ed25519_with_verify_strict() {
|
||||
let mut disagreements = Vec::new();
|
||||
let (mut valid, mut invalid) = (0, 0);
|
||||
for g in json(WYCHEPROOF)["testGroups"].as_array().unwrap() {
|
||||
let pk = hex(g["publicKey"]["pk"].as_str().unwrap());
|
||||
let vk = <[u8; 32]>::try_from(pk.as_slice()).ok().and_then(|b| VerifyingKey::from_bytes(&b).ok());
|
||||
for t in g["tests"].as_array().unwrap() {
|
||||
let id = t["tcId"].as_u64().unwrap();
|
||||
let msg = hex(t["msg"].as_str().unwrap());
|
||||
let sig = Signature::from_slice(&hex(t["sig"].as_str().unwrap())).ok();
|
||||
let ok = match (&vk, sig) {
|
||||
(Some(vk), Some(sig)) => vk.verify_strict(&msg, &sig).is_ok(),
|
||||
_ => false,
|
||||
};
|
||||
let want = match t["result"].as_str().unwrap() {
|
||||
"valid" => true,
|
||||
"invalid" => false,
|
||||
other => panic!("tcId {id}: result {other} is not handled"),
|
||||
};
|
||||
if want {
|
||||
valid += 1
|
||||
} else {
|
||||
invalid += 1
|
||||
}
|
||||
if ok != want {
|
||||
disagreements.push((id, t["comment"].as_str().unwrap_or("").to_string(), want));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(valid + invalid, 151, "numberOfTests in the file");
|
||||
let got: Vec<u64> = disagreements.iter().map(|d| d.0).collect();
|
||||
let known: Vec<u64> = KNOWN_DISAGREEMENTS.iter().map(|k| k.0).collect();
|
||||
assert_eq!(got, known, "verify_strict disagrees with Wycheproof on: {disagreements:?}");
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
//! Mandatory test 1 (v0.2.0): ML-DSA-65 known-answer tests (FIPS 204).
|
||||
//!
|
||||
//! Runs the vetted `ml-dsa` crate against NIST ACVP (keyGen and sigGen at `2972def2`, sigVer at
|
||||
//! `a7f283cd`, after the ModifyZ correction) and Wycheproof (`20b25694`). Provenance, sha256 and
|
||||
//! how the subsets were made: tests/vectors/SOURCES.md.
|
||||
//!
|
||||
//! The hedged cases go through `ExpandedSigningKey::sign_randomized` (external interface) and
|
||||
//! `sign_mu_randomized` (external mu), the paths Arcanum's composite uses, fed the vector's `rnd`
|
||||
//! by a `FixedRng`; deterministic cases use the same calls with an all-zero `rnd`, which FIPS 204
|
||||
//! Algorithm 2 defines as the deterministic variant. `sign_mu_deterministic` is never called.
|
||||
//! HashML-DSA (`preHash`) groups are not used: Arcanum signs pure ML-DSA only.
|
||||
|
||||
mod common;
|
||||
|
||||
use common::{FixedRng, assert_sha256, hex};
|
||||
use ml_dsa::common::array::Array;
|
||||
use ml_dsa::{ExpandedSigningKey, MlDsa65, Seed, Signature, VerifyingKey};
|
||||
use serde_json::Value;
|
||||
|
||||
const KEYGEN: &[u8] = include_bytes!("vectors/acvp-ml-dsa-keyGen-FIPS204-internalProjection.json");
|
||||
const KEYGEN_SHA256: &str = "e67ee6540d40e11506c3c4e3b1f79fc1cefcd49820db99fc61f87cc8ba463baf";
|
||||
const SIGGEN: &[u8] = include_bytes!("vectors/acvp-ml-dsa-sigGen-FIPS204-internalProjection.subset.json");
|
||||
const SIGGEN_SHA256: &str = "ca1f1697d78b2280d854bbe0f8e86d3601695013f14e7bb4ce0604bc80ed2b4e";
|
||||
const SIGVER: &[u8] = include_bytes!("vectors/acvp-ml-dsa-sigVer-FIPS204-internalProjection.subset.json");
|
||||
const SIGVER_SHA256: &str = "d005dfeee9039f751299a6430fdac509b97ad9ab7d25b0b502dc9a2b59b7fb0c";
|
||||
const WP_SIGN: &[u8] = include_bytes!("vectors/wycheproof-mldsa_65_sign_seed_test.json");
|
||||
const WP_SIGN_SHA256: &str = "e26b2bb9ab8d45ed570ba6828c7e40b6fa3e1545bb8bc2c449c77531760133e0";
|
||||
const WP_VERIFY: &[u8] = include_bytes!("vectors/wycheproof-mldsa_65_verify_test.subset.json");
|
||||
const WP_VERIFY_SHA256: &str = "47fc788c0913dc41cfd0ef5bc9ed44c779a6bdeeb8b3700077fd572527c33870";
|
||||
|
||||
const ZERO_RND: [u8; 32] = [0; 32];
|
||||
|
||||
fn json(file: &[u8]) -> Value {
|
||||
serde_json::from_slice(file).expect("vector json")
|
||||
}
|
||||
|
||||
/// The ML-DSA-65 groups, without HashML-DSA.
|
||||
fn groups(file: &[u8]) -> Vec<Value> {
|
||||
json(file)["testGroups"]
|
||||
.as_array()
|
||||
.expect("testGroups")
|
||||
.iter()
|
||||
.filter(|g| g["parameterSet"] == "ML-DSA-65" && g["preHash"].as_str().unwrap_or("none") != "preHash")
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn field(t: &Value, name: &str) -> Vec<u8> {
|
||||
hex(t[name].as_str().unwrap_or_else(|| panic!("field {name}")))
|
||||
}
|
||||
|
||||
fn opt_field(t: &Value, name: &str) -> Option<Vec<u8>> {
|
||||
t.get(name).and_then(Value::as_str).map(hex)
|
||||
}
|
||||
|
||||
fn vk_from(bytes: &[u8]) -> Option<VerifyingKey<MlDsa65>> {
|
||||
Array::try_from(bytes).ok().map(|a| VerifyingKey::<MlDsa65>::decode(&a))
|
||||
}
|
||||
|
||||
fn sig_from(bytes: &[u8]) -> Option<Signature<MlDsa65>> {
|
||||
Signature::<MlDsa65>::try_from(bytes).ok()
|
||||
}
|
||||
|
||||
#[allow(deprecated)]
|
||||
fn sk_from_expanded(bytes: &[u8]) -> ExpandedSigningKey<MlDsa65> {
|
||||
// ACVP's sigGen gives the FIPS 204 expanded key, not the seed. `from_expanded` is deprecated
|
||||
// (it does not validate), which is fine for official vectors; Arcanum itself uses seeds.
|
||||
ExpandedSigningKey::<MlDsa65>::from_expanded(&Array::try_from(bytes).expect("sk length"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_files_are_the_pinned_ones() {
|
||||
assert_sha256(KEYGEN, KEYGEN_SHA256, "ACVP ML-DSA keyGen");
|
||||
assert_sha256(SIGGEN, SIGGEN_SHA256, "ACVP ML-DSA sigGen subset");
|
||||
assert_sha256(SIGVER, SIGVER_SHA256, "ACVP ML-DSA sigVer subset");
|
||||
assert_sha256(WP_SIGN, WP_SIGN_SHA256, "Wycheproof mldsa_65_sign_seed");
|
||||
assert_sha256(WP_VERIFY, WP_VERIFY_SHA256, "Wycheproof mldsa_65_verify subset");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[allow(deprecated)]
|
||||
fn acvp_keygen_65() {
|
||||
let groups = groups(KEYGEN);
|
||||
assert_eq!(groups.len(), 1, "one ML-DSA-65 keyGen group");
|
||||
let mut n = 0;
|
||||
for t in groups[0]["tests"].as_array().unwrap() {
|
||||
let seed = Seed::try_from(field(t, "seed").as_slice()).expect("seed length");
|
||||
let sk = ExpandedSigningKey::<MlDsa65>::from_seed(&seed);
|
||||
assert_eq!(sk.verifying_key().encode().as_slice(), field(t, "pk").as_slice(), "pk, tcId {}", t["tcId"]);
|
||||
assert_eq!(sk.to_expanded().as_slice(), field(t, "sk").as_slice(), "sk, tcId {}", t["tcId"]);
|
||||
n += 1;
|
||||
}
|
||||
assert_eq!(n, 25);
|
||||
}
|
||||
|
||||
/// sigGen, byte for byte: deterministic groups (tgId 3, 9, 10) and hedged groups (15, 21, 22).
|
||||
#[test]
|
||||
fn acvp_siggen_65() {
|
||||
let groups = groups(SIGGEN);
|
||||
assert_eq!(groups.len(), 6);
|
||||
let mut n = 0;
|
||||
for g in &groups {
|
||||
let interface = g["signatureInterface"].as_str().unwrap();
|
||||
let external_mu = g["externalMu"].as_bool().unwrap();
|
||||
let deterministic = g["deterministic"].as_bool().unwrap();
|
||||
for t in g["tests"].as_array().unwrap() {
|
||||
let id = &t["tcId"];
|
||||
let sk = sk_from_expanded(&field(t, "sk"));
|
||||
let rnd = if deterministic { ZERO_RND.to_vec() } else { field(t, "rnd") };
|
||||
let mut rng = FixedRng::new(&rnd);
|
||||
let sig = match (interface, external_mu) {
|
||||
("external", false) => {
|
||||
let ctx = field(t, "context");
|
||||
sk.sign_randomized(&field(t, "message"), &ctx, &mut rng).expect("sign")
|
||||
}
|
||||
("internal", true) => {
|
||||
let mu = Array::try_from(field(t, "mu").as_slice()).expect("mu length");
|
||||
sk.sign_mu_randomized(&mu, &mut rng).expect("sign")
|
||||
}
|
||||
("internal", false) => {
|
||||
// ML-DSA.Sign_internal (FIPS 204 Algorithm 7) on M' = the message as given.
|
||||
// `sign_internal` takes rnd directly (and is never called by Arcanum).
|
||||
let rnd: ml_dsa::B32 = Array::try_from(rnd.as_slice()).unwrap();
|
||||
sk.sign_internal(&[field(t, "message").as_slice()], &rnd)
|
||||
}
|
||||
other => panic!("unexpected group {other:?}"),
|
||||
};
|
||||
assert_eq!(
|
||||
sig.encode().as_slice(),
|
||||
field(t, "signature").as_slice(),
|
||||
"signature, tgId {} tcId {id}",
|
||||
g["tgId"]
|
||||
);
|
||||
if interface == "external" || external_mu {
|
||||
// The hedged path must consume the vector's rnd: no more, no less.
|
||||
assert_eq!(rng.used(), 32, "the hedged path draws exactly 32 bytes of rnd, tcId {id}");
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
assert_eq!(n, 18);
|
||||
}
|
||||
|
||||
/// sigVer: accept and reject, on the corrected (a7f283cd) file.
|
||||
#[test]
|
||||
fn acvp_sigver_65() {
|
||||
let groups = groups(SIGVER);
|
||||
assert_eq!(groups.len(), 3);
|
||||
let (mut accepted, mut rejected) = (0, 0);
|
||||
for g in &groups {
|
||||
let interface = g["signatureInterface"].as_str().unwrap();
|
||||
let external_mu = g["externalMu"].as_bool().unwrap();
|
||||
for t in g["tests"].as_array().unwrap() {
|
||||
let vk = vk_from(&field(t, "pk")).expect("pk length");
|
||||
let ok = sig_from(&field(t, "signature")).is_some_and(|sig| match (interface, external_mu) {
|
||||
("external", false) => vk.verify_with_context(&field(t, "message"), &field(t, "context"), &sig),
|
||||
("internal", true) => vk.verify_mu(&Array::try_from(field(t, "mu").as_slice()).unwrap(), &sig),
|
||||
("internal", false) => vk.verify_internal(&field(t, "message"), &sig),
|
||||
other => panic!("unexpected group {other:?}"),
|
||||
});
|
||||
let want = t["testPassed"].as_bool().unwrap();
|
||||
assert_eq!(ok, want, "tgId {} tcId {} ({})", g["tgId"], t["tcId"], t["reason"]);
|
||||
if want { accepted += 1 } else { rejected += 1 }
|
||||
}
|
||||
}
|
||||
assert_eq!((accepted, rejected), (3, 12));
|
||||
}
|
||||
|
||||
/// Wycheproof signing from a seed: deterministic unless the case gives `rnd`, byte for byte; an
|
||||
/// over-long context and a seed of the wrong length are refused.
|
||||
#[test]
|
||||
fn wycheproof_sign_seed_65() {
|
||||
let (mut valid, mut invalid) = (0, 0);
|
||||
for g in json(WP_SIGN)["testGroups"].as_array().unwrap() {
|
||||
let seed_bytes = field(g, "privateSeed");
|
||||
for t in g["tests"].as_array().unwrap() {
|
||||
let id = &t["tcId"];
|
||||
let want_valid = t["result"] == "valid";
|
||||
let Ok(seed) = Seed::try_from(seed_bytes.as_slice()) else {
|
||||
assert!(!want_valid, "tcId {id}: a seed of {} bytes must be refused", seed_bytes.len());
|
||||
invalid += 1;
|
||||
continue;
|
||||
};
|
||||
let sk = ExpandedSigningKey::<MlDsa65>::from_seed(&seed);
|
||||
if let Some(pk) = opt_field(g, "publicKey") {
|
||||
assert_eq!(sk.verifying_key().encode().as_slice(), pk.as_slice(), "public key, tcId {id}");
|
||||
}
|
||||
let rnd = opt_field(t, "rnd").unwrap_or_else(|| ZERO_RND.to_vec());
|
||||
let mut rng = FixedRng::new(&rnd);
|
||||
let ctx = opt_field(t, "ctx").unwrap_or_default();
|
||||
let result = match opt_field(t, "msg") {
|
||||
Some(msg) => sk.sign_randomized(&msg, &ctx, &mut rng),
|
||||
None => sk.sign_mu_randomized(&Array::try_from(field(t, "mu").as_slice()).unwrap(), &mut rng),
|
||||
};
|
||||
if want_valid {
|
||||
let sig = result.unwrap_or_else(|e| panic!("tcId {id}: {e}"));
|
||||
assert_eq!(sig.encode().as_slice(), field(t, "sig").as_slice(), "signature, tcId {id}");
|
||||
let vk = sk.verifying_key();
|
||||
let verified = match opt_field(t, "msg") {
|
||||
Some(msg) => vk.verify_with_context(&msg, &ctx, &sig),
|
||||
None => vk.verify_mu(&Array::try_from(field(t, "mu").as_slice()).unwrap(), &sig),
|
||||
};
|
||||
assert!(verified, "tcId {id}: own signature does not verify");
|
||||
valid += 1;
|
||||
} else {
|
||||
assert!(result.is_err(), "tcId {id} ({}) must be refused", t["comment"]);
|
||||
invalid += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!((valid, invalid), (101, 4));
|
||||
}
|
||||
|
||||
/// Wycheproof verification, including bad hint encodings, infinity-norm violations, wrong lengths
|
||||
/// and an over-long context.
|
||||
#[test]
|
||||
fn wycheproof_verify_65() {
|
||||
let (mut valid, mut invalid) = (0, 0);
|
||||
for g in json(WP_VERIFY)["testGroups"].as_array().unwrap() {
|
||||
let vk = vk_from(&field(g, "publicKey"));
|
||||
for t in g["tests"].as_array().unwrap() {
|
||||
let ctx = opt_field(t, "ctx").unwrap_or_default();
|
||||
let ok = match (&vk, sig_from(&field(t, "sig"))) {
|
||||
(Some(vk), Some(sig)) => vk.verify_with_context(&field(t, "msg"), &ctx, &sig),
|
||||
_ => false,
|
||||
};
|
||||
let want = t["result"] == "valid";
|
||||
assert_eq!(ok, want, "tcId {} ({}) {:?}", t["tcId"], t["comment"], t["flags"]);
|
||||
if want { valid += 1 } else { invalid += 1 }
|
||||
}
|
||||
}
|
||||
assert_eq!(valid + invalid, 70);
|
||||
assert!(valid > 0 && invalid > 0);
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
//! Mandatory test 3 (v0.2.0): the composite is RFC 10073 `id-MLDSA65-Ed25519-SHA512`, byte for byte.
|
||||
//!
|
||||
//! - The RFC's own signatures (`s`, empty ctx; `sWithContext`) verify, from Appendix E as
|
||||
//! published in `lamps-wg/draft-composite-sigs` `testvectors.json` at `f0627ab`, and the RFC's
|
||||
//! 64-byte private key derives the RFC's 1984-byte public key.
|
||||
//! - Arcanum's own signatures verify under an **independent rebuild** of M' written here, against
|
||||
//! the component crates directly: ML-DSA-65 with ctx = Label, and Ed25519 `verify_strict`.
|
||||
//! - The ML-DSA half is hedged (two signatures of the same message differ) and the Ed25519 half
|
||||
//! is pure Ed25519 (deterministic, so equal).
|
||||
//!
|
||||
//! The RFC vectors are hedged, so there is no byte-exact composite signing KAT (docs gap).
|
||||
|
||||
mod common;
|
||||
|
||||
use arcanum::Error;
|
||||
use arcanum::sign::{
|
||||
self, AppContext, SIGNATURE_LEN, SIGNING_KEY_LEN, Signature, SigningKey, VERIFYING_KEY_LEN, VerifyingKey,
|
||||
};
|
||||
use common::{assert_sha256, b64, rng};
|
||||
use ml_dsa::MlDsa65;
|
||||
use ml_dsa::common::array::Array;
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha512};
|
||||
|
||||
const VECTORS: &[u8] = include_bytes!("vectors/composite-sigs-testvectors-MLDSA65-Ed25519.subset.json");
|
||||
const VECTORS_SHA256: &str = "33311f63d2c5a21d5dd4b05eb864de38bd7572108b38de713a40312d2b893b34";
|
||||
|
||||
/// RFC 10073 §2.2 and §6, written out here independently of `src/sign.rs`.
|
||||
const PREFIX: &[u8] = b"CompositeAlgorithmSignatures2025";
|
||||
const LABEL: &[u8] = b"COMPSIG-MLDSA65-Ed25519-SHA512";
|
||||
const ML_DSA_SIG_LEN: usize = 3309;
|
||||
const ML_DSA_PK_LEN: usize = 1952;
|
||||
|
||||
/// M' = Prefix || Label || u8(len(ctx)) || ctx || SHA-512(M) (RFC 10073 §3.2)
|
||||
fn m_prime(msg: &[u8], ctx: &[u8]) -> Vec<u8> {
|
||||
assert!(ctx.len() <= 255);
|
||||
let mut m = Vec::new();
|
||||
m.extend_from_slice(PREFIX);
|
||||
m.extend_from_slice(LABEL);
|
||||
m.push(ctx.len() as u8);
|
||||
m.extend_from_slice(ctx);
|
||||
m.extend_from_slice(&Sha512::digest(msg));
|
||||
m
|
||||
}
|
||||
|
||||
/// Verify a composite signature with the component crates only, not with Arcanum.
|
||||
fn independent_verify(pk: &[u8], msg: &[u8], ctx: &[u8], sig: &[u8]) -> (bool, bool) {
|
||||
assert_eq!(pk.len(), ML_DSA_PK_LEN + 32);
|
||||
assert_eq!(sig.len(), ML_DSA_SIG_LEN + 64);
|
||||
let mp = m_prime(msg, ctx);
|
||||
let ml_vk = ml_dsa::VerifyingKey::<MlDsa65>::decode(&Array::try_from(&pk[..ML_DSA_PK_LEN]).unwrap());
|
||||
let ml_ok = ml_dsa::Signature::<MlDsa65>::try_from(&sig[..ML_DSA_SIG_LEN])
|
||||
.is_ok_and(|s| ml_vk.verify_with_context(&mp, LABEL, &s));
|
||||
let ed_vk = ed25519_dalek::VerifyingKey::from_bytes(pk[ML_DSA_PK_LEN..].try_into().unwrap()).unwrap();
|
||||
let ed_sig = ed25519_dalek::Signature::from_slice(&sig[ML_DSA_SIG_LEN..]).unwrap();
|
||||
let ed_ok = ed_vk.verify_strict(&mp, &ed_sig).is_ok();
|
||||
(ml_ok, ed_ok)
|
||||
}
|
||||
|
||||
struct Rfc {
|
||||
m: Vec<u8>,
|
||||
ctx: Vec<u8>,
|
||||
pk: Vec<u8>,
|
||||
sk: Vec<u8>,
|
||||
s: Vec<u8>,
|
||||
s_with_context: Vec<u8>,
|
||||
}
|
||||
|
||||
fn rfc() -> Rfc {
|
||||
assert_sha256(VECTORS, VECTORS_SHA256, "RFC 10073 composite vectors subset");
|
||||
let v: Value = serde_json::from_slice(VECTORS).unwrap();
|
||||
let tests = v["tests"].as_array().unwrap();
|
||||
assert_eq!(tests.len(), 1);
|
||||
let t = &tests[0];
|
||||
assert_eq!(t["tcId"], "id-MLDSA65-Ed25519-SHA512");
|
||||
let f = |name: &str| b64(t[name].as_str().unwrap());
|
||||
Rfc {
|
||||
m: b64(v["m"].as_str().unwrap()),
|
||||
ctx: b64(v["ctx"].as_str().unwrap()),
|
||||
pk: f("pk"),
|
||||
sk: f("sk"),
|
||||
s: f("s"),
|
||||
s_with_context: f("sWithContext"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes_are_the_rfcs() {
|
||||
let r = rfc();
|
||||
assert_eq!((VERIFYING_KEY_LEN, SIGNATURE_LEN, SIGNING_KEY_LEN), (1984, 3373, 64));
|
||||
assert_eq!((r.pk.len(), r.s.len(), r.s_with_context.len(), r.sk.len()), (1984, 3373, 3373, 64));
|
||||
assert_eq!(sign::PREFIX, PREFIX);
|
||||
assert_eq!(sign::LABEL, LABEL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rfc_private_key_derives_the_rfc_public_key() {
|
||||
let r = rfc();
|
||||
let sk = SigningKey::from_bytes(&r.sk).unwrap();
|
||||
assert_eq!(sk.verifying_key().as_bytes().as_slice(), r.pk.as_slice());
|
||||
assert_eq!(sk.to_bytes().as_slice(), r.sk.as_slice(), "the private key round-trips (mldsaSeed || edSK)");
|
||||
}
|
||||
|
||||
/// The gap in docs/02_signatures.md: does `verify_strict` accept the RFC's vectors? This answers it.
|
||||
#[test]
|
||||
fn rfc_signatures_verify() {
|
||||
let r = rfc();
|
||||
let vk = VerifyingKey::from_bytes(&r.pk).unwrap();
|
||||
let s = Signature::from_bytes(&r.s).unwrap();
|
||||
let swc = Signature::from_bytes(&r.s_with_context).unwrap();
|
||||
// Arcanum's raw (hazmat) interface, with the RFC's bare ctx.
|
||||
assert_eq!(sign::verify_composite_raw(&vk, &r.m, b"", &s), Ok(()), "s (empty ctx)");
|
||||
assert_eq!(sign::verify_composite_raw(&vk, &r.m, &r.ctx, &swc), Ok(()), "sWithContext");
|
||||
// The contexts are not interchangeable.
|
||||
assert_eq!(sign::verify_composite_raw(&vk, &r.m, &r.ctx, &s), Err(Error::InvalidSignature));
|
||||
assert_eq!(sign::verify_composite_raw(&vk, &r.m, b"", &swc), Err(Error::InvalidSignature));
|
||||
// The independent rebuild agrees, half by half.
|
||||
assert_eq!(independent_verify(&r.pk, &r.m, b"", &r.s), (true, true));
|
||||
assert_eq!(independent_verify(&r.pk, &r.m, &r.ctx, &r.s_with_context), (true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn own_signatures_verify_under_an_independent_rebuild_of_m_prime() {
|
||||
let mut rng = rng(30);
|
||||
let sk = SigningKey::generate(&mut rng);
|
||||
let pk = sk.verifying_key().as_bytes().to_vec();
|
||||
let msg = b"a plan, signed by its author";
|
||||
|
||||
// Release API: the ctx is Arcanum's app prefix plus the caller's label.
|
||||
let ctx = AppContext::new(b"plans").unwrap();
|
||||
assert_eq!(ctx.as_bytes(), b"domi/arcanum/v2/sig/app/plans");
|
||||
let sig = sk.sign(msg, &ctx, &mut rng).unwrap();
|
||||
assert_eq!(independent_verify(&pk, msg, ctx.as_bytes(), sig.as_bytes()), (true, true));
|
||||
assert_eq!(sk.verifying_key().verify(msg, &ctx, &sig), Ok(()));
|
||||
|
||||
// Raw interface: an empty ctx and the longest ctx, 255 bytes.
|
||||
for ctx in [&b""[..], &[0xa5; 255][..]] {
|
||||
let sig = sign::sign_composite_raw(&sk, msg, ctx, &mut rng).unwrap();
|
||||
assert_eq!(independent_verify(&pk, msg, ctx, sig.as_bytes()), (true, true), "ctx of {} bytes", ctx.len());
|
||||
assert_eq!(sign::verify_composite_raw(sk.verifying_key(), msg, ctx, &sig), Ok(()));
|
||||
}
|
||||
|
||||
// The RFC's own private key, signing the RFC's message: verifies under the RFC's public key.
|
||||
let r = rfc();
|
||||
let rfc_sk = SigningKey::from_bytes(&r.sk).unwrap();
|
||||
let sig = sign::sign_composite_raw(&rfc_sk, &r.m, &r.ctx, &mut rng).unwrap();
|
||||
assert_eq!(independent_verify(&r.pk, &r.m, &r.ctx, sig.as_bytes()), (true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ml_dsa_half_is_hedged_and_ed25519_half_is_pure() {
|
||||
let sk = SigningKey::generate(&mut rng(31));
|
||||
let ctx = AppContext::new(b"hedge").unwrap();
|
||||
let a = sk.sign(b"same message", &ctx, &mut rng(32)).unwrap();
|
||||
let b = sk.sign(b"same message", &ctx, &mut rng(33)).unwrap();
|
||||
let (a, b) = (a.as_bytes(), b.as_bytes());
|
||||
assert_ne!(a[..ML_DSA_SIG_LEN], b[..ML_DSA_SIG_LEN], "ML-DSA must be hedged: fresh rnd per signature");
|
||||
assert_eq!(a[ML_DSA_SIG_LEN..], b[ML_DSA_SIG_LEN..], "Ed25519 over the same M' is deterministic");
|
||||
// The same RNG state gives the same signature: the RNG is the only source of randomness.
|
||||
let c = sk.sign(b"same message", &ctx, &mut rng(32)).unwrap();
|
||||
assert_eq!(a, c.as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ml_dsa_half_uses_the_label_as_its_context() {
|
||||
let mut rng = rng(34);
|
||||
let sk = SigningKey::generate(&mut rng);
|
||||
let pk = sk.verifying_key().as_bytes().to_vec();
|
||||
let ctx = AppContext::new(b"label").unwrap();
|
||||
let sig = sk.sign(b"m", &ctx, &mut rng).unwrap();
|
||||
let mp = m_prime(b"m", ctx.as_bytes());
|
||||
let ml_vk = ml_dsa::VerifyingKey::<MlDsa65>::decode(&Array::try_from(&pk[..ML_DSA_PK_LEN]).unwrap());
|
||||
let ml_sig = ml_dsa::Signature::<MlDsa65>::try_from(&sig.as_bytes()[..ML_DSA_SIG_LEN]).unwrap();
|
||||
assert!(ml_vk.verify_with_context(&mp, LABEL, &ml_sig), "ctx = Label");
|
||||
assert!(!ml_vk.verify_with_context(&mp, b"", &ml_sig), "not the empty ctx");
|
||||
assert!(!ml_vk.verify_with_context(&mp, ctx.as_bytes(), &ml_sig), "not the application ctx");
|
||||
}
|
||||
|
||||
/// An RNG that records what it hands out (backed by the test ChaCha20).
|
||||
struct Recording(chacha20::ChaCha20Rng, Vec<u8>);
|
||||
|
||||
impl rand_core::TryRng for Recording {
|
||||
type Error = core::convert::Infallible;
|
||||
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
|
||||
unimplemented!("signing draws bytes, not words")
|
||||
}
|
||||
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
|
||||
unimplemented!("signing draws bytes, not words")
|
||||
}
|
||||
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
|
||||
rand_core::Rng::fill_bytes(&mut self.0, dst);
|
||||
self.1.extend_from_slice(dst);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl rand_core::TryCryptoRng for Recording {}
|
||||
|
||||
/// QA S-03 (their `qa_s05`), RFC 10073 §3.1: `generate` draws 64 fresh bytes, the ML-DSA seed then
|
||||
/// the Ed25519 seed, independently. Kills deriving one seed from the other, or drawing only 32.
|
||||
#[test]
|
||||
fn generate_draws_two_independent_seeds() {
|
||||
let mut rec = Recording(rng(35), Vec::new());
|
||||
let sk = SigningKey::generate(&mut rec);
|
||||
assert_eq!(rec.1.len(), 64, "exactly 64 bytes drawn");
|
||||
assert_eq!(sk.to_bytes().as_slice(), rec.1.as_slice(), "the seeds are the RNG output, in order");
|
||||
assert_ne!(rec.1[..32], rec.1[32..], "two different seeds");
|
||||
let again = SigningKey::from_bytes(&rec.1).unwrap();
|
||||
assert_eq!(again.verifying_key(), sk.verifying_key());
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
//! Mandatory test 5 (v0.2.0): every byte matters. Flipping any byte of the message, the context,
|
||||
//! the public key or the signature fails verification. Contexts are prefix-free (the length of
|
||||
//! ctx is inside M'), and a key-binding signature never verifies as an application message, nor
|
||||
//! the other way round.
|
||||
|
||||
mod common;
|
||||
|
||||
use arcanum::Error;
|
||||
use arcanum::sign::{
|
||||
self, AppContext, KEM_KEY_CONTEXT, SIGNATURE_LEN, Signature, SigningKey, VERIFYING_KEY_LEN, VerifyingKey,
|
||||
};
|
||||
use arcanum::xwing;
|
||||
use common::rng;
|
||||
|
||||
const MSG: &[u8] = b"Built on Domi: every byte of this message is signed.";
|
||||
|
||||
fn setup(tag: u8) -> (SigningKey, AppContext, Signature) {
|
||||
let mut r = rng(tag);
|
||||
let sk = SigningKey::generate(&mut r);
|
||||
let c = AppContext::new(b"every-byte").unwrap();
|
||||
let sig = sk.sign(MSG, &c, &mut r).unwrap();
|
||||
assert_eq!(sk.verifying_key().verify(MSG, &c, &sig), Ok(()), "control");
|
||||
(sk, c, sig)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flipping_any_byte_of_the_message_fails() {
|
||||
let (sk, c, sig) = setup(50);
|
||||
for i in 0..MSG.len() {
|
||||
for mask in [0x01, 0x80] {
|
||||
let mut m = MSG.to_vec();
|
||||
m[i] ^= mask;
|
||||
assert_eq!(sk.verifying_key().verify(&m, &c, &sig), Err(Error::InvalidSignature), "byte {i}");
|
||||
}
|
||||
}
|
||||
let mut longer = MSG.to_vec();
|
||||
longer.push(0);
|
||||
assert_eq!(sk.verifying_key().verify(&longer, &c, &sig), Err(Error::InvalidSignature), "appended byte");
|
||||
assert_eq!(sk.verifying_key().verify(&MSG[..MSG.len() - 1], &c, &sig), Err(Error::InvalidSignature));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flipping_any_byte_of_the_context_fails() {
|
||||
let (sk, c, sig) = setup(51);
|
||||
let vk = sk.verifying_key();
|
||||
// Through the release API: every byte of the caller's label. Labels are `&'static` (QA S-09);
|
||||
// a test may leak a few to build them at run time, which a consumer must not do.
|
||||
let label = b"every-byte";
|
||||
for i in 0..label.len() {
|
||||
let mut l = label.to_vec();
|
||||
l[i] ^= 0x01;
|
||||
let l: &'static [u8] = Box::leak(l.into_boxed_slice());
|
||||
assert_eq!(vk.verify(MSG, &AppContext::new(l).unwrap(), &sig), Err(Error::InvalidSignature), "label byte {i}");
|
||||
}
|
||||
// Through the raw interface: every byte of the whole ctx, Arcanum's prefix included.
|
||||
let full = c.as_bytes().to_vec();
|
||||
assert_eq!(sign::verify_composite_raw(vk, MSG, &full, &sig), Ok(()), "control");
|
||||
for i in 0..full.len() {
|
||||
let mut f = full.clone();
|
||||
f[i] ^= 0x01;
|
||||
assert_eq!(sign::verify_composite_raw(vk, MSG, &f, &sig), Err(Error::InvalidSignature), "ctx byte {i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flipping_any_byte_of_the_public_key_fails() {
|
||||
let (sk, c, sig) = setup(52);
|
||||
let pk = *sk.verifying_key().as_bytes();
|
||||
let (mut refused_at_parse, mut refused_at_verify) = (0, 0);
|
||||
for i in 0..VERIFYING_KEY_LEN {
|
||||
let mut b = pk;
|
||||
b[i] ^= 0x01;
|
||||
match VerifyingKey::from_bytes(&b) {
|
||||
Err(e) => {
|
||||
assert_eq!(e, Error::InvalidVerifyingKey, "byte {i}");
|
||||
assert!(i >= VERIFYING_KEY_LEN - 32, "byte {i}: only the Ed25519 point can fail to parse");
|
||||
refused_at_parse += 1;
|
||||
}
|
||||
Ok(vk) => {
|
||||
assert_eq!(vk.verify(MSG, &c, &sig), Err(Error::InvalidSignature), "byte {i}");
|
||||
refused_at_verify += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(refused_at_parse + refused_at_verify, VERIFYING_KEY_LEN);
|
||||
assert!(refused_at_verify >= 1952, "every ML-DSA byte reaches verification");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flipping_any_byte_of_the_signature_fails() {
|
||||
let (sk, c, sig) = setup(53);
|
||||
for i in 0..SIGNATURE_LEN {
|
||||
let mut b = *sig.as_bytes();
|
||||
b[i] ^= 0x01;
|
||||
let bad = Signature::from_bytes(&b).unwrap();
|
||||
assert_eq!(sk.verifying_key().verify(MSG, &c, &bad), Err(Error::InvalidSignature), "byte {i}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contexts_are_prefix_free() {
|
||||
let mut r = rng(54);
|
||||
let sk = SigningKey::generate(&mut r);
|
||||
let vk = sk.verifying_key();
|
||||
let a = AppContext::new(b"a").unwrap();
|
||||
let ab = AppContext::new(b"ab").unwrap();
|
||||
let sig_a = sk.sign(MSG, &a, &mut r).unwrap();
|
||||
let sig_ab = sk.sign(MSG, &ab, &mut r).unwrap();
|
||||
assert_eq!(vk.verify(MSG, &ab, &sig_a), Err(Error::InvalidSignature), "a is a prefix of ab");
|
||||
assert_eq!(vk.verify(MSG, &a, &sig_ab), Err(Error::InvalidSignature), "ab extends a");
|
||||
assert_eq!(vk.verify(MSG, &AppContext::new(b"a\0").unwrap(), &sig_a), Err(Error::InvalidSignature));
|
||||
// Moving a byte between ctx and message: M' holds SHA-512(M), and u8(len ctx) fixes the split.
|
||||
assert_eq!(vk.verify(b"bBuilt", &a, &sk.sign(b"Built", &ab, &mut r).unwrap()), Err(Error::InvalidSignature));
|
||||
// The raw interface: the empty ctx, Arcanum's prefixes and the RFC's empty ctx are all distinct.
|
||||
let raw_empty = sign::sign_composite_raw(&sk, MSG, b"", &mut r).unwrap();
|
||||
assert_eq!(sign::verify_composite_raw(vk, MSG, b"\0", &raw_empty), Err(Error::InvalidSignature));
|
||||
assert_eq!(vk.verify(MSG, &a, &raw_empty), Err(Error::InvalidSignature));
|
||||
let app_prefix_only = sign::sign_composite_raw(&sk, MSG, b"domi/arcanum/v2/sig/app/", &mut r).unwrap();
|
||||
assert_eq!(vk.verify(MSG, &a, &app_prefix_only), Err(Error::InvalidSignature));
|
||||
// Arcanum's fixed contexts: neither is a prefix of the other.
|
||||
let app = b"domi/arcanum/v2/sig/app/";
|
||||
assert_eq!(KEM_KEY_CONTEXT, b"domi/arcanum/v2/sig/kem-key");
|
||||
assert!(!app.starts_with(KEM_KEY_CONTEXT) && !KEM_KEY_CONTEXT.starts_with(app));
|
||||
}
|
||||
|
||||
/// The key-binding message, written out here from docs/02_signatures.md, independently of the code:
|
||||
/// u8(1) || u64be(not_before) || u64be(not_after) || u16be(len id) || id || xwing_pk.
|
||||
fn binding_message(id: &[u8], kem: &xwing::PublicKey, (nb, na): (u64, u64)) -> Vec<u8> {
|
||||
let mut m = vec![1u8];
|
||||
m.extend_from_slice(&nb.to_be_bytes());
|
||||
m.extend_from_slice(&na.to_be_bytes());
|
||||
m.extend_from_slice(&(id.len() as u16).to_be_bytes());
|
||||
m.extend_from_slice(id);
|
||||
m.extend_from_slice(kem.as_bytes());
|
||||
m
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_binding_never_verifies_as_an_app_message_and_back() {
|
||||
let mut r = rng(55);
|
||||
let sk = SigningKey::generate(&mut r);
|
||||
let vk = sk.verifying_key();
|
||||
let kem = xwing::SecretKey::generate(&mut r);
|
||||
let (id, valid, now) = (b"device-7".as_slice(), (1_000, 2_000), 1_500);
|
||||
let binding = sign::bind_kem_key(&sk, id, kem.public_key(), valid, &mut r).unwrap();
|
||||
assert_eq!(sign::verify_binding(vk, id, kem.public_key(), valid, now, &binding), Ok(()), "control");
|
||||
|
||||
// The binding is exactly the documented message under the kem-key ctx.
|
||||
let msg = binding_message(id, kem.public_key(), valid);
|
||||
assert_eq!(sign::verify_composite_raw(vk, &msg, KEM_KEY_CONTEXT, &binding), Ok(()), "documented encoding");
|
||||
|
||||
// As an application message, under any application label: refused.
|
||||
for label in [b"kem-key".as_slice(), b"", b"domi/arcanum/v2/sig/kem-key", b"x"] {
|
||||
if let Ok(c) = AppContext::new(label) {
|
||||
assert_eq!(vk.verify(&msg, &c, &binding), Err(Error::InvalidSignature), "label {label:?}");
|
||||
}
|
||||
}
|
||||
// The other way round: an application signature over the very same bytes is no binding.
|
||||
let app_sig = sk.sign(&msg, &AppContext::new(b"kem-key").unwrap(), &mut r).unwrap();
|
||||
assert_eq!(sign::verify_binding(vk, id, kem.public_key(), valid, now, &app_sig), Err(Error::InvalidSignature));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_field_of_a_key_binding_matters() {
|
||||
let mut r = rng(56);
|
||||
let sk = SigningKey::generate(&mut r);
|
||||
let vk = sk.verifying_key();
|
||||
let kem = xwing::SecretKey::generate(&mut r);
|
||||
let other_kem = xwing::SecretKey::generate(&mut r);
|
||||
let (id, valid) = (b"device-7".as_slice(), (1_000u64, 2_000u64));
|
||||
let sig = sign::bind_kem_key(&sk, id, kem.public_key(), valid, &mut r).unwrap();
|
||||
let check =
|
||||
|id: &[u8], k: &xwing::PublicKey, v: (u64, u64), now: u64| sign::verify_binding(vk, id, k, v, now, &sig);
|
||||
|
||||
assert_eq!(check(id, kem.public_key(), valid, 1_000), Ok(()), "not_before is inclusive");
|
||||
assert_eq!(check(id, kem.public_key(), valid, 2_000), Ok(()), "not_after is inclusive");
|
||||
assert_eq!(check(id, kem.public_key(), valid, 999), Err(Error::OutsideValidity));
|
||||
assert_eq!(check(id, kem.public_key(), valid, 2_001), Err(Error::OutsideValidity));
|
||||
assert_eq!(check(b"device-8", kem.public_key(), valid, 1_500), Err(Error::InvalidSignature), "id");
|
||||
assert_eq!(check(b"device-7\0", kem.public_key(), valid, 1_500), Err(Error::InvalidSignature), "id length");
|
||||
assert_eq!(check(id, other_kem.public_key(), valid, 1_500), Err(Error::InvalidSignature), "X-Wing key");
|
||||
assert_eq!(check(id, kem.public_key(), (1_000, 2_001), 1_500), Err(Error::InvalidSignature), "not_after");
|
||||
assert_eq!(check(id, kem.public_key(), (999, 2_000), 1_500), Err(Error::InvalidSignature), "not_before");
|
||||
// A forged window is refused as a bad signature before its dates are looked at.
|
||||
assert_eq!(check(id, kem.public_key(), (0, u64::MAX), 5_000), Err(Error::InvalidSignature));
|
||||
// An inverted window is refused when binding and when verifying.
|
||||
assert_eq!(sign::bind_kem_key(&sk, id, kem.public_key(), (2, 1), &mut r), Err(Error::InvalidValidity));
|
||||
assert_eq!(check(id, kem.public_key(), (2_000, 1_000), 1_500), Err(Error::InvalidValidity));
|
||||
// Every byte of the X-Wing key matters (its encoding is fixed-width and signed whole).
|
||||
let mut flipped = *kem.public_key().as_bytes();
|
||||
for i in [0, 600, 1183, 1184, 1215] {
|
||||
flipped[i] ^= 0x01;
|
||||
if let Ok(k) = xwing::PublicKey::from_bytes(&flipped) {
|
||||
assert_eq!(check(id, &k, valid, 1_500), Err(Error::InvalidSignature), "X-Wing byte {i}");
|
||||
}
|
||||
flipped[i] ^= 0x01;
|
||||
}
|
||||
}
|
||||
|
||||
/// QA S-02 (their `qa_s04`): `OutsideValidity` only ever means "authentic, but not now". A forged
|
||||
/// window that also excludes `now` is `InvalidSignature`. Kills checking `now` before the signature.
|
||||
#[test]
|
||||
fn a_forged_window_that_excludes_now_is_invalid_signature_not_outside_validity() {
|
||||
let mut r = rng(57);
|
||||
let sk = SigningKey::generate(&mut r);
|
||||
let kem = xwing::SecretKey::generate(&mut r);
|
||||
let sig = sign::bind_kem_key(&sk, b"dev", kem.public_key(), (1_000, 2_000), &mut r).unwrap();
|
||||
let check =
|
||||
|v: (u64, u64), now: u64| sign::verify_binding(sk.verifying_key(), b"dev", kem.public_key(), v, now, &sig);
|
||||
assert_eq!(check((1_000, 2_000), 1_500), Ok(()), "control");
|
||||
assert_eq!(check((1_000, 2_000), 2_500), Err(Error::OutsideValidity), "control: authentic, expired");
|
||||
assert_eq!(check((1_000, 2_001), 2_500), Err(Error::InvalidSignature), "forged window, now after it");
|
||||
assert_eq!(check((3_000, 4_000), 2_500), Err(Error::InvalidSignature), "forged window, now before it");
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
//! Mandatory test 4 (v0.2.0): both halves of a composite signature are bound. A signature is
|
||||
//! accepted only when **both** the ML-DSA-65 half and the Ed25519 half verify over this M'.
|
||||
//!
|
||||
//! Refused: either half replaced by a valid half of another signature (another message, another
|
||||
//! key or another context), either half zeroed, the halves swapped. And the ML-DSA half alone is
|
||||
//! no ordinary ML-DSA signature: an empty-ctx ML-DSA verifier refuses it, on M' and on M.
|
||||
//!
|
||||
//! Pinned, not a bug: the composite is not SUF-CMA (RFC 10073 §9.2). Two hedged signatures of the
|
||||
//! same message by the same key under the same context can trade ML-DSA halves and still verify.
|
||||
|
||||
mod common;
|
||||
|
||||
use arcanum::Error;
|
||||
use arcanum::sign::{AppContext, SIGNATURE_LEN, Signature, SigningKey};
|
||||
use common::rng;
|
||||
use ml_dsa::MlDsa65;
|
||||
use ml_dsa::common::array::Array;
|
||||
use sha2::{Digest, Sha512};
|
||||
|
||||
const ML: usize = 3309; // the ML-DSA-65 half comes first
|
||||
const ML_PK: usize = 1952;
|
||||
|
||||
fn ctx(label: &'static [u8]) -> AppContext {
|
||||
AppContext::new(label).unwrap()
|
||||
}
|
||||
|
||||
fn splice(ml_from: &Signature, ed_from: &Signature) -> Signature {
|
||||
let mut b = [0u8; SIGNATURE_LEN];
|
||||
b[..ML].copy_from_slice(&ml_from.as_bytes()[..ML]);
|
||||
b[ML..].copy_from_slice(&ed_from.as_bytes()[ML..]);
|
||||
Signature::from_bytes(&b).unwrap()
|
||||
}
|
||||
|
||||
fn refused(sk: &SigningKey, msg: &[u8], c: &AppContext, sig: &Signature, what: &str) {
|
||||
assert_eq!(sk.verifying_key().verify(msg, c, sig), Err(Error::InvalidSignature), "{what}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_half_from_another_signature_is_refused() {
|
||||
let mut r = rng(40);
|
||||
let sk = SigningKey::generate(&mut r);
|
||||
let other_key = SigningKey::generate(&mut r);
|
||||
let c = ctx(b"halves");
|
||||
let msg = b"the message";
|
||||
let good = sk.sign(msg, &c, &mut r).unwrap();
|
||||
assert_eq!(sk.verifying_key().verify(msg, &c, &good), Ok(()), "control");
|
||||
|
||||
let other_msg = sk.sign(b"another message", &c, &mut r).unwrap();
|
||||
let other_ctx = sk.sign(msg, &ctx(b"another context"), &mut r).unwrap();
|
||||
let other_signer = other_key.sign(msg, &c, &mut r).unwrap();
|
||||
for (donor, what) in
|
||||
[(&other_msg, "another message"), (&other_ctx, "another context"), (&other_signer, "another key")]
|
||||
{
|
||||
refused(&sk, msg, &c, &splice(donor, &good), &format!("ML-DSA half from {what}"));
|
||||
refused(&sk, msg, &c, &splice(&good, donor), &format!("Ed25519 half from {what}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zeroed_or_missing_half_is_refused() {
|
||||
let mut r = rng(41);
|
||||
let sk = SigningKey::generate(&mut r);
|
||||
let c = ctx(b"halves");
|
||||
let good = sk.sign(b"m", &c, &mut r).unwrap();
|
||||
let mut b = *good.as_bytes();
|
||||
b[..ML].fill(0);
|
||||
refused(&sk, b"m", &c, &Signature::from_bytes(&b).unwrap(), "ML-DSA half zeroed");
|
||||
let mut b = *good.as_bytes();
|
||||
b[ML..].fill(0);
|
||||
refused(&sk, b"m", &c, &Signature::from_bytes(&b).unwrap(), "Ed25519 half zeroed");
|
||||
let mut b = *good.as_bytes();
|
||||
b[ML..].fill(0xff);
|
||||
refused(&sk, b"m", &c, &Signature::from_bytes(&b).unwrap(), "Ed25519 half all ones");
|
||||
// A signature with one half cut off is the wrong length, a typed error at parse time.
|
||||
assert!(Signature::from_bytes(&good.as_bytes()[..ML]).is_err(), "ML-DSA half alone");
|
||||
assert!(Signature::from_bytes(&good.as_bytes()[ML..]).is_err(), "Ed25519 half alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swapped_halves_are_refused() {
|
||||
let mut r = rng(42);
|
||||
let sk = SigningKey::generate(&mut r);
|
||||
let c = ctx(b"halves");
|
||||
let good = sk.sign(b"m", &c, &mut r).unwrap();
|
||||
let g = good.as_bytes();
|
||||
let mut swapped = Vec::with_capacity(SIGNATURE_LEN);
|
||||
swapped.extend_from_slice(&g[ML..]);
|
||||
swapped.extend_from_slice(&g[..ML]);
|
||||
refused(&sk, b"m", &c, &Signature::from_bytes(&swapped).unwrap(), "Ed25519 || ML-DSA");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ml_dsa_half_alone_is_not_an_ordinary_ml_dsa_signature() {
|
||||
let mut r = rng(43);
|
||||
let sk = SigningKey::generate(&mut r);
|
||||
let c = ctx(b"halves");
|
||||
let msg = b"m";
|
||||
let sig = sk.sign(msg, &c, &mut r).unwrap();
|
||||
let pk = sk.verifying_key().as_bytes();
|
||||
let vk = ml_dsa::VerifyingKey::<MlDsa65>::decode(&Array::try_from(&pk[..ML_PK]).unwrap());
|
||||
let half = ml_dsa::Signature::<MlDsa65>::try_from(&sig.as_bytes()[..ML]).unwrap();
|
||||
|
||||
let mut mp = Vec::new();
|
||||
mp.extend_from_slice(b"CompositeAlgorithmSignatures2025COMPSIG-MLDSA65-Ed25519-SHA512");
|
||||
mp.push(c.as_bytes().len() as u8);
|
||||
mp.extend_from_slice(c.as_bytes());
|
||||
mp.extend_from_slice(&Sha512::digest(msg));
|
||||
|
||||
// An application that verifies ML-DSA with the empty ctx (as the crate's `Verifier` trait does)
|
||||
// refuses the half, whether it is shown M' or the message itself.
|
||||
assert!(!vk.verify_with_context(&mp, b"", &half), "empty ctx over M'");
|
||||
assert!(!vk.verify_with_context(msg, b"", &half), "empty ctx over M");
|
||||
assert!(!vk.verify_with_context(msg, b"COMPSIG-MLDSA65-Ed25519-SHA512", &half), "Label ctx over M");
|
||||
// Control: it is a valid ML-DSA signature over M' under ctx = Label, and nothing else.
|
||||
assert!(vk.verify_with_context(&mp, b"COMPSIG-MLDSA65-Ed25519-SHA512", &half));
|
||||
|
||||
// Likewise the Ed25519 half: it signs M', never the message.
|
||||
let ed = ed25519_dalek::VerifyingKey::from_bytes(pk[ML_PK..].try_into().unwrap()).unwrap();
|
||||
let ed_half = ed25519_dalek::Signature::from_slice(&sig.as_bytes()[ML..]).unwrap();
|
||||
assert!(ed.verify_strict(msg, &ed_half).is_err(), "Ed25519 over M");
|
||||
assert!(ed.verify_strict(&mp, &ed_half).is_ok(), "control: Ed25519 over M'");
|
||||
}
|
||||
|
||||
/// RFC 10073 §9.2: not SUF-CMA. Pinned so a change in this property is noticed, not hidden.
|
||||
#[test]
|
||||
fn halves_of_two_signatures_of_the_same_message_combine_as_the_rfc_says() {
|
||||
let mut r = rng(44);
|
||||
let sk = SigningKey::generate(&mut r);
|
||||
let c = ctx(b"halves");
|
||||
let a = sk.sign(b"m", &c, &mut r).unwrap();
|
||||
let b = sk.sign(b"m", &c, &mut r).unwrap();
|
||||
assert_ne!(a, b, "hedged ML-DSA");
|
||||
assert_eq!(sk.verifying_key().verify(b"m", &c, &splice(&a, &b)), Ok(()));
|
||||
assert_eq!(sk.verifying_key().verify(b"m", &c, &splice(&b, &a)), Ok(()));
|
||||
}
|
||||
|
||||
/// QA S-01 (PR #2 review, their `qa_s03`): the Ed25519 half is checked with `verify_strict`, not
|
||||
/// plain `verify`. A signer who knows its own Ed25519 scalar `a` can make a half with R = the
|
||||
/// identity (a small-order point) and s = H(R || A || M')·a. Plain `verify` accepts it,
|
||||
/// `verify_strict` refuses it, and so must Arcanum. Kills `verify_strict` -> `verify`.
|
||||
#[test]
|
||||
fn a_small_order_r_in_the_ed25519_half_is_refused() {
|
||||
use curve25519_dalek::scalar::Scalar;
|
||||
use ed25519_dalek::Verifier as _;
|
||||
|
||||
let seeds = [0x11u8; 64]; // a throwaway key
|
||||
let sk = SigningKey::from_bytes(&seeds).unwrap();
|
||||
let vk = sk.verifying_key();
|
||||
let c = ctx(b"small-order-r");
|
||||
let msg = b"m";
|
||||
let good = sk.sign(msg, &c, &mut rng(45)).unwrap();
|
||||
|
||||
// a = clamp(SHA-512(Ed25519 seed)[..32]) (RFC 8032 §5.1.5).
|
||||
let h = Sha512::digest(&seeds[32..]);
|
||||
let mut a = [0u8; 32];
|
||||
a.copy_from_slice(&h[..32]);
|
||||
a[0] &= 248;
|
||||
a[31] &= 127;
|
||||
a[31] |= 64;
|
||||
let a = Scalar::from_bytes_mod_order(a);
|
||||
|
||||
let mut mp = Vec::new();
|
||||
mp.extend_from_slice(b"CompositeAlgorithmSignatures2025COMPSIG-MLDSA65-Ed25519-SHA512");
|
||||
mp.push(c.as_bytes().len() as u8);
|
||||
mp.extend_from_slice(c.as_bytes());
|
||||
mp.extend_from_slice(&Sha512::digest(msg));
|
||||
|
||||
let mut r = [0u8; 32];
|
||||
r[0] = 1; // the identity, canonically encoded: order 1
|
||||
let a_bytes = &vk.as_bytes()[ML_PK..];
|
||||
let mut kh = Sha512::new();
|
||||
kh.update(r);
|
||||
kh.update(a_bytes);
|
||||
kh.update(&mp);
|
||||
let k = Scalar::from_bytes_mod_order_wide(&kh.finalize().into());
|
||||
let mut ed_half = [0u8; 64];
|
||||
ed_half[..32].copy_from_slice(&r);
|
||||
ed_half[32..].copy_from_slice((k * a).as_bytes());
|
||||
|
||||
// Controls: this is the one difference between the two Ed25519 checks.
|
||||
let ed_vk = ed25519_dalek::VerifyingKey::from_bytes(a_bytes.try_into().unwrap()).unwrap();
|
||||
let ed_sig = ed25519_dalek::Signature::from_bytes(&ed_half);
|
||||
assert!(ed_vk.verify(&mp, &ed_sig).is_ok(), "control: plain verify accepts a small-order R");
|
||||
assert!(ed_vk.verify_strict(&mp, &ed_sig).is_err(), "control: verify_strict refuses it");
|
||||
|
||||
let mut b = [0u8; SIGNATURE_LEN];
|
||||
b[..ML].copy_from_slice(&good.as_bytes()[..ML]);
|
||||
b[ML..].copy_from_slice(&ed_half);
|
||||
refused(&sk, msg, &c, &Signature::from_bytes(&b).unwrap(), "small-order R in the Ed25519 half");
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
//! Mandatory test 7 (v0.2.0): hygiene of the signature API.
|
||||
//!
|
||||
//! - What a **default-features consumer** can and cannot write, by compiling small programs against
|
||||
//! Arcanum without `hazmat`, the way `qa_consumer_api.rs` does for v0.1.0 (QA A-33, A-34). The
|
||||
//! raw RFC interface is `hazmat` only, and none of `ml-dsa`'s own signing internals
|
||||
//! (`sign_internal` with caller-chosen randomness, `sign_mu_deterministic`, `sign_deterministic`,
|
||||
//! the `Signer` trait with its empty context) can be reached through Arcanum's types.
|
||||
//! - The secret types are `ZeroizeOnDrop`, including the component crates' keys (which proves their
|
||||
//! `zeroize` features are on), and `Debug` never prints key material.
|
||||
//!
|
||||
//! The feature graph (no `hazmat` anywhere, `zeroize` on) is checked in `feature_hygiene.rs`, and
|
||||
//! the heap wiping by the allocator probe in `zeroize-probe/`.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use arcanum::sign::{AppContext, SigningKey};
|
||||
use common::rng;
|
||||
use zeroize::ZeroizeOnDrop;
|
||||
|
||||
/// The cases share one crate (its dependencies are checked once), so they must not run at once.
|
||||
static LOCK: Mutex<()> = Mutex::new(());
|
||||
|
||||
const PRELUDE: &str = r#"
|
||||
#![allow(unused)]
|
||||
use core::convert::Infallible;
|
||||
use rand_core::{TryCryptoRng, TryRng};
|
||||
|
||||
/// A counter: deterministic, and therefore NOT a cryptographic RNG.
|
||||
pub struct Counter(pub u64);
|
||||
impl TryRng for Counter {
|
||||
type Error = Infallible;
|
||||
fn try_next_u32(&mut self) -> Result<u32, Infallible> { self.0 += 1; Ok(self.0 as u32) }
|
||||
fn try_next_u64(&mut self) -> Result<u64, Infallible> { self.0 += 1; Ok(self.0) }
|
||||
fn try_fill_bytes(&mut self, d: &mut [u8]) -> Result<(), Infallible> {
|
||||
for b in d { self.0 += 1; *b = self.0 as u8; }
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The same counter, *claiming* to be cryptographic (a stand-in for a real CSPRNG in the control).
|
||||
pub struct Claimed(pub Counter);
|
||||
impl TryRng for Claimed {
|
||||
type Error = Infallible;
|
||||
fn try_next_u32(&mut self) -> Result<u32, Infallible> { self.0.try_next_u32() }
|
||||
fn try_next_u64(&mut self) -> Result<u64, Infallible> { self.0.try_next_u64() }
|
||||
fn try_fill_bytes(&mut self, d: &mut [u8]) -> Result<(), Infallible> { self.0.try_fill_bytes(d) }
|
||||
}
|
||||
impl TryCryptoRng for Claimed {}
|
||||
|
||||
fn key() -> arcanum::sign::SigningKey { arcanum::sign::SigningKey::generate(&mut Claimed(Counter(0))) }
|
||||
fn ctx() -> arcanum::sign::AppContext { arcanum::sign::AppContext::new(b"consumer").unwrap() }
|
||||
"#;
|
||||
|
||||
fn consumer_dir() -> PathBuf {
|
||||
let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("sig-consumer-api");
|
||||
std::fs::create_dir_all(dir.join("src")).unwrap();
|
||||
let arcanum = env!("CARGO_MANIFEST_DIR").replace('\\', "/");
|
||||
let manifest = format!(
|
||||
"[package]\nname = \"sig-consumer-api\"\nversion = \"0.0.0\"\nedition = \"2024\"\npublish = false\n\n\
|
||||
[dependencies]\narcanum = {{ path = \"{arcanum}\" }}\n\
|
||||
rand_core = {{ version = \"0.10\", default-features = false }}\n\n[workspace]\n"
|
||||
);
|
||||
std::fs::write(dir.join("Cargo.toml"), manifest).unwrap();
|
||||
if !dir.join("Cargo.lock").exists() {
|
||||
std::fs::copy(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.lock"), dir.join("Cargo.lock")).unwrap();
|
||||
}
|
||||
dir
|
||||
}
|
||||
|
||||
/// `cargo check` a consumer whose `main` body is `body`. Returns (compiled, compiler output).
|
||||
fn check(body: &str) -> (bool, String) {
|
||||
let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let dir = consumer_dir();
|
||||
std::fs::write(dir.join("src/main.rs"), format!("{PRELUDE}\nfn main() {{\n{body}\n}}\n")).unwrap();
|
||||
let out = Command::new(env!("CARGO"))
|
||||
.current_dir(&dir)
|
||||
.args(["check", "--offline", "--quiet", "--message-format", "short"])
|
||||
.env_remove("CARGO_TARGET_DIR")
|
||||
.output()
|
||||
.expect("run cargo check");
|
||||
(out.status.success(), String::from_utf8_lossy(&out.stderr).into_owned())
|
||||
}
|
||||
|
||||
fn assert_refused(what: &str, body: &str, needles: &[&str]) {
|
||||
let (ok, err) = check(body);
|
||||
assert!(!ok, "{what}: compiled against Arcanum with default features, and must not");
|
||||
assert!(
|
||||
needles.iter().any(|n| err.contains(n)),
|
||||
"{what}: refused, but not for the expected reason ({needles:?}):\n{err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_the_release_signature_api_compiles_without_hazmat() {
|
||||
let (ok, err) = check(
|
||||
r#"
|
||||
let mut rng = Claimed(Counter(0));
|
||||
let sk = key();
|
||||
let sig = sk.sign(b"plan", &ctx(), &mut rng).unwrap();
|
||||
sk.verifying_key().verify(b"plan", &ctx(), &sig).unwrap();
|
||||
let vk = arcanum::sign::VerifyingKey::from_bytes(sk.verifying_key().as_bytes()).unwrap();
|
||||
let sig = arcanum::sign::Signature::from_bytes(sig.as_bytes()).unwrap();
|
||||
vk.verify(b"plan", &ctx(), &sig).unwrap();
|
||||
let stored = sk.to_bytes();
|
||||
let _again = arcanum::sign::SigningKey::from_bytes(stored.as_slice()).unwrap();
|
||||
let kem = arcanum::xwing::SecretKey::generate(&mut rng);
|
||||
let b = arcanum::sign::bind_kem_key(&sk, b"id", kem.public_key(), (1, 2), &mut rng).unwrap();
|
||||
arcanum::sign::verify_binding(&vk, b"id", kem.public_key(), (1, 2), 1, &b).unwrap();
|
||||
"#,
|
||||
);
|
||||
assert!(ok, "the control program must compile, or the harness is blind:\n{err}");
|
||||
}
|
||||
|
||||
/// Like QA A-33: randomness must be `CryptoRng`; a counter is refused everywhere it enters.
|
||||
#[test]
|
||||
fn a_non_crypto_rng_does_not_compile() {
|
||||
let calls = [
|
||||
("SigningKey::generate", "let _ = arcanum::sign::SigningKey::generate(&mut Counter(0));"),
|
||||
("SigningKey::sign", "let _ = key().sign(b\"m\", &ctx(), &mut Counter(0));"),
|
||||
(
|
||||
"bind_kem_key",
|
||||
"let kem = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap(); \
|
||||
let _ = arcanum::sign::bind_kem_key(&key(), b\"id\", kem.public_key(), (1, 2), &mut Counter(0));",
|
||||
),
|
||||
];
|
||||
for (what, body) in calls {
|
||||
assert_refused(what, body, &["CryptoRng"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// Like QA A-34: the raw RFC 10073 interface (any ctx, including empty) is `hazmat` only.
|
||||
#[test]
|
||||
fn the_raw_interface_is_not_reachable_without_hazmat() {
|
||||
let calls = [
|
||||
(
|
||||
"sign_composite_raw",
|
||||
"let _ = arcanum::sign::sign_composite_raw(&key(), b\"m\", b\"\", &mut Claimed(Counter(0)));",
|
||||
),
|
||||
(
|
||||
"verify_composite_raw",
|
||||
"let k = key(); let s = k.sign(b\"m\", &ctx(), &mut Claimed(Counter(0))).unwrap(); \
|
||||
let _ = arcanum::sign::verify_composite_raw(k.verifying_key(), b\"m\", b\"\", &s);",
|
||||
),
|
||||
];
|
||||
for (what, body) in calls {
|
||||
assert_refused(what, body, &["E0425"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// `ml-dsa` 0.1.2 makes `ExpandedSigningKey::sign_internal` (caller-chosen randomness) and
|
||||
/// `sign_mu_deterministic` (panics on failure) public, and its `Signer` trait signs with an
|
||||
/// empty context. None may be reachable through Arcanum: no re-export, no public field, no
|
||||
/// `Deref`/`AsRef` to the component keys, and an `AppContext` only from the Arcanum prefix.
|
||||
#[test]
|
||||
fn ml_dsa_internals_are_not_reachable() {
|
||||
let calls: [(&str, &str, &[&str]); 9] = [
|
||||
("re-export of ml_dsa", "use arcanum::ml_dsa;", &["E0432"]),
|
||||
("re-export in sign", "use arcanum::sign::ml_dsa;", &["E0432"]),
|
||||
("sign_internal through the key", "let _ = key().sign_internal(&[b\"m\"], &Default::default());", &["E0599"]),
|
||||
(
|
||||
"sign_mu_deterministic through the key",
|
||||
"let _ = key().sign_mu_deterministic(&Default::default());",
|
||||
&["E0599"],
|
||||
),
|
||||
("sign_deterministic through the key", "let _ = key().sign_deterministic(b\"m\", b\"\");", &["E0599"]),
|
||||
("a component key field", "let k = key(); let _ = &k.ml;", &["E0609", "E0616"]),
|
||||
("a foreign or empty context", "let _ = arcanum::sign::AppContext::from_raw(b\"\");", &["E0599"]),
|
||||
("cloning a signing key", "let k = key(); let _ = k.clone();", &["E0599"]),
|
||||
(
|
||||
"a label built at run time (QA S-09)",
|
||||
"let l = std::env::args().next().unwrap().into_bytes(); let _ = arcanum::sign::AppContext::new(&l);",
|
||||
&["E0597", "E0716"],
|
||||
),
|
||||
];
|
||||
for (what, body, needles) in calls {
|
||||
assert_refused(what, body, needles);
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_zeroize_on_drop<T: ZeroizeOnDrop + ?Sized>() {}
|
||||
|
||||
#[test]
|
||||
fn secret_types_are_zeroize_on_drop() {
|
||||
assert_zeroize_on_drop::<SigningKey>();
|
||||
// The component keys Arcanum holds: these bounds hold only with each crate's `zeroize` feature.
|
||||
assert_zeroize_on_drop::<ml_dsa::ExpandedSigningKey<ml_dsa::MlDsa65>>();
|
||||
assert_zeroize_on_drop::<ml_dsa::SigningKey<ml_dsa::MlDsa65>>();
|
||||
assert_zeroize_on_drop::<ed25519_dalek::SigningKey>();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_never_prints_key_material() {
|
||||
let sk = SigningKey::from_bytes(&[0xab; 64]).unwrap();
|
||||
let dbg = format!("{sk:?}");
|
||||
assert!(!dbg.contains("ab, ab") && !dbg.contains("abab") && !dbg.contains("171"), "{dbg}");
|
||||
let seeds = sk.to_bytes();
|
||||
assert_eq!(seeds.as_slice(), [0xab; 64].as_slice());
|
||||
let ctx = AppContext::new(b"debug").unwrap();
|
||||
let sig = sk.sign(b"m", &ctx, &mut rng(70)).unwrap();
|
||||
let _ = format!("{sig:?} {:?} {ctx:?}", sk.verifying_key());
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Mandatory test 6 (v0.2.0): malformed signature input gives typed errors, never a panic.
|
||||
//! Wrong lengths, weak and non-canonical Ed25519 keys, contexts of 0 and 256 bytes, an over-long
|
||||
//! key id, random bytes. The same entry points are fuzzed by fuzz/fuzz_targets/signatures.rs.
|
||||
|
||||
mod common;
|
||||
|
||||
use arcanum::sign::{
|
||||
self, AppContext, MAX_APP_LABEL_LEN, SIGNATURE_LEN, SIGNING_KEY_LEN, Signature, SigningKey, VERIFYING_KEY_LEN,
|
||||
VerifyingKey,
|
||||
};
|
||||
use arcanum::{Error, Input, xwing};
|
||||
use common::{hex, rng};
|
||||
use rand_core::Rng;
|
||||
|
||||
const LENGTHS: [usize; 14] = [0, 1, 31, 32, 33, 63, 64, 65, 1952, 1983, 1985, 3309, 3372, 3374];
|
||||
|
||||
#[test]
|
||||
fn wrong_lengths_are_typed_errors() {
|
||||
for len in LENGTHS {
|
||||
let b = vec![0u8; len];
|
||||
if len != VERIFYING_KEY_LEN {
|
||||
assert_eq!(
|
||||
VerifyingKey::from_bytes(&b).unwrap_err(),
|
||||
Error::InvalidLength { input: Input::VerifyingKey, expected: VERIFYING_KEY_LEN, actual: len }
|
||||
);
|
||||
}
|
||||
if len != SIGNATURE_LEN {
|
||||
assert_eq!(
|
||||
Signature::from_bytes(&b).unwrap_err(),
|
||||
Error::InvalidLength { input: Input::Signature, expected: SIGNATURE_LEN, actual: len }
|
||||
);
|
||||
}
|
||||
if len != SIGNING_KEY_LEN {
|
||||
assert_eq!(
|
||||
SigningKey::from_bytes(&b).unwrap_err(),
|
||||
Error::InvalidLength { input: Input::SigningKey, expected: SIGNING_KEY_LEN, actual: len }
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(SigningKey::from_bytes(&[7u8; SIGNING_KEY_LEN]).is_ok(), "any two 32-byte seeds are a key");
|
||||
assert!(Signature::from_bytes(&[0u8; SIGNATURE_LEN]).is_ok(), "any 3373 bytes parse; verify decides");
|
||||
}
|
||||
|
||||
/// The small-order points of edwards25519 (the 8-torsion), canonical and non-canonical
|
||||
/// encodings, and encodings of y >= p. All must be refused as an Ed25519 half.
|
||||
const WEAK_OR_NON_CANONICAL: [&str; 10] = [
|
||||
"0100000000000000000000000000000000000000000000000000000000000000", // identity
|
||||
"ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", // order 2
|
||||
"0000000000000000000000000000000000000000000000000000000000000000", // order 4
|
||||
"0000000000000000000000000000000000000000000000000000000000000080", // order 4
|
||||
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05", // order 8
|
||||
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85", // order 8
|
||||
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a", // order 8
|
||||
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa", // order 8
|
||||
"0100000000000000000000000000000000000000000000000000000000000080", // identity, sign bit set
|
||||
"eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", // y = p + 1 (non-canonical 1)
|
||||
];
|
||||
|
||||
fn with_ed_half(base: &[u8; VERIFYING_KEY_LEN], ed: &[u8]) -> [u8; VERIFYING_KEY_LEN] {
|
||||
let mut b = *base;
|
||||
b[VERIFYING_KEY_LEN - 32..].copy_from_slice(ed);
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weak_and_non_canonical_ed25519_keys_are_refused() {
|
||||
let base = *SigningKey::generate(&mut rng(60)).verifying_key().as_bytes();
|
||||
for h in WEAK_OR_NON_CANONICAL {
|
||||
let b = with_ed_half(&base, &hex(h));
|
||||
assert_eq!(VerifyingKey::from_bytes(&b).unwrap_err(), Error::InvalidVerifyingKey, "{h}");
|
||||
}
|
||||
// Every y >= p (19 values, sign bit clear and set) is a non-canonical encoding.
|
||||
for low in 0xedu8..=0xff {
|
||||
for top in [0x7f, 0xff] {
|
||||
let mut e = [0xffu8; 32];
|
||||
e[0] = low;
|
||||
e[31] = top;
|
||||
assert_eq!(VerifyingKey::from_bytes(&with_ed_half(&base, &e)).unwrap_err(), Error::InvalidVerifyingKey);
|
||||
}
|
||||
}
|
||||
// An honest key with its sign bit flipped is another valid point: it parses, but cannot verify.
|
||||
let sk = SigningKey::generate(&mut rng(61));
|
||||
let c = AppContext::new(b"t").unwrap();
|
||||
let sig = sk.sign(b"m", &c, &mut rng(62)).unwrap();
|
||||
let mut b = *sk.verifying_key().as_bytes();
|
||||
b[VERIFYING_KEY_LEN - 1] ^= 0x80;
|
||||
if let Ok(vk) = VerifyingKey::from_bytes(&b) {
|
||||
assert_eq!(vk.verify(b"m", &c, &sig), Err(Error::InvalidSignature));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contexts_of_the_wrong_length_are_typed_errors() {
|
||||
let sk = SigningKey::generate(&mut rng(63));
|
||||
let vk = sk.verifying_key();
|
||||
assert_eq!(MAX_APP_LABEL_LEN, 255 - b"domi/arcanum/v2/sig/app/".len());
|
||||
assert!(AppContext::new(&[b'x'; MAX_APP_LABEL_LEN]).is_ok());
|
||||
assert_eq!(AppContext::new(&[b'x'; MAX_APP_LABEL_LEN]).unwrap().as_bytes().len(), 255);
|
||||
assert_eq!(
|
||||
AppContext::new(&[b'x'; MAX_APP_LABEL_LEN + 1]).unwrap_err(),
|
||||
Error::TooLong { input: Input::Context, maximum: MAX_APP_LABEL_LEN, actual: MAX_APP_LABEL_LEN + 1 }
|
||||
);
|
||||
assert_eq!(AppContext::new(b"").unwrap_err(), Error::TooShort { input: Input::Context, minimum: 1, actual: 0 });
|
||||
// QA S-09: the constructor is a `const fn`, so a bad label can fail the consumer's build.
|
||||
const OK: Result<AppContext, Error> = AppContext::new(b"const");
|
||||
const EMPTY: Result<AppContext, Error> = AppContext::new(b"");
|
||||
assert_eq!(OK.unwrap().as_bytes(), b"domi/arcanum/v2/sig/app/const");
|
||||
assert!(EMPTY.is_err());
|
||||
|
||||
// The raw RFC interface: 255 bytes is the most, 256 is a typed error (sign and verify).
|
||||
let sig = sign::sign_composite_raw(&sk, b"m", &[1; 255], &mut rng(64)).unwrap();
|
||||
assert_eq!(sign::verify_composite_raw(vk, b"m", &[1; 255], &sig), Ok(()));
|
||||
let too_long = Error::TooLong { input: Input::Context, maximum: 255, actual: 256 };
|
||||
assert_eq!(sign::sign_composite_raw(&sk, b"m", &[1; 256], &mut rng(65)).unwrap_err(), too_long);
|
||||
assert_eq!(sign::verify_composite_raw(vk, b"m", &[1; 256], &sig), Err(too_long));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_over_long_key_id_is_a_typed_error() {
|
||||
let mut r = rng(66);
|
||||
let sk = SigningKey::generate(&mut r);
|
||||
let kem = xwing::SecretKey::generate(&mut r);
|
||||
let id = vec![0u8; 65_536];
|
||||
let err = Error::TooLong { input: Input::KeyId, maximum: 65_535, actual: 65_536 };
|
||||
assert_eq!(sign::bind_kem_key(&sk, &id, kem.public_key(), (0, 1), &mut r), Err(err.clone()));
|
||||
let sig = sign::bind_kem_key(&sk, &id[..65_535], kem.public_key(), (0, 1), &mut r).unwrap();
|
||||
assert_eq!(sign::verify_binding(sk.verifying_key(), &id[..65_535], kem.public_key(), (0, 1), 0, &sig), Ok(()));
|
||||
assert_eq!(sign::verify_binding(sk.verifying_key(), &id, kem.public_key(), (0, 1), 0, &sig), Err(err));
|
||||
// The empty id is allowed (a key bound to "no name" is still bound to this signer).
|
||||
let sig = sign::bind_kem_key(&sk, b"", kem.public_key(), (0, 1), &mut r).unwrap();
|
||||
assert_eq!(sign::verify_binding(sk.verifying_key(), b"", kem.public_key(), (0, 1), 1, &sig), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_bytes_never_panic() {
|
||||
let mut r = rng(67);
|
||||
let sk = SigningKey::generate(&mut r);
|
||||
let c = AppContext::new(b"random").unwrap();
|
||||
let good = sk.sign(b"m", &c, &mut r).unwrap();
|
||||
let kem = xwing::SecretKey::generate(&mut r);
|
||||
for round in 0..256 {
|
||||
let len = [VERIFYING_KEY_LEN, SIGNATURE_LEN, SIGNING_KEY_LEN, 0, 17][round % 5];
|
||||
let mut buf = vec![0u8; len];
|
||||
r.fill_bytes(&mut buf);
|
||||
if let Ok(vk) = VerifyingKey::from_bytes(&buf) {
|
||||
assert!(vk.verify(b"m", &c, &good).is_err());
|
||||
assert!(sign::verify_binding(&vk, b"id", kem.public_key(), (0, 9), 1, &good).is_err());
|
||||
}
|
||||
if let Ok(sig) = Signature::from_bytes(&buf) {
|
||||
assert_eq!(sk.verifying_key().verify(b"m", &c, &sig), Err(Error::InvalidSignature));
|
||||
let _ = sign::verify_composite_raw(sk.verifying_key(), &buf, &buf[..len.min(255)], &sig);
|
||||
}
|
||||
if let Ok(k) = SigningKey::from_bytes(&buf) {
|
||||
let sig = k.sign(&buf, &c, &mut r).unwrap();
|
||||
assert_eq!(k.verifying_key().verify(&buf, &c, &sig), Ok(()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// QA S-05 (their `qa_s07`, inverted): an ML-DSA-65 public key with t1 = 0 is the ML-DSA analogue
|
||||
/// of a weak Ed25519 key. The component crate accepts it, and its ML-DSA half can be computed by
|
||||
/// anyone, with no secret (s1 = s2 = t0 = 0); Arcanum refuses the key at parse.
|
||||
#[test]
|
||||
#[allow(deprecated)]
|
||||
fn an_ml_dsa_key_with_zero_t1_is_refused() {
|
||||
use ml_dsa::common::array::Array;
|
||||
use shake::Update as _;
|
||||
|
||||
let rho = [0x5au8; 32];
|
||||
let mut ml_pk = rho.to_vec();
|
||||
ml_pk.extend_from_slice(&[0u8; 1920]); // t1 = 0
|
||||
let ed = ed25519_dalek::SigningKey::from_bytes(&[0x22; 32]); // a throwaway Ed25519 key
|
||||
let mut pk = ml_pk.clone();
|
||||
pk.extend_from_slice(ed.verifying_key().as_bytes());
|
||||
assert_eq!(VerifyingKey::from_bytes(&pk).unwrap_err(), Error::InvalidVerifyingKey);
|
||||
|
||||
// Control: one non-zero t1 byte, anywhere, and the key parses.
|
||||
for i in [32, 1000, 1951] {
|
||||
let mut p = pk.clone();
|
||||
p[i] = 1;
|
||||
assert!(VerifyingKey::from_bytes(&p).is_ok(), "t1 byte {i} set");
|
||||
}
|
||||
// rho alone may be anything, including zero: only t1 = 0 is weak.
|
||||
let mut p = pk.clone();
|
||||
p[..32].fill(0);
|
||||
p[100] = 1;
|
||||
assert!(VerifyingKey::from_bytes(&p).is_ok());
|
||||
|
||||
// Why: with the component crate alone, a secret-free key signs for this public key. The expanded
|
||||
// key packs eta - 0 = 4 into 4 bits (0x44 per byte) for s1 and s2, and 2^12 - 0 into 13 bits for
|
||||
// t0; K is public (zero) and tr is unused by sign_mu.
|
||||
let mut sk = rho.to_vec();
|
||||
sk.extend_from_slice(&[0u8; 32 + 64]);
|
||||
sk.extend(std::iter::repeat_n(0x44u8, 640 + 768));
|
||||
let mut t0 = vec![0u8; 2496];
|
||||
for i in 0..(6 * 256) {
|
||||
let bit = 13 * i + 12;
|
||||
t0[bit / 8] |= 1 << (bit % 8);
|
||||
}
|
||||
sk.extend_from_slice(&t0);
|
||||
assert_eq!(sk.len(), 4032);
|
||||
let ml_sk = ml_dsa::ExpandedSigningKey::<ml_dsa::MlDsa65>::from_expanded(&Array::try_from(sk.as_slice()).unwrap());
|
||||
let ml_vk = ml_dsa::VerifyingKey::<ml_dsa::MlDsa65>::decode(&Array::try_from(ml_pk.as_slice()).unwrap());
|
||||
let mu = ml_vk
|
||||
.compute_mu(
|
||||
|h| {
|
||||
h.update(b"any message at all");
|
||||
Ok(())
|
||||
},
|
||||
b"",
|
||||
)
|
||||
.unwrap();
|
||||
let half = ml_sk.sign_mu_randomized(&mu, &mut rng(68)).unwrap();
|
||||
assert!(ml_vk.verify_mu(&mu, &half), "the component crate accepts a secret-free signature");
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//! QA S-11 (PR #2 review): how much stack building a signing key and signing need. ML-DSA-65 keeps
|
||||
//! large polynomial vectors on the stack; a thread that is too small aborts the process with a
|
||||
//! stack overflow, which is not an `Error` a caller can handle. The figure is documented on
|
||||
//! `SigningKey`: at least 256 KiB in a release build (128 KiB overflows, QA measured).
|
||||
//!
|
||||
//! The pinned test runs in release builds only (debug frames are larger). The others are
|
||||
//! measurements, run by hand one at a time, because an overflow aborts the whole test binary:
|
||||
//! `cargo test --test sig_stack -- --ignored --exact on_a_<n>_kib_stack`.
|
||||
|
||||
mod common;
|
||||
|
||||
use arcanum::sign::{AppContext, SigningKey};
|
||||
use common::rng;
|
||||
|
||||
fn generate_sign_verify_on(kib: usize) {
|
||||
std::thread::Builder::new()
|
||||
.stack_size(kib * 1024)
|
||||
.spawn(|| {
|
||||
let sk = SigningKey::generate(&mut rng(80));
|
||||
let ctx = AppContext::new(b"stack").unwrap();
|
||||
let sig = sk.sign(b"m", &ctx, &mut rng(81)).unwrap();
|
||||
assert_eq!(sk.verifying_key().verify(b"m", &ctx, &sig), Ok(()));
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(debug_assertions, ignore = "the documented 256 KiB is for release builds")]
|
||||
fn generate_and_sign_fit_in_256_kib_of_stack() {
|
||||
generate_sign_verify_on(256);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "measurement: may abort the test binary"]
|
||||
fn on_a_128_kib_stack() {
|
||||
generate_sign_verify_on(128);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "measurement: may abort the test binary"]
|
||||
fn on_a_256_kib_stack() {
|
||||
generate_sign_verify_on(256);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "measurement: may abort the test binary"]
|
||||
fn on_a_512_kib_stack() {
|
||||
generate_sign_verify_on(512);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "measurement: may abort the test binary"]
|
||||
fn on_a_1024_kib_stack() {
|
||||
generate_sign_verify_on(1024);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
# Known-answer vector sources
|
||||
|
||||
Every file here is kept byte-for-byte as published (`.gitattributes` marks the folder `-text`).
|
||||
Every v0.1.0 file here is kept byte-for-byte as published; v0.2.0 adds three subsets and one
|
||||
extraction, each made by a script in this folder (below). `.gitattributes` marks the folder `-text`.
|
||||
The tests check each file's sha256 before using it, so a changed file fails the test instead of
|
||||
silently changing what is verified. Fetched 2026-11-25.
|
||||
|
||||
@@ -18,6 +19,50 @@ URLs:
|
||||
|
||||
Only the ML-KEM-768 groups of the ACVP files are used (the files also hold 512 and 1024).
|
||||
|
||||
## v0.2.0: signatures (ML-DSA-65, Ed25519, the RFC 10073 composite)
|
||||
|
||||
Fetched 2026-11-25 with curl from `raw.githubusercontent.com` (RFC 8032 from `www.rfc-editor.org`),
|
||||
each into its own empty directory, and handled as data. Every git blob id below matches the GitHub
|
||||
API tree listing of the named commit. The tests check the sha256 of the file **in this folder**.
|
||||
|
||||
**Kept whole, byte for byte** (each under about 1 MB):
|
||||
|
||||
| File | sha256 (= the original) | Source |
|
||||
|:--|:--|:--|
|
||||
| `acvp-ml-dsa-keyGen-FIPS204-internalProjection.json` | `e67ee6540d40e11506c3c4e3b1f79fc1cefcd49820db99fc61f87cc8ba463baf` | NIST ACVP-Server `gen-val/json-files/ML-DSA-keyGen-FIPS204/internalProjection.json` at `2972def23bf9f3680c2c531561ed9bdd0f1086ad` (2026-07-20); 882,437 bytes, blob `ebf2104da140b725675aea4cc47676c0536421f7` |
|
||||
| `wycheproof-ed25519_test.json` | `752d2ea7d7c6cf4736381b6cbacb61f8182b126ab7cd9b058f00c50084975536` | C2SP Wycheproof `testvectors_v1/ed25519_test.json` at `20b256949ea8f21a11375619b1825027ca0668bd` (2026-10-12); 126,699 bytes, blob `42d44cd7eca6003c7de611b6487c9cc57a124b38` |
|
||||
| `wycheproof-mldsa_65_sign_seed_test.json` | `e26b2bb9ab8d45ed570ba6828c7e40b6fa3e1545bb8bc2c449c77531760133e0` | Wycheproof `testvectors_v1/mldsa_65_sign_seed_test.json` at the same commit; 886,331 bytes, blob `ff302e20c0b847e66fdcc7444cd63fc1cd7bf634` |
|
||||
|
||||
**Reduced subsets** (the original is larger than about 1 MB, or holds other algorithms). Made by
|
||||
`make_subsets.py` in this folder, which refuses an original whose sha256 is not the one below,
|
||||
keeps every selected test case and group header unchanged (whole cases and whole groups are
|
||||
dropped, never fields), and writes two-space-indented JSON with LF endings; two runs gave identical
|
||||
bytes. Command: `python -I make_subsets.py --acvp-siggen ... --acvp-sigver ... --wycheproof-mldsa-verify ... --composite ... --out .`
|
||||
|
||||
| File here (sha256) | Original (sha256, size, blob) | Selection |
|
||||
|:--|:--|:--|
|
||||
| `acvp-ml-dsa-sigGen-FIPS204-internalProjection.subset.json` (`ca1f1697d78b2280d854bbe0f8e86d3601695013f14e7bb4ce0604bc80ed2b4e`) | ACVP-Server `gen-val/json-files/ML-DSA-sigGen-FIPS204/internalProjection.json` at `2972def23bf9f3680c2c531561ed9bdd0f1086ad`: `72dcaf5f69853ca267ccd16af9cb40949786aca0fcfbf05d1ebeba132b93af22`, 8,971,659 bytes, blob `c090942249958e2071d56bf458b19e31256ded3e` | ML-DSA-65 groups without HashML-DSA (`preHash`): tgId 3, 9, 10 (deterministic) and 15, 21, 22 (hedged, with `rnd`); the first 3 cases of each by tcId (31-33, 121-123, 136-138, 211-213, 301-303, 316-318), 18 cases |
|
||||
| `acvp-ml-dsa-sigVer-FIPS204-internalProjection.subset.json` (`d005dfeee9039f751299a6430fdac509b97ad9ab7d25b0b502dc9a2b59b7fb0c`) | ACVP-Server `gen-val/json-files/ML-DSA-sigVer-FIPS204/internalProjection.json` at **`a7f283cdc87d2d6dd93c1bac59e5622c5f9f8324`** (2026-07-31, after the ModifyZ correction): `47cdd6314c7f746d02421ffcba89d4dbc7bb875ac49e07a029fdfc26fba55437`, 4,533,178 bytes, blob `4c8caf12220e44dfa711fefe20e0285aaad844be` | ML-DSA-65 groups without `preHash`: tgId 3, 9, 10; the first case of each (testPassed, reason) pair, so one valid case and one of each of the four modifications (message, commitment, z, hint) per group, 15 cases |
|
||||
| `wycheproof-mldsa_65_verify_test.subset.json` (`47fc788c0913dc41cfd0ef5bc9ed44c779a6bdeeb8b3700077fd572527c33870`) | Wycheproof `testvectors_v1/mldsa_65_verify_test.json` at `20b256949ea8f21a11375619b1825027ca0668bd`: `1ca235f61928421a173a171780beb00264ae9155dc33c52a11e1766cc7979034`, 1,664,284 bytes, blob `fa871a3c8c76b0cf871879243ad34fa2cbd79000` | All 25 groups; in each, at most 4 cases per (result, set of flags), first by tcId: 70 of 210 cases, every flag kept (most of the dropped ones are 40 `ManySteps` valid signatures and 44 `InfinityNormViolation` cases); `numberOfTests` is updated to 70 |
|
||||
| `composite-sigs-testvectors-MLDSA65-Ed25519.subset.json` (`33311f63d2c5a21d5dd4b05eb864de38bd7572108b38de713a40312d2b893b34`) | `lamps-wg/draft-composite-sigs` `src/testvectors.json` at `f0627ab34acfe1aee0abce4bee91ed2b577eab76` (2026-01-07): `a60f697f9fd94c3cd5e4501a40c4396d9a9ffc7cf0f8a1ddd87dedbb46a7abf0`, 491,883 bytes, blob `eac3df25ca915882d3bcb3062835555787b02f5a` | The top-level `m` and `ctx`, and only the `tcId = "id-MLDSA65-Ed25519-SHA512"` entry of `tests` (unchanged, with its `x5c`) |
|
||||
|
||||
**Extracted from a text RFC** by `extract_rfc8032.py` in this folder (it checks the RFC's sha256,
|
||||
skips page breaks, joins the hex lines and checks each stated length):
|
||||
|
||||
| File here (sha256) | Original | Selection |
|
||||
|:--|:--|:--|
|
||||
| `rfc8032-7.1-ed25519.json` (`fad8e499cdc3e0324a5b4a93cdbabb33f8aed1df73ecacfdb364f433b0fdf12b`) | <https://www.rfc-editor.org/rfc/rfc8032.txt>: `ed63657ff389301282b169b0abde9b5dd2c7e4d524fdfa5da6ff3094fc93c4c3`, 103,210 bytes | §7.1, the five Ed25519 vectors: TEST 1, 2, 3, 1024 and SHA(abc) |
|
||||
|
||||
URLs, with `<commit>` as in the tables:
|
||||
|
||||
- `https://raw.githubusercontent.com/usnistgov/ACVP-Server/<commit>/gen-val/json-files/ML-DSA-{keyGen,sigGen,sigVer}-FIPS204/internalProjection.json`
|
||||
- `https://raw.githubusercontent.com/C2SP/wycheproof/<commit>/testvectors_v1/{ed25519_test,mldsa_65_sign_seed_test,mldsa_65_verify_test}.json`
|
||||
- `https://raw.githubusercontent.com/lamps-wg/draft-composite-sigs/<commit>/src/testvectors.json`
|
||||
|
||||
Not used: the HashML-DSA (`preHash`) groups (Arcanum signs pure ML-DSA only); the ML-DSA-44 and
|
||||
ML-DSA-87 groups; the full sigGen/sigVer/verify files (their sha256 above lets anyone check the
|
||||
subsets against them by rerunning the script).
|
||||
|
||||
## Vectors kept in test source
|
||||
|
||||
| Test | Source |
|
||||
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,73 @@
|
||||
"""Extract the five Ed25519 test vectors of RFC 8032 section 7.1 into JSON.
|
||||
|
||||
Usage: python -I extract_rfc8032.py PATH/rfc8032.txt OUT.json
|
||||
|
||||
PATH/rfc8032.txt is https://www.rfc-editor.org/rfc/rfc8032.txt, unchanged (its sha256 is pinned
|
||||
below and in SOURCES.md). Page breaks are skipped; every hex field is joined as printed, and the
|
||||
message length is checked against the "(length N bytes)" the RFC states.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
|
||||
PINNED = "ed63657ff389301282b169b0abde9b5dd2c7e4d524fdfa5da6ff3094fc93c4c3"
|
||||
FIELDS = {"SECRET KEY:": "secret_key", "PUBLIC KEY:": "public_key", "SIGNATURE:": "signature"}
|
||||
|
||||
|
||||
def main():
|
||||
src, out = sys.argv[1], sys.argv[2]
|
||||
raw = open(src, "rb").read()
|
||||
got = hashlib.sha256(raw).hexdigest()
|
||||
if got != PINNED:
|
||||
raise SystemExit(f"{src}: sha256 {got} is not the pinned {PINNED}")
|
||||
lines = raw.decode("ascii").splitlines()
|
||||
start = lines.index("7.1. Test Vectors for Ed25519")
|
||||
end = lines.index("7.2. Test Vectors for Ed25519ctx")
|
||||
tests, cur, field, declared = [], None, None, None
|
||||
for line in lines[start:end]:
|
||||
s = line.strip()
|
||||
if s.startswith("Josefsson & Liusvaara") or s.startswith("RFC 8032 ") or s == "\f" or s == "":
|
||||
continue
|
||||
if s.startswith("-----TEST "):
|
||||
cur = {"name": s[len("-----TEST "):], "secret_key": "", "public_key": "", "message": "",
|
||||
"signature": ""}
|
||||
tests.append(cur)
|
||||
field = None
|
||||
continue
|
||||
if cur is None or s == "-----":
|
||||
continue
|
||||
m = re.fullmatch(r"MESSAGE \(length (\d+) bytes?\):", s)
|
||||
if m:
|
||||
field, declared = "message", int(m.group(1))
|
||||
cur["_declared"] = declared
|
||||
continue
|
||||
if s in FIELDS:
|
||||
field = FIELDS[s]
|
||||
continue
|
||||
if s in ("ALGORITHM:", "Ed25519"):
|
||||
field = None
|
||||
continue
|
||||
if field and re.fullmatch(r"[0-9a-f]+", s):
|
||||
cur[field] += s
|
||||
continue
|
||||
raise SystemExit(f"unexpected line in section 7.1: {line!r}")
|
||||
for t in tests:
|
||||
n = t.pop("_declared")
|
||||
if len(t["message"]) != 2 * n:
|
||||
raise SystemExit(f"TEST {t['name']}: message is {len(t['message']) // 2} bytes, RFC says {n}")
|
||||
for k, size in (("secret_key", 32), ("public_key", 32), ("signature", 64)):
|
||||
if len(t[k]) != 2 * size:
|
||||
raise SystemExit(f"TEST {t['name']}: {k} is not {size} bytes")
|
||||
if [t["name"] for t in tests] != ["1", "2", "3", "1024", "SHA(abc)"]:
|
||||
raise SystemExit(f"unexpected tests: {[t['name'] for t in tests]}")
|
||||
doc = {"source": "RFC 8032 section 7.1, https://www.rfc-editor.org/rfc/rfc8032.txt", "tests": tests}
|
||||
with open(out, "w", encoding="utf-8", newline="\n") as f:
|
||||
json.dump(doc, f, indent=2)
|
||||
f.write("\n")
|
||||
print(f"{out}: {len(tests)} vectors")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Reduce the large official vector files to the subsets kept in this folder.
|
||||
|
||||
Usage (each argument is the path to the ORIGINAL file, downloaded unchanged from the URL and
|
||||
commit listed in SOURCES.md):
|
||||
|
||||
python -I make_subsets.py --acvp-siggen PATH --acvp-sigver PATH \
|
||||
--wycheproof-mldsa-verify PATH --composite PATH --out DIR
|
||||
|
||||
The script refuses an original whose sha256 is not the pinned one, keeps every field of every
|
||||
test case it selects unchanged (only whole test cases and whole groups are dropped), and writes
|
||||
JSON with two-space indentation and LF line endings. Running it twice gives identical bytes.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
|
||||
PINNED = {
|
||||
"acvp_siggen": "72dcaf5f69853ca267ccd16af9cb40949786aca0fcfbf05d1ebeba132b93af22",
|
||||
"acvp_sigver": "47cdd6314c7f746d02421ffcba89d4dbc7bb875ac49e07a029fdfc26fba55437",
|
||||
"wycheproof_mldsa_verify": "1ca235f61928421a173a171780beb00264ae9155dc33c52a11e1766cc7979034",
|
||||
"composite": "a60f697f9fd94c3cd5e4501a40c4396d9a9ffc7cf0f8a1ddd87dedbb46a7abf0",
|
||||
}
|
||||
|
||||
# ACVP sigGen: ML-DSA-65 only, no HashML-DSA (preHash) groups, the first N cases of each group.
|
||||
SIGGEN_PER_GROUP = 3
|
||||
# Wycheproof verify: per group, at most N cases for each (result, set of flags).
|
||||
WYCHEPROOF_PER_KIND = 4
|
||||
COMPOSITE_ENTRY = "id-MLDSA65-Ed25519-SHA512"
|
||||
|
||||
|
||||
def load(path, key):
|
||||
with open(path, "rb") as f:
|
||||
raw = f.read()
|
||||
got = hashlib.sha256(raw).hexdigest()
|
||||
if got != PINNED[key]:
|
||||
raise SystemExit(f"{path}: sha256 {got} is not the pinned {PINNED[key]}")
|
||||
return json.loads(raw.decode("utf-8"))
|
||||
|
||||
|
||||
def write(out_dir, name, obj):
|
||||
path = os.path.join(out_dir, name)
|
||||
with open(path, "w", encoding="utf-8", newline="\n") as f:
|
||||
json.dump(obj, f, indent=2, ensure_ascii=False)
|
||||
f.write("\n")
|
||||
n = sum(len(g["tests"]) for g in obj["testGroups"]) if "testGroups" in obj else len(obj["tests"])
|
||||
print(f"{name}: {n} cases")
|
||||
|
||||
|
||||
def acvp_siggen(d):
|
||||
groups = []
|
||||
for g in d["testGroups"]:
|
||||
if g["parameterSet"] != "ML-DSA-65" or g["preHash"] == "preHash":
|
||||
continue
|
||||
g = dict(g)
|
||||
g["tests"] = sorted(g["tests"], key=lambda t: t["tcId"])[:SIGGEN_PER_GROUP]
|
||||
groups.append(g)
|
||||
d = dict(d)
|
||||
d["testGroups"] = groups
|
||||
return d
|
||||
|
||||
|
||||
def acvp_sigver(d):
|
||||
# One case for each (testPassed, reason) in each ML-DSA-65 non-preHash group.
|
||||
groups = []
|
||||
for g in d["testGroups"]:
|
||||
if g["parameterSet"] != "ML-DSA-65" or g["preHash"] == "preHash":
|
||||
continue
|
||||
seen = set()
|
||||
kept = []
|
||||
for t in sorted(g["tests"], key=lambda t: t["tcId"]):
|
||||
kind = (t["testPassed"], t.get("reason"))
|
||||
if kind not in seen:
|
||||
seen.add(kind)
|
||||
kept.append(t)
|
||||
g = dict(g)
|
||||
g["tests"] = kept
|
||||
groups.append(g)
|
||||
d = dict(d)
|
||||
d["testGroups"] = groups
|
||||
return d
|
||||
|
||||
|
||||
def wycheproof_verify(d):
|
||||
groups = []
|
||||
for g in d["testGroups"]:
|
||||
count = collections.Counter()
|
||||
kept = []
|
||||
for t in sorted(g["tests"], key=lambda t: t["tcId"]):
|
||||
kind = (t["result"], frozenset(t.get("flags", [])))
|
||||
if count[kind] < WYCHEPROOF_PER_KIND:
|
||||
count[kind] += 1
|
||||
kept.append(t)
|
||||
g = dict(g)
|
||||
g["tests"] = kept
|
||||
groups.append(g)
|
||||
d = dict(d)
|
||||
d["testGroups"] = groups
|
||||
d["numberOfTests"] = sum(len(g["tests"]) for g in groups)
|
||||
return d
|
||||
|
||||
|
||||
def composite(d):
|
||||
entries = [t for t in d["tests"] if t["tcId"] == COMPOSITE_ENTRY]
|
||||
if len(entries) != 1:
|
||||
raise SystemExit(f"expected exactly one {COMPOSITE_ENTRY} entry, found {len(entries)}")
|
||||
return {"m": d["m"], "ctx": d["ctx"], "tests": entries}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--acvp-siggen", required=True)
|
||||
p.add_argument("--acvp-sigver", required=True)
|
||||
p.add_argument("--wycheproof-mldsa-verify", required=True)
|
||||
p.add_argument("--composite", required=True)
|
||||
p.add_argument("--out", required=True)
|
||||
a = p.parse_args()
|
||||
write(a.out, "acvp-ml-dsa-sigGen-FIPS204-internalProjection.subset.json",
|
||||
acvp_siggen(load(a.acvp_siggen, "acvp_siggen")))
|
||||
write(a.out, "acvp-ml-dsa-sigVer-FIPS204-internalProjection.subset.json",
|
||||
acvp_sigver(load(a.acvp_sigver, "acvp_sigver")))
|
||||
write(a.out, "wycheproof-mldsa_65_verify_test.subset.json",
|
||||
wycheproof_verify(load(a.wycheproof_mldsa_verify, "wycheproof_mldsa_verify")))
|
||||
write(a.out, "composite-sigs-testvectors-MLDSA65-Ed25519.subset.json",
|
||||
composite(load(a.composite, "composite")))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"source": "RFC 8032 section 7.1, https://www.rfc-editor.org/rfc/rfc8032.txt",
|
||||
"tests": [
|
||||
{
|
||||
"name": "1",
|
||||
"secret_key": "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
|
||||
"public_key": "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a",
|
||||
"message": "",
|
||||
"signature": "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"
|
||||
},
|
||||
{
|
||||
"name": "2",
|
||||
"secret_key": "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb",
|
||||
"public_key": "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c",
|
||||
"message": "72",
|
||||
"signature": "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"
|
||||
},
|
||||
{
|
||||
"name": "3",
|
||||
"secret_key": "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7",
|
||||
"public_key": "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025",
|
||||
"message": "af82",
|
||||
"signature": "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a"
|
||||
},
|
||||
{
|
||||
"name": "1024",
|
||||
"secret_key": "f5e5767cf153319517630f226876b86c8160cc583bc013744c6bf255f5cc0ee5",
|
||||
"public_key": "278117fc144c72340f67d0f2316e8386ceffbf2b2428c9c51fef7c597f1d426e",
|
||||
"message": "08b8b2b733424243760fe426a4b54908632110a66c2f6591eabd3345e3e4eb98fa6e264bf09efe12ee50f8f54e9f77b1e355f6c50544e23fb1433ddf73be84d879de7c0046dc4996d9e773f4bc9efe5738829adb26c81b37c93a1b270b20329d658675fc6ea534e0810a4432826bf58c941efb65d57a338bbd2e26640f89ffbc1a858efcb8550ee3a5e1998bd177e93a7363c344fe6b199ee5d02e82d522c4feba15452f80288a821a579116ec6dad2b3b310da903401aa62100ab5d1a36553e06203b33890cc9b832f79ef80560ccb9a39ce767967ed628c6ad573cb116dbefefd75499da96bd68a8a97b928a8bbc103b6621fcde2beca1231d206be6cd9ec7aff6f6c94fcd7204ed3455c68c83f4a41da4af2b74ef5c53f1d8ac70bdcb7ed185ce81bd84359d44254d95629e9855a94a7c1958d1f8ada5d0532ed8a5aa3fb2d17ba70eb6248e594e1a2297acbbb39d502f1a8c6eb6f1ce22b3de1a1f40cc24554119a831a9aad6079cad88425de6bde1a9187ebb6092cf67bf2b13fd65f27088d78b7e883c8759d2c4f5c65adb7553878ad575f9fad878e80a0c9ba63bcbcc2732e69485bbc9c90bfbd62481d9089beccf80cfe2df16a2cf65bd92dd597b0707e0917af48bbb75fed413d238f5555a7a569d80c3414a8d0859dc65a46128bab27af87a71314f318c782b23ebfe808b82b0ce26401d2e22f04d83d1255dc51addd3b75a2b1ae0784504df543af8969be3ea7082ff7fc9888c144da2af58429ec96031dbcad3dad9af0dcbaaaf268cb8fcffead94f3c7ca495e056a9b47acdb751fb73e666c6c655ade8297297d07ad1ba5e43f1bca32301651339e22904cc8c42f58c30c04aafdb038dda0847dd988dcda6f3bfd15c4b4c4525004aa06eeff8ca61783aacec57fb3d1f92b0fe2fd1a85f6724517b65e614ad6808d6f6ee34dff7310fdc82aebfd904b01e1dc54b2927094b2db68d6f903b68401adebf5a7e08d78ff4ef5d63653a65040cf9bfd4aca7984a74d37145986780fc0b16ac451649de6188a7dbdf191f64b5fc5e2ab47b57f7f7276cd419c17a3ca8e1b939ae49e488acba6b965610b5480109c8b17b80e1b7b750dfc7598d5d5011fd2dcc5600a32ef5b52a1ecc820e308aa342721aac0943bf6686b64b2579376504ccc493d97e6aed3fb0f9cd71a43dd497f01f17c0e2cb3797aa2a2f256656168e6c496afc5fb93246f6b1116398a346f1a641f3b041e989f7914f90cc2c7fff357876e506b50d334ba77c225bc307ba537152f3f1610e4eafe595f6d9d90d11faa933a15ef1369546868a7f3a45a96768d40fd9d03412c091c6315cf4fde7cb68606937380db2eaaa707b4c4185c32eddcdd306705e4dc1ffc872eeee475a64dfac86aba41c0618983f8741c5ef68d3a101e8a3b8cac60c905c15fc910840b94c00a0b9d0",
|
||||
"signature": "0aab4c900501b3e24d7cdf4663326a3a87df5e4843b2cbdb67cbf6e460fec350aa5371b1508f9f4528ecea23c436d94b5e8fcd4f681e30a6ac00a9704a188a03"
|
||||
},
|
||||
{
|
||||
"name": "SHA(abc)",
|
||||
"secret_key": "833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42",
|
||||
"public_key": "ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf",
|
||||
"message": "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
|
||||
"signature": "dc2a4459e7369633a52b1bf277839a00201009a3efbf3ecb69bea2186c26b58909351fc9ac90b3ecfdfbc7c66431e0303dca179c138ac17ad9bef1177331a704"
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Generated
+95
-1
@@ -14,11 +14,13 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "arcanum"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"chacha20poly1305",
|
||||
"ed25519-dalek",
|
||||
"hkdf",
|
||||
"hmac",
|
||||
"ml-dsa",
|
||||
"ml-kem",
|
||||
"rand_core",
|
||||
"sha2",
|
||||
@@ -34,6 +36,7 @@ version = "0.0.0"
|
||||
dependencies = [
|
||||
"arcanum",
|
||||
"chacha20",
|
||||
"ml-dsa",
|
||||
"rand_core",
|
||||
"zeroize",
|
||||
]
|
||||
@@ -44,6 +47,12 @@ version = "1.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.12.1"
|
||||
@@ -103,6 +112,12 @@ version = "0.5.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
|
||||
|
||||
[[package]]
|
||||
name = "const-oid"
|
||||
version = "0.10.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.3.1"
|
||||
@@ -140,6 +155,7 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"curve25519-dalek-derive",
|
||||
"digest",
|
||||
"fiat-crypto",
|
||||
"rustc_version",
|
||||
"subtle",
|
||||
@@ -157,6 +173,16 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "der"
|
||||
version = "0.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004"
|
||||
dependencies = [
|
||||
"const-oid",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.11.3"
|
||||
@@ -169,6 +195,28 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
|
||||
dependencies = [
|
||||
"signature",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ed25519-dalek"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
|
||||
dependencies = [
|
||||
"curve25519-dalek",
|
||||
"ed25519",
|
||||
"sha2",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fiat-crypto"
|
||||
version = "0.3.0"
|
||||
@@ -239,6 +287,22 @@ version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "ml-dsa"
|
||||
version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6f6d49c3f3f0e10e18ca975ffda66f8da0ec36521c1d911adcbc521bf0743f5c"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"ctutils",
|
||||
"hybrid-array",
|
||||
"module-lattice",
|
||||
"pkcs8",
|
||||
"shake",
|
||||
"signature",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ml-kem"
|
||||
version = "0.3.4"
|
||||
@@ -275,6 +339,16 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkcs8"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
|
||||
dependencies = [
|
||||
"der",
|
||||
"spki",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "poly1305"
|
||||
version = "0.9.1"
|
||||
@@ -357,6 +431,26 @@ dependencies = [
|
||||
"sponge-cursor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signature"
|
||||
version = "3.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "spki"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"der",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sponge-cursor"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -11,6 +11,9 @@ arcanum = { path = ".." }
|
||||
zeroize = { version = "1.8", default-features = false, features = ["alloc"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# QA S-04: the probe computes the canary key's expanded ML-DSA key to watch its bytes. Same version
|
||||
# and features as Arcanum's own dependency.
|
||||
ml-dsa = { version = "=0.1.2", default-features = false, features = ["alloc", "rand_core", "zeroize"] }
|
||||
chacha20 = { version = "0.10", default-features = false, features = ["rng"] }
|
||||
rand_core = { version = "0.10", default-features = false }
|
||||
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
//! QA A-29: a global allocator that, in `dealloc`, scans every block for a 32-byte canary before
|
||||
//! handing it back to the system allocator. If a secret built from the canary is freed without
|
||||
//! being wiped first, [`seen`] turns true.
|
||||
//! being wiped first, [`disarm`] returns true.
|
||||
//!
|
||||
//! QA S-04 (PR #2): secrets *derived* from the canary never contain it, so up to [`MAX_PATTERNS`]
|
||||
//! further 32-byte patterns can be watched too ([`watch`]), e.g. bytes of the expanded ML-DSA key.
|
||||
//!
|
||||
//! `unsafe` lives here only, in a crate that is not published and that nothing depends on;
|
||||
//! Arcanum itself keeps `#![forbid(unsafe_code)]`. Limits: the probe sees the heap only. Stack
|
||||
//! copies made by moves are invisible to it (and to `zeroize`), see docs/THREAT_MODEL.md.
|
||||
|
||||
use std::alloc::{GlobalAlloc, Layout, System};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
|
||||
|
||||
/// The marker. Exactly 32 bytes, the size of every Arcanum secret.
|
||||
pub const CANARY: [u8; 32] = *b"ARCANUM-ZEROIZE-CANARY-012345678";
|
||||
@@ -15,6 +18,43 @@ pub const CANARY: [u8; 32] = *b"ARCANUM-ZEROIZE-CANARY-012345678";
|
||||
static SEEN: AtomicBool = AtomicBool::new(false);
|
||||
static ARMED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
/// How many extra patterns [`watch`] can hold.
|
||||
pub const MAX_PATTERNS: usize = 4;
|
||||
// Atomics, not a `Vec` or a `Mutex`: `dealloc` must not allocate or block.
|
||||
static PATTERNS: [[AtomicU8; 32]; MAX_PATTERNS] = [const { [const { AtomicU8::new(0) }; 32] }; MAX_PATTERNS];
|
||||
static PATTERN_COUNT: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// Also look for these 32-byte patterns (besides [`CANARY`]) from now on; `watch(&[])` stops.
|
||||
///
|
||||
/// # Panics
|
||||
/// If given more than [`MAX_PATTERNS`] patterns.
|
||||
pub fn watch(patterns: &[[u8; 32]]) {
|
||||
assert!(patterns.len() <= MAX_PATTERNS, "at most {MAX_PATTERNS} patterns");
|
||||
PATTERN_COUNT.store(0, Ordering::SeqCst);
|
||||
for (slot, p) in PATTERNS.iter().zip(patterns) {
|
||||
for (a, b) in slot.iter().zip(p) {
|
||||
a.store(*b, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
PATTERN_COUNT.store(patterns.len(), Ordering::SeqCst);
|
||||
}
|
||||
|
||||
fn holds_secret(block: &[u8]) -> bool {
|
||||
if block.windows(CANARY.len()).any(|w| w == CANARY) {
|
||||
return true;
|
||||
}
|
||||
for slot in PATTERNS.iter().take(PATTERN_COUNT.load(Ordering::SeqCst)) {
|
||||
let mut p = [0u8; 32];
|
||||
for (b, a) in p.iter_mut().zip(slot) {
|
||||
*b = a.load(Ordering::Relaxed);
|
||||
}
|
||||
if block.windows(32).any(|w| w == p) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Start watching (and forget anything seen before).
|
||||
pub fn arm() {
|
||||
SEEN.store(false, Ordering::SeqCst);
|
||||
@@ -39,7 +79,7 @@ unsafe impl GlobalAlloc for Probe {
|
||||
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||
if ARMED.load(Ordering::Relaxed) && layout.size() >= CANARY.len() {
|
||||
let block = unsafe { std::slice::from_raw_parts(ptr, layout.size()) };
|
||||
if block.windows(CANARY.len()).any(|w| w == CANARY) {
|
||||
if holds_secret(block) {
|
||||
SEEN.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,11 +8,12 @@
|
||||
|
||||
use arcanum::exchange;
|
||||
use arcanum::seal;
|
||||
use arcanum::sign::{self, AppContext, SigningKey};
|
||||
use arcanum::xwing::SecretKey;
|
||||
use arcanum_zeroize_probe::{CANARY, arm, disarm};
|
||||
use arcanum_zeroize_probe::{CANARY, arm, disarm, watch};
|
||||
use chacha20::ChaCha20Rng;
|
||||
use rand_core::SeedableRng;
|
||||
use zeroize::Zeroizing;
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
fn rng(tag: u8) -> ChaCha20Rng {
|
||||
ChaCha20Rng::from_seed([tag; 32])
|
||||
@@ -88,4 +89,57 @@ fn secrets_are_wiped_before_their_heap_memory_is_freed() {
|
||||
let psk = Box::new(is.wireguard_psk(1));
|
||||
drop((psk, is, rs));
|
||||
assert!(!disarm(), "an exchange freed its context unwiped");
|
||||
|
||||
// --- v0.2.0: signatures ---
|
||||
// Both seeds are the canary. Building the key runs `ml-dsa`'s `SigningKey::from_seed`, which
|
||||
// keeps a copy of the ML-DSA seed in a heap box (`alloc`) and wipes it on drop (`zeroize`).
|
||||
let seeds: Zeroizing<Vec<u8>> = Zeroizing::new([CANARY, CANARY].concat());
|
||||
arm();
|
||||
drop(std::hint::black_box(Box::new(SigningKey::from_bytes(&seeds).unwrap())));
|
||||
assert!(!disarm(), "a boxed signing key (or ml-dsa's seed box) was freed with a seed in memory");
|
||||
|
||||
// The exported seeds.
|
||||
let sk = SigningKey::from_bytes(&seeds).unwrap();
|
||||
arm();
|
||||
drop(std::hint::black_box(Box::new(sk.to_bytes())));
|
||||
assert!(!disarm(), "a boxed to_bytes() copy was freed unwiped");
|
||||
|
||||
// Signing, an app message and a key binding, with the canary key; then the key is dropped.
|
||||
let ctx = AppContext::new(b"probe").unwrap();
|
||||
let kem = SecretKey::from_bytes(&[9; 32]).unwrap();
|
||||
arm();
|
||||
let sk = Box::new(SigningKey::from_bytes(&seeds).unwrap());
|
||||
let sig = sk.sign(b"message", &ctx, &mut rng(6)).unwrap();
|
||||
assert_eq!(sk.verifying_key().verify(b"message", &ctx, &sig), Ok(()));
|
||||
let bound = sign::bind_kem_key(&sk, b"id", kem.public_key(), (0, 1), &mut rng(7)).unwrap();
|
||||
assert_eq!(sign::verify_binding(sk.verifying_key(), b"id", kem.public_key(), (0, 1), 0, &bound), Ok(()));
|
||||
drop((sig, bound, sk));
|
||||
assert!(!disarm(), "signing freed a buffer that held a seed");
|
||||
|
||||
// --- QA S-04: the expanded ML-DSA key, which never contains the canary ---
|
||||
// FIPS 204 skEncode of the canary key: rho (0..32), K (32..64), tr (64..128), s1 (128..768), ...
|
||||
// Watch K (held raw in ml-dsa's ExpandedSigningKey) and a window of the encoded s1 (in any
|
||||
// encoded copy of the key, the shape QA's mutation Q15 leaked).
|
||||
#[allow(deprecated)]
|
||||
let mut expanded = ml_dsa::ExpandedSigningKey::<ml_dsa::MlDsa65>::from_seed(&CANARY.into()).to_expanded();
|
||||
let k: [u8; 32] = expanded[32..64].try_into().unwrap();
|
||||
let s1: [u8; 32] = expanded[128..160].try_into().unwrap();
|
||||
watch(&[k, s1]);
|
||||
// Controls: an unwiped copy of the encoded expanded key is seen, a wiped one is not.
|
||||
arm();
|
||||
drop(std::hint::black_box(expanded.to_vec()));
|
||||
assert!(disarm(), "control: an unwiped copy of the expanded key must be seen");
|
||||
arm();
|
||||
drop(std::hint::black_box(Zeroizing::new(expanded.to_vec())));
|
||||
assert!(!disarm(), "control: a Zeroizing copy must not be seen");
|
||||
expanded.as_mut_slice().zeroize();
|
||||
|
||||
// Arcanum: build, sign, bind and drop with the canary key, watching the expanded key's bytes.
|
||||
arm();
|
||||
let sk = Box::new(SigningKey::from_bytes(&seeds).unwrap());
|
||||
let sig = sk.sign(b"message", &ctx, &mut rng(8)).unwrap();
|
||||
let bound = sign::bind_kem_key(&sk, b"id", kem.public_key(), (0, 1), &mut rng(9)).unwrap();
|
||||
drop((sig, bound, sk));
|
||||
assert!(!disarm(), "a signing key was freed with expanded ML-DSA key material (K or s1) in memory");
|
||||
watch(&[]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user