14 Commits

Author SHA1 Message Date
mnovak 7f7b2b641a docs(CLAUDE.md): no build or test while CPU or RAM is over 90 %, or a written-to drive over 95 % (Mark) 2026-11-29 01:55:15 +01:00
mnovak 5529560a72 Merge ci/linux: the suite once on Linux, on Fabrica's NixOS runner (PR #3)
Run rjx52agvjswxe: 126/0/5 debug, 127/0/4 release, zeroize probe 1 passed. No library change.
2026-11-29 01:53:08 +01:00
mnovak dafcebdef0 ci(linux): every run line starts with nix, with no && inside, so Fabrica's preflight does not read cargo as a runner tool 2026-11-26 04:24:32 +01:00
mnovak cbde0650a4 ci: the suite once on Linux, on Fabrica's NixOS runner (pipeline linux, flake ci shell)
Mark, 2026-11-26: the Linux run goes on Fabrica's server runner. The flake gives only the
toolchain (nixos-26.05, locked as Ianitor's); the pipeline runs cargo test in debug and release
and the zeroize probe. It builds and switches nothing on the server.
2026-11-26 04:21:08 +01:00
mnovak fc96614fce Merge feature/signatures: v0.2.0, hybrid signatures ML-DSA-65 + Ed25519 (RFC 10073), PR #2
QA review-arcanum-pr2.md: 0 blockers, 0 majors, 12 minors. S-01 to S-06 and
S-09 to S-11 answered in code, tests or docs; S-07, S-08, S-12 and the S-04
stack residue inside ml-dsa recorded as gaps.
Owner fresh clone at 1e7e0bb: 126/0/5 debug, 127/0/4 release; clippy, fmt,
cargo deny and the zeroize probe clean.
2026-11-26 04:06:55 +01:00
mnovak 1e7e0bb16c docs: HANDOVER for the v0.2.0 QA round (S-01 to S-12)
What was fixed and how each of QA's mutations now fails, what is recorded
as a gap, the counts at 0b2480b (126 passed / 5 ignored in debug, 127 / 4
in release, clippy and fmt clean, the probe, cargo deny) and a 601 s fuzz
run with no crash, and the consumer advice added (legacy_compatibility
ban, const contexts, 512 KiB signing threads, the binding checks left to
the caller).
2026-11-26 04:03:13 +01:00
mnovak 0b2480bf83 docs: QA S-04, S-07, S-08, S-12 as gaps; the expanded key is 35 kB on the stack
- The expanded ML-DSA-65 key is 34,992 bytes on the stack (QA measured;
  A_hat's rows are boxed inside ml-dsa), not 64 kB, and it is exactly the
  secret part. src/sign.rs and docs/02_signatures.md corrected.
- S-04: ml-dsa's signing loop leaves rnd, rho'' and y on the stack; a
  leaked y gives s1. Recorded in docs/02 and docs/THREAT_MODEL.md, with the
  key-construction stack copy.
- S-07: under open question 1, the recommendation for Day 3: a separate,
  freshly generated composite identity, never a wrapped Tessera Ed25519
  seed (RFC 10073 3.1); from_bytes cannot detect reuse (also on its docs).
- S-08: verify_binding does not tie id to vk and has no serial; both are
  the caller's, with the Day 3 replay rule (QA E-07); also on its docs.
- S-12: decoded on 2026-11-26, none of the 9 ML-DSA-65 "modified z" sigVer
  cases at a7f283cd reaches the z infinity-norm bound (max 524,077 <
  524,092), so no ACVP case could be added; only Wycheproof covers it.
- S-05, S-10, S-11 noted under "As built" and gaps.
2026-11-26 03:49:56 +01:00
mnovak 9f9318664f docs: the stack a signing key needs, and a release test that pins it (QA S-11)
ML-DSA-65 keeps large vectors on the stack, and a thread that is too small
aborts the process; that is not an Error a caller can handle. Measured
here with tests/sig_stack.rs (Windows x86-64, a thread per run):

  release: 128 KiB overflows, 256/512/1024 KiB pass
  debug (deps at opt-level 2): 128 and 256 KiB overflow, 512/1024 KiB pass

SigningKey's docs now say so and advise at least 512 KiB for threads that
sign. generate_and_sign_fit_in_256_kib_of_stack pins the release figure
(ignored in debug builds); the four on_a_<n>_kib_stack measurements are
ignored and run by hand, one at a time.
2026-11-26 03:49:04 +01:00
mnovak 002371445b test: the zeroize probe also watches the expanded ML-DSA key (QA S-04)
The probe looked only for its 32-byte canary, i.e. the seeds; the key
material that actually signs is derived from them and never contains it,
so an unwiped copy of the expanded key went unseen (QA's mutation Q15).

The probe allocator now also watches up to four further 32-byte patterns,
held in atomics (dealloc must not allocate or lock). The test computes the
canary key's FIPS 204 expanded encoding with ml-dsa itself and watches K
(held raw inside ml-dsa's ExpandedSigningKey) and a 32-byte window of the
encoded s1; controls show an unwiped copy is seen and a Zeroizing one is
not; then building, signing, binding and dropping a canary SigningKey must
free no block holding either.

Q15 re-checked: a SigningKey field holding an unwiped Vec of
ml.to_expanded() fails the probe at the new assertion (reverted). The
ml-dsa rnd / rho'' / y stack residue is out of the probe's reach (stack,
not heap) and is recorded as a gap.
2026-11-26 03:48:11 +01:00
mnovak 274cf37d69 docs: verification timing does show which half failed, harmlessly (QA S-06)
The design doc, VerifyingKey::verify and Error::InvalidSignature claimed
that both halves are always checked so timing does not tell which failed.
Not so: a malformed ML-DSA half is refused at decode without verification,
and verify_strict returns early on a bad R (QA measured 59/187/217 us
against 225 us). The docs now say the error does not name the half, the
timing may, and that is fine because verification uses only public data
(RFC 10073 3.3 allows failing early). The `&` and its comment, which
bought nothing (both booleans were already computed), become a plain `&&`.
No behaviour change.
2026-11-26 03:46:47 +01:00
mnovak 413dbaa279 build: cargo deny bans ed25519-dalek/legacy_compatibility (QA S-10)
With legacy_compatibility, ed25519-dalek checks only the top bits of S, so
S + l is accepted: a second encoding of the Ed25519 half, and the
malleability promise of verify_strict is gone. Feature unification lets
any crate in the final binary turn it on. deny.toml now bans it for
ed25519-dalek and curve25519-dalek, and ed25519-dalek/hazmat with it
(cargo-deny 0.20 [[bans.features]]).

Checked: bans ok as committed; enabling legacy_compatibility on
ed25519-dalek in Cargo.toml fails `cargo deny --offline check bans` for
both crates, and enabling hazmat fails it for ed25519-dalek (reverted).
2026-11-26 03:46:21 +01:00
mnovak abcc375741 fix: AppContext::new is a const fn over a &'static label (QA S-09)
A label is one fixed string per purpose; taking any runtime bytes let a
consumer derive it from a peer name, a file name or a message field, and
two purposes could then collide. AppContext::new now takes
&'static [u8] and is a const fn, so contexts are built as consts and a bad
label fails the consumer's build; there is no runtime constructor (the
simplest API: one constructor, no escape hatch until a need appears).

Tests: a const OK and a const EMPTY context; sig_hygiene refuses a
consumer that passes a runtime Vec (E0597/E0716); the one test that needs
runtime labels (flipping label bytes) leaks them on purpose. The random
labels in sig_malformed and fuzz mode 5's AppContext part are dropped (the
raw-ctx part of mode 5 stays). A doctest shows the const pattern, and
docs/02_signatures.md says so.
2026-11-26 03:45:39 +01:00
mnovak 2329eb0719 fix: refuse an ML-DSA-65 public key with t1 = 0 (QA S-05)
With t1 = 0 (Wycheproof's ZeroPublicKey), ML-DSA verification only checks
c~ = H(mu || w1(A·z)), which anyone can satisfy with s1 = s2 = t0 = 0: such
a composite key is silently no stronger than its Ed25519 half.
VerifyingKey::from_bytes now refuses it as InvalidVerifyingKey, like a
small-order Ed25519 half. Invisible to honest keys (t1 = 0 has negligible
probability); rho may be anything.

sig_malformed::an_ml_dsa_key_with_zero_t1_is_refused, from QA's qa_s07
inverted: the key is refused, one non-zero t1 byte anywhere makes it parse,
and with the component crate alone a secret-free expanded key signs for it.
Removing the check makes the test fail.
2026-11-26 03:44:02 +01:00
mnovak 99db18af16 test: pin verify_strict, the verify_binding order and independent seeds (QA S-01 to S-03)
Ported from QA's proof tests for PR #2 (qa_s03 to qa_s05):

- S-01, sig_halves: an Ed25519 half with a small-order R (the identity,
  s = H(R || A || M')·a from a throwaway key's own scalar) is accepted by
  plain verify and refused by verify_strict; Arcanum must refuse it.
- S-02, sig_every_byte: a forged window that also excludes now gives
  InvalidSignature, never OutsideValidity.
- S-03, sig_composite: generate draws exactly 64 bytes, and the two seeds
  are those bytes in order (RFC 10073 3.1, independent component keys).

Each mutation QA describes now fails (applied to src/sign.rs, reverted):
Q1 verify_strict -> verify fails the S-01 test; Q3 now checked before the
signature fails the S-02 test; Q4 the Ed25519 seed copied from the ML-DSA
seed fails the S-03 test. Adds curve25519-dalek =5.0.0 as a dev-dependency
(already in the lock) for the scalar arithmetic.
2026-11-26 03:42:56 +01:00
23 changed files with 584 additions and 38 deletions
+23
View File
@@ -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
+10
View File
@@ -16,3 +16,13 @@ Read HANDOVER.md and the day's docs/NN_*.md before writing code.
## Workflow ## Workflow
(D)TDD doc → tests → code. Branch, PR with critical self-review, merge --no-ff, push, verify. (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. 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
View File
@@ -20,6 +20,7 @@ dependencies = [
"base64", "base64",
"chacha20", "chacha20",
"chacha20poly1305", "chacha20poly1305",
"curve25519-dalek",
"ed25519-dalek", "ed25519-dalek",
"hex", "hex",
"hkdf", "hkdf",
+2
View File
@@ -44,6 +44,8 @@ hex = "0.4"
sha2 = "0.11" sha2 = "0.11"
# The RFC 10073 vectors are base64. # The RFC 10073 vectors are base64.
base64 = "0.22" 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. # ML-KEM in a debug build is slow; the byte-flip tests run thousands of exchanges.
[profile.dev.package."*"] [profile.dev.package."*"]
+59
View File
@@ -2,6 +2,65 @@
Newest entry first. Where this file and the code disagree, the code wins and the next entry says so. 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 ## 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 **What it adds:** `arcanum::sign`, hybrid signatures ML-DSA-65 + Ed25519, exactly RFC 10073
+11
View File
@@ -29,6 +29,17 @@ multiple-versions = "deny"
wildcards = "deny" wildcards = "deny"
highlight = "all" 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] [sources]
unknown-registry = "deny" unknown-registry = "deny"
unknown-git = "deny" unknown-git = "deny"
+43 -6
View File
@@ -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 `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) 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, 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 `Error::InvalidSignature`, whichever half failed. **Correction (QA S-06):** the timing *does* tell which half
tell which component failed (RFC 10073 §3.2). 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) ## 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 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 canonical one, as well as small-order points (`Error::InvalidVerifyingKey`). Invisible to honest
keys and to the RFC's vectors. 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 - **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; - **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 `verify_binding` checks, in this order, the window's shape and the id length
(`InvalidValidity`, `TooLong`), the signature (`InvalidSignature`), then `now` (`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 - 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, 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`. 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 - Stack copies: building a `SigningKey` moves the expanded ML-DSA key through the stack before it is boxed:
before it is boxed; the allocator probe sees only the heap (as in v0.1.0's threat model). **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) ## Questions (none blocks the work)
1. Should Tessera's device identity itself move to this composite key, or should Tessera keep Ed25519 and 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 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 2. Validity windows on key bindings: the default the engine should use (proposal: 30 days, renewed by the
control service). control service).
+6
View File
@@ -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 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 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. 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
View File
@@ -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
}
+17
View File
@@ -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 ];
};
};
}
+2 -4
View File
@@ -96,10 +96,8 @@ fuzz_target!(|input: &[u8]| {
} }
} }
5 => { 5 => {
// Any label, and any raw ctx (0..=255 bytes, or a typed error for longer). // Any raw ctx (0..=255 bytes, or a typed error for longer). `AppContext` labels are
if let Ok(c) = AppContext::new(data) { // `&'static` and fixed at compile time, so there is no runtime label to fuzz.
assert!(vk.verify(MSG, &c, &f.sig).is_err() || c == f.ctx);
}
let raw = xor_into(f.ctx.as_bytes(), data); let raw = xor_into(f.ctx.as_bytes(), data);
match sign::verify_composite_raw(vk, MSG, &raw, &f.sig) { match sign::verify_composite_raw(vk, MSG, &raw, &f.sig) {
Ok(()) => assert_eq!(raw, f.ctx.as_bytes()), Ok(()) => assert_eq!(raw, f.ctx.as_bytes()),
+2 -1
View File
@@ -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 /// The Ed25519 half of a verifying key is not a canonically encoded point, or is a point of
/// small order (a weak key). /// small order (a weak key).
InvalidVerifyingKey, 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, InvalidSignature,
/// ML-DSA signing failed (the randomness source or the rejection-sampling bound). Retry with /// ML-DSA signing failed (the randomness source or the rejection-sampling bound). Retry with
/// fresh randomness. /// fresh randomness.
+70 -15
View File
@@ -22,8 +22,10 @@
//! under another: `ctx` and its length are inside M'. //! 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 //! **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 //! small-order point or not the canonical encoding of its point, or whose ML-DSA-65 half has
//! ([`Error::InvalidVerifyingKey`]), and Ed25519 is checked with `verify_strict`. //! 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 //! **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. //! 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_PUBLIC_KEY_LEN: usize = 1952;
const ML_DSA_SIGNATURE_LEN: usize = 3309; const ML_DSA_SIGNATURE_LEN: usize = 3309;
const ML_DSA_RHO_LEN: usize = 32;
const SEED_LEN: usize = 32; const SEED_LEN: usize = 32;
const M_PRIME_MAX_LEN: usize = 32 + 30 + 1 + MAX_CONTEXT_LEN + 64; 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 /// 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 /// 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. /// 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)] #[derive(Clone, PartialEq, Eq)]
pub struct AppContext { pub struct AppContext {
bytes: [u8; MAX_CONTEXT_LEN], bytes: [u8; MAX_CONTEXT_LEN],
@@ -89,12 +105,13 @@ pub struct AppContext {
} }
impl 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 /// # Errors
/// [`Error::TooShort`] for an empty label; [`Error::TooLong`] for one over /// [`Error::TooShort`] for an empty label; [`Error::TooLong`] for one over
/// [`MAX_APP_LABEL_LEN`] (231) bytes. /// [`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() { if label.is_empty() {
return Err(Error::TooShort { input: Input::Context, minimum: 1, actual: 0 }); 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 mut bytes = [0u8; MAX_CONTEXT_LEN];
let p = APP_CONTEXT_PREFIX.len(); let p = APP_CONTEXT_PREFIX.len();
bytes[..p].copy_from_slice(APP_CONTEXT_PREFIX); let mut i = 0;
bytes[p..p + label.len()].copy_from_slice(label); 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() }) Ok(Self { bytes, len: p + label.len() })
} }
@@ -165,8 +190,9 @@ impl VerifyingKey {
/// ///
/// # Errors /// # Errors
/// [`Error::InvalidLength`] if it is not 1984 bytes; [`Error::InvalidVerifyingKey`] if the /// [`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. /// 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). /// 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> { pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
let bytes: &[u8; VERIFYING_KEY_LEN] = exact(Input::VerifyingKey, bytes)?; 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_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 { if ed.is_weak() || ed.to_edwards().compress().to_bytes() != ed_bytes {
return Err(Error::InvalidVerifyingKey); 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]) let enc = EncodedVerifyingKey::<MlDsa65>::try_from(&bytes[..ML_DSA_PUBLIC_KEY_LEN])
.map_err(|_| Error::InvalidVerifyingKey)?; .map_err(|_| Error::InvalidVerifyingKey)?;
let ml = ml_dsa::VerifyingKey::<MlDsa65>::decode(&enc); 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. /// Verify a signature over `msg` made with [`SigningKey::sign`] under the same context.
/// ///
/// # Errors /// # Errors
/// [`Error::InvalidSignature`] if either half (or both) fails. Both halves are always checked /// [`Error::InvalidSignature`] if either half (or both) fails. The error does not say which
/// before answering, and the error does not say which failed (RFC 10073 §3.2). /// 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> { pub fn verify(&self, msg: &[u8], ctx: &AppContext, sig: &Signature) -> Result<(), Error> {
self.verify_m_prime(&MPrime::of_message(msg, ctx.as_bytes())?, sig) self.verify_m_prime(&MPrime::of_message(msg, ctx.as_bytes())?, sig)
} }
fn verify_m_prime(&self, mp: &MPrime, sig: &Signature) -> Result<(), Error> { fn verify_m_prime(&self, mp: &MPrime, sig: &Signature) -> Result<(), Error> {
let mp = mp.as_bytes(); let mp = mp.as_bytes();
// A malformed ML-DSA half (bad hint encoding, z out of range) cannot verify; that it was // A malformed ML-DSA half (bad hint encoding, z out of range) is refused at decode, without
// malformed is public, the signature itself says so. // 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]) 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)); .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_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(); 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 /// 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. /// 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 { pub struct SigningKey {
seeds: Zeroizing<[u8; SIGNING_KEY_LEN]>, 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>>, ml: Box<ExpandedSigningKey<MlDsa65>>,
ed: ed25519_dalek::SigningKey, ed: ed25519_dalek::SigningKey,
public: VerifyingKey, 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 /// Parse a stored signing key: the ML-DSA-65 seed, then the Ed25519 seed (RFC 10073's
/// private key format). /// 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 /// # Errors
/// [`Error::InvalidLength`] if it is not 64 bytes. Every 64-byte value is a valid key. /// [`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> { 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). /// 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 /// # Errors
/// In this order: [`Error::InvalidValidity`] or [`Error::TooLong`] for a malformed window or id; /// 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 /// [`Error::InvalidSignature`] if the binding is not authentic; [`Error::OutsideValidity`] if it is
+33
View File
@@ -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, b"", &ml_sig), "not the empty ctx");
assert!(!ml_vk.verify_with_context(&mp, ctx.as_bytes(), &ml_sig), "not the application 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
View File
@@ -43,12 +43,14 @@ fn flipping_any_byte_of_the_message_fails() {
fn flipping_any_byte_of_the_context_fails() { fn flipping_any_byte_of_the_context_fails() {
let (sk, c, sig) = setup(51); let (sk, c, sig) = setup(51);
let vk = sk.verifying_key(); 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"; let label = b"every-byte";
for i in 0..label.len() { for i in 0..label.len() {
let mut l = label.to_vec(); let mut l = label.to_vec();
l[i] ^= 0x01; 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. // Through the raw interface: every byte of the whole ctx, Arcanum's prefix included.
let full = c.as_bytes().to_vec(); 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"); assert_eq!(sign::verify_composite_raw(vk, &msg, KEM_KEY_CONTEXT, &binding), Ok(()), "documented encoding");
// As an application message, under any application label: refused. // 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) { if let Ok(c) = AppContext::new(label) {
assert_eq!(vk.verify(&msg, &c, &binding), Err(Error::InvalidSignature), "label {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; 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
View File
@@ -20,7 +20,7 @@ use sha2::{Digest, Sha512};
const ML: usize = 3309; // the ML-DSA-65 half comes first const ML: usize = 3309; // the ML-DSA-65 half comes first
const ML_PK: usize = 1952; const ML_PK: usize = 1952;
fn ctx(label: &[u8]) -> AppContext { fn ctx(label: &'static [u8]) -> AppContext {
AppContext::new(label).unwrap() 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(&a, &b)), Ok(()));
assert_eq!(sk.verifying_key().verify(b"m", &c, &splice(&b, &a)), 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");
}
+6 -1
View File
@@ -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. /// `Deref`/`AsRef` to the component keys, and an `AppContext` only from the Arcanum prefix.
#[test] #[test]
fn ml_dsa_internals_are_not_reachable() { 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 of ml_dsa", "use arcanum::ml_dsa;", &["E0432"]),
("re-export in sign", "use arcanum::sign::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_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 component key field", "let k = key(); let _ = &k.ml;", &["E0609", "E0616"]),
("a foreign or empty context", "let _ = arcanum::sign::AppContext::from_raw(b\"\");", &["E0599"]), ("a foreign or empty context", "let _ = arcanum::sign::AppContext::from_raw(b\"\");", &["E0599"]),
("cloning a signing key", "let k = key(); let _ = k.clone();", &["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 { for (what, body, needles) in calls {
assert_refused(what, body, needles); assert_refused(what, body, needles);
+62 -2
View File
@@ -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 } 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 }); 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). // 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(); 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(); let sig = k.sign(&buf, &c, &mut r).unwrap();
assert_eq!(k.verifying_key().verify(&buf, &c, &sig), Ok(())); 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");
}
+57
View File
@@ -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
View File
@@ -36,6 +36,7 @@ version = "0.0.0"
dependencies = [ dependencies = [
"arcanum", "arcanum",
"chacha20", "chacha20",
"ml-dsa",
"rand_core", "rand_core",
"zeroize", "zeroize",
] ]
+3
View File
@@ -11,6 +11,9 @@ arcanum = { path = ".." }
zeroize = { version = "1.8", default-features = false, features = ["alloc"] } zeroize = { version = "1.8", default-features = false, features = ["alloc"] }
[dev-dependencies] [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"] } chacha20 = { version = "0.10", default-features = false, features = ["rng"] }
rand_core = { version = "0.10", default-features = false } rand_core = { version = "0.10", default-features = false }
+43 -3
View File
@@ -1,13 +1,16 @@
//! QA A-29: a global allocator that, in `dealloc`, scans every block for a 32-byte canary before //! 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 //! 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; //! `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 //! 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. //! copies made by moves are invisible to it (and to `zeroize`), see docs/THREAT_MODEL.md.
use std::alloc::{GlobalAlloc, Layout, System}; 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. /// The marker. Exactly 32 bytes, the size of every Arcanum secret.
pub const CANARY: [u8; 32] = *b"ARCANUM-ZEROIZE-CANARY-012345678"; 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 SEEN: AtomicBool = AtomicBool::new(false);
static ARMED: 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). /// Start watching (and forget anything seen before).
pub fn arm() { pub fn arm() {
SEEN.store(false, Ordering::SeqCst); SEEN.store(false, Ordering::SeqCst);
@@ -39,7 +79,7 @@ unsafe impl GlobalAlloc for Probe {
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
if ARMED.load(Ordering::Relaxed) && layout.size() >= CANARY.len() { if ARMED.load(Ordering::Relaxed) && layout.size() >= CANARY.len() {
let block = unsafe { std::slice::from_raw_parts(ptr, layout.size()) }; 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); SEEN.store(true, Ordering::SeqCst);
} }
} }
+29 -2
View File
@@ -10,10 +10,10 @@ use arcanum::exchange;
use arcanum::seal; use arcanum::seal;
use arcanum::sign::{self, AppContext, SigningKey}; use arcanum::sign::{self, AppContext, SigningKey};
use arcanum::xwing::SecretKey; use arcanum::xwing::SecretKey;
use arcanum_zeroize_probe::{CANARY, arm, disarm}; use arcanum_zeroize_probe::{CANARY, arm, disarm, watch};
use chacha20::ChaCha20Rng; use chacha20::ChaCha20Rng;
use rand_core::SeedableRng; use rand_core::SeedableRng;
use zeroize::Zeroizing; use zeroize::{Zeroize, Zeroizing};
fn rng(tag: u8) -> ChaCha20Rng { fn rng(tag: u8) -> ChaCha20Rng {
ChaCha20Rng::from_seed([tag; 32]) 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(())); assert_eq!(sign::verify_binding(sk.verifying_key(), b"id", kem.public_key(), (0, 1), 0, &bound), Ok(()));
drop((sig, bound, sk)); drop((sig, bound, sk));
assert!(!disarm(), "signing freed a buffer that held a seed"); 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(&[]);
} }