Compare commits
15 Commits
d56ee10f0d
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| e950660ca3 | |||
| 7f7b2b641a | |||
| 5529560a72 | |||
| dafcebdef0 | |||
| cbde0650a4 | |||
| fc96614fce | |||
| 1e7e0bb16c | |||
| 0b2480bf83 | |||
| 9f9318664f | |||
| 002371445b | |||
| 274cf37d69 | |||
| 413dbaa279 | |||
| abcc375741 | |||
| 2329eb0719 | |||
| 99db18af16 |
@@ -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
+1
@@ -20,6 +20,7 @@ dependencies = [
|
||||
"base64",
|
||||
"chacha20",
|
||||
"chacha20poly1305",
|
||||
"curve25519-dalek",
|
||||
"ed25519-dalek",
|
||||
"hex",
|
||||
"hkdf",
|
||||
|
||||
@@ -44,6 +44,8 @@ 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."*"]
|
||||
|
||||
+59
@@ -2,6 +2,65 @@
|
||||
|
||||
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
|
||||
|
||||
@@ -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"
|
||||
|
||||
+43
-6
@@ -104,8 +104,11 @@ pub mod sign {
|
||||
`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, and checks both halves before answering, so timing does not
|
||||
tell which component failed (RFC 10073 §3.2).
|
||||
`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)
|
||||
|
||||
@@ -146,8 +149,15 @@ Where the code differs from, or adds to, the design above (the code wins):
|
||||
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`.
|
||||
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`
|
||||
@@ -169,13 +179,40 @@ Where the code differs from, or adds to, the design above (the code wins):
|
||||
- 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 (about 64 kB) through the stack
|
||||
before it is boxed; the allocator probe sees only the heap (as in v0.1.0's threat model).
|
||||
- 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.
|
||||
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 ];
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -96,10 +96,8 @@ fuzz_target!(|input: &[u8]| {
|
||||
}
|
||||
}
|
||||
5 => {
|
||||
// Any label, and any raw ctx (0..=255 bytes, or a typed error for longer).
|
||||
if let Ok(c) = AppContext::new(data) {
|
||||
assert!(vk.verify(MSG, &c, &f.sig).is_err() || c == f.ctx);
|
||||
}
|
||||
// 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()),
|
||||
|
||||
+2
-1
@@ -86,7 +86,8 @@ pub enum Error {
|
||||
/// 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 (deliberately not said which).
|
||||
/// 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.
|
||||
|
||||
+70
-15
@@ -22,8 +22,10 @@
|
||||
//! 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 is refused when parsed
|
||||
//! ([`Error::InvalidVerifyingKey`]), and Ed25519 is checked with `verify_strict`.
|
||||
//! 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.
|
||||
@@ -69,6 +71,7 @@ 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;
|
||||
|
||||
@@ -82,6 +85,19 @@ const _: () = assert!(SIGNATURE_LEN == ML_DSA_SIGNATURE_LEN + ed25519_dalek::SIG
|
||||
/// 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],
|
||||
@@ -89,12 +105,13 @@ pub struct AppContext {
|
||||
}
|
||||
|
||||
impl AppContext {
|
||||
/// `domi/arcanum/v2/sig/app/` + `label`. Use one fixed label per purpose (Day 3: `plans`).
|
||||
/// `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 fn new(label: &[u8]) -> Result<Self, Error> {
|
||||
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 });
|
||||
}
|
||||
@@ -103,8 +120,16 @@ impl AppContext {
|
||||
}
|
||||
let mut bytes = [0u8; MAX_CONTEXT_LEN];
|
||||
let p = APP_CONTEXT_PREFIX.len();
|
||||
bytes[..p].copy_from_slice(APP_CONTEXT_PREFIX);
|
||||
bytes[p..p + label.len()].copy_from_slice(label);
|
||||
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() })
|
||||
}
|
||||
|
||||
@@ -165,8 +190,9 @@ impl VerifyingKey {
|
||||
///
|
||||
/// # 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.
|
||||
/// Every 1952-byte ML-DSA-65 public key is well formed (FIPS 204 `pkDecode` cannot fail).
|
||||
/// 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]);
|
||||
@@ -176,6 +202,12 @@ impl VerifyingKey {
|
||||
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);
|
||||
@@ -191,22 +223,23 @@ impl VerifyingKey {
|
||||
/// Verify a signature over `msg` made with [`SigningKey::sign`] under the same context.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::InvalidSignature`] if either half (or both) fails. Both halves are always checked
|
||||
/// before answering, and the error does not say which failed (RFC 10073 §3.2).
|
||||
/// [`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) cannot verify; that it was
|
||||
// malformed is public, the signature itself says so.
|
||||
// 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();
|
||||
// `&`, not `&&`: both results are computed whatever the first one says.
|
||||
if ml_ok & ed_ok { Ok(()) } else { Err(Error::InvalidSignature) }
|
||||
if ml_ok && ed_ok { Ok(()) } else { Err(Error::InvalidSignature) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -252,9 +285,18 @@ impl fmt::Debug for Signature {
|
||||
|
||||
/// 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 about 64 kB.
|
||||
// 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,
|
||||
@@ -274,6 +316,12 @@ impl SigningKey {
|
||||
/// 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> {
|
||||
@@ -383,6 +431,13 @@ pub fn bind_kem_key<R: CryptoRng + ?Sized>(
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -175,3 +175,36 @@ fn ml_dsa_half_uses_the_label_as_its_context() {
|
||||
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());
|
||||
}
|
||||
|
||||
+21
-3
@@ -43,12 +43,14 @@ fn flipping_any_byte_of_the_message_fails() {
|
||||
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.
|
||||
// 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;
|
||||
assert_eq!(vk.verify(MSG, &AppContext::new(&l).unwrap(), &sig), Err(Error::InvalidSignature), "label byte {i}");
|
||||
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();
|
||||
@@ -148,7 +150,7 @@ fn a_key_binding_never_verifies_as_an_app_message_and_back() {
|
||||
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"[..], b"", b"domi/arcanum/v2/sig/kem-key", b"x"] {
|
||||
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:?}");
|
||||
}
|
||||
@@ -194,3 +196,19 @@ fn every_field_of_a_key_binding_matters() {
|
||||
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");
|
||||
}
|
||||
|
||||
+56
-1
@@ -20,7 +20,7 @@ use sha2::{Digest, Sha512};
|
||||
const ML: usize = 3309; // the ML-DSA-65 half comes first
|
||||
const ML_PK: usize = 1952;
|
||||
|
||||
fn ctx(label: &[u8]) -> AppContext {
|
||||
fn ctx(label: &'static [u8]) -> AppContext {
|
||||
AppContext::new(label).unwrap()
|
||||
}
|
||||
|
||||
@@ -133,3 +133,58 @@ fn halves_of_two_signatures_of_the_same_message_combine_as_the_rfc_says() {
|
||||
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");
|
||||
}
|
||||
|
||||
@@ -157,7 +157,7 @@ fn the_raw_interface_is_not_reachable_without_hazmat() {
|
||||
/// `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]); 8] = [
|
||||
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"]),
|
||||
@@ -170,6 +170,11 @@ fn ml_dsa_internals_are_not_reachable() {
|
||||
("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);
|
||||
|
||||
+62
-2
@@ -101,6 +101,11 @@ fn contexts_of_the_wrong_length_are_typed_errors() {
|
||||
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();
|
||||
@@ -149,7 +154,62 @@ fn random_bytes_never_panic() {
|
||||
let sig = k.sign(&buf, &c, &mut r).unwrap();
|
||||
assert_eq!(k.verifying_key().verify(&buf, &c, &sig), Ok(()));
|
||||
}
|
||||
// Random labels: typed errors or a context, never a panic.
|
||||
let _ = AppContext::new(&buf[..len.min(300)]);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
Generated
+1
@@ -36,6 +36,7 @@ version = "0.0.0"
|
||||
dependencies = [
|
||||
"arcanum",
|
||||
"chacha20",
|
||||
"ml-dsa",
|
||||
"rand_core",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,10 +10,10 @@ 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])
|
||||
@@ -115,4 +115,31 @@ fn secrets_are_wiped_before_their_heap_memory_is_freed() {
|
||||
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