33 Commits

Author SHA1 Message Date
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
mnovak d56ee10f0d docs: HANDOVER for v0.2.0, the as-built notes and the answered verify_strict gap
HANDOVER: the builder's counts (121 tests in debug and release, clippy,
fmt, the zeroize probe, deny, audit, a 605 s fuzz run with no crash), seven
mutation checks, the vector sources, and what is not verified.

docs/02_signatures.md: an "As built" section (the raw interface stays
hedged, the canonical Ed25519 key check, label lengths, the order of the
binding checks, crate features); the gap on verify_strict is answered (it
accepts both RFC 10073 vectors and agrees with all 151 Wycheproof
verdicts), and the subsets and stack copies are listed as gaps. The app
context prefix in the AppContext paragraph is corrected to
domi/arcanum/v2/sig/app/.

README: signatures in the summary, a usage sketch, the new fuzz target.
2026-11-25 13:46:43 +01:00
mnovak b245e1054c docs: the expanded ML-DSA-65 key is about 64 kB, not 60 2026-11-25 13:33:53 +01:00
mnovak ddda8415eb test: fuzz target for the signature API (mandatory test 6)
fuzz/fuzz_targets/signatures.rs: raw bytes into VerifyingKey, Signature,
SigningKey and AppContext; and the input XORed into a valid verifying key,
signature, message, raw ctx, key-binding id/window/time, X-Wing key and
binding signature. Beyond "never panics" it asserts that only the exact
signed bytes verify.

Run on 5a52854 plus this target, Windows 10, nightly 1.102.0
(739adecd4 2026-11-24), libFuzzer + ASan (MSVC 14.44 asan runtime),
corpus and artifacts on D:, 12 seed inputs: 605 s, 38,609 executions,
63 exec/s, 0 crashes, 0 artifacts, coverage 3,549, 122 corpus units.
2026-11-25 13:33:53 +01:00
mnovak 5a52854ccc feat: hybrid signatures ML-DSA-65 + Ed25519, RFC 10073 id-MLDSA65-Ed25519-SHA512
arcanum::sign, as docs/02_signatures.md sets out. M' = Prefix || Label ||
u8(len ctx) || ctx || SHA-512(M), built on the stack. The ML-DSA-65 half is
ExpandedSigningKey::sign_randomized(M', ctx = Label, rng), hedged; the
Ed25519 half is pure Ed25519 over M' (try_sign), checked with verify_strict.
Verification computes both halves before answering, and returns one
InvalidSignature whichever failed. ml-dsa's Signer/Verifier traits,
sign_deterministic and sign_mu_deterministic are never called.

- SigningKey: two 32-byte seeds (RFC 10073's private key format), the
  expanded ML-DSA key boxed; ZeroizeOnDrop, not Clone, Debug redacted.
- VerifyingKey: 1984 bytes; refuses an Ed25519 half that is not a point,
  not its canonical encoding, or of small order (InvalidVerifyingKey).
- AppContext: only "domi/arcanum/v2/sig/app/" + a 1..=231-byte label.
- bind_kem_key / verify_binding: an X-Wing public key bound to a key id and
  an inclusive validity window under "domi/arcanum/v2/sig/kem-key"; the
  message is hashed field by field; window and id are checked first, then
  the signature, then now (InvalidValidity, TooLong, InvalidSignature,
  OutsideValidity).
- sign_composite_raw / verify_composite_raw: the bare RFC ctx, hazmat only.
  They still take an RNG (the ML-DSA half stays hedged), not the
  deterministic variant the doc mentions.
- Error gains TooLong, InvalidVerifyingKey, InvalidSignature,
  SigningFailed, InvalidValidity, OutsideValidity; Input gains SigningKey,
  VerifyingKey, Signature, Context, KeyId.

Also fixes tests/kat_mldsa65.rs, which passed a &[&Vec<u8>] to
sign_internal and did not compile.

cargo test (debug): 121 passed, 0 failed (82 from v0.1.0, golden_v1
unchanged). clippy --all-targets --all-features -D warnings: clean.
2026-11-25 13:12:22 +01:00
mnovak 2a432f5d86 test: the v0.2.0 signature tests, written before the code
The mandatory tests of docs/02_signatures.md, against the API the doc sets
out (arcanum::sign). They do not compile yet: the module does not exist.

1 kat_mldsa65: ACVP keyGen, sigGen (deterministic and hedged groups, byte
  for byte, through sign_randomized/sign_mu_randomized fed the vector's
  rnd), sigVer on the corrected file; Wycheproof sign_seed and verify.
2 kat_ed25519: RFC 8032 section 7.1 and Wycheproof, with verify_strict.
3 sig_composite: the RFC 10073 vectors s and sWithContext verify, the RFC
  key derives the RFC public key, own signatures verify under an
  independent rebuild of M', ML-DSA hedged with ctx = Label.
4 sig_halves: either half swapped in from another signature, zeroed or
  cut, or the halves swapped, is refused; the ML-DSA half fails an
  empty-ctx verifier. Not SUF-CMA (RFC 10073 9.2) is pinned.
5 sig_every_byte: any flipped byte of message, ctx, public key or
  signature fails; contexts are prefix-free; key bindings and app
  messages never verify as each other; every binding field matters.
6 sig_malformed: wrong lengths, weak and non-canonical Ed25519 keys,
  0- and 256-byte contexts, a 65536-byte key id, random bytes.
7 sig_hygiene and feature_hygiene: compile-fail checks against a
  default-features consumer (hazmat raw interface, ml-dsa internals,
  non-crypto RNG, Clone), ZeroizeOnDrop, Debug; ml-dsa and ed25519-dalek
  in the normal graph with zeroize and without hazmat or defaults. The
  allocator probe covers the signing keys.
8 golden_v1.rs is untouched.

Adds ml-dsa =0.1.2 (alloc, rand_core, zeroize) and ed25519-dalek =3.0.0
(zeroize) with default features off, base64 for the tests, and bumps the
version to 0.2.0. The fuzz target follows with the code.
2026-11-25 12:48:39 +01:00
mnovak 5b9e3ee8fb test: v0.2.0 signature vectors (ACVP ML-DSA, Wycheproof, RFC 8032, RFC 10073)
Official vectors for the signature tests, fetched 2026-11-25 at the commits
docs/02_signatures.md names: ACVP keyGen and sigGen at 2972def2, sigVer at
a7f283cd (after the ModifyZ correction), Wycheproof at 20b25694, the
composite-sigs repository at f0627ab, and RFC 8032 section 7.1.

Files under about 1 MB are kept whole. The larger ones are reduced to their
ML-DSA-65 groups and a few cases per group by make_subsets.py, which checks
each original's sha256 and drops only whole cases and groups; RFC 8032's
vectors are extracted from the RFC text by extract_rfc8032.py. SOURCES.md
records the URL, commit, git blob, original sha256 and the selection of
every file.
2026-11-25 12:40:04 +01:00
mnovak c7294612ae docs: v0.2.0 design, hybrid signatures ML-DSA-65 + Ed25519 per RFC 10073
Mark decided on 2026-11-25 to add post-quantum signatures before Day 3, so
exchanged X-Wing keys can be authenticated post-quantum. The construction is
RFC 10073 id-MLDSA65-Ed25519-SHA512, byte for byte, on ml-dsa =0.1.2 and
ed25519-dalek =3.0.0. Covers the crate choices and the API traps (the crate's
Signer/Verifier traits use an empty context and sign deterministically), the
Arcanum contexts, a key-binding helper, the eight mandatory tests with their
vector sources (ACVP after the 2026-07-31 sigVer correction, Wycheproof, the
RFC's Appendix E), risks and gaps. Tests and code follow.
2026-11-25 11:10:31 +01:00
mnovak 2fae9ad3eb Merge feature/arcanum: Day 1, Arcanum (PR #1)
X-Wing draft -11 (ML-KEM-768 + X25519) unmodified, a mutual exchange with the
full transcript bound in Arcanum's HKDF layer, the WireGuard PSK per 120 s
epoch, and a one-shot sealed box. Two QA reviews answered, R2-01 to R2-05
fixed. 82 tests passed in debug and release; fuzzed 631 s on 96086be with no
crash. Not audited.
2026-11-25 09:37:59 +01:00
mnovak 9f8d1161ad docs: HANDOVER for v0.1.0, with the owner session's counts, mutation checks and fuzz run 2026-11-25 09:37:57 +01:00
mnovak 96086be4b3 docs: R2-01 to R2-05 decisions, canonical pk_X, and rules for Arcanum's consumers 2026-11-25 08:37:11 +01:00
mnovak 6780abc0c2 fix: QA second review R2-01 to R2-05
R2-01: PublicKey::encapsulate, SecretKey::decapsulate and SharedSecret::as_bytes
are hazmat-only; release consumers reach keys only through exchange and seal.
R2-02: PublicKey::from_bytes refuses a non-canonical X25519 half (bit 255 set,
or a value of at least 2^255 - 19). Honest keys and the draft vectors pass.
R2-03: schedule::expand takes one static label and one fixed-width field, so
its info is injective by signature. v1 bytes unchanged (golden vectors pass).
R2-04: generate, initiate, respond and seal say the RNG must be the OS RNG.
R2-05: Initiation is ZeroizeOnDrop; seal's buffer stays Zeroizing until the
plaintext in it is encrypted, so the MessageTooLong path wipes it.
QA's A-33 case for PublicKey::encapsulate moves to exchange::respond, and its
A-08 test pins the new expand signature to the v1 encoding.
2026-11-25 08:37:11 +01:00
mnovak f3e17f3d5c test(qa): A-29 allocator probe, secrets wiped before their heap memory is freed
A separate, unpublished crate with its own workspace (like fuzz/), because a
GlobalAlloc needs unsafe and arcanum keeps forbid(unsafe_code). dealloc scans
each freed block for a 32-byte canary. Controls prove it sees an unwiped Vec
and the reallocation case; checked by adding a reserve(1) after decryption in
open(), which it catches. Heap only: stack copies are out of its reach.
2026-11-25 08:16:44 +01:00
mnovak f31872d0d5 test(qa): compile-fail checks against a default-features consumer (A-33, A-34, R2-01)
Builds a throwaway crate that depends on arcanum without features and runs
cargo check --offline on small programs: the safe API compiles (control), a
non-CryptoRng RNG is refused (A-33), and no _derand/from_seed entry point is
reachable (A-34). Each was checked by reintroducing the bug.

qa_r2_01_raw_shared_secret_is_not_reachable_without_hazmat FAILS on purpose:
PublicKey::encapsulate(..).1.as_bytes() hands a release consumer the raw
one-way X-Wing secret, the single-direction PSK that A-15 rules out.
2026-11-25 08:16:44 +01:00
mnovak 3dfc75075f test(qa): second review, A-03/A-06/A-08/A-09/A-18/A-28/A-30/A-31 and R2-02 (non-canonical pk_X)
Completes the partial QA cases and adds the not-done ones that need no new
dependency: compile-time checks that no secret type is Copy, Clone, PartialEq
or Display (A-28, A-31, hand-rolled assert_not_impl), ZeroizeOnDrop markers,
redacted Debug, no input bytes in errors (A-30), distinct secrets for all 1120
ciphertext flips (A-03), a spliced key (A-06), deterministic implicit rejection
(A-18), and the KDF-encoding and purpose-separation unit tests (A-08, A-09).

qa_r2_02_non_canonical_x25519_public_key_is_refused FAILS on purpose: a pk_X
with bit 255 set parses, and the exchange then silently derives mismatched PSKs.
2026-11-25 08:16:44 +01:00
mnovak 853f59ca60 fix: report an over-long plaintext as MessageTooLong, not DecryptionFailed 2026-11-25 07:48:55 +01:00
mnovak e0c6d53a99 docs: record D-QA-1, the mutual exchange (A-15), the hazmat gate (A-35) and the corrected ml-kem fact 2026-11-25 07:47:46 +01:00
mnovak 91b84459b0 test: frozen v1 golden vectors for PSKs and the sealed format (QA A-10, A-38) 2026-11-25 07:42:27 +01:00
mnovak 6233c8244e test: hygiene check sees arcanum's own features; A-15 binding goes through session_prk 2026-11-25 07:40:57 +01:00
mnovak 89b5329f06 feat: X-Wing (draft -11), mutual exchange, WireGuard PSK per epoch, sealed box
X-Wing is composed from ml-kem, x25519-dalek, sha3 and shake and matches the
draft's vectors. The PSK comes from a mutual exchange (each peer encapsulates
to the other, QA A-15) bound to the full transcript in Arcanum's own HKDF layer
(QA D-QA-1). Low-order X25519 values are refused. Deterministic entry points
sit behind the off-by-default hazmat feature, enabled only for the tests.
2026-11-25 07:38:55 +01:00
mnovak c7d050ed65 test: the six mandatory tests, pinned KAT vectors, fuzz target and cargo-deny config (written before the code) 2026-11-25 07:28:48 +01:00
mnovak ed9b8a3b17 docs: Day 1 analysis (X-Wing draft -11, key schedule, PSK rotation) and threat model 2026-11-25 07:23:10 +01:00
64 changed files with 17708 additions and 2 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
Generated
+626
View File
@@ -0,0 +1,626 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aead"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "arcanum"
version = "0.2.0"
dependencies = [
"arcanum",
"base64",
"chacha20",
"chacha20poly1305",
"curve25519-dalek",
"ed25519-dalek",
"hex",
"hkdf",
"hmac",
"ml-dsa",
"ml-kem",
"rand_core",
"serde",
"serde_json",
"sha2",
"sha3",
"shake",
"x-wing",
"x25519-dalek",
"zeroize",
]
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
"zeroize",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"rand_core",
"zeroize",
]
[[package]]
name = "chacha20poly1305"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
"aead",
"chacha20",
"cipher",
"poly1305",
"zeroize",
]
[[package]]
name = "cipher"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
"block-buffer",
"crypto-common",
"inout",
]
[[package]]
name = "cmov"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
[[package]]
name = "const-oid"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
"rand_core",
]
[[package]]
name = "ctutils"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
dependencies = [
"cmov",
]
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
dependencies = [
"cfg-if",
"cpufeatures",
"curve25519-dalek-derive",
"digest",
"fiat-crypto",
"rustc_version",
"subtle",
"zeroize",
]
[[package]]
name = "curve25519-dalek-derive"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "der"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004"
dependencies = [
"const-oid",
"zeroize",
]
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
"ctutils",
"zeroize",
]
[[package]]
name = "ed25519"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
dependencies = [
"signature",
]
[[package]]
name = "ed25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
dependencies = [
"curve25519-dalek",
"ed25519",
"sha2",
"subtle",
"zeroize",
]
[[package]]
name = "fiat-crypto"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
[[package]]
name = "hex"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
[[package]]
name = "hkdf"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
dependencies = [
"hmac",
]
[[package]]
name = "hmac"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
dependencies = [
"digest",
]
[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
"ctutils",
"typenum",
"zeroize",
]
[[package]]
name = "inout"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
dependencies = [
"hybrid-array",
]
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "keccak"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8f198d1db720e4940b5a493201d199d9f24f568f8f746bd13706243a2f71598"
dependencies = [
"cfg-if",
"cpufeatures",
]
[[package]]
name = "kem"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01737161ba802849cfd486b5bd209d38ba4943494c249a8126005170c7621edd"
dependencies = [
"crypto-common",
"rand_core",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "ml-dsa"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f6d49c3f3f0e10e18ca975ffda66f8da0ec36521c1d911adcbc521bf0743f5c"
dependencies = [
"crypto-common",
"ctutils",
"hybrid-array",
"module-lattice",
"pkcs8",
"shake",
"signature",
"zeroize",
]
[[package]]
name = "ml-kem"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84ca78b66f46050d49fa21693ae8adab2081d8101b65d8067316b6b70b64a0d1"
dependencies = [
"hybrid-array",
"kem",
"module-lattice",
"rand_core",
"sha3",
"shake",
"zeroize",
]
[[package]]
name = "module-lattice"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4a1e412c8ee83a1c678f427806219c49c96b2511b9f07497514f0e43fb26155"
dependencies = [
"ctutils",
"hybrid-array",
"num-traits",
"zeroize",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "pkcs8"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
dependencies = [
"der",
"spki",
]
[[package]]
name = "poly1305"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
dependencies = [
"cpufeatures",
"universal-hash",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "sha2"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha3"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc9bad02c26382724b2d2692c6f179285e4b54eeecd7968f52a50059c3c11759"
dependencies = [
"digest",
"keccak",
"sponge-cursor",
]
[[package]]
name = "shake"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09057cb2149ad4cbd2da1e26b351f9a4c354219421229c69c3063e6f61947c4a"
dependencies = [
"digest",
"keccak",
"sponge-cursor",
]
[[package]]
name = "signature"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
dependencies = [
"digest",
"rand_core",
]
[[package]]
name = "spki"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
dependencies = [
"base64ct",
"der",
]
[[package]]
name = "sponge-cursor"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620"
dependencies = [
"zeroize",
]
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "universal-hash"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
dependencies = [
"crypto-common",
"ctutils",
]
[[package]]
name = "x-wing"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01576e56599d01d75c5efcd5b30fa5de29e776f5a225e43fbf8c92c7302d4c8b"
dependencies = [
"kem",
"ml-kem",
"sha3",
"shake",
"x25519-dalek",
]
[[package]]
name = "x25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6"
dependencies = [
"curve25519-dalek",
"rand_core",
"zeroize",
]
[[package]]
name = "zeroize"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+54
View File
@@ -0,0 +1,54 @@
[package]
name = "arcanum"
version = "0.2.0"
edition = "2024"
rust-version = "1.88"
license = "CPAL-1.0"
description = "Hybrid post-quantum key exchange (X-Wing: ML-KEM-768 + X25519), key schedule, WireGuard PSK derivation, sealing and hybrid signatures (ML-DSA-65 + Ed25519, RFC 10073) for the Domi ecosystem"
repository = "https://gitea.marek-novak.cz/mnovak/arcanum"
readme = "README.md"
publish = false
[dependencies]
# Primitives: every one from a vetted crate, none written here (docs/01_arcanum.md).
ml-kem = { version = "=0.3.4", default-features = false, features = ["zeroize"] }
x25519-dalek = { version = "=3.0.0", default-features = false, features = ["static_secrets", "zeroize"] }
sha3 = { version = "0.12", default-features = false, features = ["zeroize"] }
shake = { version = "0.1", default-features = false, features = ["zeroize"] }
sha2 = { version = "0.11", default-features = false, features = ["zeroize"] }
hkdf = { version = "0.13", default-features = false }
hmac = { version = "0.13", default-features = false, features = ["zeroize"] }
chacha20poly1305 = { version = "0.11", default-features = false, features = ["alloc", "zeroize"] }
rand_core = { version = "0.10", default-features = false }
zeroize = { version = "1.8", default-features = false, features = ["alloc", "zeroize_derive"] }
# v0.2.0 signatures (docs/02_signatures.md): ML-DSA-65 (FIPS 204) and Ed25519 (RFC 8032), combined as
# RFC 10073 id-MLDSA65-Ed25519-SHA512. Pinned exactly; `zeroize` is opt-in in ml-dsa and must stay on.
ml-dsa = { version = "=0.1.2", default-features = false, features = ["alloc", "rand_core", "zeroize"] }
ed25519-dalek = { version = "=3.0.0", default-features = false, features = ["zeroize"] }
[features]
# Deterministic entry points (`_derand`, `from_seed`) and the bare RFC 10073 signature interface
# (`sign_composite_raw`, `verify_composite_raw`) for the known-answer tests. Off by default;
# never enable it in a release build (tests/feature_hygiene.rs checks the normal dependency graph).
hazmat = []
[dev-dependencies]
# The tests enable `hazmat` on the crate itself; dev-dependencies never reach a normal build.
arcanum = { path = ".", features = ["hazmat"] }
# Reference implementation for the differential test only; never linked into the library.
x-wing = { version = "=0.1.1" }
chacha20 = { version = "0.10", default-features = false, features = ["rng"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
hex = "0.4"
sha2 = "0.11"
# The RFC 10073 vectors are base64.
base64 = "0.22"
# Ed25519 scalar arithmetic, for the small-order-R half (QA S-01). Already in the lock via ed25519-dalek.
curve25519-dalek = { version = "=5.0.0", default-features = false }
# ML-KEM in a debug build is slow; the byte-flip tests run thousands of exchanges.
[profile.dev.package."*"]
opt-level = 2
[profile.test.package."*"]
opt-level = 2
+189
View File
@@ -0,0 +1,189 @@
# Handover — Arcanum
Newest entry first. Where this file and the code disagree, the code wins and the next entry says so.
## 2026-11-26 — v0.2.0, QA review answered (builder), still on `feature/signatures`, not merged, not tagged
QA's review (`Via/qa/review-arcanum-pr2.md`, head `d56ee10`): no blocker, no major, 12 minors (S-01 to
S-12). Answered in `99db18a..` this entry; QA's proof tests (`qa_sig_review.rs`) ported where they pin
something, into the existing test files.
**Fixed:**
- S-01, S-02, S-03: tests pin `verify_strict` (a small-order R in the Ed25519 half is refused), the order
of checks in `verify_binding` (a forged window outside `now` is `InvalidSignature`, never
`OutsideValidity`) and two independent seeds in `generate` (exactly 64 bytes drawn, in order). QA's
mutations now fail: Q1 `verify_strict` → `verify` fails `a_small_order_r_in_the_ed25519_half_is_refused`;
Q3 `now` checked first fails `a_forged_window_that_excludes_now_is_invalid_signature_not_outside_validity`;
Q4 the Ed25519 seed copied from the ML-DSA seed fails `generate_draws_two_independent_seeds`.
- S-05: an ML-DSA-65 key with t1 = 0 is refused as `InvalidVerifyingKey`; removing the check fails
`an_ml_dsa_key_with_zero_t1_is_refused`.
- S-09: `AppContext::new` is a `const fn` taking `&'static [u8]`, the only constructor; a consumer passing a
runtime `Vec` does not compile (`sig_hygiene`, E0597/E0716). **API change** from `d56ee10`.
- S-10: `deny.toml` bans `legacy_compatibility` on `ed25519-dalek` and `curve25519-dalek`, and
`ed25519-dalek/hazmat`; enabling either in `Cargo.toml` fails `cargo deny --offline check bans` (checked,
reverted).
- S-06: the docs no longer claim timing hides which half failed; it does not, harmlessly (public data only).
`&` became `&&`; no behaviour change.
- S-04: the zeroize probe also watches the canary key's expanded ML-DSA K and a window of encoded s1; QA's
Q15 (an unwiped `to_expanded()` copy in `SigningKey`) now fails the probe.
- S-11: stack need documented on `SigningKey`, measured with `tests/sig_stack.rs`: release overflows at
128 KiB and fits in 256 KiB; Arcanum's debug profile overflows at 256 KiB and fits in 512 KiB. A thread
that is too small aborts the process. **Consumers that sign on small threads (worker pools, async
blocking pools, JNI): give them at least 512 KiB.** The release figure is pinned by a test (ignored in
debug).
- The expanded key moves about 35 kB (34,992 B) through the stack when a key is built, not 64 kB.
**Recorded as gaps** (docs/02_signatures.md, and THREAT_MODEL for S-04): S-04's `rnd`/ρ''/y stack residue
inside `ml-dsa`; S-07, the composite is a **separate** identity, never a wrapped Tessera Ed25519 seed
(recommendation under open question 1; `from_bytes` cannot detect reuse); S-08, a binding does not tie
`id` to `vk` and has no serial (Day 3's replay design with QA E-07; also on `verify_binding`'s docs);
S-12, none of the 9 ML-DSA-65 "modified z" sigVer cases at `a7f283cd` reaches the ‖z‖∞ bound (largest
|z| 524,077 < 524,092, decoded by script from the original file), so no ACVP case could be added; only
Wycheproof tests the bound.
**Counts, run by the builder** at `0b2480b` (this entry only adds docs), Windows 10, `cargo 1.99.0`:
| Run | Result |
|:--|:--|
| `cargo test` (debug) | **126 passed, 0 failed, 5 ignored** (the release-only stack test and four stack measurements) |
| `cargo test --release` | **127 passed, 0 failed, 4 ignored** (the four measurements) |
| `cargo clippy --all-targets --all-features -- -D warnings` | clean |
| `cargo fmt --check` (crate, probe, fuzz) | clean |
| `zeroize-probe` (`--test-threads=1`) | 1 passed (now also K and s1 of the expanded key) |
| `cargo deny --offline check` | advisories ok, bans ok, licenses ok, sources ok |
| fuzz `signatures` (rebuilt: `src/` and the target changed) | **601 s, 181,113 executions, 0 crashes, 0 artifacts** (301 exec/s, coverage 3,564), on `0b2480b` |
`cargo audit` was not re-run (no dependency changed except the `curve25519-dalek` dev-dependency,
already in the lock). New since `d56ee10`: 3 tests (S-01 to S-03), 1 (S-05), 1 doctest (the `const`
`AppContext`), `sig_stack.rs` (1 + 4 ignored).
**For consumers, added:** ban `ed25519-dalek/legacy_compatibility` and `curve25519-dalek/legacy_compatibility`
in `deny.toml`, next to `ed25519-dalek/hazmat`; build `AppContext`s as `const`s; check that `vk` is the
right key for `id` before trusting `verify_binding`, and refuse bindings older than the newest per `id`.
## 2026-11-25 — v0.2.0 built (builder), on `feature/signatures` (PR #2), not merged, not tagged
**What it adds:** `arcanum::sign`, hybrid signatures ML-DSA-65 + Ed25519, exactly RFC 10073
`id-MLDSA65-Ed25519-SHA512` (design: `docs/02_signatures.md`, which now has an "As built" section).
Public key 1984 B, signature 3373 B, private key 64 B (ML-DSA seed || Ed25519 seed). The ML-DSA half is
`ExpandedSigningKey::sign_randomized(M', ctx = Label, rng)`, hedged; the Ed25519 half is pure Ed25519 over
M', checked with `verify_strict`; one `InvalidSignature` whichever half fails. `AppContext` (only
`domi/arcanum/v2/sig/app/` + a 1–231-byte label), `bind_kem_key` / `verify_binding` for X-Wing keys under
`domi/arcanum/v2/sig/kem-key`. The bare RFC interface (`sign_composite_raw`, `verify_composite_raw`, any
ctx) is `hazmat` only and still hedged. Stricter than the RFC: a non-canonical or small-order Ed25519 key
is refused at parse. `ml-dsa =0.1.2` (alloc, rand_core, zeroize) and `ed25519-dalek =3.0.0` (zeroize),
default features off. v0.1.0's bytes are unchanged (`tests/golden_v1.rs` untouched, passing).
**Vectors** (`tests/vectors/SOURCES.md`, sha256 of every original and subset): ACVP ML-DSA keyGen (whole)
and sigGen at `2972def2`, sigVer at `a7f283cd`; Wycheproof `ed25519_test` and `mldsa_65_sign_seed` (whole)
and `mldsa_65_verify` (subset) at `20b25694`; the composite-sigs `testvectors.json` at `f0627ab` (the
`id-MLDSA65-Ed25519-SHA512` entry); RFC 8032 §7.1. Subsets made by `tests/vectors/make_subsets.py`.
**Counts, run by the builder** on `feature/signatures`, Windows 10, `cargo 1.99.0` stable MSVC,
`--target-dir D:/cargo-target/arcanum-v2` (intermediates in `D:/cargo-build/`, the machine's `build-dir`):
| Run | Result |
|:--|:--|
| `cargo test` (debug) | **121 passed, 0 failed, 0 ignored** (82 from v0.1.0 + 39 new) |
| `cargo test --release` | **121 passed, 0 failed, 0 ignored** |
| `cargo clippy --all-targets --all-features -- -D warnings` | clean |
| `cargo fmt --check` | clean |
| `zeroize-probe` (`--test-threads=1`) | 1 passed (now also covers the signing key, `to_bytes`, signing and binding) |
| `cargo deny check` | advisories ok, bans ok, licenses ok, sources ok |
| `cargo audit` | 64 crates, 0 vulnerabilities, 0 warnings (advisory db of 2026-11-25, 1,568 advisories) |
| fuzz `signatures` (new) | **605 s, 38,609 executions, 0 crashes, 0 artifacts** (libFuzzer + ASan, nightly `1.102.0` 2026-11-24, MSVC 14.44 asan runtime; coverage 3,549; 63 exec/s; corpus and artifacts on D:), on `5a52854` + the target |
New tests: `kat_mldsa65` 6, `kat_ed25519` 3, `sig_composite` 6, `sig_halves` 5, `sig_every_byte` 7,
`sig_malformed` 5, `sig_hygiene` 6, `feature_hygiene` +1.
**Answers to the doc's open gap:** `verify_strict` accepts both RFC 10073 vectors (`s`, `sWithContext`),
and agrees with all 151 Wycheproof Ed25519 verdicts.
**Mutation checks by the builder** (each reintroduced with `src/sign.rs` edited, seen to fail, reverted;
`git diff` clean after):
- M1, test 4: verify checks only the ML-DSA half (`if ml_ok`): fails `a_zeroed_or_missing_half_is_refused`
and `a_half_from_another_signature_is_refused`.
- M2, test 3/4: the ML-DSA half signs and verifies with an empty ctx instead of Label: fails
`rfc_signatures_verify`, `own_signatures_verify_under_an_independent_rebuild_of_m_prime`,
`ml_dsa_half_uses_the_label_as_its_context` (cargo stopped there; `sig_halves` not reached).
- M3, test 5: ctx left out of M' (its length kept): fails `flipping_any_byte_of_the_context_fails`.
- M4, test 5: `not_after` left out of the binding hash: fails `every_field_of_a_key_binding_matters` and
`a_key_binding_never_verifies_as_an_app_message_and_back` (the documented encoding no longer matches).
- M5, hygiene: `verify_composite_raw` ungated: fails `the_raw_interface_is_not_reachable_without_hazmat`.
- M6, hygiene: `#[derive(Clone)]` on `SigningKey`: fails `ml_dsa_internals_are_not_reachable`.
- M7, test 6: `is_weak()` dropped from the key check: fails `weak_and_non_canonical_ed25519_keys_are_refused`.
**Not verified:** constant time (dudect, Day 7); anything on Linux; interop with a non-Rust RFC 10073
implementation beyond the RFC's own vector (one key, two signatures); a byte-exact composite signing KAT
(the RFC's vectors are hedged; byte-exact checks exist per half); the ACVP and Wycheproof cases dropped by
the subsets; HashML-DSA (not used). The fuzz run is one 10-minute run at 63 exec/s (ASan and ML-DSA are
slow), far fewer executions than v0.1.0's target. The first test commit (`2a432f5`) failed by not compiling
(the module did not exist); it also had one test bug, fixed in `5a52854`. Not audited.
**For consumers:** as for v0.1.0, and also ban a direct `ml-dsa` dependency in `deny.toml` (its
`sign_internal`, `sign_mu_deterministic` and empty-ctx `Signer` are public) and `ed25519-dalek/hazmat`;
never use a composite signature as an identifier (not SUF-CMA, RFC 10073 §9.2, pinned by `sig_halves`).
## 2026-11-25 — v0.1.0 (owner session)
**Who owns this:** the Via owner session. Mark's decisions go through the orchestrator session.
**Released:** `v0.1.0`, an annotated tag on the `--no-ff` merge of PR #1 (`feature/arcanum`, head
`96086be` plus this file) into `main`. **Not audited.** Whether later releases must be signed through
Artifex is an open question for Mark; this tag is not signed.
**What it is:** one `#![no_std]`, `#![forbid(unsafe_code)]` crate, no I/O, no clock, randomness as a
parameter.
- `xwing`: X-Wing (ML-KEM-768 + X25519), draft-connolly-cfrg-xwing-kem-**11**, unmodified (D-QA-1), stricter
in two ways invisible to honest peers: low-order X25519 inputs are `NonContributory`, and a public key whose
X25519 half is not canonical is `InvalidPublicKey` (QA R2-02).
- **The raw one-way KEM is `hazmat` only** (QA R2-01): a release consumer can parse keys and ciphertexts and
generate a key pair, but cannot encapsulate, decapsulate or read an X-Wing secret.
- `exchange`: the mutual exchange (QA A-15), the full transcript bound in Arcanum's HKDF-SHA-256 layer
under `domi/arcanum/v1/...` labels, `Session::wireguard_psk(epoch)`; `RECOMMENDED_EPOCH_SECONDS = 120`.
- `seal`: a one-shot sealed box, 1137 bytes of overhead, no sender authentication, not HPKE.
- `expand` takes exactly one label and one fixed-width field (QA R2-03); the v1 bytes are unchanged
(`tests/golden_v1.rs`).
- Every function that takes an RNG says it must be the OS RNG or a CSPRNG seeded once from it (QA R2-04).
- Licence: CustosPublic's CPAL-1.0 text byte for byte, Exhibit A naming Arcanum, Exhibit B "Built on Domi".
**Counts, run by the owner session** on a fresh clone at `96086be`, Windows 10, `cargo 1.99.0` stable MSVC:
| Run | Result |
|:--|:--|
| `cargo test` (debug) | **82 passed, 0 failed, 0 ignored** |
| `cargo test --release` | **82 passed, 0 failed, 0 ignored** |
| `cargo clippy --all-targets --all-features -- -D warnings` | clean |
| `cargo fmt --check` | clean |
| `zeroize-probe` (`--test-threads=1`) | 1 passed |
| `cargo deny check` | advisories ok, bans ok, licenses ok, sources ok |
| `cargo audit` | 55 crates, 0 vulnerabilities |
| fuzz `untrusted_input` | **631 s, 172,694 executions, 0 crashes, 0 artifacts** (libFuzzer + ASan, nightly `1.102.0`, Windows MSVC; coverage 1,812 edges), on `96086be` |
**Mutation checks by the owner session** (each reintroduced, seen to fail, reverted):
- R2-02: skipping the canonical check fails `qa_r2_02_non_canonical_x25519_public_key_is_refused`.
- R2-01: making `encapsulate` and `SharedSecret::as_bytes` public again fails
`qa_r2_01_raw_shared_secret_is_not_reachable_without_hazmat`. Ungating `as_bytes` alone does not fail
it, correctly: no release function produces a `SharedSecret` then. The test reaches the secret only
through `encapsulate`, not `decapsulate` (a minor gap).
**For consumers (via, via-core, Canalis, Custos, Tabellarius):** depend by git tag, never by path; never
enable `arcanum/hazmat` outside tests, and repeat `tests/feature_hygiene.rs`'s `cargo tree` check in CI; ban a
direct `ml-kem` dependency in `deny.toml` (its `encapsulate_deterministic` is public); pass the OS RNG and
grep for `from_seed(` outside `tests/`.
**Carried to Day 3 (recorded, not Arcanum bugs):** no forward secrecy against later theft of both static
secret keys (a fresh exchange with an ephemeral key pair per epoch); no key-confirmation message; epoch
state and the replay window (A-12, A-13) live in the engine; `Initiation<'a>` borrows the secret key, which
may need an owned variant in async code (a 0.x API change).
**Not verified:** constant time (QA A-32, dudect, belongs in the Day 7 audit pack on a quiet Linux box);
anything on Linux; FIPS 203 from the NIST PDF; RFC 7748's 1,000,000-iteration vector; interop with a
non-Rust X-Wing. There is no CI: every number here was run by hand.
## 2026-11-25 — Day 1 built (builder), reviewed twice (QA)
The builder's PR (67 tests, 661 s of fuzzing) and two QA reviews: the first QA attack plan
(`Via/qa/01_arcanum_attacks.md`), and the second review (`Via/qa/review-arcanum-pr1.md`, findings R2-01 to
R2-05, comments #49902–#49909), answered in `6780abc` and `96086be` (replies #49927–#49931, summary #49951).
+32 -2
View File
@@ -4,14 +4,44 @@ Arcanum is the shared post-quantum crypto core of the Domi ecosystem. It is one
crate that gives every Domi product a hybrid key exchange: ML-KEM-768 (FIPS 203) combined crate that gives every Domi product a hybrid key exchange: ML-KEM-768 (FIPS 203) combined
with X25519, so a shared secret stays safe as long as either of the two holds. with X25519, so a shared secret stays safe as long as either of the two holds.
Since v0.2.0 it also signs: a hybrid ML-DSA-65 + Ed25519 signature, exactly RFC 10073
`id-MLDSA65-Ed25519-SHA512`, which stays unforgeable while either half holds, and a helper that
binds an X-Wing public key to its owner.
Via Domi uses it first, to derive and rotate the WireGuard pre-shared key. Canalis, Custos Via Domi uses it first, to derive and rotate the WireGuard pre-shared key. Canalis, Custos
sealing and Tabellarius are expected to adopt it later. sealing and Tabellarius are expected to adopt it later.
- No primitive is written here. ML-KEM, X25519, SHA-3, HKDF and ChaCha20-Poly1305 come from - No primitive is written here. ML-KEM, X25519, ML-DSA, Ed25519, SHA-2, SHA-3, HKDF and
vetted RustCrypto and dalek crates. ChaCha20-Poly1305 come from vetted RustCrypto and dalek crates.
- No I/O, no network, no clock. Randomness is passed in by the caller. - No I/O, no network, no clock. Randomness is passed in by the caller.
- No `unsafe` code. - No `unsafe` code.
## Use
```rust
let init = arcanum::exchange::initiate(&my_secret, &peer_public, context, &mut rng)?;
// send init.ciphertext() to the peer, which calls exchange::respond and sends back ct_ri
let session = init.finish(&ct_ri)?;
let psk = session.wireguard_psk(arcanum::epoch_at(unix_seconds)); // one exchange per 120 s epoch
```
```rust
let ctx = arcanum::sign::AppContext::new(b"plans")?;
let sig = signing_key.sign(plan_bytes, &ctx, &mut rng)?; // 3373 bytes
signing_key.verifying_key().verify(plan_bytes, &ctx, &sig)?; // 1984-byte public key
let binding = arcanum::sign::bind_kem_key(&signing_key, device_id, xwing_sk.public_key(), (from, until), &mut rng)?;
```
## Checks
```
cargo test # KATs, binding, epochs, malformed input, golden vectors, feature graph
cargo deny check
cargo audit
cargo +nightly fuzz run --release untrusted_input -- -max_total_time=600
cargo +nightly fuzz run --release signatures -- -max_total_time=600
```
**Not audited.** Nothing here is called secure before an external audit. **Not audited.** Nothing here is called secure before an external audit.
The design, the risks and the threat model are in `docs/`. The design, the risks and the threat model are in `docs/`.
+47
View File
@@ -0,0 +1,47 @@
# cargo deny configuration for Arcanum (mandatory test 6). Run: cargo deny check
[graph]
all-features = true
[advisories]
# Every RustSec advisory, including unmaintained and unsound crates, is an error.
version = 2
yanked = "deny"
ignore = []
[licenses]
version = 2
# Licences of the dependency tree; each was checked against the crates' own LICENSE files.
allow = [
"Apache-2.0",
"MIT",
"BSD-3-Clause",
"Unicode-3.0",
]
confidence-threshold = 0.9
[licenses.private]
ignore = true
[bans]
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"
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
allow-git = []
+303
View File
@@ -0,0 +1,303 @@
# Day 1 — Arcanum
Status: v0.1.0 candidate, **not audited**. Nothing here is called secure before an external audit.
## Why
Every Domi product that moves data between devices (Via first, then Canalis, Custos sealing and
Tabellarius) needs a key exchange that survives a future quantum computer. Traffic recorded today
can be decrypted later ("harvest now, decrypt later"), so the protection has to be in place before
such a computer exists. Arcanum is the one small, reviewable crate that provides it, so the
ecosystem audits one piece of code instead of five.
## What
| Piece | What it does | Standard |
|:--|:--|:--|
| `xwing` | Hybrid KEM: ML-KEM-768 + X25519, X-Wing exactly as drafted | draft-connolly-cfrg-xwing-kem-11, FIPS 203, RFC 7748 |
| `exchange` | A **mutual** exchange: each peer encapsulates to the other's public key; both get a `Session` bound to both secrets, the full transcript and a caller context | HKDF (RFC 5869) with SHA-256 |
| `Session::wireguard_psk(epoch)` | The 32-byte WireGuard pre-shared key for one rotation epoch | HKDF-Expand |
| `seal` / `open` | One-shot sealed box to a recipient's hybrid public key | X-Wing + HKDF + ChaCha20-Poly1305 (RFC 8439) |
Not in scope for Day 1: networking, WireGuard itself, signatures (ML-DSA comes later), migrating
other Domi apps.
## How
### Primitives (all from vetted crates, none written here)
| Primitive | Crate | Version locked | Notes |
|:--|:--|:--|:--|
| ML-KEM-768 | `ml-kem` (RustCrypto) | 0.3.4 | FIPS 203 final. README: "never been independently audited". |
| X25519 | `x25519-dalek` | 3.0.0 | with `curve25519-dalek` 5.0.0 |
| SHA3-256 | `sha3` (RustCrypto) | 0.12.0 | X-Wing combiner |
| SHAKE256 | `shake` (RustCrypto) | 0.1.0 | X-Wing key expansion |
| HKDF-SHA-256 | `hkdf` 0.13.0, `hmac` 0.13.0, `sha2` 0.11.1 | | key schedule |
| ChaCha20-Poly1305 | `chacha20poly1305` (RustCrypto) | 0.11.0 | sealing |
| Zeroisation | `zeroize` | 1.9.2 | every secret type is `ZeroizeOnDrop` |
Exact versions are pinned by `Cargo.lock`, which is committed. `ml-kem` and `x25519-dalek` are
pinned with `=` in `Cargo.toml` as well, so an upgrade is a deliberate edit that re-runs the KATs.
### The hybrid KEM: X-Wing, draft -11 (decision D-QA-1)
Facts checked on 2026-11-25:
- The current draft is **draft-connolly-cfrg-xwing-kem-11**, dated 2026-09-23, an individual
Internet-Draft (intended status Informational), not an RFC and not CFRG-adopted.
Source: <https://datatracker.ietf.org/doc/draft-connolly-cfrg-xwing-kem/>.
- Its change log lists only editorial changes since -06 (ASN.1 module, SHAKE output length stated
in bits, implementation list, PEM header). Source: Appendix G of
<https://www.ietf.org/archive/id/draft-connolly-cfrg-xwing-kem-11.txt>.
- Appendix C has three vectors and still carries the note "TODO: replace with test vectors that
re-use ML-KEM, X25519 values", so **later drafts may change the vectors**. Arcanum pins the vector
file by sha256 together with the draft number (`tests/vectors/SOURCES.md`); a changed file fails
the KAT, and moving to a new draft is a deliberate decision.
- RustCrypto's `x-wing` 0.1.1 (2026-10-01) describes itself as draft 06; its vectors are the same
three as draft -11 (identical after removing whitespace).
**Decision D-QA-1 (recommended by QA, adopted).** Mark's spec asks for a combiner that hashes both
shared secrets, both ciphertexts and both public keys, "X-Wing-style … use it if it fits". X-Wing's
combiner hashes `ss_M`, `ss_X`, `ct_X` and `pk_X` and deliberately leaves `ct_M` and `pk_M` to
ML-KEM's own binding (draft -11 §5.3). So:
1. **The KEM is X-Wing, unmodified**, so the draft's vectors pass byte for byte:
```
expand(sk) = SHAKE256(sk, 96 bytes) -> d = [0:32], z = [32:64], sk_X = [64:96]
(pk_M, dk_M) = ML-KEM-768.KeyGen_internal(d, z); pk_X = X25519(sk_X, 9)
Encaps(pk, eseed) : (ct_M, ss_M) = ML-KEM-768.Encaps_internal(pk_M, eseed[0:32])
ek_X = eseed[32:64]; ct_X = X25519(ek_X, 9); ss_X = X25519(ek_X, pk_X)
Combiner = SHA3-256(ss_M || ss_X || ct_X || pk_X || "\.//^\")
```
2. **Both public keys and both ciphertexts are bound in Arcanum's own key schedule**, where the
`domi/arcanum/v1/...` labels live (below). That meets the spec in full, and the spec's own
"use it if it fits" condition holds.
Arcanum composes X-Wing from `ml-kem`, `x25519-dalek`, `sha3` and `shake` rather than calling the
`x-wing` crate, because mandatory test 3 needs the combiner as a separate function and because
Arcanum wants typed errors for every malformed input. The composition is about twenty lines of
glue between vetted primitives. It is pinned by the draft's three vectors **and** by a differential
test against RustCrypto `x-wing` (a dev-dependency only) over random seeds and random ciphertexts.
**Stricter than the draft, on purpose.** Arcanum rejects an X25519 public key or ciphertext part
that is a low-order point (`was_contributory() == false`, a constant-time check in `x25519-dalek`).
An honest key or ciphertext is never such a point, so this changes no honest exchange and no
official vector; it removes the case where the classical half silently contributes a known value
(QA A-16, A-17). RustCrypto ships the same option as `DecapsulationKeyRejectNonContrib`.
**Canonical X25519 public keys only (QA R2-02).** Draft -11 says nothing about the encoding of
`pk_X` beyond "the 32 byte string representing the u-coordinate" (§4), and its Python reference
decodes with `% p`, so it would accept aliases. RFC 7748 decoders mask bit 255 and reduce mod p,
which means `pk_X`, `pk_X` with bit 255 set, and `pk_X + p` (where that fits) are the same key to
X25519 but different bytes to the combiner and the transcript: a peer given an alias "succeeds" and
silently derives a PSK the owner never matches. `PublicKey::from_bytes` therefore refuses an
X25519 half with bit 255 set or a value of at least 2^255 - 19, as `Error::InvalidPublicKey`.
X25519 outputs are always canonical, so no honest key and no official vector is affected. A
ciphertext's `ct_X` is not checked this way: it is single-use, and its raw bytes are bound by the
combiner (QA A-04), so an alias only gives a different secret.
**ML-KEM key check.** The draft requires the FIPS 203 §7.2 encapsulation key check.
`ml-kem`'s `EncapsulationKey::new` performs it; Arcanum maps its failure to
`Error::InvalidPublicKey`, and the NIST ACVP `encapsulationKeyCheck` vectors check that.
**X25519 clamping.** Five bits of the 32-byte X25519 ephemeral scalar (bits 0–2 of the first byte,
bits 6–7 of the last) are clamped by RFC 7748, so changing only those bits of `eseed[32:64]` does
not change the exchange. That is the standard's behaviour, not a binding gap; the byte-flip test
flips bit 4 of each byte.
### Is `ml-kem` stable enough?
- `ml-kem` 0.3.4 (2026-10-31) is the newest release; the 0.3 line has been out since 2026-04-28
(0.3.0, 0.3.2, 0.3.3, 0.3.4). Source: <https://crates.io/api/v1/crates/ml-kem>. It depends on
`rand_core` 0.10 (read from its `Cargo.toml`).
- It is still 0.x, so a minor bump may break the API. Its README says it implements FIPS 203
(final) and that it **"has never been independently audited"**. Source:
<https://github.com/RustCrypto/KEMs/blob/master/ml-kem/README.md>.
- **Correction to a QA fact (F10):** in 0.3.4, `EncapsulationKey::encapsulate_deterministic` is
public **whether or not** the `hazmat` feature is on; `hazmat` only un-hides it in the docs
(`#[cfg_attr(not(feature = "hazmat"), doc(hidden))]`, `src/encapsulation_key.rs`). So `ml-kem`'s
feature gives no protection; Arcanum's own `hazmat` feature (below) is what gates the
deterministic paths for Domi code.
- Judgement: stable enough for X-Wing in a household mesh where WireGuard's classical security
remains underneath (the PSK can only add security, see THREAT_MODEL.md), **not** stable enough to
be the only protection of anything. The version is pinned; an upgrade re-runs the KATs.
### `x25519-dalek`
`x25519-dalek` 3.0.0 (2026-07-06), the newest stable release, on `curve25519-dalek` 5.0.0, with
`SharedSecret::was_contributory()`. Source: <https://crates.io/api/v1/crates/x25519-dalek> and the
crate source. Used with `static_secrets` and `zeroize`.
### The exchange is mutual (decision on QA A-15)
A PSK from a **single** encapsulation authenticates only the receiver: anyone who knows the
responder's public key can encapsulate to it. Today WireGuard's static X25519 keys authenticate
the peers, but a quantum attacker can recover those from the public keys, and then a one-way PSK
is the only thing left — and the attacker could impersonate the initiator and choose it.
**Chosen: both directions.** The initiator encapsulates to the responder (`ct_IR`), the responder
encapsulates back to the initiator (`ct_RI`), and the session is derived from both secrets and the
whole transcript. Whoever lacks either secret key cannot compute the PSK. This is the design
Rosenpass uses for the same reason. API:
```
let init = exchange::initiate(&my_sk, &peer_pk, context, rng)?; // send init.ciphertext()
let (ct_ri, session) = exchange::respond(&my_sk, &peer_pk, &ct_ir, context, rng)?; // send ct_ri
let session = init.finish(&ct_ri)?;
```
What Day 3 must still do (recorded here and in THREAT_MODEL.md):
- **Authenticate the public keys.** Mutual KEM authentication is only as good as each side's copy
of the other's hybrid public key. Via distributes them signed with Tessera. If Tessera's
signatures are classical (Ed25519), a quantum attacker who can forge them can substitute keys.
That is the gap ML-DSA closes later.
- **Forward secrecy against key theft.** With static key pairs, someone who later steals both
secret keys and has recorded the exchanges can recompute every PSK. Day 3 should add an
ephemeral key pair per exchange (Rosenpass does), or rotate the key pairs.
- **One exchange per epoch**, every 120 s (below).
- **Replay and rollback protection** (QA A-13). Arcanum is pure and keeps no epoch state, so
refusing an old epoch or an old exchange is the caller's job. Arcanum does not wrap epochs: the
caller passes a `u64`, and `epoch_at` is a division (QA A-12 becomes a Day 3 test).
### Key schedule (labels `domi/arcanum/v1/...`)
```
exchange: th = SHA-256("domi/arcanum/v1/transcript/exchange"
|| pk_I (1216) || pk_R (1216) || ct_IR (1120) || ct_RI (1120)
|| u64be(len ctx) || ctx)
prk = HKDF-Extract(salt = "domi/arcanum/v1/extract", ikm = ss_IR || ss_RI || th)
psk(epoch) = HKDF-Expand(prk, "domi/arcanum/v1/wireguard-psk" || u64be(epoch), 32)
seal: th = SHA-256("domi/arcanum/v1/transcript/seal" || pk (1216) || ct (1120)
|| u64be(len aad) || aad)
prk = HKDF-Extract(salt = "domi/arcanum/v1/extract", ikm = ss || th)
key = HKDF-Expand(prk, "domi/arcanum/v1/seal/key", 32)
nonce = HKDF-Expand(prk, "domi/arcanum/v1/seal/nonce", 12)
```
- `pk_*` are whole hybrid public keys (`pk_M || pk_X`) and `ct_*` whole ciphertexts
(`ct_M || ct_X`), so both public keys and both ciphertexts of each direction are hashed.
- Roles are bound by position (initiator first), so a reflected exchange gives a different PSK
(QA A-14).
- Every transcript field before the context is fixed-width and the context is length-prefixed, so
the transcript encoding is injective (QA A-08). The HKDF-Expand helper takes exactly one label
and one fixed-width field array (QA R2-03), so its `info` is injective by its signature, not by
the discipline of its callers; this did not change any v1 byte (the golden vectors are unchanged). Labels are unique, versioned and prefix-free (QA A-07, a unit
test). The epoch is a full 64-bit big-endian value (QA A-11).
- `ctx` is the caller's binding (for Via: both Tessera device ids, the protocol name, the version).
- A v2 changes the labels and never reuses these. The v1 outputs are frozen by golden vectors
(`tests/golden_v1.rs`, QA A-10, A-38), so a "harmless" relabel fails loudly instead of making
every stored Custos blob unopenable.
### WireGuard PSK and rotation
- Rosenpass, the reference design, rotates every two minutes: `REKEY_AFTER_TIME_RESPONDER = 120 s`,
`REKEY_AFTER_TIME_INITIATOR = 130 s` (so the roles alternate), and `REJECT_AFTER_TIME = 180 s`.
Source: <https://github.com/rosenpass/rosenpass/blob/main/rosenpass/src/protocol/constants.rs>,
read 2026-11-25; the code comment cites WireGuard's own two-minute rekey. The Go port
(cunicu.li/go-rosenpass) uses the same 120 s / +10 s / 3 min.
- Arcanum takes no clock. It exports `RECOMMENDED_EPOCH_SECONDS = 120` and a pure helper
`epoch_at(unix_seconds) = unix_seconds / 120`; the caller passes the time.
- `Session::wireguard_psk(epoch)` is deterministic: both peers get the same PSK for the same epoch,
and successive epochs differ. **Forward secrecy between epochs needs a fresh exchange per
epoch.** Deriving several epochs from one session is a fallback when an exchange fails.
### Sealing
`sealed = 0x01 || ct (1120 B) || ChaCha20-Poly1305 ciphertext || tag (16 B)`, AEAD associated
data = the version byte, key and nonce from the schedule above. Each seal uses a fresh
encapsulation, so a key and nonce are never used twice. Overhead is 1137 bytes. **Anyone who knows
the recipient's public key can seal**: there is no sender authentication, and ChaCha20-Poly1305 is
not key-committing, so Custos must not read a successful `open` as proof of who sealed it
(QA A-27). The output buffer is allocated once at its final size, so no buffer that held
plaintext is reallocated and freed unwiped (QA A-29). This is a documented construction, not HPKE
(RFC 9180).
### Shape of the API
- `#![no_std]` with `alloc`, `#![forbid(unsafe_code)]`, no I/O, no clock, no OS RNG in the normal
dependency graph (checked by `tests/feature_hygiene.rs`).
- Randomness is a parameter: `&mut R where R: rand_core::CryptoRng` (rand_core 0.10). **`rng` must
be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it once per
process, never a fixed, derived or configured seed (QA R2-04). `CryptoRng` is only a marker: a
CSPRNG with a constant seed satisfies it and makes `generate`, `initiate`, `respond` and `seal`
fully deterministic, which no type check can prevent. Each of those functions says so.
- **The raw one-way KEM is not in the release API (QA R2-01).** `PublicKey::encapsulate`,
`SecretKey::decapsulate` and `SharedSecret::as_bytes` exist only with `hazmat`. A one-way X-Wing
secret authenticates only the receiver and is bound to no transcript, so a release consumer
can reach a key only through `exchange` (mutual, transcript-bound) or `seal`. Interop with other
X-Wing users, if Domi ever needs it, gets its own loudly named feature and the same
feature-graph check.
- **The `hazmat` feature** exposes the deterministic entry points (`SecretKey::from_seed`,
`PublicKey::encapsulate_derand`, `exchange::{initiate,respond}_derand`, `seal::seal_derand`)
used by the known-answer tests. It is off by default. The tests turn it on through a
self-dev-dependency, which never reaches a normal build; `tests/feature_hygiene.rs` asserts that
neither `arcanum/hazmat` nor `ml-kem/hazmat` is in the normal-edge feature graph, and proves the
check can see the feature when it is on (QA A-34, A-35); `tests/qa_consumer_api.rs` compiles a
default-features consumer to prove none of these items, nor the raw KEM, can be named.
- **Rules for consumers (via-core, via, and later Canalis, Custos, Tabellarius):**
- run the same `cargo tree -e features,normal -i arcanum` / `-i ml-kem` check in CI, so no
`[dependencies]` entry turns on `arcanum/hazmat`;
- **no direct `ml-kem` (or `x25519-dalek`, `x-wing`) dependency**: ban them in `deny.toml`
(`[bans] deny = [...]`, with `arcanum` as the only allowed wrapper). In `ml-kem` 0.3.4,
`encapsulate_deterministic` is public with or without its `hazmat` feature, so a direct
dependency reopens chosen-randomness encapsulation;
- grep for `from_seed(` outside `tests/`, which catches a CSPRNG seeded from a constant (R2-04).
- Every secret type (`SecretKey`, `SharedSecret`, `Session`, `Initiation`, `WireGuardPsk`) is
`ZeroizeOnDrop` (`Initiation` got the marker with QA R2-05), is not `Copy` or `Clone`, has no
`PartialEq`, and prints as `[redacted]` in `Debug` (compile-time asserted in `tests/qa_review.rs`).
`seal` keeps its output buffer `Zeroizing` until the plaintext in it has been encrypted, so the
`MessageTooLong` path wipes the copy (R2-05).
- Every parser returns `Result<_, arcanum::Error>`; errors carry only lengths and variants.
## Tests (written first)
| # | Mandatory test | File |
|:--|:--|:--|
| 1 | KATs: ML-KEM-768 (NIST ACVP), X25519 (RFC 7748), X-Wing (draft -11) + differential vs `x-wing` | `tests/kat_mlkem768.rs`, `tests/kat_x25519.rs`, `tests/kat_xwing.rs` |
| 2 | Both sides derive the same secret; any changed input byte changes it | `tests/exchange.rs` |
| 3 | A zeroed component secret changes the output (both halves bound) | `src/binding_tests.rs`, `tests/binding.rs` |
| 4 | PSK epochs differ and are reproducible | `tests/psk_epochs.rs` |
| 5 | Malformed input gives typed errors, never a panic; fuzz target | `tests/malformed.rs`, `fuzz/fuzz_targets/untrusted_input.rs` |
| 6 | `cargo deny`, `cargo audit` clean; no unsafe | `deny.toml`, `tests/no_unsafe.rs`, `#![forbid(unsafe_code)]` |
Also: `tests/golden_v1.rs` (frozen v1 outputs), `tests/feature_hygiene.rs` (no hazmat, no OS RNG
in the release graph), and QA's `tests/qa_review.rs`, `tests/qa_consumer_api.rs` (what a
default-features consumer can and cannot compile), `src/qa_review_tests.rs` and `zeroize-probe/`.
Vector provenance is in `tests/vectors/SOURCES.md`. QA's attack plan
(`F:\Akce\Via\qa\01_arcanum_attacks.md`) is mapped case by case in the PR's self-review.
## Risks
| Risk | Consequence | Mitigation |
|:--|:--|:--|
| A bug in our X-Wing glue | Peers agree on a weak secret, or interoperate with nobody | Official vectors + differential test vs RustCrypto `x-wing` |
| `ml-kem` or `x25519-dalek` bug, side channel | Weaker PQ or classical half | Hybrid: either half suffices; versions pinned; `cargo audit` |
| Reusing one session for many epochs | No forward secrecy between epochs | Documented; Day 3 runs a fresh exchange per epoch |
| Substituted public key (MITM) | Attacker learns the PSK | Mutual exchange; Via must authenticate both hybrid public keys (Tessera); PQ signatures later. See THREAT_MODEL.md |
| Static key theft later | Recorded exchanges recomputable | Day 3 adds ephemeral keys or rotates key pairs |
| Deterministic API reaching production | Predictable PSKs | `hazmat` off by default; feature-graph test; consumers repeat it |
| Secrets left in memory | Key recovery from a memory dump | `ZeroizeOnDrop` everywhere we own the bytes; residuals listed below |
| Draft changes before RFC | Interop break with other X-Wing users | Draft number and vector sha256 pinned; labels versioned |
| A relabel or re-encoding | Stored sealed blobs unopenable; peers disagree | Golden v1 vectors |
## Gaps (known, not hidden)
- **Not audited**, and neither are `ml-kem` nor the `x-wing` reference.
- **No post-quantum authentication of public keys.** The mutual exchange authenticates whoever
holds the secret keys matching the public keys each side was given; getting the right public
keys is the caller's job, and ML-DSA is out of scope.
- **No forward secrecy against later theft of static secret keys** within Arcanum itself.
- **Side channels** are inherited from the crates; Arcanum adds no constant-time analysis of its
own (QA A-32, a dudect run, is not done).
- **Zeroisation residuals:** HKDF/HMAC and SHA-3 internal states are wiped only as far as those
crates' `zeroize` features go; values moved by the compiler may leave copies on the stack;
`PublicKey` copies are not secret. QA's allocator probe (`zeroize-probe/`, A-29) checks the heap
only: no secret block is freed unwiped; stack copies are out of its reach.
- **Sealing is not HPKE**, and has no sender authentication.
- **X25519 RFC 7748 1,000,000-iteration vector** is not run (minutes in a debug build); the
1- and 1,000-iteration vectors are.
- **FIPS 203 itself** was not read from the NIST PDF; the ML-KEM facts rest on the ACVP vectors,
the draft's references and the `ml-kem` source.
- **Fuzzing** ran on Windows MSVC with libFuzzer for the time recorded in the PR, not continuously.
+218
View File
@@ -0,0 +1,218 @@
# Arcanum v0.2.0: hybrid post-quantum signatures
> (D)TDD document, written before the tests and the code. Mark decided on 2026-11-25: "Yes, before Day 3".
> Research behind every fact here, with URLs and dates: `F:\Akce\Via\research\ml-dsa-2026-11-25.md`.
> The crate facts below were also read from the local cargo registry (`ml-dsa-0.1.2`, `ed25519-dalek-3.0.0`).
## Why
Arcanum v0.1.0 makes the key exchange post-quantum, but its threat model says that everything rests on each
peer holding the **real** hybrid public key of the other. Today that key would be vouched for by Tessera's
Ed25519 signatures, which a quantum attacker can forge, and then substitute keys. v0.2.0 adds a signature
that stays secure while either ML-DSA or Ed25519 does, so Day 3 can authenticate exchanged X-Wing public
keys, and signed plans, post-quantum.
## What
- A **composite signature, ML-DSA-65 + Ed25519**, exactly RFC 10073 (November 2026) `id-MLDSA65-Ed25519-SHA512`
(OID `1.3.6.1.5.5.7.6.48`). No combiner of our own.
- **Key binding:** a helper that signs an X-Wing public key (and a key id and a validity) under a fixed
Arcanum context, so Day 3 can check "this X-Wing key belongs to that device" with one call.
- Same rules as v0.1.0: `#![no_std]`, `#![forbid(unsafe_code)]`, no I/O, no clock, randomness as a parameter,
secrets zeroised on drop, typed errors, deterministic entry points only under `hazmat`.
Out of scope: certificates and X.509 (we use the RFC's construction, not its ASN.1); SLH-DSA; HashML-DSA;
changing v0.1.0's KEM, exchange or seal bytes (they stay frozen by `tests/golden_v1.rs`).
## How
### Primitives (vetted crates, none written here)
| Crate | Version | Features | Why |
|:--|:--|:--|:--|
| `ml-dsa` (RustCrypto) | `=0.1.2` (2026-10-31) | `default-features = false`, `rand_core`, `zeroize`, `alloc` | FIPS 204; pure Rust, `forbid(unsafe_code)`, `no_std`; hedged signing with a context; same ecosystem as `ml-kem` (rand_core 0.10, signature 3, module-lattice 0.2.4, keccak 0.2) |
| `ed25519-dalek` | `=3.0.0` (2026-07-06) | `default-features = false`, `zeroize` | RFC 8032; shares `curve25519-dalek 5.0.0` with `x25519-dalek`; `verify_strict` |
| `sha2` | `0.11` (already a dependency) | — | PH = SHA-512 |
Alternatives looked at and refused: `fips204` (no RustSec history, deterministic signing only behind a test
feature), `libcrux-ml-dsa` (SIMD `unsafe`, four advisories in 2026), `aws-lc-rs` (needs std, empty context
only), `pqcrypto-mldsa` (archived).
**Parameter set: ML-DSA-65**, NIST category 3, matching ML-KEM-768 in X-Wing. It is RFC 10073's
recommendation for the Ed25519 composite and RustCrypto's default. Cost: public key 1984 B, signature
3373 B, private key 64 B (two seeds). ML-DSA-44 (OpenSSH 10.6's choice, signature 2484 B) is the fallback if
size ever matters more than a matched level; it would be a new label, never a silent switch.
### The construction (RFC 10073 §2.2, §3.2, §3.3, §4, §6)
```
Prefix = "CompositeAlgorithmSignatures2025" (32 ASCII bytes)
Label = "COMPSIG-MLDSA65-Ed25519-SHA512" (ASCII, fixed)
M' = Prefix || Label || u8(len(ctx)) || ctx || SHA-512(M) ctx: 0..=255 bytes
Sign: mldsaSig = ML-DSA-65.Sign(mldsaSK, M', ctx = Label) hedged (fresh rnd from the caller's RNG)
edSig = Ed25519.Sign(edSK, M') pure Ed25519, no Ed25519ctx
sig = mldsaSig (3309 B) || edSig (64 B)
Verify: split by fixed lengths (wrong length: invalid); rebuild M';
valid only if ML-DSA-65.Verify(mldsaPK, M', mldsaSig, ctx = Label)
and Ed25519.verify_strict(edPK, M', edSig)
Keys: public = mldsaPK (1952 B) || edPK (32 B)
private = mldsaSeed (32 B) || edSeed (32 B), both generated fresh and never used outside the composite
```
Crate calls, chosen because the convenient traits are wrong for this: `ml-dsa`'s `Signer`/`Verifier` impls
sign **deterministically** with an **empty** context, which is not RFC 10073. Arcanum calls the inherent
`ExpandedSigningKey::sign_randomized(M', Label, rng)` and `VerifyingKey::verify_with_context(M', Label, sig)`,
and builds the expanded key with `ExpandedSigningKey::from_seed`. `SigningKey::sign_internal` (public in 0.1.2,
caller-chosen randomness) is never called outside `hazmat` tests, and via must ban a direct `ml-dsa`
dependency the way it bans `ml-kem`.
### Arcanum's contexts
The RFC's `ctx` is the application's domain separator. Arcanum fixes one per purpose, versioned like the KDF
labels, so a signature made for one purpose never verifies for another:
| Purpose | ctx |
|:--|:--|
| Binding an X-Wing public key to its owner | `domi/arcanum/v2/sig/kem-key` |
| A caller's own messages (Day 3: plans) | `domi/arcanum/v2/sig/app/` + the caller's label (total ≤ 255 B) |
The key-binding message is `u8(version=1) || u64be(not_before) || u64be(not_after) || u16be(len(id)) || id ||
xwing_pk (1216 B)`: fixed widths and one length prefix, so it is injective. Arcanum has no clock: the caller
passes `now` to `verify_binding`.
### Shape of the API
```rust
pub mod sign {
pub struct SigningKey; // two 32-byte seeds; ZeroizeOnDrop; no Clone/Copy/PartialEq/Display; Debug redacted
pub struct VerifyingKey; // 1984 bytes; from_bytes checks lengths and the Ed25519 point (not weak)
pub struct Signature; // 3373 bytes
impl SigningKey {
pub fn generate<R: CryptoRng + ?Sized>(rng: &mut R) -> Self;
pub fn from_bytes(&[u8]) -> Result<Self, Error>; pub fn to_bytes(&self) -> Zeroizing<[u8; 64]>;
pub fn verifying_key(&self) -> &VerifyingKey;
pub fn sign<R: CryptoRng + ?Sized>(&self, msg: &[u8], ctx: &AppContext, rng: &mut R) -> Result<Signature, Error>;
}
impl VerifyingKey { pub fn verify(&self, msg: &[u8], ctx: &AppContext, sig: &Signature) -> Result<(), Error>; }
pub fn bind_kem_key<R>(sk: &SigningKey, id: &[u8], kem: &xwing::PublicKey, valid: (u64, u64), rng: &mut R) -> Result<Signature, Error>;
pub fn verify_binding(vk: &VerifyingKey, id: &[u8], kem: &xwing::PublicKey, valid: (u64, u64), now: u64, sig: &Signature) -> Result<(), Error>;
#[cfg(feature = "hazmat")] pub fn sign_composite_raw(...); // the bare RFC ctx, for the RFC's own vectors
}
```
`AppContext` is a newtype that can only be built with the `domi/arcanum/v2/sig/app/` prefix, so a caller can
never pass an empty or foreign context by accident. The bare RFC interface (any ctx, deterministic ML-DSA)
exists only under `hazmat`, for the known-answer tests. Verification returns one error,
`Error::InvalidSignature`, whichever half failed. **Correction (QA S-06):** the timing *does* tell which half
failed: a malformed ML-DSA half is refused at decode without being verified, and `verify_strict` returns early
on an undecodable or small-order R (QA measured 59 µs, 187 µs and 217 µs against 225 µs for a valid signature).
That is harmless: verification handles only public data (the message, the public key, the signature), so its
timing leaks nothing secret, and RFC 10073 §3.3 allows failing early. No dummy work is added.
## Tests (written first)
| # | Mandatory test | Source of truth |
|:--|:--|:--|
| 1 | ML-DSA-65 KATs: keyGen, sigGen (deterministic groups, byte for byte), sigVer (accept and reject) | NIST ACVP-Server `gen-val/json-files/ML-DSA-*-FIPS204/`, keyGen/sigGen at `2972def2` (2026-07-20), **sigVer at `a7f283cd` (2026-07-31, the ModifyZ correction)**; sha256 pinned in `tests/vectors/SOURCES.md` |
| 2 | Ed25519 KATs and edge cases, with `verify_strict` | RFC 8032 §7.1; Wycheproof `ed25519_test.json` |
| 3 | The composite: verify the RFC's `s` and `sWithContext` for `id-MLDSA65-Ed25519-SHA512`; our own signatures verify under an independent rebuild of M′ in the test | RFC 10073 Appendix E (`lamps-wg/draft-composite-sigs` `testvectors.json` at `f0627ab`) |
| 4 | Both halves are bound: a signature with either half replaced by a valid half from another signature, a zeroed half, or the halves swapped, is refused; an empty-ctx ML-DSA verifier refuses the ML-DSA half alone | constructed |
| 5 | Every byte matters: flipping any byte of the message, ctx, public key or signature fails verification; contexts are prefix-free and a key-binding signature never verifies as an app message, or the other way round | constructed |
| 6 | Malformed input (wrong lengths, a weak Ed25519 key, a 256-byte ctx) gives typed errors, never a panic; a fuzz target, 10 minutes | `cargo fuzz` |
| 7 | Hygiene: `hazmat` and `ml-dsa`'s own randomness-taking internals are not reachable from a default-features consumer (compile-fail, like v0.1.0's A-33/A-34); the feature graph has no `hazmat`; secret types are ZeroizeOnDrop and freed wiped (the allocator probe) | v0.1.0's `feature_hygiene.rs`, `qa_consumer_api.rs`, `zeroize-probe` |
| 8 | v0.1.0 is unchanged: `tests/golden_v1.rs` still passes | v0.1.0 |
Also Wycheproof `mldsa_65_sign_seed_test.json` and `mldsa_65_verify_test.json` (`20b25694`, 2026-10-12).
RustCrypto's own ACVP copies predate the sigVer correction, so Arcanum runs the current files itself.
## Risks
| Risk | Consequence | Mitigation |
|:--|:--|:--|
| `ml-dsa` is unaudited and 0.1.x; three advisories in 2026 (a timing side channel, signature malleability, a `use_hint` bug), constant-time fixes in 0.1.2 | a forgery or a key leak in the PQ half | the hybrid: Ed25519 still holds; version pinned; ACVP + Wycheproof + RFC vectors; `cargo audit` in every run |
| Using the crate's `Signer`/`Verifier` traits | signatures that are not RFC 10073 (empty ctx, deterministic) | never called; the RFC vectors fail if they are |
| `zeroize` is opt-in in `ml-dsa` | secret keys left in memory | the feature is set, a hygiene test asserts it in the feature graph, the allocator probe covers signing |
| The composite is **not SUF-CMA** and only weakly non-separable (RFC 10073 §9.2) | two valid signatures for one message; an Ed25519 half could be lifted out | Arcanum never uses a signature as an identifier; component keys never exist outside the composite; the Ed25519 half signs M′, which starts with the RFC Prefix (§9.4) |
| Signing can fail (rejection sampling bound) | a panic in a release build | 0.1.2 returns an error from the hedged path; Arcanum surfaces it as `Error::SigningFailed`; the deterministic `sign_mu_deterministic` (documented to panic) is never called |
| A 1984-byte key and a 3373-byte signature | larger control messages | fine over the control channel; noted for Day 5's QR import (classic keys only there) |
## As built (v0.2.0, `src/sign.rs`)
Where the code differs from, or adds to, the design above (the code wins):
- **The raw interface stays hedged.** `sign_composite_raw(sk, msg, ctx, rng)` and
`verify_composite_raw(vk, msg, ctx, sig)` take any `ctx` of 0 to 255 bytes but still sign through
`sign_randomized` with the caller's RNG; there is no deterministic ML-DSA path in Arcanum at all.
A test that needs repeatable bytes passes a seeded RNG. Both are `hazmat` only.
- **A stricter Ed25519 key check.** `ed25519-dalek`'s `VerifyingKey::from_bytes` accepts y >= p and
a set sign bit on x = 0. Arcanum re-encodes the point and refuses any encoding that is not the
canonical one, as well as small-order points (`Error::InvalidVerifyingKey`). Invisible to honest
keys and to the RFC's vectors.
- **And a weak ML-DSA key check** (QA S-05): an ML-DSA-65 half whose t1 is all zero is refused as
`InvalidVerifyingKey`. With t1 = 0 a signature needs no secret (Wycheproof's `ZeroPublicKey`), so such a
composite would silently be no stronger than Ed25519. ρ may be anything.
- **App labels are 1 to 231 bytes** (`MAX_APP_LABEL_LEN` = 255 minus the 24-byte prefix); an empty
label is `TooShort`, a longer one `TooLong`. **And `&'static`** (QA S-09): `AppContext::new` is a
`const fn` taking `&'static [u8]`, so a label is written in the source, not derived from a peer
name, file name or message field at run time (a consumer would have to leak memory on purpose to
get around it). A consumer builds its contexts as `const`s, which also moves the length check to
its compile time. There is no runtime constructor.
- **Key bindings** are hashed field by field (no allocation); the window is inclusive at both ends;
`verify_binding` checks, in this order, the window's shape and the id length
(`InvalidValidity`, `TooLong`), the signature (`InvalidSignature`), then `now`
(`OutsideValidity`), so `OutsideValidity` always means an authentic but expired binding.
- `ml-dsa` gets `alloc` (its large vectors are boxed), `rand_core` and `zeroize`, default features
off; `ed25519-dalek` gets only `zeroize` (not `fast`: no precomputed tables).
## Gaps
- **Not audited**, like v0.1.0; the Day 7 audit pack covers both versions.
- No constant-time measurement (dudect) of our own; inherited from the crates.
- No HashML-DSA and no X.509: not needed.
- The RFC's signing vectors are hedged, so the composite has no byte-exact signing KAT; byte-exact checks exist
for the ML-DSA half (ACVP deterministic groups) and Ed25519.
- ~~Whether `verify_strict` refuses any RFC 10073 vector~~: **it does not.** Test 3 (2026-11-25) verifies
both the RFC's `s` (empty ctx) and `sWithContext` with `verify_strict`, through Arcanum and through the
independent rebuild of M'. `verify_strict` also agrees with all 151 Wycheproof `ed25519_test.json` verdicts
(test 2: no disagreement to list).
- ACVP sigGen, sigVer and Wycheproof `mldsa_65_verify` run as subsets (`tests/vectors/SOURCES.md`): 18 of
the sigGen cases, 15 sigVer cases, 70 of 210 Wycheproof verify cases. The full files' sha256 are pinned,
so the subsets can be rechecked against them by rerunning `make_subsets.py`.
- Stack copies: building a `SigningKey` moves the expanded ML-DSA key through the stack before it is boxed:
**about 35 kB** (34,992 B, QA's measurement; `A_hat`'s rows are boxed inside `ml-dsa`), and those bytes are
exactly the secret part (s1, s2, t0 and their NTT forms). The allocator probe sees only the heap.
- **Stack residue inside `ml-dsa`** (QA S-04): every signature leaves `rnd`, ρ'' and the mask y on the stack,
unwiped, in `try_raw_sign_mu`; with the public z, a leaked y gives c·s1 and so s1. Arcanum cannot reach
it; it is in `docs/THREAT_MODEL.md`. The allocator probe now watches the expanded key's K and s1 bytes on
the heap as well as the seed canary, but no heap probe can see the stack.
- **Stack size** (QA S-11): building a key and signing need more than 128 KiB of stack in release (fit in
256 KiB) and more than 256 KiB in Arcanum's debug profile (fit in 512 KiB); a smaller thread aborts the
process. Documented on `SigningKey`; pinned for release by `tests/sig_stack.rs`.
- **ACVP never reaches the ‖z‖∞ bound** (QA S-12). The sigVer file at `a7f283cd` has 9 "modified signature - z"
cases in its ML-DSA-65 non-preHash groups (3 kept in the subset); decoded with a script on 2026-11-26, the
largest |z| coefficient among them is 524,077, below γ1 − β = 524,092, so all 9 decode and are refused only
by the c̃ comparison. No ACVP case could be added for the bound; only Wycheproof's `InfinityNormViolation`
cases (6 kept) test `ml-dsa`'s norm check at decode. Which of the 9 the ModifyZ correction changed was not
checked (that needs the `2972def2` sigVer file).
- **Key bindings have no serial and do not tie `id` to `vk`** (QA S-08). `verify_binding` checks that the
holder of `vk` bound `kem` to `id` within the window; that `vk` is the right key for `id`, and that a newer
binding has not replaced this one, are the caller's. For Day 3 (with the plan-replay rule, QA E-07): short
windows, and keep only the binding with the newest `not_before` per `id` (no format change needed).
- **Feature unification** (QA S-10): `ed25519-dalek/legacy_compatibility` in any crate of a consumer's binary
would accept a non-reduced S (a second encoding of the Ed25519 half). Arcanum's `deny.toml` bans it (and
`ed25519-dalek/hazmat`); consumers must ban it in theirs.
## Questions (none blocks the work)
1. Should Tessera's device identity itself move to this composite key, or should Tessera keep Ed25519 and
this key be a separate Via identity signed by it? Day 3's `docs/03_engine.md` must decide; Arcanum works
either way. **Recommendation (QA S-07):** the composite key is a **separate, freshly generated** identity
(`SigningKey::generate`), optionally certified once by the old Ed25519 key. Never build it as
`SigningKey::from_bytes(new_mldsa_seed || tessera_ed25519_seed)`: RFC 10073 §3.1 forbids reusing a component
key, and with only weak non-separability (§9.2) any Tessera path that signs caller-influenced bytes
beginning with the RFC Prefix would become a forgery oracle for the composite once ML-DSA falls. If the two
keys ever coexist on one device, Tessera's Ed25519 signer should refuse messages that begin with
`CompositeAlgorithmSignatures2025` (§9.4). `from_bytes` cannot detect reuse: any 64 bytes are a key.
2. Validity windows on key bindings: the default the engine should use (proposal: 30 days, renewed by the
control service).
+69
View File
@@ -0,0 +1,69 @@
# Arcanum threat model
Scope: the `arcanum` crate v0.1.0 — the X-Wing hybrid KEM, the mutual exchange, the key schedule, the WireGuard PSK
derivation and the sealing helper. **Not audited.**
## Assets
1. The responder's hybrid secret key (a 32-byte seed).
2. Each exchange's shared secret and the `Session` derived from it.
3. Each epoch's WireGuard pre-shared key.
4. The plaintext inside a sealed box.
## Adversaries and what Arcanum protects against
| Adversary | Can do | Protected? | Why |
|:--|:--|:--|:--|
| **Harvest now, decrypt later** | Records every control-channel message and WireGuard packet today; gets a large quantum computer later | **Yes**, the main goal | The PSK comes from X-Wing. Shor breaks X25519, but ML-KEM-768 is believed to resist quantum attack, and X-Wing's secret is secure if either half is. WireGuard mixes the PSK into its key schedule, so recorded traffic stays confidential. |
| Classical passive eavesdropper | Records traffic, no quantum computer | Yes | Both halves hold. |
| A future break of ML-KEM (cryptanalysis or an implementation bug) | Recovers `ss_M` | Yes, classically | X25519 still protects the secret (hybrid). |
| A break of X25519 | Recovers `ss_X` | Yes | ML-KEM still protects it. |
| Active attacker who modifies ciphertexts | Flips bytes in transit | Detected or harmless | Changed `ct_M` → ML-KEM implicit rejection gives an unrelated secret; changed `ct_X` → different `ss_X`; the transcript hash binds both. The peers' PSKs differ and WireGuard simply fails to handshake. Low-order X25519 values are rejected with a typed error. |
| Malformed or hostile input | Sends wrong lengths, invalid ML-KEM keys, random bytes | No panic, typed error | Tests 5 and the fuzz target. |
| **Impersonating one peer** (QA A-15) | Knows both public keys, sends its own encapsulation as if from the initiator | **Yes** | The exchange is mutual: the PSK needs both directions' secrets, and the responder's encapsulation goes to the real initiator's key. Without that secret key the attacker cannot compute the PSK, even after breaking WireGuard's X25519 keys. |
| Epoch confusion | Replays an old exchange for a new epoch | Harmless for secrecy | The epoch is in every PSK derivation; an attacker who cannot decapsulate cannot compute any epoch's PSK. Refusing to re-install an old PSK (rollback) is the caller's job: Arcanum keeps no state. |
## What Arcanum does NOT protect against
| Not protected | Why, and who has to handle it |
|:--|:--|
| **Endpoint compromise** | Malware on a device reads keys and plaintext from memory. Zeroisation narrows the window; it does not close it. Keys at rest belong in Custos or Tessera. |
| **Traffic analysis** | Who talks to whom, when and how much is visible on the wire. Padding and cover traffic are the Stealth transport's job (Day 7), and only partly. |
| **Substituted public keys** | The mutual exchange authenticates whoever holds the secret keys matching the public keys each side was *given*. An attacker who gets a peer to accept her public key in place of the real one learns that exchange's PSK. In Via, WireGuard's static keys still authenticate the tunnel classically, so this falls back to classical security, not to plaintext. Via must distribute both hybrid public keys signed with Tessera (Day 3). If those signatures are classical (Ed25519), a quantum attacker who can forge them can substitute keys; ML-DSA closes that later. |
| **Theft of static secret keys later** | With static key pairs, whoever later steals both secret keys and has recorded the exchanges can recompute their PSKs. Day 3 must add an ephemeral key pair per exchange (as Rosenpass does) or rotate key pairs. |
| **Bad randomness** | The caller supplies the RNG. A broken RNG breaks every scheme. The `_derand` functions exist only with the off-by-default `hazmat` feature, for known-answer tests; reusing their seeds is catastrophic. |
| **Side channels** | Timing and cache behaviour are those of `ml-kem`, `x25519-dalek`, `sha3` and `chacha20poly1305`. Arcanum adds only fixed-length, data-independent glue, but has not been measured. |
| **Reusing one session for many epochs** | Supported, but a leaked session reveals every epoch's PSK derived from it. Forward secrecy needs one exchange per epoch. |
| **Denial of service** | An attacker on the path can always drop packets. |
| **Legacy peers** | Classic WireGuard peers (routers, third-party clients) get no Arcanum PSK and are labelled "not post-quantum" by Via. |
## Trust assumptions
- ML-KEM-768 is IND-CCA2 secure against quantum adversaries (FIPS 203).
- X25519 is a secure Diffie–Hellman group against classical adversaries (RFC 7748).
- SHA3-256, SHAKE256 and HKDF-SHA-256 behave as their standards say; X-Wing's security argument
(draft-connolly-cfrg-xwing-kem-11) holds.
- The vetted crates implement those standards correctly; the known-answer tests check the parts
Arcanum uses, not everything.
- The caller authenticates the responder's public key and supplies a cryptographically secure RNG.
## Blast radius if Arcanum is wrong
Via uses Arcanum only as the WireGuard PSK. A total failure of Arcanum (for example, both peers
derive a predictable PSK) reduces a Via tunnel to plain WireGuard: still authenticated and encrypted
classically, but open to harvest-now-decrypt-later. It never reduces it below WireGuard. Sealing
(Custos, Tabellarius) is different: there Arcanum is the only layer, which is why those migrations
wait for the audit.
## Residual memory exposure
Moves in Rust copy stack bytes, and `zeroize` cannot reach those copies; hash and HMAC states are
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
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 ];
};
};
}
+597
View File
@@ -0,0 +1,597 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aead"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
[[package]]
name = "arcanum"
version = "0.2.0"
dependencies = [
"chacha20poly1305",
"ed25519-dalek",
"hkdf",
"hmac",
"ml-dsa",
"ml-kem",
"rand_core",
"sha2",
"sha3",
"shake",
"x25519-dalek",
"zeroize",
]
[[package]]
name = "arcanum-fuzz"
version = "0.0.0"
dependencies = [
"arcanum",
"chacha20",
"libfuzzer-sys",
"rand_core",
]
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
"zeroize",
]
[[package]]
name = "cc"
version = "1.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69"
dependencies = [
"find-msvc-tools",
"jobserver",
"libc",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"rand_core",
"zeroize",
]
[[package]]
name = "chacha20poly1305"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
"aead",
"chacha20",
"cipher",
"poly1305",
"zeroize",
]
[[package]]
name = "cipher"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
"block-buffer",
"crypto-common",
"inout",
]
[[package]]
name = "cmov"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
[[package]]
name = "const-oid"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
"rand_core",
]
[[package]]
name = "ctutils"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
dependencies = [
"cmov",
]
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
dependencies = [
"cfg-if",
"cpufeatures",
"curve25519-dalek-derive",
"digest",
"fiat-crypto",
"rustc_version",
"subtle",
"zeroize",
]
[[package]]
name = "curve25519-dalek-derive"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "der"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004"
dependencies = [
"const-oid",
"zeroize",
]
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"crypto-common",
"ctutils",
"zeroize",
]
[[package]]
name = "ed25519"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
dependencies = [
"signature",
]
[[package]]
name = "ed25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
dependencies = [
"curve25519-dalek",
"ed25519",
"sha2",
"subtle",
"zeroize",
]
[[package]]
name = "fiat-crypto"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "getrandom"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
dependencies = [
"cfg-if",
"libc",
"r-efi",
]
[[package]]
name = "hkdf"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
dependencies = [
"hmac",
]
[[package]]
name = "hmac"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
dependencies = [
"digest",
]
[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
"ctutils",
"typenum",
"zeroize",
]
[[package]]
name = "inout"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
dependencies = [
"hybrid-array",
]
[[package]]
name = "jobserver"
version = "0.1.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
dependencies = [
"getrandom",
"libc",
]
[[package]]
name = "keccak"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8f198d1db720e4940b5a493201d199d9f24f568f8f746bd13706243a2f71598"
dependencies = [
"cfg-if",
"cpufeatures",
]
[[package]]
name = "kem"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01737161ba802849cfd486b5bd209d38ba4943494c249a8126005170c7621edd"
dependencies = [
"crypto-common",
"rand_core",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libfuzzer-sys"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2"
dependencies = [
"arbitrary",
"cc",
]
[[package]]
name = "ml-dsa"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f6d49c3f3f0e10e18ca975ffda66f8da0ec36521c1d911adcbc521bf0743f5c"
dependencies = [
"crypto-common",
"ctutils",
"hybrid-array",
"module-lattice",
"pkcs8",
"shake",
"signature",
"zeroize",
]
[[package]]
name = "ml-kem"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84ca78b66f46050d49fa21693ae8adab2081d8101b65d8067316b6b70b64a0d1"
dependencies = [
"hybrid-array",
"kem",
"module-lattice",
"rand_core",
"sha3",
"shake",
"zeroize",
]
[[package]]
name = "module-lattice"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4a1e412c8ee83a1c678f427806219c49c96b2511b9f07497514f0e43fb26155"
dependencies = [
"ctutils",
"hybrid-array",
"num-traits",
"zeroize",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "pkcs8"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
dependencies = [
"der",
"spki",
]
[[package]]
name = "poly1305"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
dependencies = [
"cpufeatures",
"universal-hash",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "sha2"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha3"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc9bad02c26382724b2d2692c6f179285e4b54eeecd7968f52a50059c3c11759"
dependencies = [
"digest",
"keccak",
"sponge-cursor",
]
[[package]]
name = "shake"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09057cb2149ad4cbd2da1e26b351f9a4c354219421229c69c3063e6f61947c4a"
dependencies = [
"digest",
"keccak",
"sponge-cursor",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "signature"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
dependencies = [
"digest",
"rand_core",
]
[[package]]
name = "spki"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
dependencies = [
"base64ct",
"der",
]
[[package]]
name = "sponge-cursor"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620"
dependencies = [
"zeroize",
]
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "universal-hash"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
dependencies = [
"crypto-common",
"ctutils",
]
[[package]]
name = "x25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6"
dependencies = [
"curve25519-dalek",
"rand_core",
"zeroize",
]
[[package]]
name = "zeroize"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
+34
View File
@@ -0,0 +1,34 @@
[package]
name = "arcanum-fuzz"
version = "0.0.0"
edition = "2024"
license = "CPAL-1.0"
publish = false
[package.metadata]
cargo-fuzz = true
[dependencies]
libfuzzer-sys = "0.4"
arcanum = { path = "..", features = ["hazmat"] }
# A seeded RNG for the signing fixture (fuzz input never chooses randomness).
chacha20 = { version = "0.10", default-features = false, features = ["rng"] }
rand_core = { version = "0.10", default-features = false }
# Keep the fuzz crate out of the library's own dependency graph and checks.
[workspace]
members = ["."]
[[bin]]
name = "untrusted_input"
path = "fuzz_targets/untrusted_input.rs"
test = false
doc = false
bench = false
[[bin]]
name = "signatures"
path = "fuzz_targets/signatures.rs"
test = false
doc = false
bench = false
+133
View File
@@ -0,0 +1,133 @@
//! v0.2.0 mandatory test 6, fuzzed: every signature entry point that takes bytes from the network
//! returns a typed result for any input and never panics, and only the exact bytes that were
//! signed verify (one key, one message, one context: the hedged ML-DSA half is not re-signed).
//!
//! The first byte picks the mode. Modes 0-1 parse raw bytes. Modes 2-7 XOR the input into a valid
//! verifying key, signature, message, context or key binding, so the fuzzer reaches ML-DSA's hint
//! and norm checks and Ed25519's point decoding instead of stopping at the length checks.
#![no_main]
use arcanum::sign::{self, AppContext, Signature, SigningKey, VerifyingKey};
use arcanum::xwing;
use chacha20::ChaCha20Rng;
use libfuzzer_sys::fuzz_target;
use rand_core::SeedableRng;
use std::sync::OnceLock;
const MSG: &[u8] = b"fuzz message";
const LABEL: &[u8] = b"fuzz";
const ID: &[u8] = b"fuzz-device";
const VALID: (u64, u64) = (100, 200);
struct Fixture {
sk: SigningKey,
ctx: AppContext,
sig: Signature,
kem: xwing::SecretKey,
binding: Signature,
}
fn xor_into(base: &[u8], data: &[u8]) -> Vec<u8> {
let mut out = base.to_vec();
for (i, b) in data.iter().enumerate() {
if i < out.len() {
out[i] ^= b;
} else {
out.push(*b);
}
}
out
}
fn be_u64(data: &[u8], at: usize) -> u64 {
let mut b = [0u8; 8];
for (i, x) in b.iter_mut().enumerate() {
*x = data.get(at + i).copied().unwrap_or(0);
}
u64::from_be_bytes(b)
}
fuzz_target!(|input: &[u8]| {
let Some((&mode, data)) = input.split_first() else { return };
// Key generation and signing are built once; redoing them per input would dominate the time.
static FIX: OnceLock<Fixture> = OnceLock::new();
let f = FIX.get_or_init(|| {
let mut rng = ChaCha20Rng::from_seed([0x5a; 32]);
let sk = SigningKey::from_bytes(&[0x42; 64]).unwrap();
let ctx = AppContext::new(LABEL).unwrap();
let sig = sk.sign(MSG, &ctx, &mut rng).unwrap();
let kem = xwing::SecretKey::from_bytes(&[0x43; 32]).unwrap();
let binding = sign::bind_kem_key(&sk, ID, kem.public_key(), VALID, &mut rng).unwrap();
Fixture { sk, ctx, sig, kem, binding }
});
let vk = f.sk.verifying_key();
match mode % 8 {
0 => {
if let Ok(k) = VerifyingKey::from_bytes(data) {
assert!(k.verify(MSG, &f.ctx, &f.sig).is_err() || &k == vk);
}
}
1 => {
if let Ok(s) = Signature::from_bytes(data) {
assert!(vk.verify(MSG, &f.ctx, &s).is_err() || s == f.sig);
}
let _ = SigningKey::from_bytes(data).map(|k| k.verifying_key().as_bytes()[0]);
}
2 => {
let bad = xor_into(f.sig.as_bytes(), data);
if let Ok(s) = Signature::from_bytes(&bad) {
if vk.verify(MSG, &f.ctx, &s).is_ok() {
assert_eq!(s, f.sig, "a changed signature verified");
}
}
}
3 => {
let bad = xor_into(vk.as_bytes(), data);
if let Ok(k) = VerifyingKey::from_bytes(&bad) {
if k.verify(MSG, &f.ctx, &f.sig).is_ok() {
assert_eq!(&k, vk, "a signature verified under a changed key");
}
}
}
4 => {
let m = xor_into(MSG, data);
if vk.verify(&m, &f.ctx, &f.sig).is_ok() {
assert_eq!(m, MSG, "a changed message verified");
}
}
5 => {
// Any raw ctx (0..=255 bytes, or a typed error for longer). `AppContext` labels are
// `&'static` and fixed at compile time, so there is no runtime label to fuzz.
let raw = xor_into(f.ctx.as_bytes(), data);
match sign::verify_composite_raw(vk, MSG, &raw, &f.sig) {
Ok(()) => assert_eq!(raw, f.ctx.as_bytes()),
Err(e) => assert!(raw.len() <= 255 || matches!(e, arcanum::Error::TooLong { .. })),
}
}
6 => {
// A key binding with a changed id, window and time.
let id = xor_into(ID, data.get(17..).unwrap_or(&[]));
let valid = (VALID.0 ^ be_u64(data, 0), VALID.1 ^ be_u64(data, 8));
let now = 150 ^ u64::from(data.first().copied().unwrap_or(0));
if sign::verify_binding(vk, &id, f.kem.public_key(), valid, now, &f.binding).is_ok() {
assert_eq!((id.as_slice(), valid), (ID, VALID), "a changed binding verified");
assert!((VALID.0..=VALID.1).contains(&now));
}
}
_ => {
// A changed X-Wing key in a binding, and a changed binding signature.
let kem = xor_into(f.kem.public_key().as_bytes(), data);
if let Ok(k) = xwing::PublicKey::from_bytes(&kem) {
if sign::verify_binding(vk, ID, &k, VALID, 150, &f.binding).is_ok() {
assert_eq!(&k, f.kem.public_key(), "a binding verified for another X-Wing key");
}
}
let bad = xor_into(f.binding.as_bytes(), data);
if let Ok(s) = Signature::from_bytes(&bad) {
if sign::verify_binding(vk, ID, f.kem.public_key(), VALID, 150, &s).is_ok() {
assert_eq!(s, f.binding, "a changed binding signature verified");
}
}
}
}
});
+103
View File
@@ -0,0 +1,103 @@
//! Mandatory test 5, fuzzed: every entry point that takes bytes from the network must return a
//! typed result for any input, and never panic. Also QA A-43: a sealed box opens only if it is
//! exactly what `seal` produced.
//!
//! The first byte picks the mode. Modes 0-3 parse raw bytes. Modes 4-7 XOR the input into a valid
//! public key, ciphertext or sealed box, so the fuzzer reaches decapsulation and the AEAD instead
//! of stopping at the length checks.
#![no_main]
use arcanum::xwing::{Ciphertext, PublicKey, SecretKey};
use arcanum::{exchange, seal};
use libfuzzer_sys::fuzz_target;
use std::sync::OnceLock;
const ESEED_I: [u8; 64] = [0x24; 64];
const ESEED_R: [u8; 64] = [0x25; 64];
fn xor_into(base: &[u8], data: &[u8]) -> Vec<u8> {
let mut out = base.to_vec();
for (i, b) in data.iter().enumerate() {
if i < out.len() {
out[i] ^= b;
} else {
out.push(*b);
}
}
out
}
fuzz_target!(|input: &[u8]| {
let Some((&mode, data)) = input.split_first() else { return };
// Keys are built once; expanding them on every run would dominate the fuzzing time.
static KEYS: OnceLock<(SecretKey, SecretKey)> = OnceLock::new();
let (me, peer) = KEYS.get_or_init(|| (SecretKey::from_seed([0x42; 32]), SecretKey::from_seed([0x43; 32])));
match mode % 8 {
0 => {
if let Ok(pk) = PublicKey::from_bytes(data) {
let _ = exchange::initiate_derand(me, &pk, b"fuzz", &ESEED_I);
}
}
1 => {
if let Ok(ct) = Ciphertext::from_bytes(data) {
let _ = exchange::respond_derand(me, peer.public_key(), &ct, b"fuzz", &ESEED_R);
if let Ok(init) = exchange::initiate_derand(me, peer.public_key(), b"fuzz", &ESEED_I) {
let _ = init.finish(&ct);
}
}
}
2 => {
let _ = seal::open(me, data, b"fuzz");
}
3 => {
if let Ok(k) = SecretKey::from_bytes(data) {
let _ = k.public_key().as_bytes();
}
}
4 => {
let pk = xor_into(peer.public_key().as_bytes(), data);
if let Ok(pk) = PublicKey::from_bytes(&pk) {
if let Ok(init) = exchange::initiate_derand(me, &pk, b"fuzz", &ESEED_I) {
let _ = exchange::respond_derand(peer, me.public_key(), init.ciphertext(), b"fuzz", &ESEED_R);
}
}
}
5 | 6 => {
// Tamper with ct_IR (mode 5) or ct_RI (mode 6) of an honest exchange.
let init = exchange::initiate_derand(me, peer.public_key(), b"fuzz", &ESEED_I).unwrap();
let honest_ir = init.ciphertext().clone();
let (honest_ri, responder) =
exchange::respond_derand(peer, me.public_key(), &honest_ir, b"fuzz", &ESEED_R).unwrap();
let honest_psk = *responder.wireguard_psk(0).as_bytes();
if mode % 8 == 5 {
let bad = xor_into(honest_ir.as_bytes(), data);
if let Ok(bad) = Ciphertext::from_bytes(&bad) {
if let Ok((_, s)) = exchange::respond_derand(peer, me.public_key(), &bad, b"fuzz", &ESEED_R) {
// Only an unchanged ciphertext may reproduce the honest PSK.
if bad != honest_ir {
assert_ne!(s.wireguard_psk(0).as_bytes(), &honest_psk);
}
}
}
} else {
let bad = xor_into(honest_ri.as_bytes(), data);
if let Ok(bad) = Ciphertext::from_bytes(&bad) {
if let Ok(s) = init.finish(&bad) {
if bad != honest_ri {
assert_ne!(s.wireguard_psk(0).as_bytes(), &honest_psk);
}
}
}
}
}
_ => {
let sealed = seal::seal_derand(me.public_key(), b"fuzz plaintext", b"fuzz", &ESEED_I).unwrap();
let bad = xor_into(&sealed, data);
if let Ok(pt) = seal::open(me, &bad, b"fuzz") {
// Only the unchanged box may open.
assert_eq!(bad, sealed);
assert_eq!(pt.as_slice(), b"fuzz plaintext");
}
}
}
});
+2
View File
@@ -0,0 +1,2 @@
max_width = 120
use_small_heuristics = "Max"
+162
View File
@@ -0,0 +1,162 @@
//! Mandatory test 3, at the combiner: replacing either component secret by zeros must change the
//! output, so both halves are bound. Also QA A-02 (the combiner is exactly the draft's SHA3-256)
//! and A-07 (labels are prefix-free). These are unit tests because the combiner and the schedule
//! are crate-private (exposing them would invite misuse).
use sha3::{Digest, Sha3_256};
use crate::schedule::{ALL_LABELS, Transcript, session_prk};
use crate::xwing::{CIPHERTEXT_LEN, Ciphertext, PUBLIC_KEY_LEN, PublicKey, SecretKey, SharedSecret};
use crate::xwing::{SHARED_SECRET_LEN, combiner};
use zeroize::Zeroizing;
const SS_M: [u8; 32] = [0xa1; 32];
const SS_X: [u8; 32] = [0xb2; 32];
const CT_X: [u8; 32] = [0xc3; 32];
const PK_X: [u8; 32] = [0xd4; 32];
const ZERO: [u8; SHARED_SECRET_LEN] = [0; SHARED_SECRET_LEN];
#[test]
fn zeroing_the_ml_kem_secret_changes_the_output() {
let honest = combiner(&SS_M, &SS_X, &CT_X, &PK_X);
assert_ne!(combiner(&ZERO, &SS_X, &CT_X, &PK_X), honest);
}
#[test]
fn zeroing_the_x25519_secret_changes_the_output() {
let honest = combiner(&SS_M, &SS_X, &CT_X, &PK_X);
assert_ne!(combiner(&SS_M, &ZERO, &CT_X, &PK_X), honest);
}
#[test]
fn zeroing_both_differs_from_zeroing_either() {
let only_m = combiner(&ZERO, &SS_X, &CT_X, &PK_X);
let only_x = combiner(&SS_M, &ZERO, &CT_X, &PK_X);
let both = combiner(&ZERO, &ZERO, &CT_X, &PK_X);
assert_ne!(only_m, only_x);
assert_ne!(both, only_m);
assert_ne!(both, only_x);
}
/// Swapping the two secrets must not give the same output: the positions are bound, not just the set.
#[test]
fn the_two_halves_are_not_interchangeable() {
assert_ne!(combiner(&SS_M, &SS_X, &CT_X, &PK_X), combiner(&SS_X, &SS_M, &CT_X, &PK_X));
}
/// Every single bit of either component secret reaches the output.
#[test]
fn every_bit_of_each_component_reaches_the_output() {
let honest = combiner(&SS_M, &SS_X, &CT_X, &PK_X);
for byte in 0..32 {
for bit in 0..8 {
let mut m = SS_M;
m[byte] ^= 1 << bit;
assert_ne!(combiner(&m, &SS_X, &CT_X, &PK_X), honest, "ss_M byte {byte} bit {bit}");
let mut x = SS_X;
x[byte] ^= 1 << bit;
assert_ne!(combiner(&SS_M, &x, &CT_X, &PK_X), honest, "ss_X byte {byte} bit {bit}");
}
}
}
fn ss(b: [u8; 32]) -> SharedSecret {
SharedSecret(Zeroizing::new(b))
}
/// The binding survives the key schedule, through the real `session_prk`: a zeroed component of
/// the first direction's X-Wing secret, or a missing second direction, gives a different session.
/// The last case is QA A-15: an attacker who impersonates the initiator knows ss_IR (she made it)
/// and the whole transcript, but not ss_RI; every guess of hers that reuses known values fails.
#[test]
fn zeroed_components_and_a_missing_direction_give_a_different_session() {
let pk_i = SecretKey::from_bytes(&[1u8; 32]).unwrap().public_key().clone();
let pk_r = SecretKey::from_bytes(&[2u8; 32]).unwrap().public_key().clone();
let ct_ir = Ciphertext::from_bytes(&[3u8; CIPHERTEXT_LEN]).unwrap();
let ct_ri = Ciphertext::from_bytes(&[4u8; CIPHERTEXT_LEN]).unwrap();
let t = Transcript { initiator: &pk_i, responder: &pk_r, ct_ir: &ct_ir, ct_ri: &ct_ri, context: b"ctx" };
let ss_ir = combiner(&SS_M, &SS_X, &CT_X, &PK_X);
let ss_ri = combiner(&[0x01; 32], &[0x02; 32], &CT_X, &PK_X);
let honest = *session_prk(&ss(ss_ir), &ss(ss_ri), &t);
let no_m = *session_prk(&ss(combiner(&ZERO, &SS_X, &CT_X, &PK_X)), &ss(ss_ri), &t);
let no_x = *session_prk(&ss(combiner(&SS_M, &ZERO, &CT_X, &PK_X)), &ss(ss_ri), &t);
assert_ne!(honest, no_m);
assert_ne!(honest, no_x);
for guess in [ZERO, ss_ir, [0xff; 32]] {
assert_ne!(*session_prk(&ss(ss_ir), &ss(guess), &t), honest, "PSK computable without ss_RI");
}
}
/// QA A-02: recomputed independently, the combiner is SHA3-256(ss_M || ss_X || ct_X || pk_X ||
/// 5c2e2f2f5e5c), label last, no length prefixes.
#[test]
fn the_combiner_is_the_drafts_sha3_256() {
let mut h = Sha3_256::new();
for part in [&SS_M[..], &SS_X, &CT_X, &PK_X, &[0x5c, 0x2e, 0x2f, 0x2f, 0x5e, 0x5c]] {
h.update(part);
}
let want: [u8; 32] = h.finalize().into();
assert_eq!(combiner(&SS_M, &SS_X, &CT_X, &PK_X), want);
}
/// QA A-07: every label is unique, ASCII, versioned, and none is a prefix of another.
#[test]
fn labels_are_versioned_and_prefix_free() {
for (i, a) in ALL_LABELS.iter().enumerate() {
assert!(a.is_ascii() && a.starts_with(b"domi/arcanum/v1/"));
for (j, b) in ALL_LABELS.iter().enumerate() {
if i != j {
assert!(!b.starts_with(a), "{} is a prefix of {}", a.escape_ascii(), b.escape_ascii());
}
}
}
}
/// QA A-05: with both X-Wing secrets held fixed, every part of the transcript (both public keys,
/// both ciphertexts, the context and its length) still changes the session. This isolates the
/// key-schedule binding from what X-Wing itself hashes.
#[test]
fn the_schedule_binds_the_full_transcript() {
let ss_ir = SharedSecret(Zeroizing::new([7u8; 32]));
let ss_ri = SharedSecret(Zeroizing::new([8u8; 32]));
let pk_i = SecretKey::from_bytes(&[1u8; 32]).unwrap().public_key().clone();
let pk_r = SecretKey::from_bytes(&[2u8; 32]).unwrap().public_key().clone();
let ct_ir = Ciphertext::from_bytes(&[3u8; CIPHERTEXT_LEN]).unwrap();
let ct_ri = Ciphertext::from_bytes(&[4u8; CIPHERTEXT_LEN]).unwrap();
let prk = |i: &PublicKey, r: &PublicKey, a: &Ciphertext, b: &Ciphertext, ctx: &[u8]| {
*session_prk(&ss_ir, &ss_ri, &Transcript { initiator: i, responder: r, ct_ir: a, ct_ri: b, context: ctx })
};
let honest = prk(&pk_i, &pk_r, &ct_ir, &ct_ri, b"ctx");
let flip_pk = |pk: &PublicKey, n: usize| {
let mut b = *pk.as_bytes();
b[n] ^= 0x01;
PublicKey::from_bytes(&b).ok()
};
let flip_ct = |ct: &Ciphertext, n: usize| {
let mut b = *ct.as_bytes();
b[n] ^= 0x01;
Ciphertext::from_bytes(&b).unwrap()
};
let mut checked = 0;
for n in (0..PUBLIC_KEY_LEN).step_by(37).chain([0, 1183, 1184, PUBLIC_KEY_LEN - 1]) {
if let Some(p) = flip_pk(&pk_i, n) {
assert_ne!(prk(&p, &pk_r, &ct_ir, &ct_ri, b"ctx"), honest, "pk_I[{n}]");
checked += 1;
}
if let Some(p) = flip_pk(&pk_r, n) {
assert_ne!(prk(&pk_i, &p, &ct_ir, &ct_ri, b"ctx"), honest, "pk_R[{n}]");
checked += 1;
}
}
assert!(checked > 20, "the sampled public-key flips must mostly parse");
for n in (0..CIPHERTEXT_LEN).step_by(37).chain([0, 1087, 1088, CIPHERTEXT_LEN - 1]) {
assert_ne!(prk(&pk_i, &pk_r, &flip_ct(&ct_ir, n), &ct_ri, b"ctx"), honest, "ct_IR[{n}]");
assert_ne!(prk(&pk_i, &pk_r, &ct_ir, &flip_ct(&ct_ri, n), b"ctx"), honest, "ct_RI[{n}]");
}
assert_ne!(prk(&pk_r, &pk_i, &ct_ir, &ct_ri, b"ctx"), honest, "roles swapped");
assert_ne!(prk(&pk_i, &pk_r, &ct_ri, &ct_ir, b"ctx"), honest, "ciphertexts swapped");
assert_ne!(prk(&pk_i, &pk_r, &ct_ir, &ct_ri, b"ctX"), honest, "context");
assert_ne!(prk(&pk_i, &pk_r, &ct_ir, &ct_ri, b"ctx\0"), honest, "context length");
}
+131
View File
@@ -0,0 +1,131 @@
//! Typed errors. No variant carries secret material, so an error can always be logged.
use core::fmt;
/// Which input was malformed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Input {
/// A hybrid public key (`pk_M || pk_X`).
PublicKey,
/// A hybrid secret key (the 32-byte seed).
SecretKey,
/// A hybrid ciphertext (`ct_M || ct_X`).
Ciphertext,
/// A sealed box.
SealedBox,
/// A composite signing key (ML-DSA-65 seed || Ed25519 seed).
SigningKey,
/// A composite verifying key (ML-DSA-65 public key || Ed25519 public key).
VerifyingKey,
/// A composite signature (ML-DSA-65 signature || Ed25519 signature).
Signature,
/// A signature context, or the caller's label inside one.
Context,
/// The key id in a key binding.
KeyId,
}
impl fmt::Display for Input {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Input::PublicKey => "public key",
Input::SecretKey => "secret key",
Input::Ciphertext => "ciphertext",
Input::SealedBox => "sealed box",
Input::SigningKey => "signing key",
Input::VerifyingKey => "verifying key",
Input::Signature => "signature",
Input::Context => "signature context",
Input::KeyId => "key id",
})
}
}
/// Everything that can go wrong in Arcanum. Every parser returns one of these; none panics.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
/// The input has a fixed length and this is not it.
InvalidLength {
/// What was being parsed.
input: Input,
/// The required length in bytes.
expected: usize,
/// The length that was given.
actual: usize,
},
/// The input is shorter than the smallest valid value.
TooShort {
/// What was being parsed.
input: Input,
/// The minimum length in bytes.
minimum: usize,
/// The length that was given.
actual: usize,
},
/// The input is longer than the largest valid value.
TooLong {
/// What was being parsed.
input: Input,
/// The maximum length in bytes.
maximum: usize,
/// The length that was given.
actual: usize,
},
/// The ML-KEM-768 part of a public key fails the FIPS 203 §7.2 encapsulation key check.
InvalidPublicKey,
/// An X25519 value is a low-order point, so the classical half would contribute nothing.
NonContributory,
/// A sealed box was made by a format version this build does not know.
UnsupportedVersion(u8),
/// A sealed box failed authentication: wrong key, wrong associated data, or tampered.
DecryptionFailed,
/// The plaintext is longer than ChaCha20-Poly1305 allows (about 256 GiB).
MessageTooLong,
/// The Ed25519 half of a verifying key is not a canonically encoded point, or is a point of
/// small order (a weak key).
InvalidVerifyingKey,
/// A signature does not verify: one half, the other, or both. The error does not say which; the
/// verification time may, which is harmless because verification uses only public data.
InvalidSignature,
/// ML-DSA signing failed (the randomness source or the rejection-sampling bound). Retry with
/// fresh randomness.
SigningFailed,
/// A key binding's validity window ends before it starts (`not_before > not_after`).
InvalidValidity,
/// A key binding is authentic, but `now` lies outside its validity window.
OutsideValidity,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::InvalidLength { input, expected, actual } => {
write!(f, "{input} has the wrong length: expected {expected} bytes, got {actual}")
}
Error::TooShort { input, minimum, actual } => {
write!(f, "{input} is too short: at least {minimum} bytes, got {actual}")
}
Error::TooLong { input, maximum, actual } => {
write!(f, "{input} is too long: at most {maximum} bytes, got {actual}")
}
Error::InvalidPublicKey => f.write_str("public key fails the ML-KEM-768 encapsulation key check"),
Error::NonContributory => f.write_str("X25519 value is a low-order point"),
Error::UnsupportedVersion(v) => write!(f, "sealed box version {v} is not supported"),
Error::DecryptionFailed => f.write_str("sealed box could not be opened"),
Error::MessageTooLong => f.write_str("message is too long to seal"),
Error::InvalidVerifyingKey => f.write_str("verifying key has a weak or non-canonical Ed25519 point"),
Error::InvalidSignature => f.write_str("signature does not verify"),
Error::SigningFailed => f.write_str("signing failed; retry with fresh randomness"),
Error::InvalidValidity => f.write_str("key binding validity ends before it starts"),
Error::OutsideValidity => f.write_str("key binding is not valid at this time"),
}
}
}
impl core::error::Error for Error {}
pub(crate) fn exact<const N: usize>(input: Input, bytes: &[u8]) -> Result<&[u8; N], Error> {
bytes.try_into().map_err(|_| Error::InvalidLength { input, expected: N, actual: bytes.len() })
}
+216
View File
@@ -0,0 +1,216 @@
//! A mutual exchange between two peers, and the WireGuard PSK it yields per epoch.
//!
//! Each peer has a hybrid key pair, and each knows the other's public key (authenticated by the
//! caller; for Via, signed with the device's Tessera key). The exchange runs both directions:
//!
//! ```text
//! initiator I responder R
//! (ct_IR, ss_IR) = Encaps(pk_R) ct_IR -> ss_IR = Decaps(sk_R, ct_IR)
//! (ct_RI, ss_RI) = Encaps(pk_I)
//! ss_RI = Decaps(sk_I, ct_RI) <- ct_RI
//! ```
//!
//! The session is derived from **both** secrets and the whole transcript, so a peer that cannot
//! decapsulate the other direction cannot compute it. A single encapsulation would authenticate
//! only the receiver: anyone who knows `pk_R` can encapsulate to it, so once a quantum computer
//! breaks WireGuard's static X25519 keys, an attacker could impersonate the initiator and choose
//! the responder's PSK (QA finding A-15). Rosenpass is mutual for the same reason.
//!
//! **Forward secrecy between epochs needs one exchange per epoch** (Rosenpass rotates every
//! 120 s), and forward secrecy against a later theft of a static key needs the key pairs to be
//! ephemeral, or an ephemeral exchange added on top (Day 3).
use alloc::vec::Vec;
use core::fmt;
use rand_core::CryptoRng;
use zeroize::{ZeroizeOnDrop, Zeroizing};
use crate::error::Error;
use crate::schedule::{LABEL_WIREGUARD_PSK, Prk, Transcript, expand, session_prk};
use crate::xwing::{Ciphertext, ENCAPSULATION_SEED_LEN, PublicKey, SecretKey, SharedSecret};
/// Length of a WireGuard pre-shared key.
pub const WIREGUARD_PSK_LEN: usize = 32;
/// The keys both peers hold after one exchange. Zeroised on drop; never printed.
pub struct Session {
prk: Prk,
}
impl Session {
/// The WireGuard pre-shared key for `epoch` (see [`crate::epoch_at`]). Deterministic: both
/// peers get the same key for the same epoch, and different epochs give different keys.
#[must_use]
pub fn wireguard_psk(&self, epoch: u64) -> WireGuardPsk {
WireGuardPsk(expand(&self.prk, LABEL_WIREGUARD_PSK, &epoch.to_be_bytes()))
}
}
impl fmt::Debug for Session {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Session([redacted])")
}
}
impl ZeroizeOnDrop for Session {}
/// A 32-byte WireGuard pre-shared key. Zeroised on drop; never printed.
pub struct WireGuardPsk(Zeroizing<[u8; WIREGUARD_PSK_LEN]>);
impl WireGuardPsk {
/// The raw key, to hand to WireGuard (`wg set ... preshared-key`).
#[must_use]
pub fn as_bytes(&self) -> &[u8; WIREGUARD_PSK_LEN] {
&self.0
}
}
impl fmt::Debug for WireGuardPsk {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("WireGuardPsk([redacted])")
}
}
impl ZeroizeOnDrop for WireGuardPsk {}
/// The initiator's state between sending its ciphertext and receiving the responder's.
/// Holds the first-direction secret; zeroised on drop.
pub struct Initiation<'a> {
me: &'a SecretKey,
peer: PublicKey,
ct_ir: Ciphertext,
ss_ir: SharedSecret,
context: Zeroizing<Vec<u8>>,
}
// The secret fields wipe themselves: `ss_ir` is a `ZeroizeOnDrop` `SharedSecret` and `context` is
// `Zeroizing`; `me` is a borrow and `peer`/`ct_ir` are public (QA R2-05).
impl ZeroizeOnDrop for Initiation<'_> {}
impl fmt::Debug for Initiation<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("Initiation([redacted])")
}
}
impl Initiation<'_> {
/// The ciphertext to send to the responder.
#[must_use]
pub fn ciphertext(&self) -> &Ciphertext {
&self.ct_ir
}
/// Finish with the responder's ciphertext.
///
/// # Errors
/// [`Error::NonContributory`] if its X25519 part is a low-order point. A tampered ML-KEM part
/// is not reported; it yields a session that does not match the responder's, and the
/// WireGuard handshake then fails.
pub fn finish(self, ct_ri: &Ciphertext) -> Result<Session, Error> {
let ss_ri = self.me.decapsulate_inner(ct_ri)?;
let t = Transcript {
initiator: self.me.public_key(),
responder: &self.peer,
ct_ir: &self.ct_ir,
ct_ri,
context: &self.context,
};
Ok(Session { prk: session_prk(&self.ss_ir, &ss_ri, &t) })
}
}
/// Start an exchange as the initiator: encapsulate to the responder and keep the state.
///
/// **`rng` must be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it
/// once per process; never a fixed, derived or configured seed. `CryptoRng` is only a marker: a
/// CSPRNG with a constant seed satisfies it and makes this call fully deterministic (QA R2-04).
///
/// # Errors
/// [`Error::NonContributory`] if the responder's X25519 key is a low-order point.
pub fn initiate<'a, R: CryptoRng + ?Sized>(
me: &'a SecretKey,
responder: &PublicKey,
context: &[u8],
rng: &mut R,
) -> Result<Initiation<'a>, Error> {
let mut eseed = Zeroizing::new([0u8; ENCAPSULATION_SEED_LEN]);
rng.fill_bytes(eseed.as_mut_slice());
initiate_inner(me, responder, context, &eseed)
}
/// Answer an exchange as the responder: decapsulate the initiator's ciphertext, encapsulate back,
/// and return the ciphertext to send together with the finished session.
///
/// **`rng` must be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it
/// once per process; never a fixed, derived or configured seed. `CryptoRng` is only a marker: a
/// CSPRNG with a constant seed satisfies it and makes this call fully deterministic (QA R2-04).
///
/// # Errors
/// [`Error::NonContributory`] if the initiator's ciphertext or public key has a low-order X25519
/// part.
pub fn respond<R: CryptoRng + ?Sized>(
me: &SecretKey,
initiator: &PublicKey,
ct_ir: &Ciphertext,
context: &[u8],
rng: &mut R,
) -> Result<(Ciphertext, Session), Error> {
let mut eseed = Zeroizing::new([0u8; ENCAPSULATION_SEED_LEN]);
rng.fill_bytes(eseed.as_mut_slice());
respond_inner(me, initiator, ct_ir, context, &eseed)
}
/// [`initiate`] with explicit randomness. **Hazmat** (feature `hazmat`), for known-answer tests:
/// reusing an `eseed` reuses the secret.
///
/// # Errors
/// As [`initiate`].
#[cfg(feature = "hazmat")]
pub fn initiate_derand<'a>(
me: &'a SecretKey,
responder: &PublicKey,
context: &[u8],
eseed: &[u8; ENCAPSULATION_SEED_LEN],
) -> Result<Initiation<'a>, Error> {
initiate_inner(me, responder, context, eseed)
}
/// [`respond`] with explicit randomness. **Hazmat** (feature `hazmat`), for known-answer tests.
///
/// # Errors
/// As [`respond`].
#[cfg(feature = "hazmat")]
pub fn respond_derand(
me: &SecretKey,
initiator: &PublicKey,
ct_ir: &Ciphertext,
context: &[u8],
eseed: &[u8; ENCAPSULATION_SEED_LEN],
) -> Result<(Ciphertext, Session), Error> {
respond_inner(me, initiator, ct_ir, context, eseed)
}
fn initiate_inner<'a>(
me: &'a SecretKey,
responder: &PublicKey,
context: &[u8],
eseed: &[u8; ENCAPSULATION_SEED_LEN],
) -> Result<Initiation<'a>, Error> {
let (ct_ir, ss_ir) = responder.encapsulate_inner(eseed)?;
Ok(Initiation { me, peer: responder.clone(), ct_ir, ss_ir, context: Zeroizing::new(context.to_vec()) })
}
fn respond_inner(
me: &SecretKey,
initiator: &PublicKey,
ct_ir: &Ciphertext,
context: &[u8],
eseed: &[u8; ENCAPSULATION_SEED_LEN],
) -> Result<(Ciphertext, Session), Error> {
let ss_ir = me.decapsulate_inner(ct_ir)?;
let (ct_ri, ss_ri) = initiator.encapsulate_inner(eseed)?;
let t = Transcript { initiator, responder: me.public_key(), ct_ir, ct_ri: &ct_ri, context };
let session = Session { prk: session_prk(&ss_ir, &ss_ri, &t) };
Ok((ct_ri, session))
}
+49
View File
@@ -0,0 +1,49 @@
//! # Arcanum
//!
//! The post-quantum crypto core of the Domi ecosystem. **Not audited.**
//!
//! - [`xwing`]: the hybrid KEM ML-KEM-768 + X25519 (X-Wing, draft-connolly-cfrg-xwing-kem-11).
//! - [`exchange`]: a mutual exchange between two peers (each encapsulates to the other), bound to
//! the full transcript and a context, and the WireGuard pre-shared key it yields per epoch.
//! - [`seal`]: a one-shot sealed box to a recipient's hybrid public key.
//! - [`sign`] (v0.2.0): hybrid signatures ML-DSA-65 + Ed25519, exactly RFC 10073
//! `id-MLDSA65-Ed25519-SHA512`, and a helper that binds an X-Wing public key to its owner.
//!
//! No primitive is implemented here; they come from `ml-kem`, `x25519-dalek`, `ml-dsa`,
//! `ed25519-dalek`, `sha3`, `shake`, `sha2`, `hkdf` and `chacha20poly1305`. No I/O, no clock: randomness and time are parameters.
//! Design, sources and risks: `docs/01_arcanum.md`, `docs/02_signatures.md` and `docs/THREAT_MODEL.md`.
//!
//! The `hazmat` feature exposes the deterministic (`_derand`, `from_seed`) entry points and the
//! bare RFC 10073 signature interface (`sign_composite_raw`, `verify_composite_raw`) used by the
//! known-answer tests. It is off by default and must never be enabled in a release build.
#![no_std]
#![forbid(unsafe_code)]
#![deny(missing_docs)]
extern crate alloc;
mod error;
pub mod exchange;
mod schedule;
pub mod seal;
pub mod sign;
pub mod xwing;
#[cfg(test)]
mod binding_tests;
#[cfg(test)]
mod qa_review_tests;
pub use error::{Error, Input};
pub use exchange::{Session, WIREGUARD_PSK_LEN, WireGuardPsk};
/// The recommended rotation interval in seconds. Rosenpass's responder rekeys every 120 s
/// (`REKEY_AFTER_TIME_RESPONDER`), following WireGuard's own two-minute rekey.
pub const RECOMMENDED_EPOCH_SECONDS: u64 = 120;
/// The epoch number at `unix_seconds`, for [`Session::wireguard_psk`]. Arcanum has no clock; the
/// caller passes the time.
#[must_use]
pub const fn epoch_at(unix_seconds: u64) -> u64 {
unix_seconds / RECOMMENDED_EPOCH_SECONDS
}
+105
View File
@@ -0,0 +1,105 @@
//! QA second review (PR #1): A-08 and A-09, which need the crate-private key schedule.
use alloc::vec::Vec;
use std::collections::HashSet;
use crate::schedule::{
LABEL_SEAL_KEY, LABEL_SEAL_NONCE, LABEL_WIREGUARD_PSK, Prk, Transcript, expand, seal_prk, session_prk,
};
use crate::xwing::{CIPHERTEXT_LEN, Ciphertext, SecretKey, SharedSecret};
use zeroize::Zeroizing;
extern crate std;
fn ss(b: u8) -> SharedSecret {
SharedSecret(Zeroizing::new([b; 32]))
}
/// The `info` strings every `expand` call in the crate uses, built exactly as the call sites do.
fn psk_info(epoch: u64) -> Vec<u8> {
[LABEL_WIREGUARD_PSK, &epoch.to_be_bytes()].concat()
}
/// QA A-08. `expand` concatenates its parts raw, so it is injective only because every call site
/// passes a fixed label followed by fixed-width fields. This test pins both halves of that
/// argument: (1) the helper itself is NOT length-prefixed (so a future variable-width part is a
/// collision, and this test documents it for whoever adds one), and (2) the encodings actually in
/// use are injective: fixed lengths per purpose, and no two purposes share a length-and-prefix.
#[test]
fn a08_kdf_info_encodings_in_use_are_injective() {
let prk: Prk = Zeroizing::new([9u8; 32]);
// (1) Builder fix for R2-03: the helper now takes exactly one label and one fixed-width field,
// so the old ["ab","c"] vs ["a","bc"] collision cannot be written any more. Its bytes are still
// the v1 encoding, HKDF-Expand(prk, label || field), so the golden vectors did not change.
let raw = |info: &[u8]| {
let mut o = [0u8; 32];
hkdf::Hkdf::<sha2::Sha256>::from_prk(prk.as_slice()).unwrap().expand(info, &mut o).unwrap();
o
};
assert_eq!(*expand::<32, 8>(&prk, LABEL_WIREGUARD_PSK, &7u64.to_be_bytes()), raw(&psk_info(7)));
assert_eq!(*expand::<32, 0>(&prk, LABEL_SEAL_KEY, &[]), raw(LABEL_SEAL_KEY));
// (2) Every info string in use: one fixed length per purpose, and none a prefix of another.
let mut infos: Vec<Vec<u8>> = [0u64, 1, 255, 256, 1 << 32, u64::MAX].iter().map(|&e| psk_info(e)).collect();
infos.push(LABEL_SEAL_KEY.to_vec());
infos.push(LABEL_SEAL_NONCE.to_vec());
for info in &infos[..6] {
assert_eq!(info.len(), LABEL_WIREGUARD_PSK.len() + 8, "a PSK info has one fixed width");
}
for (i, a) in infos.iter().enumerate() {
for (j, b) in infos.iter().enumerate() {
if i != j {
assert_ne!(a, b);
assert!(!b.starts_with(a), "info {i} is a prefix of info {j}");
}
}
}
// The exchange transcript: the only variable field (the context) is last and length-prefixed,
// so moving a byte across the context boundary changes the hash.
let pk_i = SecretKey::from_bytes(&[1u8; 32]).unwrap().public_key().clone();
let pk_r = SecretKey::from_bytes(&[2u8; 32]).unwrap().public_key().clone();
let ct = Ciphertext::from_bytes(&[3u8; CIPHERTEXT_LEN]).unwrap();
let t = |ctx: &[u8]| {
*session_prk(
&ss(1),
&ss(2),
&Transcript { initiator: &pk_i, responder: &pk_r, ct_ir: &ct, ct_ri: &ct, context: ctx },
)
};
assert_ne!(t(b""), t(&[0u8; 8]), "an empty context is not 8 zero bytes");
assert_ne!(t(b"x"), t(b"x\0"));
}
/// QA A-09: from one X-Wing secret, no two purposes ever yield the same key. The seal key and
/// nonce, and the PSKs of 1024 epochs, are all distinct; and even under a single PRK the labels
/// keep the purposes apart.
#[test]
fn a09_one_secret_never_yields_the_same_key_for_two_purposes() {
let r = SecretKey::from_bytes(&[5u8; 32]).unwrap();
let ct = Ciphertext::from_bytes(&[6u8; CIPHERTEXT_LEN]).unwrap();
let secret = ss(7);
// The same secret, used as a seal and as both directions of an exchange.
let seal = seal_prk(&secret, r.public_key(), &ct, b"");
let session = session_prk(
&secret,
&secret,
&Transcript { initiator: r.public_key(), responder: r.public_key(), ct_ir: &ct, ct_ri: &ct, context: b"" },
);
assert_ne!(*seal, *session, "seal and exchange PRKs must differ for one secret");
let mut keys: HashSet<[u8; 32]> = HashSet::new();
for prk in [&seal, &session] {
let key = *expand::<32, 0>(prk, LABEL_SEAL_KEY, &[]);
assert!(keys.insert(key));
let mut nonce = [0u8; 32];
nonce[..12].copy_from_slice(&*expand::<12, 0>(prk, LABEL_SEAL_NONCE, &[]));
// HKDF output is prefix-consistent: a shared label would make the nonce the key's prefix.
assert_ne!(nonce[..12], key[..12], "the nonce is a prefix of the key: labels shared");
assert!(keys.insert(nonce));
for e in 0..1024u64 {
assert!(keys.insert(*expand::<32, 8>(prk, LABEL_WIREGUARD_PSK, &e.to_be_bytes())), "epoch {e}");
}
}
assert_eq!(keys.len(), 2 * (2 + 1024));
}
+118
View File
@@ -0,0 +1,118 @@
//! The key schedule: HKDF-SHA-256 (RFC 5869) with versioned `domi/arcanum/v1/...` labels.
//!
//! X-Wing is used exactly as specified; its combiner binds `ct_X` and `pk_X` and leaves `ct_M` and
//! `pk_M` to ML-KEM. The roadmap's decided combiner binds both public keys and both ciphertexts,
//! so that is done here, in Arcanum's own derivation (QA decision D-QA-1(a)):
//!
//! ```text
//! exchange: th = SHA-256("domi/arcanum/v1/transcript/exchange"
//! || pk_I || pk_R || ct_IR || ct_RI || u64be(len ctx) || ctx)
//! prk = HKDF-Extract(salt = "domi/arcanum/v1/extract", ikm = ss_IR || ss_RI || th)
//! seal: th = SHA-256("domi/arcanum/v1/transcript/seal" || pk || ct || u64be(len aad) || aad)
//! prk = HKDF-Extract(salt = "domi/arcanum/v1/extract", ikm = ss || th)
//! keys: okm = HKDF-Expand(prk, label || fixed-width fields)
//! ```
//!
//! Every hashed field before the context is fixed-width and the context is length-prefixed, so
//! the encoding is injective. Roles are bound by position. A v2 schedule gets new labels; these
//! are never reused.
use hkdf::{Hkdf, HkdfExtract};
use sha2::{Digest, Sha256};
use zeroize::{Zeroize, Zeroizing};
use crate::xwing::{Ciphertext, PublicKey, SharedSecret};
pub(crate) const LABEL_TRANSCRIPT_EXCHANGE: &[u8] = b"domi/arcanum/v1/transcript/exchange";
pub(crate) const LABEL_TRANSCRIPT_SEAL: &[u8] = b"domi/arcanum/v1/transcript/seal";
pub(crate) const LABEL_EXTRACT: &[u8] = b"domi/arcanum/v1/extract";
pub(crate) const LABEL_WIREGUARD_PSK: &[u8] = b"domi/arcanum/v1/wireguard-psk";
pub(crate) const LABEL_SEAL_KEY: &[u8] = b"domi/arcanum/v1/seal/key";
pub(crate) const LABEL_SEAL_NONCE: &[u8] = b"domi/arcanum/v1/seal/nonce";
/// Every label, for the prefix-freeness test.
#[cfg(test)]
pub(crate) const ALL_LABELS: [&[u8]; 6] = [
LABEL_TRANSCRIPT_EXCHANGE,
LABEL_TRANSCRIPT_SEAL,
LABEL_EXTRACT,
LABEL_WIREGUARD_PSK,
LABEL_SEAL_KEY,
LABEL_SEAL_NONCE,
];
/// Pseudo-random key of one exchange or one seal.
pub(crate) type Prk = Zeroizing<[u8; 32]>;
/// The transcript of one mutual exchange, in role order.
pub(crate) struct Transcript<'a> {
pub(crate) initiator: &'a PublicKey,
pub(crate) responder: &'a PublicKey,
pub(crate) ct_ir: &'a Ciphertext,
pub(crate) ct_ri: &'a Ciphertext,
pub(crate) context: &'a [u8],
}
impl Transcript<'_> {
fn hash(&self) -> [u8; 32] {
let mut h = Sha256::new();
h.update(LABEL_TRANSCRIPT_EXCHANGE);
h.update(self.initiator.as_bytes());
h.update(self.responder.as_bytes());
h.update(self.ct_ir.as_bytes());
h.update(self.ct_ri.as_bytes());
h.update((self.context.len() as u64).to_be_bytes());
h.update(self.context);
h.finalize().into()
}
}
fn extract(secrets: &[&[u8; 32]], th: &[u8; 32]) -> Prk {
let mut ext = HkdfExtract::<Sha256>::new(Some(LABEL_EXTRACT));
for s in secrets {
ext.input_ikm(s.as_slice());
}
ext.input_ikm(th);
let (mut prk, _) = ext.finalize();
let mut out = Zeroizing::new([0u8; 32]);
out.copy_from_slice(prk.as_slice());
prk.as_mut_slice().zeroize();
out
}
/// The PRK of a mutual exchange: both directions' X-Wing secrets and the whole transcript.
pub(crate) fn session_prk(ss_ir: &SharedSecret, ss_ri: &SharedSecret, t: &Transcript<'_>) -> Prk {
extract(&[ss_ir.bytes(), ss_ri.bytes()], &t.hash())
}
/// The PRK of one sealed box: the X-Wing secret, the recipient key, the ciphertext and the aad.
pub(crate) fn seal_prk(ss: &SharedSecret, recipient: &PublicKey, ct: &Ciphertext, aad: &[u8]) -> Prk {
let mut h = Sha256::new();
h.update(LABEL_TRANSCRIPT_SEAL);
h.update(recipient.as_bytes());
h.update(ct.as_bytes());
h.update((aad.len() as u64).to_be_bytes());
h.update(aad);
let th: [u8; 32] = h.finalize().into();
extract(&[ss.bytes()], &th)
}
/// HKDF-Expand to `N` bytes with `info = label || field`.
///
/// The signature is what makes the encoding injective (QA R2-03): exactly one label, which must be
/// one of the `LABEL_*` constants above (unique and prefix-free, tested in `binding_tests`), and
/// exactly one fixed-width field. If two calls give the same `info`, their labels are equal (in a
/// prefix-free set a label is determined by the string it starts), so their fields are equal too.
/// Several values go into one fixed-width array, never into separate parts. This is byte for byte
/// the v1 encoding (`tests/golden_v1.rs` is unchanged).
pub(crate) fn expand<const N: usize, const K: usize>(
prk: &Prk,
label: &'static [u8],
field: &[u8; K],
) -> Zeroizing<[u8; N]> {
// Infallible: a 32-byte PRK is the SHA-256 output size, and N <= 32 is far below 255 * 32.
let hk = Hkdf::<Sha256>::from_prk(prk.as_slice()).expect("PRK is 32 bytes");
let mut out = Zeroizing::new([0u8; N]);
hk.expand_multi_info(&[label, field.as_slice()], out.as_mut_slice()).expect("N is at most 255 * 32");
out
}
+128
View File
@@ -0,0 +1,128 @@
//! One-shot sealed box to a recipient's hybrid public key, for Custos sealing and Tabellarius.
//!
//! ```text
//! sealed = 0x01 || ct (1120 B) || ChaCha20-Poly1305(key, nonce, plaintext, aad = 0x01) || tag
//! th = SHA-256("domi/arcanum/v1/transcript/seal" || pk || ct || u64be(len aad) || aad)
//! prk = HKDF-Extract(salt = "domi/arcanum/v1/extract", ikm = ss || th)
//! key = HKDF-Expand(prk, "domi/arcanum/v1/seal/key", 32)
//! nonce = HKDF-Expand(prk, "domi/arcanum/v1/seal/nonce", 12)
//! ```
//!
//! Every seal runs a fresh encapsulation, so a key and nonce pair is never used twice.
//!
//! **Anyone who knows the recipient's public key can seal.** There is no sender authentication,
//! and ChaCha20-Poly1305 is not key-committing: a successful [`open`] says nothing about who
//! sealed. This is a documented construction, not HPKE (RFC 9180).
use alloc::vec::Vec;
use chacha20poly1305::aead::AeadInOut;
use chacha20poly1305::{ChaCha20Poly1305, KeyInit, Nonce};
use rand_core::CryptoRng;
use zeroize::Zeroizing;
use crate::error::{Error, Input};
use crate::schedule::{LABEL_SEAL_KEY, LABEL_SEAL_NONCE, Prk, expand, seal_prk};
use crate::xwing::{CIPHERTEXT_LEN, Ciphertext, ENCAPSULATION_SEED_LEN, PublicKey, SecretKey};
/// The format version written as the first byte.
pub const VERSION: u8 = 1;
const TAG_LEN: usize = 16;
const HEADER_LEN: usize = 1 + CIPHERTEXT_LEN;
/// Bytes a sealed box adds to the plaintext: version, ciphertext and the Poly1305 tag.
pub const OVERHEAD: usize = HEADER_LEN + TAG_LEN;
fn cipher(prk: &Prk) -> (ChaCha20Poly1305, Nonce) {
let key = expand::<32, 0>(prk, LABEL_SEAL_KEY, &[]);
let nonce = expand::<12, 0>(prk, LABEL_SEAL_NONCE, &[]);
// Infallible: the key is exactly 32 bytes.
let aead = ChaCha20Poly1305::new_from_slice(key.as_slice()).expect("32-byte key");
(aead, Nonce::from(*nonce))
}
/// Seal `plaintext` to `recipient`, bound to `aad` (which is not encrypted and must be given again
/// to open).
///
/// **`rng` must be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it
/// once per process; never a fixed, derived or configured seed. `CryptoRng` is only a marker: a
/// CSPRNG with a constant seed satisfies it and makes this call fully deterministic (QA R2-04).
///
/// # Errors
/// [`Error::NonContributory`] if the recipient's X25519 key is a low-order point.
pub fn seal<R: CryptoRng + ?Sized>(
recipient: &PublicKey,
plaintext: &[u8],
aad: &[u8],
rng: &mut R,
) -> Result<Vec<u8>, Error> {
let mut eseed = Zeroizing::new([0u8; ENCAPSULATION_SEED_LEN]);
rng.fill_bytes(eseed.as_mut_slice());
seal_inner(recipient, plaintext, aad, &eseed)
}
/// [`seal`] with explicit randomness. **Hazmat** (feature `hazmat`), for tests: reusing an
/// `eseed` reuses key and nonce.
///
/// # Errors
/// As [`seal`].
#[cfg(feature = "hazmat")]
pub fn seal_derand(
recipient: &PublicKey,
plaintext: &[u8],
aad: &[u8],
eseed: &[u8; ENCAPSULATION_SEED_LEN],
) -> Result<Vec<u8>, Error> {
seal_inner(recipient, plaintext, aad, eseed)
}
fn seal_inner(
recipient: &PublicKey,
plaintext: &[u8],
aad: &[u8],
eseed: &[u8; ENCAPSULATION_SEED_LEN],
) -> Result<Vec<u8>, Error> {
let (ct, ss) = recipient.encapsulate_inner(eseed)?;
let (aead, nonce) = cipher(&seal_prk(&ss, recipient, &ct, aad));
// Allocated once at its final size, so no buffer that held plaintext is ever reallocated. It is
// `Zeroizing` until the plaintext has been encrypted in place, so an early return (the
// `MessageTooLong` path) wipes the copy instead of freeing it unwiped (QA R2-05).
let mut out = Zeroizing::new(Vec::with_capacity(plaintext.len() + OVERHEAD));
out.push(VERSION);
out.extend_from_slice(ct.as_bytes());
out.extend_from_slice(plaintext);
// ChaCha20-Poly1305 refuses only messages over 2^38 bytes; that is reported, not a panic.
let tag = aead
.encrypt_inout_detached(&nonce, &[VERSION], (&mut out[HEADER_LEN..]).into())
.map_err(|_| Error::MessageTooLong)?;
out.extend_from_slice(tag.as_slice());
// Now only ciphertext: move the buffer out without copying it (the wrapper keeps an empty Vec).
Ok(core::mem::take(&mut *out))
}
/// Open a sealed box with the recipient's secret key and the same `aad`.
///
/// # Errors
/// [`Error::TooShort`], [`Error::UnsupportedVersion`], [`Error::NonContributory`], or
/// [`Error::DecryptionFailed`] for a wrong key, wrong `aad`, or any tampering.
pub fn open(recipient: &SecretKey, sealed: &[u8], aad: &[u8]) -> Result<Zeroizing<Vec<u8>>, Error> {
if sealed.len() < OVERHEAD {
return Err(Error::TooShort { input: Input::SealedBox, minimum: OVERHEAD, actual: sealed.len() });
}
let (header, rest) = sealed.split_at(HEADER_LEN);
let (&version, ct) = header.split_first().ok_or(Error::DecryptionFailed)?;
if version != VERSION {
return Err(Error::UnsupportedVersion(version));
}
let ct = Ciphertext::from_bytes(ct)?;
let ss = recipient.decapsulate_inner(&ct)?;
let (aead, nonce) = cipher(&seal_prk(&ss, recipient.public_key(), &ct, aad));
let (body, tag) = rest.split_at(rest.len() - TAG_LEN);
let tag = chacha20poly1305::Tag::try_from(tag).map_err(|_| Error::DecryptionFailed)?;
// The tag is checked before anything is decrypted; on failure the buffer holds only ciphertext.
let mut plaintext = Zeroizing::new(body.to_vec());
aead.decrypt_inout_detached(&nonce, &[VERSION], plaintext.as_mut_slice().into(), &tag)
.map_err(|_| Error::DecryptionFailed)?;
Ok(plaintext)
}
+484
View File
@@ -0,0 +1,484 @@
//! Hybrid post-quantum signatures: ML-DSA-65 + Ed25519, exactly RFC 10073
//! `id-MLDSA65-Ed25519-SHA512` (OID 1.3.6.1.5.5.7.6.48). A signature stays unforgeable while
//! either ML-DSA-65 or Ed25519 does.
//!
//! ```text
//! Prefix = "CompositeAlgorithmSignatures2025" Label = "COMPSIG-MLDSA65-Ed25519-SHA512"
//! M' = Prefix || Label || u8(len(ctx)) || ctx || SHA-512(M) (RFC 10073 §3.2)
//! sig = ML-DSA-65.Sign(sk_ml, M', ctx = Label) hedged, 3309 bytes
//! || Ed25519.Sign(sk_ed, M') pure Ed25519, 64 bytes
//! valid iff ML-DSA-65.Verify(pk_ml, M', sig_ml, ctx = Label) and Ed25519 verify_strict(pk_ed, M', sig_ed)
//! public key = pk_ml (1952 bytes) || pk_ed (32 bytes)
//! private key = ML-DSA seed (32 bytes) || Ed25519 seed (32 bytes)
//! ```
//!
//! This module is glue: ML-DSA-65 from `ml-dsa` (FIPS 204), Ed25519 from `ed25519-dalek` (RFC 8032),
//! SHA-512 from `sha2`. It never uses `ml-dsa`'s `Signer`/`Verifier` traits (deterministic, empty
//! ctx), only `ExpandedSigningKey::sign_randomized` and `VerifyingKey::verify_with_context`.
//!
//! **Contexts.** The RFC's `ctx` is a domain separator. Arcanum fixes it per purpose:
//! [`KEM_KEY_CONTEXT`] for [`bind_kem_key`], and [`APP_CONTEXT_PREFIX`] + the caller's label for
//! [`SigningKey::sign`], through [`AppContext`]. A signature made for one context never verifies
//! under another: `ctx` and its length are inside M'.
//!
//! **Stricter than the RFC**, invisible to honest signers: a verifying key whose Ed25519 half is a
//! small-order point or not the canonical encoding of its point, or whose ML-DSA-65 half has
//! t1 = 0, is refused when parsed ([`Error::InvalidVerifyingKey`]), and Ed25519 is checked with
//! `verify_strict`. Both refused shapes are "weak keys": with t1 = 0 an ML-DSA signature needs no
//! secret at all (QA S-05), as a small-order Ed25519 key lets signatures verify for many messages.
//!
//! **Not SUF-CMA** (RFC 10073 §9.2): two signatures of one message under one key can trade their
//! hedged ML-DSA halves. Never use a signature as an identifier.
//!
//! The bare RFC interface (any `ctx`, including empty) is `hazmat` only, for the RFC's vectors.
use alloc::boxed::Box;
use core::{array, fmt};
use ed25519_dalek::Signer as _;
use ml_dsa::{EncodedSignature, EncodedVerifyingKey, ExpandedSigningKey, MlDsa65, Seed};
use rand_core::CryptoRng;
use sha2::{Digest, Sha512};
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
use crate::error::{Error, Input, exact};
use crate::xwing;
/// RFC 10073 §2.2: the prefix of every composite M'.
pub const PREFIX: &[u8] = b"CompositeAlgorithmSignatures2025";
/// RFC 10073 §6: the label of `id-MLDSA65-Ed25519-SHA512`, also ML-DSA's own `ctx`.
pub const LABEL: &[u8] = b"COMPSIG-MLDSA65-Ed25519-SHA512";
/// The context of a key binding ([`bind_kem_key`]).
pub const KEM_KEY_CONTEXT: &[u8] = b"domi/arcanum/v2/sig/kem-key";
/// The prefix of every application context ([`AppContext`]).
pub const APP_CONTEXT_PREFIX: &[u8] = b"domi/arcanum/v2/sig/app/";
/// The longest `ctx` RFC 10073 allows (it is encoded as one byte in M').
pub const MAX_CONTEXT_LEN: usize = 255;
/// The longest label an [`AppContext`] can take: 255 minus the 24-byte prefix.
pub const MAX_APP_LABEL_LEN: usize = MAX_CONTEXT_LEN - APP_CONTEXT_PREFIX.len();
/// The longest key id in a key binding (its length is a big-endian `u16`).
pub const MAX_KEY_ID_LEN: usize = u16::MAX as usize;
/// The version byte at the start of every key-binding message.
pub const KEY_BINDING_VERSION: u8 = 1;
/// Length of a composite verifying key: ML-DSA-65 public key (1952) + Ed25519 public key (32).
pub const VERIFYING_KEY_LEN: usize = 1984;
/// Length of a stored composite signing key: two 32-byte seeds.
pub const SIGNING_KEY_LEN: usize = 64;
/// Length of a composite signature: ML-DSA-65 signature (3309) + Ed25519 signature (64).
pub const SIGNATURE_LEN: usize = 3373;
const ML_DSA_PUBLIC_KEY_LEN: usize = 1952;
const ML_DSA_SIGNATURE_LEN: usize = 3309;
const ML_DSA_RHO_LEN: usize = 32;
const SEED_LEN: usize = 32;
const M_PRIME_MAX_LEN: usize = 32 + 30 + 1 + MAX_CONTEXT_LEN + 64;
// The fixed lengths above are the crates' own; a crate update that changed one fails to compile.
const _: () = assert!(PREFIX.len() == 32 && LABEL.len() == 30);
const _: () = assert!(core::mem::size_of::<EncodedVerifyingKey<MlDsa65>>() == ML_DSA_PUBLIC_KEY_LEN);
const _: () = assert!(core::mem::size_of::<EncodedSignature<MlDsa65>>() == ML_DSA_SIGNATURE_LEN);
const _: () = assert!(VERIFYING_KEY_LEN == ML_DSA_PUBLIC_KEY_LEN + ed25519_dalek::PUBLIC_KEY_LENGTH);
const _: () = assert!(SIGNATURE_LEN == ML_DSA_SIGNATURE_LEN + ed25519_dalek::SIGNATURE_LENGTH);
/// An application context: [`APP_CONTEXT_PREFIX`] followed by the caller's label, 25 to 255 bytes
/// in all. It can only be built with that prefix, so a caller cannot pass an empty context, the
/// key-binding context or a foreign one by accident.
///
/// The label is `&'static` (QA S-09): one fixed label per purpose, written in the source, never
/// derived from a peer name, a file name or a message field (two purposes whose labels came from
/// data could collide). Build it once, at compile time:
///
/// ```
/// use arcanum::sign::AppContext;
/// const PLANS: AppContext = match AppContext::new(b"plans") {
/// Ok(ctx) => ctx,
/// Err(_) => panic!("label is 1 to 231 bytes"),
/// };
/// assert_eq!(PLANS.as_bytes(), b"domi/arcanum/v2/sig/app/plans");
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct AppContext {
bytes: [u8; MAX_CONTEXT_LEN],
len: usize,
}
impl AppContext {
/// `domi/arcanum/v2/sig/app/` + `label`, for a fixed, compile-time label (Day 3: `plans`).
/// A `const fn`, so a `const` context is checked when the consumer compiles.
///
/// # Errors
/// [`Error::TooShort`] for an empty label; [`Error::TooLong`] for one over
/// [`MAX_APP_LABEL_LEN`] (231) bytes.
pub const fn new(label: &'static [u8]) -> Result<Self, Error> {
if label.is_empty() {
return Err(Error::TooShort { input: Input::Context, minimum: 1, actual: 0 });
}
if label.len() > MAX_APP_LABEL_LEN {
return Err(Error::TooLong { input: Input::Context, maximum: MAX_APP_LABEL_LEN, actual: label.len() });
}
let mut bytes = [0u8; MAX_CONTEXT_LEN];
let p = APP_CONTEXT_PREFIX.len();
let mut i = 0;
while i < p {
bytes[i] = APP_CONTEXT_PREFIX[i];
i += 1;
}
let mut j = 0;
while j < label.len() {
bytes[p + j] = label[j];
j += 1;
}
Ok(Self { bytes, len: p + label.len() })
}
/// The whole context, prefix included: the RFC's `ctx`.
#[must_use]
pub fn as_bytes(&self) -> &[u8] {
&self.bytes[..self.len]
}
}
impl fmt::Debug for AppContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("AppContext").field(&self.as_bytes().escape_ascii()).finish()
}
}
/// M' (RFC 10073 §3.2), built on the stack: at most 382 bytes.
struct MPrime {
bytes: [u8; M_PRIME_MAX_LEN],
len: usize,
}
impl MPrime {
/// M' from the message's SHA-512, which the caller computed (all at once, or field by field).
fn new(ph: &[u8; 64], ctx: &[u8]) -> Result<Self, Error> {
let ctx_len = u8::try_from(ctx.len()).map_err(|_| Error::TooLong {
input: Input::Context,
maximum: MAX_CONTEXT_LEN,
actual: ctx.len(),
})?;
let mut m = Self { bytes: [0u8; M_PRIME_MAX_LEN], len: 0 };
for part in [PREFIX, LABEL, &[ctx_len], ctx, ph] {
m.bytes[m.len..m.len + part.len()].copy_from_slice(part);
m.len += part.len();
}
Ok(m)
}
fn of_message(msg: &[u8], ctx: &[u8]) -> Result<Self, Error> {
Self::new(&Sha512::digest(msg).into(), ctx)
}
fn as_bytes(&self) -> &[u8] {
&self.bytes[..self.len]
}
}
/// A composite verifying key (`pk_ml || pk_ed`), validated on parse.
#[derive(Clone)]
pub struct VerifyingKey {
bytes: [u8; VERIFYING_KEY_LEN],
ml: ml_dsa::VerifyingKey<MlDsa65>,
ed: ed25519_dalek::VerifyingKey,
}
impl VerifyingKey {
/// Parse a composite verifying key received from somewhere else.
///
/// # Errors
/// [`Error::InvalidLength`] if it is not 1984 bytes; [`Error::InvalidVerifyingKey`] if the
/// Ed25519 half is not a point, is not the canonical encoding of its point, or has small order,
/// or if the ML-DSA-65 half's t1 (its bytes 32..1952) is all zero. Every other 1952-byte
/// ML-DSA-65 public key is well formed (FIPS 204 `pkDecode` cannot fail).
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
let bytes: &[u8; VERIFYING_KEY_LEN] = exact(Input::VerifyingKey, bytes)?;
let ed_bytes: [u8; 32] = array::from_fn(|i| bytes[ML_DSA_PUBLIC_KEY_LEN + i]);
let ed = ed25519_dalek::VerifyingKey::from_bytes(&ed_bytes).map_err(|_| Error::InvalidVerifyingKey)?;
// `from_bytes` accepts y >= p and a set sign bit on x = 0 (RFC 8032 §5.1.3 says to refuse
// them); re-encoding the point and comparing refuses every non-canonical encoding.
if ed.is_weak() || ed.to_edwards().compress().to_bytes() != ed_bytes {
return Err(Error::InvalidVerifyingKey);
}
// t1 = 0 (Wycheproof's `ZeroPublicKey`): ML-DSA verification then checks only
// c~ = H(mu || w1(A·z)), which anyone can satisfy with s1 = s2 = t0 = 0. An honest key has
// t1 = 0 with negligible probability.
if bytes[ML_DSA_RHO_LEN..ML_DSA_PUBLIC_KEY_LEN].iter().all(|&b| b == 0) {
return Err(Error::InvalidVerifyingKey);
}
let enc = EncodedVerifyingKey::<MlDsa65>::try_from(&bytes[..ML_DSA_PUBLIC_KEY_LEN])
.map_err(|_| Error::InvalidVerifyingKey)?;
let ml = ml_dsa::VerifyingKey::<MlDsa65>::decode(&enc);
Ok(Self { bytes: *bytes, ml, ed })
}
/// The 1984-byte encoding.
#[must_use]
pub fn as_bytes(&self) -> &[u8; VERIFYING_KEY_LEN] {
&self.bytes
}
/// Verify a signature over `msg` made with [`SigningKey::sign`] under the same context.
///
/// # Errors
/// [`Error::InvalidSignature`] if either half (or both) fails. The error does not say which
/// half failed; the time taken may (a malformed ML-DSA half is refused at decode, and
/// `verify_strict` stops early on a bad R). That is fine: verification handles only public data,
/// so its timing reveals nothing secret (RFC 10073 §3.3 allows failing early; QA S-06).
pub fn verify(&self, msg: &[u8], ctx: &AppContext, sig: &Signature) -> Result<(), Error> {
self.verify_m_prime(&MPrime::of_message(msg, ctx.as_bytes())?, sig)
}
fn verify_m_prime(&self, mp: &MPrime, sig: &Signature) -> Result<(), Error> {
let mp = mp.as_bytes();
// A malformed ML-DSA half (bad hint encoding, z out of range) is refused at decode, without
// the verification step: quicker, and visible in the timing, but everything here is public.
let ml_ok = ml_dsa::Signature::<MlDsa65>::try_from(&sig.0[..ML_DSA_SIGNATURE_LEN])
.is_ok_and(|s| self.ml.verify_with_context(mp, LABEL, &s));
let ed_sig = ed25519_dalek::Signature::from_bytes(&array::from_fn(|i| sig.0[ML_DSA_SIGNATURE_LEN + i]));
let ed_ok = self.ed.verify_strict(mp, &ed_sig).is_ok();
if ml_ok && ed_ok { Ok(()) } else { Err(Error::InvalidSignature) }
}
}
impl PartialEq for VerifyingKey {
fn eq(&self, other: &Self) -> bool {
self.bytes == other.bytes
}
}
impl Eq for VerifyingKey {}
impl fmt::Debug for VerifyingKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("VerifyingKey").field("len", &VERIFYING_KEY_LEN).finish_non_exhaustive()
}
}
/// A composite signature (`sig_ml || sig_ed`). Any 3373 bytes parse; verification decides.
#[derive(Clone, PartialEq, Eq)]
pub struct Signature([u8; SIGNATURE_LEN]);
impl Signature {
/// Parse a signature.
///
/// # Errors
/// [`Error::InvalidLength`] if it is not 3373 bytes.
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
exact(Input::Signature, bytes).map(|b| Self(*b))
}
/// The 3373-byte encoding.
#[must_use]
pub fn as_bytes(&self) -> &[u8; SIGNATURE_LEN] {
&self.0
}
}
impl fmt::Debug for Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Signature").field("len", &SIGNATURE_LEN).finish_non_exhaustive()
}
}
/// A composite signing key: two independent 32-byte seeds and the keys expanded from them, all
/// zeroised on drop. Not `Clone`; `Debug` prints nothing secret.
///
/// **Stack** (QA S-11): building a key ([`SigningKey::generate`], [`SigningKey::from_bytes`]) and
/// signing keep ML-DSA-65's polynomial vectors on the stack. Measured on Windows x86-64
/// (`tests/sig_stack.rs`): a release build needs more than 128 KiB and fits in 256 KiB; a debug
/// build (with dependencies at `opt-level = 2`, as in Arcanum's own profile) needs more than
/// 256 KiB and fits in 512 KiB. Too small a thread **aborts the process** with a stack overflow;
/// it is not an error that can be caught. Default threads (1–2 MiB) are fine; give worker,
/// blocking-pool or JNI threads that sign at least 512 KiB, and measure unoptimised debug builds.
pub struct SigningKey {
seeds: Zeroizing<[u8; SIGNING_KEY_LEN]>,
// Boxed: the expanded ML-DSA-65 key is 34,992 bytes on the stack (its A_hat rows are already
// boxed inside ml-dsa); those bytes are the secret part, s1, s2, t0 and their NTT forms.
ml: Box<ExpandedSigningKey<MlDsa65>>,
ed: ed25519_dalek::SigningKey,
public: VerifyingKey,
}
impl SigningKey {
/// Generate a new key pair from the caller's RNG: 64 fresh bytes, both seeds at once.
///
/// **`rng` must be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it
/// once per process; never a fixed, derived or configured seed (QA R2-04).
pub fn generate<R: CryptoRng + ?Sized>(rng: &mut R) -> Self {
let mut seeds = Zeroizing::new([0u8; SIGNING_KEY_LEN]);
rng.fill_bytes(seeds.as_mut_slice());
Self::expand(seeds)
}
/// Parse a stored signing key: the ML-DSA-65 seed, then the Ed25519 seed (RFC 10073's
/// private key format).
///
/// **The 64 bytes must come from [`SigningKey::generate`]** (or from another RFC 10073 composite
/// key), never from component seeds used anywhere else: RFC 10073 §3.1 forbids reusing a
/// component key, and an existing Ed25519 seed (Tessera's, say) wrapped in here would make
/// every classic signer of that key a potential forgery oracle for the composite if ML-DSA
/// ever falls (QA S-07). This function cannot tell: any 64 bytes are a valid key.
///
/// # Errors
/// [`Error::InvalidLength`] if it is not 64 bytes. Every 64-byte value is a valid key.
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
let seeds: &[u8; SIGNING_KEY_LEN] = exact(Input::SigningKey, bytes)?;
Ok(Self::expand(Zeroizing::new(*seeds)))
}
/// The 64 bytes to store in Custos or Tessera. Handle with care.
#[must_use]
pub fn to_bytes(&self) -> Zeroizing<[u8; SIGNING_KEY_LEN]> {
Zeroizing::new(*self.seeds)
}
/// The matching verifying key.
#[must_use]
pub fn verifying_key(&self) -> &VerifyingKey {
&self.public
}
/// Sign `msg` under an application context. The ML-DSA half is hedged: 32 fresh bytes come
/// from `rng`, which must be the OS RNG or a CSPRNG seeded from it (see [`SigningKey::generate`]).
///
/// # Errors
/// [`Error::SigningFailed`] if the RNG fails or ML-DSA's rejection sampling gives up (it is
/// bounded; with a working RNG this does not happen in practice). Retry with fresh randomness.
pub fn sign<R: CryptoRng + ?Sized>(&self, msg: &[u8], ctx: &AppContext, rng: &mut R) -> Result<Signature, Error> {
self.sign_m_prime(&MPrime::of_message(msg, ctx.as_bytes())?, rng)
}
fn sign_m_prime<R: CryptoRng + ?Sized>(&self, mp: &MPrime, rng: &mut R) -> Result<Signature, Error> {
let mp = mp.as_bytes();
let ml = self.ml.sign_randomized(mp, LABEL, rng).map_err(|_| Error::SigningFailed)?;
let ed = self.ed.try_sign(mp).map_err(|_| Error::SigningFailed)?;
let mut out = [0u8; SIGNATURE_LEN];
out[..ML_DSA_SIGNATURE_LEN].copy_from_slice(ml.encode().as_slice());
out[ML_DSA_SIGNATURE_LEN..].copy_from_slice(&ed.to_bytes());
Ok(Signature(out))
}
fn expand(seeds: Zeroizing<[u8; SIGNING_KEY_LEN]>) -> Self {
let mut ml_seed = Seed::default();
ml_seed.as_mut_slice().copy_from_slice(&seeds[..SEED_LEN]);
let ml = Box::new(ExpandedSigningKey::<MlDsa65>::from_seed(&ml_seed));
ml_seed.as_mut_slice().zeroize();
let mut ed_seed = Zeroizing::new([0u8; SEED_LEN]);
ed_seed.copy_from_slice(&seeds[SEED_LEN..]);
let ed = ed25519_dalek::SigningKey::from_bytes(&ed_seed);
let ml_pk = ml.verifying_key();
let ed_pk = ed.verifying_key();
let mut bytes = [0u8; VERIFYING_KEY_LEN];
bytes[..ML_DSA_PUBLIC_KEY_LEN].copy_from_slice(ml_pk.encode().as_slice());
bytes[ML_DSA_PUBLIC_KEY_LEN..].copy_from_slice(ed_pk.as_bytes());
Self { seeds, ml, ed, public: VerifyingKey { bytes, ml: ml_pk, ed: ed_pk } }
}
}
impl fmt::Debug for SigningKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SigningKey([redacted])")
}
}
// `seeds` is `Zeroizing`; `ml-dsa`'s `ExpandedSigningKey` and `ed25519-dalek`'s `SigningKey` wipe
// themselves on drop (their `zeroize` features are enabled in Cargo.toml, and
// tests/sig_hygiene.rs asserts the bounds).
impl ZeroizeOnDrop for SigningKey {}
/// SHA-512 of the key-binding message
/// `u8(1) || u64be(not_before) || u64be(not_after) || u16be(len(id)) || id || xwing_pk (1216 bytes)`,
/// fed field by field. Fixed widths and one length prefix: the encoding is injective.
fn binding_digest(id: &[u8], kem: &xwing::PublicKey, (not_before, not_after): (u64, u64)) -> Result<[u8; 64], Error> {
if not_before > not_after {
return Err(Error::InvalidValidity);
}
let id_len = u16::try_from(id.len()).map_err(|_| Error::TooLong {
input: Input::KeyId,
maximum: MAX_KEY_ID_LEN,
actual: id.len(),
})?;
let mut h = Sha512::new();
h.update([KEY_BINDING_VERSION]);
h.update(not_before.to_be_bytes());
h.update(not_after.to_be_bytes());
h.update(id_len.to_be_bytes());
h.update(id);
h.update(kem.as_bytes());
Ok(h.finalize().into())
}
/// Sign "this X-Wing public key belongs to `id` from `valid.0` to `valid.1` (inclusive, the
/// caller's clock, usually Unix seconds)", under [`KEM_KEY_CONTEXT`].
///
/// # Errors
/// [`Error::InvalidValidity`] if `valid.0 > valid.1`; [`Error::TooLong`] for an id over 65,535
/// bytes; [`Error::SigningFailed`] as for [`SigningKey::sign`].
pub fn bind_kem_key<R: CryptoRng + ?Sized>(
sk: &SigningKey,
id: &[u8],
kem: &xwing::PublicKey,
valid: (u64, u64),
rng: &mut R,
) -> Result<Signature, Error> {
sk.sign_m_prime(&MPrime::new(&binding_digest(id, kem, valid)?, KEM_KEY_CONTEXT)?, rng)
}
/// Check a key binding made by [`bind_kem_key`], at time `now` (Arcanum has no clock).
///
/// **Two checks stay with the caller** (QA S-08): (1) that `vk` is *the* verifying key of `id`,
/// from a trusted source: a binding only says "the holder of `vk` says `kem` is `id`'s"; and
/// (2) freshness: there is no serial, so after a rotation the previous binding still verifies
/// until its `valid.1`. Keep windows short and keep only the binding with the newest `valid.0`
/// per `id`, refusing older ones (Day 3's replay design, QA E-07). `(0, u64::MAX)` is an
/// eternal binding; avoid it.
///
/// # Errors
/// In this order: [`Error::InvalidValidity`] or [`Error::TooLong`] for a malformed window or id;
/// [`Error::InvalidSignature`] if the binding is not authentic; [`Error::OutsideValidity`] if it is
/// authentic but `now` is before `valid.0` or after `valid.1`.
pub fn verify_binding(
vk: &VerifyingKey,
id: &[u8],
kem: &xwing::PublicKey,
valid: (u64, u64),
now: u64,
sig: &Signature,
) -> Result<(), Error> {
vk.verify_m_prime(&MPrime::new(&binding_digest(id, kem, valid)?, KEM_KEY_CONTEXT)?, sig)?;
if !(valid.0..=valid.1).contains(&now) {
return Err(Error::OutsideValidity);
}
Ok(())
}
/// RFC 10073 composite signing with the bare `ctx` (0 to 255 bytes, empty allowed), for the RFC's
/// own vectors. **Hazmat** (feature `hazmat`): release code signs through [`AppContext`] or
/// [`bind_kem_key`], so its contexts can never collide. The ML-DSA half is still hedged; a test
/// that needs repeatable bytes passes a seeded RNG.
///
/// # Errors
/// [`Error::TooLong`] for a `ctx` over 255 bytes; [`Error::SigningFailed`].
#[cfg(feature = "hazmat")]
pub fn sign_composite_raw<R: CryptoRng + ?Sized>(
sk: &SigningKey,
msg: &[u8],
ctx: &[u8],
rng: &mut R,
) -> Result<Signature, Error> {
sk.sign_m_prime(&MPrime::of_message(msg, ctx)?, rng)
}
/// RFC 10073 composite verification with the bare `ctx`. **Hazmat** (feature `hazmat`).
///
/// # Errors
/// [`Error::TooLong`] for a `ctx` over 255 bytes; [`Error::InvalidSignature`].
#[cfg(feature = "hazmat")]
pub fn verify_composite_raw(vk: &VerifyingKey, msg: &[u8], ctx: &[u8], sig: &Signature) -> Result<(), Error> {
vk.verify_m_prime(&MPrime::of_message(msg, ctx)?, sig)
}
+342
View File
@@ -0,0 +1,342 @@
//! X-Wing: the hybrid KEM ML-KEM-768 + X25519, as specified in draft-connolly-cfrg-xwing-kem-11.
//!
//! This module is glue between vetted primitives: ML-KEM-768 from `ml-kem` (FIPS 203), X25519 from
//! `x25519-dalek` (RFC 7748), SHAKE256 from `shake` and SHA3-256 from `sha3` (FIPS 202). It is pinned
//! by the draft's three test vectors and a differential test against RustCrypto's `x-wing` crate.
//!
//! Two deliberate differences from the draft, both stricter and both invisible to honest peers and
//! to the official vectors: a low-order X25519 public key or ciphertext part is refused with
//! [`Error::NonContributory`], and a public key whose X25519 half is not the canonical encoding
//! (bit 255 set, or a value of at least 2^255 - 19) is refused with [`Error::InvalidPublicKey`]
//! (docs/01_arcanum.md).
//!
//! **The raw one-way KEM is not part of the release API** (QA R2-01). Without the `hazmat` feature
//! a consumer can parse keys and ciphertexts and generate a key pair, but cannot encapsulate,
//! decapsulate or read an X-Wing secret: a PSK must come from [`crate::exchange`], which needs both
//! directions and binds the transcript, and sealing goes through [`crate::seal`].
use core::{array, fmt};
use ml_kem::array::Array;
use ml_kem::{B32, Decapsulate, KeyExport, MlKem768, Seed};
use rand_core::CryptoRng;
use sha3::{Digest, Sha3_256};
use shake::{ExtendableOutput, Shake256, Update, XofReader};
use x25519_dalek::{PublicKey as X25519Public, StaticSecret};
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
use crate::error::{Error, Input, exact};
type MlKemEncapsulationKey = ml_kem::EncapsulationKey<MlKem768>;
type MlKemDecapsulationKey = ml_kem::DecapsulationKey<MlKem768>;
/// Length of a hybrid public key: ML-KEM-768 encapsulation key (1184) + X25519 public key (32).
pub const PUBLIC_KEY_LEN: usize = 1216;
/// Length of a hybrid secret key: a 32-byte seed, expanded with SHAKE256.
pub const SECRET_KEY_LEN: usize = 32;
/// Length of a hybrid ciphertext: ML-KEM-768 ciphertext (1088) + X25519 ephemeral public key (32).
pub const CIPHERTEXT_LEN: usize = 1120;
/// Length of the X-Wing shared secret.
pub const SHARED_SECRET_LEN: usize = 32;
/// Length of the encapsulation randomness: 32 bytes for ML-KEM, 32 for the X25519 ephemeral key.
pub const ENCAPSULATION_SEED_LEN: usize = 64;
const ML_KEM_PUBLIC_KEY_LEN: usize = 1184;
const ML_KEM_CIPHERTEXT_LEN: usize = 1088;
/// The X-Wing label, ASCII `\.//^\` (hex 5c2e2f2f5e5c), draft -11 §5.3.
const XWING_LABEL: &[u8; 6] = br"\.//^\";
/// X-Wing Combiner (draft -11 §5.3): SHA3-256(ss_M || ss_X || ct_X || pk_X || XWingLabel).
pub(crate) fn combiner(ss_m: &[u8; 32], ss_x: &[u8; 32], ct_x: &[u8; 32], pk_x: &[u8; 32]) -> [u8; SHARED_SECRET_LEN] {
let mut h = Sha3_256::new();
Digest::update(&mut h, ss_m);
Digest::update(&mut h, ss_x);
Digest::update(&mut h, ct_x);
Digest::update(&mut h, pk_x);
Digest::update(&mut h, XWING_LABEL);
h.finalize().into()
}
/// The X-Wing shared secret. Zeroised on drop; never printed.
pub struct SharedSecret(pub(crate) Zeroizing<[u8; SHARED_SECRET_LEN]>);
impl SharedSecret {
/// The raw 32 bytes. **Hazmat** (feature `hazmat`): a one-way X-Wing secret authenticates only
/// the receiver and is bound to no transcript, so it must never be used as a key directly.
#[cfg(feature = "hazmat")]
#[must_use]
pub fn as_bytes(&self) -> &[u8; SHARED_SECRET_LEN] {
&self.0
}
pub(crate) fn bytes(&self) -> &[u8; SHARED_SECRET_LEN] {
&self.0
}
}
impl fmt::Debug for SharedSecret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SharedSecret([redacted])")
}
}
impl ZeroizeOnDrop for SharedSecret {}
/// A hybrid public key (`pk_M || pk_X`), validated on parse.
#[derive(Clone)]
pub struct PublicKey {
bytes: [u8; PUBLIC_KEY_LEN],
pk_m: MlKemEncapsulationKey,
pk_x: X25519Public,
}
impl PublicKey {
/// Parse a hybrid public key received from somewhere else.
///
/// # Errors
/// [`Error::InvalidLength`] if it is not 1216 bytes; [`Error::InvalidPublicKey`] if the ML-KEM
/// part fails the FIPS 203 §7.2 encapsulation key check, or the X25519 part is not canonical.
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
let bytes: &[u8; PUBLIC_KEY_LEN] = exact(Input::PublicKey, bytes)?;
let m: [u8; ML_KEM_PUBLIC_KEY_LEN] = array::from_fn(|i| bytes[i]);
let pk_m = MlKemEncapsulationKey::new(&Array::from(m)).map_err(|_| Error::InvalidPublicKey)?;
let x: [u8; 32] = array::from_fn(|i| bytes[ML_KEM_PUBLIC_KEY_LEN + i]);
if !is_canonical_x25519(&x) {
return Err(Error::InvalidPublicKey);
}
Ok(Self { bytes: *bytes, pk_m, pk_x: X25519Public::from(x) })
}
/// The 1216-byte encoding.
#[must_use]
pub fn as_bytes(&self) -> &[u8; PUBLIC_KEY_LEN] {
&self.bytes
}
/// Encapsulate a fresh shared secret to this key. **Hazmat** (feature `hazmat`), see the module
/// docs; release code uses [`crate::exchange`] or [`crate::seal`].
///
/// # Errors
/// [`Error::NonContributory`] if the X25519 part of the key is a low-order point.
#[cfg(feature = "hazmat")]
pub fn encapsulate<R: CryptoRng + ?Sized>(&self, rng: &mut R) -> Result<(Ciphertext, SharedSecret), Error> {
let mut eseed = Zeroizing::new([0u8; ENCAPSULATION_SEED_LEN]);
rng.fill_bytes(eseed.as_mut_slice());
self.encapsulate_inner(&eseed)
}
/// X-Wing `EncapsulateDerand` (draft -11 §5.4.1): the randomness is given explicitly.
///
/// **Hazmat** (feature `hazmat`). For known-answer tests. Using the same `eseed` twice gives
/// the same secret to anyone who sees both ciphertexts. Use [`PublicKey::encapsulate`].
///
/// # Errors
/// [`Error::NonContributory`] if the X25519 part of the key is a low-order point.
#[cfg(feature = "hazmat")]
pub fn encapsulate_derand(
&self,
eseed: &[u8; ENCAPSULATION_SEED_LEN],
) -> Result<(Ciphertext, SharedSecret), Error> {
self.encapsulate_inner(eseed)
}
pub(crate) fn encapsulate_inner(
&self,
eseed: &[u8; ENCAPSULATION_SEED_LEN],
) -> Result<(Ciphertext, SharedSecret), Error> {
let mut m = B32::from(array::from_fn::<u8, 32, _>(|i| eseed[i]));
let (ct_m, mut ss_m) = self.pk_m.encapsulate_deterministic(&m);
m.as_mut_slice().zeroize();
let ek_x: Zeroizing<[u8; 32]> = Zeroizing::new(array::from_fn(|i| eseed[32 + i]));
let ek_x = StaticSecret::from(*ek_x);
let ct_x = X25519Public::from(&ek_x);
let ss_x = ek_x.diffie_hellman(&self.pk_x);
drop(ek_x);
let result = if ss_x.was_contributory() {
let ss_m_arr = as32(&ss_m);
Ok(combiner(&ss_m_arr, ss_x.as_bytes(), ct_x.as_bytes(), self.pk_x.as_bytes()))
} else {
Err(Error::NonContributory)
};
ss_m.as_mut_slice().zeroize();
let ss = result?;
let mut ct = [0u8; CIPHERTEXT_LEN];
ct[..ML_KEM_CIPHERTEXT_LEN].copy_from_slice(ct_m.as_slice());
ct[ML_KEM_CIPHERTEXT_LEN..].copy_from_slice(ct_x.as_bytes());
Ok((Ciphertext(ct), SharedSecret(Zeroizing::new(ss))))
}
}
impl PartialEq for PublicKey {
fn eq(&self, other: &Self) -> bool {
self.bytes == other.bytes
}
}
impl Eq for PublicKey {}
impl fmt::Debug for PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PublicKey").field("len", &PUBLIC_KEY_LEN).finish_non_exhaustive()
}
}
/// A hybrid ciphertext (`ct_M || ct_X`). Any 1120 bytes parse; a tampered ML-KEM part is handled
/// by implicit rejection, a low-order X25519 part is refused at decapsulation.
#[derive(Clone, PartialEq, Eq)]
pub struct Ciphertext([u8; CIPHERTEXT_LEN]);
impl Ciphertext {
/// Parse a ciphertext.
///
/// # Errors
/// [`Error::InvalidLength`] if it is not 1120 bytes.
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
exact(Input::Ciphertext, bytes).map(|b| Self(*b))
}
/// The 1120-byte encoding.
#[must_use]
pub fn as_bytes(&self) -> &[u8; CIPHERTEXT_LEN] {
&self.0
}
}
impl fmt::Debug for Ciphertext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Ciphertext").field("len", &CIPHERTEXT_LEN).finish_non_exhaustive()
}
}
/// A hybrid secret key. Stored as its 32-byte seed plus the expanded keys; all zeroised on drop.
pub struct SecretKey {
seed: Zeroizing<[u8; SECRET_KEY_LEN]>,
dk_m: MlKemDecapsulationKey,
sk_x: StaticSecret,
public: PublicKey,
}
impl SecretKey {
/// Generate a new key pair from the caller's RNG.
///
/// **`rng` must be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it
/// once per process; never a fixed, derived or configured seed. `CryptoRng` is only a marker: a
/// CSPRNG with a constant seed satisfies it and makes this call fully deterministic (QA R2-04).
pub fn generate<R: CryptoRng + ?Sized>(rng: &mut R) -> Self {
let mut seed = Zeroizing::new([0u8; SECRET_KEY_LEN]);
rng.fill_bytes(seed.as_mut_slice());
Self::expand(seed)
}
/// X-Wing `GenerateKeyPairDerand` (draft -11 §5.2.1): the key from a given 32-byte seed.
/// **Hazmat** (feature `hazmat`), for tests: the caller's copy of `seed` is not wiped. Real
/// code uses [`SecretKey::generate`], or [`SecretKey::from_bytes`] on a buffer it zeroises.
#[cfg(feature = "hazmat")]
#[must_use]
pub fn from_seed(seed: [u8; SECRET_KEY_LEN]) -> Self {
Self::expand(Zeroizing::new(seed))
}
/// Parse a stored secret key (its 32-byte seed).
///
/// # Errors
/// [`Error::InvalidLength`] if it is not 32 bytes. Every 32-byte value is a valid key.
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
let seed: &[u8; SECRET_KEY_LEN] = exact(Input::SecretKey, bytes)?;
Ok(Self::expand(Zeroizing::new(*seed)))
}
/// The 32-byte seed, for storing in Custos or Tessera. Handle with care.
#[must_use]
pub fn to_seed(&self) -> Zeroizing<[u8; SECRET_KEY_LEN]> {
Zeroizing::new(*self.seed)
}
/// The matching public key.
#[must_use]
pub fn public_key(&self) -> &PublicKey {
&self.public
}
/// X-Wing `Decapsulate` (draft -11 §5.5). **Hazmat** (feature `hazmat`), see the module docs.
///
/// # Errors
/// [`Error::NonContributory`] if the X25519 part of the ciphertext is a low-order point. A
/// tampered ML-KEM part is not an error: ML-KEM's implicit rejection returns an unrelated secret.
#[cfg(feature = "hazmat")]
pub fn decapsulate(&self, ct: &Ciphertext) -> Result<SharedSecret, Error> {
self.decapsulate_inner(ct)
}
pub(crate) fn decapsulate_inner(&self, ct: &Ciphertext) -> Result<SharedSecret, Error> {
let ct_x: [u8; 32] = array::from_fn(|i| ct.0[ML_KEM_CIPHERTEXT_LEN + i]);
let ss_x = self.sk_x.diffie_hellman(&X25519Public::from(ct_x));
if !ss_x.was_contributory() {
return Err(Error::NonContributory);
}
let ct_m: [u8; ML_KEM_CIPHERTEXT_LEN] = array::from_fn(|i| ct.0[i]);
let mut ss_m = self.dk_m.decapsulate(&Array::from(ct_m));
let ss_m_arr = as32(&ss_m);
let ss = combiner(&ss_m_arr, ss_x.as_bytes(), &ct_x, self.public.pk_x.as_bytes());
ss_m.as_mut_slice().zeroize();
Ok(SharedSecret(Zeroizing::new(ss)))
}
/// `expandDecapsulationKey` (draft -11 §5.2): SHAKE256(seed) -> d || z || sk_X.
fn expand(seed: Zeroizing<[u8; SECRET_KEY_LEN]>) -> Self {
let mut expanded = Zeroizing::new([0u8; 96]);
let mut xof = Shake256::default();
Update::update(&mut xof, seed.as_slice());
xof.finalize_xof().read(expanded.as_mut_slice());
let mut ml_seed = Seed::default();
ml_seed.as_mut_slice().copy_from_slice(&expanded[..64]);
let dk_m = MlKemDecapsulationKey::from_seed(ml_seed);
ml_seed.as_mut_slice().zeroize();
let mut sk_x_bytes = Zeroizing::new([0u8; 32]);
sk_x_bytes.copy_from_slice(&expanded[64..]);
let sk_x = StaticSecret::from(*sk_x_bytes);
let pk_x = X25519Public::from(&sk_x);
let pk_m = dk_m.encapsulation_key().clone();
let mut bytes = [0u8; PUBLIC_KEY_LEN];
bytes[..ML_KEM_PUBLIC_KEY_LEN].copy_from_slice(pk_m.to_bytes().as_slice());
bytes[ML_KEM_PUBLIC_KEY_LEN..].copy_from_slice(pk_x.as_bytes());
Self { seed, dk_m, sk_x, public: PublicKey { bytes, pk_m, pk_x } }
}
}
impl fmt::Debug for SecretKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SecretKey([redacted])")
}
}
// `seed` is `Zeroizing`, and `ml-kem`'s and `x25519-dalek`'s key types wipe themselves on drop
// (their `zeroize` features are enabled in Cargo.toml).
impl ZeroizeOnDrop for SecretKey {}
/// RFC 7748 encodes a u-coordinate as 32 little-endian bytes of a value below p = 2^255 - 19, with
/// bit 255 clear; X25519 outputs (every honest public key) are always in that form. Decoders mask
/// bit 255 and reduce mod p, so other encodings alias a canonical key: refuse them (QA R2-02).
fn is_canonical_x25519(u: &[u8; 32]) -> bool {
if u[31] & 0x80 != 0 {
return false;
}
// With bit 255 clear, u >= p only for 2^255 - 19 ..= 2^255 - 1: ed..ff, then 30 x ff, then 7f.
let at_least_p = u[31] == 0x7f && u[1..31].iter().all(|&b| b == 0xff) && u[0] >= 0xed;
!at_least_p
}
/// Copy a 32-byte ML-KEM shared key into a stack array that is wiped on drop.
fn as32(k: &ml_kem::SharedKey) -> Zeroizing<[u8; 32]> {
let mut out = Zeroizing::new([0u8; 32]);
out.copy_from_slice(k.as_slice());
out
}
+142
View File
@@ -0,0 +1,142 @@
//! Mandatory test 3, through the public API: an attacker can force the X25519 half to zero by
//! sending a low-order point. Arcanum refuses that with a typed error instead of producing a
//! secret that only one half protects (QA A-16, A-17). The combiner-level half of test 3, which
//! zeroes each component directly, is `src/binding_tests.rs`. Also QA A-04 (raw ct_X is hashed).
mod common;
use arcanum::Error;
use arcanum::exchange;
use arcanum::xwing::{Ciphertext, PublicKey, SecretKey};
use common::rng;
/// Curve25519 u-coordinates of small order and non-canonical encodings of them (libsodium's
/// blocklist). Each is also used with bit 255 set, which X25519 ignores (RFC 7748 §5).
const LOW_ORDER: [&str; 7] = [
"0000000000000000000000000000000000000000000000000000000000000000",
"0100000000000000000000000000000000000000000000000000000000000000",
"e0eb7a7c3b41b8ae1656e3faf19fc46ada098deb9c32b1fd866205165f49b800",
"5f9c95bca3508c24b1d0b1559c83ef5b04445cc4581c8e86d8224eddd09f1157",
"ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
"edffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
"eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f",
];
fn low_order_points() -> Vec<[u8; 32]> {
LOW_ORDER
.iter()
.flat_map(|h| {
let p: [u8; 32] = hex::decode(h).unwrap().try_into().unwrap();
let mut high = p;
high[31] |= 0x80;
[p, high]
})
.collect()
}
/// Guards the fixture: if a byte above were mistyped, the point would not be low order.
#[test]
fn the_fixture_points_really_are_low_order() {
let s = x25519_dalek::StaticSecret::from([0x5a; 32]);
for p in low_order_points() {
assert!(!s.diffie_hellman(&p.into()).was_contributory(), "{}", hex::encode(p));
}
}
#[test]
fn low_order_x25519_ciphertext_is_refused() {
let i = SecretKey::from_seed([0x43; 32]);
let r = SecretKey::from_seed([0x44; 32]);
let init = exchange::initiate_derand(&i, r.public_key(), b"ctx", &[0x55; 64]).unwrap();
let (ct_ri, _) = exchange::respond_derand(&r, i.public_key(), init.ciphertext(), b"ctx", &[0x56; 64]).unwrap();
for point in low_order_points() {
let mut bad = *init.ciphertext().as_bytes();
bad[1088..].copy_from_slice(&point);
let bad = Ciphertext::from_bytes(&bad).unwrap();
assert_eq!(r.decapsulate(&bad).err(), Some(Error::NonContributory));
let resp = exchange::respond_derand(&r, i.public_key(), &bad, b"ctx", &[0x56; 64]);
assert_eq!(resp.err(), Some(Error::NonContributory));
let mut bad = *ct_ri.as_bytes();
bad[1088..].copy_from_slice(&point);
let again = exchange::initiate_derand(&i, r.public_key(), b"ctx", &[0x55; 64]).unwrap();
assert_eq!(again.finish(&Ciphertext::from_bytes(&bad).unwrap()).err(), Some(Error::NonContributory));
}
}
#[test]
fn low_order_x25519_public_key_is_refused() {
let i = SecretKey::from_seed([0x43; 32]);
let r = SecretKey::from_seed([0x44; 32]);
let mut refused_at_parse = 0;
for point in low_order_points() {
let mut bad = *r.public_key().as_bytes();
bad[1184..].copy_from_slice(&point);
// Non-canonical encodings (bit 255 set, or p and p + 1) are refused when parsed (QA R2-02);
// the canonical low-order points parse and are refused when used.
let canonical = point[31] & 0x80 == 0 && !(point[31] == 0x7f && point[0] >= 0xed);
let pk = match PublicKey::from_bytes(&bad) {
Ok(pk) => {
assert!(canonical, "a non-canonical pk_X parsed: {}", hex::encode(point));
pk
}
Err(e) => {
assert_eq!(e, Error::InvalidPublicKey);
assert!(!canonical, "a canonical pk_X was refused: {}", hex::encode(point));
refused_at_parse += 1;
continue;
}
};
assert_eq!(pk.encapsulate_derand(&[0x55; 64]).err(), Some(Error::NonContributory));
assert_eq!(exchange::initiate_derand(&i, &pk, b"ctx", &[0x55; 64]).err(), Some(Error::NonContributory));
assert_eq!(arcanum::seal::seal(&pk, b"x", b"", &mut rng(1)).err(), Some(Error::NonContributory));
}
// 7 points with bit 255 set, plus p and p + 1.
assert_eq!(refused_at_parse, 9);
}
/// QA R2-02 boundary: p - 1 is the largest canonical u-coordinate (and low order), p is the
/// smallest non-canonical one, and an honest key is always canonical.
#[test]
fn the_canonical_boundary_is_exactly_p() {
let r = SecretKey::from_seed([0x44; 32]);
let with_x = |x: [u8; 32]| {
let mut b = *r.public_key().as_bytes();
b[1184..].copy_from_slice(&x);
PublicKey::from_bytes(&b)
};
let mut p_minus_1 = [0xff; 32];
p_minus_1[0] = 0xec;
p_minus_1[31] = 0x7f;
let mut p = p_minus_1;
p[0] = 0xed;
let mut below = [0xff; 32];
below[31] = 0x7f;
below[1] = 0xfe; // 2^255 - 1 - 2^8: below p although its first byte is 0xff
assert!(with_x(p_minus_1).is_ok());
assert_eq!(with_x(p).err(), Some(Error::InvalidPublicKey));
assert!(with_x(below).is_ok());
assert!(PublicKey::from_bytes(r.public_key().as_bytes()).is_ok());
}
/// QA A-04: X25519 ignores bit 255 of ct_X, so ct_X and ct_X ^ 0x80 give the same ss_X. The
/// output must still differ, because the combiner hashes the raw bytes.
#[test]
fn the_high_bit_of_ct_x_is_bound() {
let r = SecretKey::from_seed([0x44; 32]);
let (ct, ss) = r.public_key().encapsulate(&mut rng(4)).unwrap();
let mut b = *ct.as_bytes();
b[1119] ^= 0x80;
let out = r.decapsulate(&Ciphertext::from_bytes(&b).unwrap()).unwrap();
assert_ne!(out.as_bytes(), ss.as_bytes());
}
/// The honest exchange is not affected by the check.
#[test]
fn honest_points_pass_the_check() {
let i = SecretKey::from_seed([0x43; 32]);
let r = SecretKey::from_seed([0x44; 32]);
let init = exchange::initiate_derand(&i, r.public_key(), b"ctx", &[0x55; 64]).unwrap();
let (ct_ri, rs) = exchange::respond_derand(&r, i.public_key(), init.ciphertext(), b"ctx", &[0x56; 64]).unwrap();
assert_eq!(init.finish(&ct_ri).unwrap().wireguard_psk(3).as_bytes(), rs.wireguard_psk(3).as_bytes());
}
+72
View File
@@ -0,0 +1,72 @@
//! Helpers shared by the integration tests. Test fixtures only: no real keys, no network.
#![allow(dead_code)]
use chacha20::ChaCha20Rng;
use rand_core::SeedableRng;
use sha2::{Digest, Sha256};
/// A deterministic RNG for tests. Never used outside tests.
pub fn rng(label: u8) -> ChaCha20Rng {
ChaCha20Rng::from_seed([label; 32])
}
pub fn hex(s: &str) -> Vec<u8> {
hex::decode(s).expect("vector hex")
}
pub fn arr<const N: usize>(s: &str) -> [u8; N] {
hex(s).try_into().expect("vector length")
}
/// Fail loudly if a pinned vector file is not the one recorded in tests/vectors/SOURCES.md.
pub fn assert_sha256(bytes: &[u8], expected_hex: &str, name: &str) {
let got = hex::encode(Sha256::digest(bytes));
assert_eq!(got, expected_hex, "{name} is not the pinned file (see tests/vectors/SOURCES.md)");
}
/// Standard base64 (RFC 4648 §4, with padding), as the RFC 10073 vectors use.
pub fn b64(s: &str) -> Vec<u8> {
use base64::Engine;
base64::engine::general_purpose::STANDARD.decode(s).expect("vector base64")
}
/// An "RNG" that returns exactly the given bytes, then panics. It lets a known-answer test feed a
/// vector's `rnd` to the hedged signing path that Arcanum uses (`sign_randomized`), and proves
/// that path draws exactly 32 bytes. Claims `TryCryptoRng` only so the signing API accepts it.
pub struct FixedRng {
bytes: Vec<u8>,
pos: usize,
}
impl FixedRng {
pub fn new(bytes: &[u8]) -> Self {
Self { bytes: bytes.to_vec(), pos: 0 }
}
pub fn used(&self) -> usize {
self.pos
}
}
impl rand_core::TryRng for FixedRng {
type Error = core::convert::Infallible;
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
let mut b = [0u8; 4];
self.try_fill_bytes(&mut b)?;
Ok(u32::from_le_bytes(b))
}
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
let mut b = [0u8; 8];
self.try_fill_bytes(&mut b)?;
Ok(u64::from_le_bytes(b))
}
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
let end = self.pos + dst.len();
assert!(end <= self.bytes.len(), "FixedRng: asked for more bytes than the vector gives");
dst.copy_from_slice(&self.bytes[self.pos..end]);
self.pos = end;
Ok(())
}
}
impl rand_core::TryCryptoRng for FixedRng {}
+244
View File
@@ -0,0 +1,244 @@
//! Mandatory test 2: both sides of a hybrid exchange derive the same secret, and changing any
//! single input byte changes it. Also QA A-14 (roles bound) and A-15 (both directions needed).
//!
//! The exchange is mutual (each peer encapsulates to the other, docs/01_arcanum.md). Its inputs
//! are: both peers' seeds, both encapsulation seeds, both public keys (as the other side received
//! them), both ciphertexts (as the other side received them), and the context. Every byte of the
//! public keys, the ciphertexts, the seeds and the context is flipped in turn.
mod common;
use arcanum::exchange::{self, Session};
use arcanum::xwing::{CIPHERTEXT_LEN, Ciphertext, PUBLIC_KEY_LEN, PublicKey, SecretKey};
use common::rng;
use std::collections::HashSet;
const SEED_I: [u8; 32] = [0x11; 32];
const SEED_R: [u8; 32] = [0x12; 32];
const ESEED_I: [u8; 64] = [0x21; 64];
const ESEED_R: [u8; 64] = [0x22; 64];
const CONTEXT: &[u8] = b"via/test: device-a <-> device-b";
fn psk(session: &Session) -> [u8; 32] {
*session.wireguard_psk(0).as_bytes()
}
/// The honest exchange: (PSK, ct_IR, ct_RI).
fn honest() -> ([u8; 32], Ciphertext, Ciphertext) {
let i = SecretKey::from_seed(SEED_I);
let r = SecretKey::from_seed(SEED_R);
let init = exchange::initiate_derand(&i, r.public_key(), CONTEXT, &ESEED_I).unwrap();
let ct_ir = init.ciphertext().clone();
let (ct_ri, rs) = exchange::respond_derand(&r, i.public_key(), &ct_ir, CONTEXT, &ESEED_R).unwrap();
let is = init.finish(&ct_ri).unwrap();
assert_eq!(psk(&is), psk(&rs));
(psk(&rs), ct_ir, ct_ri)
}
#[test]
fn both_sides_derive_the_same_secret() {
let mut g = rng(1);
for _ in 0..32 {
let i = SecretKey::generate(&mut g);
let r = SecretKey::generate(&mut g);
let init = exchange::initiate(&i, r.public_key(), CONTEXT, &mut g).unwrap();
let (ct_ri, rs) = exchange::respond(&r, i.public_key(), init.ciphertext(), CONTEXT, &mut g).unwrap();
let is = init.finish(&ct_ri).unwrap();
for epoch in [0, 1, 7, u64::MAX] {
assert_eq!(is.wireguard_psk(epoch).as_bytes(), rs.wireguard_psk(epoch).as_bytes());
}
}
}
#[test]
fn both_sides_agree_after_keys_and_ciphertexts_go_through_bytes() {
let i = SecretKey::from_seed(SEED_I);
let r = SecretKey::from_seed(SEED_R);
let r_pk = PublicKey::from_bytes(r.public_key().as_bytes()).unwrap();
let i_pk = PublicKey::from_bytes(i.public_key().as_bytes()).unwrap();
let init = exchange::initiate_derand(&i, &r_pk, CONTEXT, &ESEED_I).unwrap();
let ct_ir = Ciphertext::from_bytes(init.ciphertext().as_bytes()).unwrap();
let (ct_ri, rs) = exchange::respond_derand(&r, &i_pk, &ct_ir, CONTEXT, &ESEED_R).unwrap();
let ct_ri = Ciphertext::from_bytes(ct_ri.as_bytes()).unwrap();
assert_eq!(psk(&init.finish(&ct_ri).unwrap()), psk(&rs));
}
#[test]
fn fresh_randomness_gives_a_fresh_secret() {
let mut g = rng(2);
let i = SecretKey::generate(&mut g);
let r = SecretKey::generate(&mut g);
let mut seen = HashSet::new();
for _ in 0..64 {
let init = exchange::initiate(&i, r.public_key(), CONTEXT, &mut g).unwrap();
let (_, rs) = exchange::respond(&r, i.public_key(), init.ciphertext(), CONTEXT, &mut g).unwrap();
assert!(seen.insert(psk(&rs)), "two exchanges produced the same secret");
}
}
/// Flip each byte of ct_IR as the responder receives it: the responder's secret changes.
#[test]
fn every_byte_of_the_initiators_ciphertext_changes_the_secret() {
let (honest_psk, ct_ir, _) = honest();
let i = SecretKey::from_seed(SEED_I);
let r = SecretKey::from_seed(SEED_R);
let mut accepted = 0;
for n in 0..CIPHERTEXT_LEN {
let mut bad = *ct_ir.as_bytes();
bad[n] ^= 0x01;
let bad = Ciphertext::from_bytes(&bad).unwrap();
// A refusal (a low-order X25519 value) is also "not the honest secret".
if let Ok((_, s)) = exchange::respond_derand(&r, i.public_key(), &bad, CONTEXT, &ESEED_R) {
assert_ne!(psk(&s), honest_psk, "ct_IR byte {n} did not change the secret");
accepted += 1;
}
}
assert!(accepted > CIPHERTEXT_LEN - 32, "flipped ciphertexts must mostly decapsulate (implicit rejection)");
}
/// Flip each byte of ct_RI as the initiator receives it: the initiator's secret changes.
#[test]
fn every_byte_of_the_responders_ciphertext_changes_the_secret() {
let (honest_psk, _, ct_ri) = honest();
let i = SecretKey::from_seed(SEED_I);
let r = SecretKey::from_seed(SEED_R);
let mut accepted = 0;
for n in 0..CIPHERTEXT_LEN {
let mut bad = *ct_ri.as_bytes();
bad[n] ^= 0x01;
let bad = Ciphertext::from_bytes(&bad).unwrap();
let init = exchange::initiate_derand(&i, r.public_key(), CONTEXT, &ESEED_I).unwrap();
if let Ok(s) = init.finish(&bad) {
assert_ne!(psk(&s), honest_psk, "ct_RI byte {n} did not change the secret");
accepted += 1;
}
}
assert!(accepted > CIPHERTEXT_LEN - 32);
}
/// Flip each byte of the responder's public key as the initiator received it, and of the
/// initiator's public key as the responder received it.
#[test]
fn every_public_key_byte_changes_the_secret() {
let (honest_psk, ct_ir, _) = honest();
let i = SecretKey::from_seed(SEED_I);
let r = SecretKey::from_seed(SEED_R);
let mut used = 0;
for n in 0..PUBLIC_KEY_LEN {
// The initiator's view of the responder's key.
let mut bad = *r.public_key().as_bytes();
bad[n] ^= 0x01;
// A flipped ML-KEM coefficient can fail the FIPS 203 modulus check: refused, not accepted.
if let Ok(pk) = PublicKey::from_bytes(&bad) {
let init = exchange::initiate_derand(&i, &pk, CONTEXT, &ESEED_I).unwrap();
let (ct_ri, rs) =
exchange::respond_derand(&r, i.public_key(), init.ciphertext(), CONTEXT, &ESEED_R).unwrap();
let is = init.finish(&ct_ri).unwrap();
assert_ne!(psk(&is), honest_psk, "initiator: responder key byte {n}");
assert_ne!(psk(&is), psk(&rs), "initiator: responder key byte {n} still agrees");
used += 1;
}
// The responder's view of the initiator's key.
let mut bad = *i.public_key().as_bytes();
bad[n] ^= 0x01;
if let Ok(pk) = PublicKey::from_bytes(&bad) {
let (_, rs) = exchange::respond_derand(&r, &pk, &ct_ir, CONTEXT, &ESEED_R).unwrap();
assert_ne!(psk(&rs), honest_psk, "responder: initiator key byte {n}");
used += 1;
}
}
assert!(used > PUBLIC_KEY_LEN, "most flipped keys still parse; the test must exercise them");
}
#[test]
fn every_seed_byte_changes_the_secret() {
let (honest_psk, _, _) = honest();
let run = |si: [u8; 32], sr: [u8; 32], ei: [u8; 64], er: [u8; 64]| {
let i = SecretKey::from_seed(si);
let r = SecretKey::from_seed(sr);
let init = exchange::initiate_derand(&i, r.public_key(), CONTEXT, &ei).unwrap();
let (_, rs) = exchange::respond_derand(&r, i.public_key(), init.ciphertext(), CONTEXT, &er).unwrap();
psk(&rs)
};
for n in 0..32 {
let mut s = SEED_I;
s[n] ^= 1;
assert_ne!(run(s, SEED_R, ESEED_I, ESEED_R), honest_psk, "initiator seed byte {n}");
let mut s = SEED_R;
s[n] ^= 1;
assert_ne!(run(SEED_I, s, ESEED_I, ESEED_R), honest_psk, "responder seed byte {n}");
}
// Bit 4 of each byte: X25519 clamps bits 0-2 of byte 32 and bits 6-7 of byte 63 of the
// ephemeral scalar (RFC 7748 §5), so flipping those bits is, by design, no change at all.
for n in 0..64 {
let mut e = ESEED_I;
e[n] ^= 0x10;
assert_ne!(run(SEED_I, SEED_R, e, ESEED_R), honest_psk, "initiator eseed byte {n}");
let mut e = ESEED_R;
e[n] ^= 0x10;
assert_ne!(run(SEED_I, SEED_R, ESEED_I, e), honest_psk, "responder eseed byte {n}");
}
}
#[test]
fn every_context_byte_changes_the_secret() {
let (honest_psk, ct_ir, _) = honest();
let i = SecretKey::from_seed(SEED_I);
let r = SecretKey::from_seed(SEED_R);
let resp = |ctx: &[u8]| psk(&exchange::respond_derand(&r, i.public_key(), &ct_ir, ctx, &ESEED_R).unwrap().1);
for n in 0..CONTEXT.len() {
let mut ctx = CONTEXT.to_vec();
ctx[n] ^= 0x01;
assert_ne!(resp(&ctx), honest_psk, "context byte {n}");
}
// Length is bound too: a prefix or an extension of the context is a different context.
for ctx in [&CONTEXT[..CONTEXT.len() - 1], b"", &[CONTEXT, b"\0"].concat()[..]] {
assert_ne!(resp(ctx), honest_psk);
}
}
/// QA A-15, through the public API: an attacker who plays the initiator without its secret key
/// can send ct_IR, but cannot finish: ct_RI is encapsulated to the real initiator. (The API cannot
/// express her full knowledge, so this alone would pass even with a one-direction schedule; the
/// test that fails then is `src/binding_tests.rs`, checked by reintroducing that bug.)
#[test]
fn an_impersonated_initiator_cannot_compute_the_psk() {
let i = SecretKey::from_seed(SEED_I); // the real initiator, whom the attacker impersonates
let r = SecretKey::from_seed(SEED_R);
let mallory = SecretKey::from_seed([0x66; 32]);
let mut g = rng(3);
// Mallory encapsulates to the responder (anyone can) and sends it as "from I".
let forged = exchange::initiate(&mallory, r.public_key(), CONTEXT, &mut g).unwrap();
let (ct_ri, responder_session) =
exchange::respond(&r, i.public_key(), forged.ciphertext(), CONTEXT, &mut g).unwrap();
// Her best effort: finish with her own key. ct_RI was made for I's key, not hers.
let mallory_session = forged.finish(&ct_ri).unwrap();
assert_ne!(psk(&mallory_session), psk(&responder_session));
}
/// QA A-14: roles are bound by position. Running the exchange with the roles swapped (same two
/// keys, same randomness) gives a different PSK, so a reflected message cannot complete it.
#[test]
fn roles_are_bound() {
let a = SecretKey::from_seed(SEED_I);
let b = SecretKey::from_seed(SEED_R);
let ab = exchange::initiate_derand(&a, b.public_key(), CONTEXT, &ESEED_I).unwrap();
let (ct, ab_resp) = exchange::respond_derand(&b, a.public_key(), ab.ciphertext(), CONTEXT, &ESEED_R).unwrap();
let ab_init = ab.finish(&ct).unwrap();
let ba = exchange::initiate_derand(&b, a.public_key(), CONTEXT, &ESEED_I).unwrap();
let (ct, ba_resp) = exchange::respond_derand(&a, b.public_key(), ba.ciphertext(), CONTEXT, &ESEED_R).unwrap();
let ba_init = ba.finish(&ct).unwrap();
assert_eq!(psk(&ab_init), psk(&ab_resp));
assert_eq!(psk(&ba_init), psk(&ba_resp));
assert_ne!(psk(&ab_init), psk(&ba_init));
}
#[test]
fn the_wrong_secret_key_does_not_agree() {
let (honest_psk, ct_ir, _) = honest();
let i = SecretKey::from_seed(SEED_I);
let other = SecretKey::from_seed([0x33; 32]);
let (_, s) = exchange::respond_derand(&other, i.public_key(), &ct_ir, CONTEXT, &ESEED_R).unwrap();
assert_ne!(psk(&s), honest_psk);
}
+70
View File
@@ -0,0 +1,70 @@
//! QA A-35: no test-only feature may reach a normal (release) build through Cargo feature
//! unification. Checks the normal-edge graph a consumer of Arcanum gets with default features.
//!
//! `arcanum/hazmat` exposes the deterministic entry points. `ml-kem/hazmat` only un-hides docs in
//! 0.3.4 (its `encapsulate_deterministic` is public either way), but is kept out on principle.
//! Consumers (via-core, via) must run the same check in their own CI: a `[dependencies]` entry
//! there could still enable `arcanum/hazmat`.
use std::process::Command;
fn tree(args: &[&str]) -> String {
let out = Command::new(env!("CARGO"))
.current_dir(env!("CARGO_MANIFEST_DIR"))
.args(["tree", "--offline", "--locked", "-e", "features,normal", "--prefix", "none"])
.args(args)
.output()
.expect("run cargo tree");
assert!(out.status.success(), "cargo tree failed: {}", String::from_utf8_lossy(&out.stderr));
String::from_utf8(out.stdout).unwrap()
}
fn assert_no_hazmat(t: &str, what: &str) {
for line in t.lines() {
assert!(!line.contains("feature \"hazmat\""), "{what}: hazmat reached a normal build: {line}\n{t}");
}
}
#[test]
fn arcanum_default_features_do_not_include_hazmat() {
let t = tree(&["-i", "arcanum"]);
assert!(t.contains("arcanum feature \"default\""), "the tree must list arcanum's features:\n{t}");
assert_no_hazmat(&t, "arcanum");
// Prove the check can see the feature at all: asking for it must make it appear.
let with = tree(&["-i", "arcanum", "--features", "hazmat"]);
assert!(with.contains("arcanum feature \"hazmat\""), "the check is blind:\n{with}");
}
#[test]
fn ml_kem_hazmat_is_not_in_the_normal_graph() {
let t = tree(&["-i", "ml-kem"]);
assert!(t.contains("ml-kem feature \"zeroize\""), "the tree must list ml-kem's features:\n{t}");
assert_no_hazmat(&t, "ml-kem");
}
#[test]
fn no_os_rng_in_the_normal_graph() {
// Randomness is a parameter (QA A-36): nothing in the normal graph may pull an OS RNG.
let t = tree(&["-p", "arcanum"]);
assert!(t.contains("rand_core"), "the tree must include rand_core:\n{t}");
assert!(!t.contains("getrandom"), "getrandom reached a normal build:\n{t}");
}
/// v0.2.0, mandatory test 7: the signature crates enter the normal graph with `zeroize` on and
/// no `hazmat`. `ed25519-dalek` has a `hazmat` feature of its own (raw `ExpandedSecretKey`
/// signing, `verify_stream`); `ml-dsa`'s `default` would pull `getrandom` and `pkcs8`.
#[test]
fn signature_crates_have_zeroize_and_no_hazmat() {
let t = tree(&["-i", "ml-dsa"]);
assert!(t.contains("ml-dsa feature \"zeroize\""), "ml-dsa must have zeroize:\n{t}");
assert!(t.contains("ml-dsa feature \"rand_core\""), "the tree must list ml-dsa's features:\n{t}");
assert!(!t.contains("ml-dsa feature \"default\""), "ml-dsa's default features reached a normal build:\n{t}");
assert!(!t.contains("ml-dsa feature \"getrandom\""), "ml-dsa's getrandom reached a normal build:\n{t}");
assert_no_hazmat(&t, "ml-dsa");
let t = tree(&["-i", "ed25519-dalek"]);
assert!(t.contains("ed25519-dalek feature \"zeroize\""), "ed25519-dalek must have zeroize:\n{t}");
assert!(!t.contains("ed25519-dalek feature \"default\""), "ed25519-dalek's defaults reached a normal build:\n{t}");
assert_no_hazmat(&t, "ed25519-dalek");
// (That the check can see a `hazmat` feature at all is proved for arcanum's own, above.)
}
+47
View File
@@ -0,0 +1,47 @@
//! QA A-10 and A-38: the v1 key schedule and the v1 sealed-box format are frozen. These values
//! were produced by this implementation (not by an outside source, so they prove stability, not
//! correctness; correctness is the KATs' job). If one fails, a label, an encoding or a field order
//! changed: every sealed blob Custos stored would stop opening and two peers on different builds
//! would silently disagree. Never regenerate these; a v2 adds new ones next to them.
use arcanum::exchange;
use arcanum::seal;
use arcanum::xwing::SecretKey;
use sha2::{Digest, Sha256};
const CONTEXT: &[u8] = b"domi/arcanum golden v1";
fn golden_session() -> exchange::Session {
let i = SecretKey::from_seed([0xa0; 32]);
let r = SecretKey::from_seed([0xb0; 32]);
let init = exchange::initiate_derand(&i, r.public_key(), CONTEXT, &[0xc0; 64]).unwrap();
let (ct_ri, rs) = exchange::respond_derand(&r, i.public_key(), init.ciphertext(), CONTEXT, &[0xd0; 64]).unwrap();
let is = init.finish(&ct_ri).unwrap();
assert_eq!(is.wireguard_psk(0).as_bytes(), rs.wireguard_psk(0).as_bytes());
rs
}
#[test]
fn v1_wireguard_psks_are_frozen() {
let s = golden_session();
for (epoch, want) in [
(0u64, "9fcb41a416cbd9d678e559bebe907cf9e7e483b7d9f7ded6583c871017cbe73a"),
(1, "3db1a6ede8d5ccec1faaa420d5a69e1b03ad4592525294d57dd29ae6d3fa8d91"),
(1 << 32, "39d30c3a9180d03264cca955a7fbba06ebd6e90b40e409ada57611253f0c042b"),
(u64::MAX - 1, "1931400ca68353ecc85fe76a1e01e4cce5f4f99a51d309f776235ab459ea464e"),
] {
assert_eq!(hex::encode(s.wireguard_psk(epoch).as_bytes()), want, "epoch {epoch}");
}
}
#[test]
fn v1_sealed_box_is_frozen_and_opens() {
let r = SecretKey::from_seed([0xb0; 32]);
let sealed = seal::seal_derand(r.public_key(), b"Built on Domi", b"golden aad", &[0xe0; 64]).unwrap();
assert_eq!(
hex::encode(Sha256::digest(&sealed)),
"4effac5a1d96cc34d663d5c9873dfb816552389becdfd415a2ca33f244a3018c",
"the v1 sealed format changed"
);
assert_eq!(seal::open(&r, &sealed, b"golden aad").unwrap().as_slice(), b"Built on Domi");
}
+95
View File
@@ -0,0 +1,95 @@
//! Mandatory test 2 (v0.2.0): Ed25519 known answers and edge cases, verified with `verify_strict`,
//! the check Arcanum's composite uses.
//!
//! RFC 8032 §7.1 (all five vectors, signing byte for byte) and Wycheproof `ed25519_test.json`
//! (`20b25694`). Provenance and sha256: tests/vectors/SOURCES.md. Pure Ed25519 signing is
//! deterministic by definition (RFC 8032 §5.1.6); `ed25519_dalek::Signer::sign` is that algorithm.
mod common;
use common::{assert_sha256, hex};
use ed25519_dalek::{Signature, Signer, SigningKey, VerifyingKey};
use serde_json::Value;
const RFC8032: &[u8] = include_bytes!("vectors/rfc8032-7.1-ed25519.json");
const RFC8032_SHA256: &str = "fad8e499cdc3e0324a5b4a93cdbabb33f8aed1df73ecacfdb364f433b0fdf12b";
const WYCHEPROOF: &[u8] = include_bytes!("vectors/wycheproof-ed25519_test.json");
const WYCHEPROOF_SHA256: &str = "752d2ea7d7c6cf4736381b6cbacb61f8182b126ab7cd9b058f00c50084975536";
/// Wycheproof cases where `verify_strict` disagrees with the file's verdict, with the reason.
/// Empty unless a run shows otherwise; each entry must be explained in docs/02_signatures.md.
const KNOWN_DISAGREEMENTS: &[(u64, &str)] = &[];
fn json(file: &[u8]) -> Value {
serde_json::from_slice(file).expect("vector json")
}
fn arr<const N: usize>(v: &Value) -> [u8; N] {
hex(v.as_str().expect("hex field")).try_into().expect("field length")
}
#[test]
fn vector_files_are_the_pinned_ones() {
assert_sha256(RFC8032, RFC8032_SHA256, "RFC 8032 section 7.1 extraction");
assert_sha256(WYCHEPROOF, WYCHEPROOF_SHA256, "Wycheproof ed25519_test");
}
#[test]
fn rfc8032_section_7_1() {
let tests = json(RFC8032)["tests"].as_array().unwrap().clone();
assert_eq!(tests.len(), 5);
for t in &tests {
let name = t["name"].as_str().unwrap();
let sk = SigningKey::from_bytes(&arr(&t["secret_key"]));
let pk: [u8; 32] = arr(&t["public_key"]);
let msg = hex(t["message"].as_str().unwrap());
let want: [u8; 64] = arr(&t["signature"]);
assert_eq!(sk.verifying_key().to_bytes(), pk, "TEST {name}: public key");
let sig = sk.sign(&msg);
assert_eq!(sig.to_bytes(), want, "TEST {name}: signature");
let vk = VerifyingKey::from_bytes(&pk).unwrap();
assert!(vk.verify_strict(&msg, &sig).is_ok(), "TEST {name}: verify_strict");
let mut other = msg.clone();
other.push(0);
assert!(vk.verify_strict(&other, &sig).is_err(), "TEST {name}: an extended message must fail");
let mut bad = want;
bad[0] ^= 1;
assert!(vk.verify_strict(&msg, &Signature::from_bytes(&bad)).is_err(), "TEST {name}: flipped R");
}
}
#[test]
fn wycheproof_ed25519_with_verify_strict() {
let mut disagreements = Vec::new();
let (mut valid, mut invalid) = (0, 0);
for g in json(WYCHEPROOF)["testGroups"].as_array().unwrap() {
let pk = hex(g["publicKey"]["pk"].as_str().unwrap());
let vk = <[u8; 32]>::try_from(pk.as_slice()).ok().and_then(|b| VerifyingKey::from_bytes(&b).ok());
for t in g["tests"].as_array().unwrap() {
let id = t["tcId"].as_u64().unwrap();
let msg = hex(t["msg"].as_str().unwrap());
let sig = Signature::from_slice(&hex(t["sig"].as_str().unwrap())).ok();
let ok = match (&vk, sig) {
(Some(vk), Some(sig)) => vk.verify_strict(&msg, &sig).is_ok(),
_ => false,
};
let want = match t["result"].as_str().unwrap() {
"valid" => true,
"invalid" => false,
other => panic!("tcId {id}: result {other} is not handled"),
};
if want {
valid += 1
} else {
invalid += 1
}
if ok != want {
disagreements.push((id, t["comment"].as_str().unwrap_or("").to_string(), want));
}
}
}
assert_eq!(valid + invalid, 151, "numberOfTests in the file");
let got: Vec<u64> = disagreements.iter().map(|d| d.0).collect();
let known: Vec<u64> = KNOWN_DISAGREEMENTS.iter().map(|k| k.0).collect();
assert_eq!(got, known, "verify_strict disagrees with Wycheproof on: {disagreements:?}");
}
+234
View File
@@ -0,0 +1,234 @@
//! Mandatory test 1 (v0.2.0): ML-DSA-65 known-answer tests (FIPS 204).
//!
//! Runs the vetted `ml-dsa` crate against NIST ACVP (keyGen and sigGen at `2972def2`, sigVer at
//! `a7f283cd`, after the ModifyZ correction) and Wycheproof (`20b25694`). Provenance, sha256 and
//! how the subsets were made: tests/vectors/SOURCES.md.
//!
//! The hedged cases go through `ExpandedSigningKey::sign_randomized` (external interface) and
//! `sign_mu_randomized` (external mu), the paths Arcanum's composite uses, fed the vector's `rnd`
//! by a `FixedRng`; deterministic cases use the same calls with an all-zero `rnd`, which FIPS 204
//! Algorithm 2 defines as the deterministic variant. `sign_mu_deterministic` is never called.
//! HashML-DSA (`preHash`) groups are not used: Arcanum signs pure ML-DSA only.
mod common;
use common::{FixedRng, assert_sha256, hex};
use ml_dsa::common::array::Array;
use ml_dsa::{ExpandedSigningKey, MlDsa65, Seed, Signature, VerifyingKey};
use serde_json::Value;
const KEYGEN: &[u8] = include_bytes!("vectors/acvp-ml-dsa-keyGen-FIPS204-internalProjection.json");
const KEYGEN_SHA256: &str = "e67ee6540d40e11506c3c4e3b1f79fc1cefcd49820db99fc61f87cc8ba463baf";
const SIGGEN: &[u8] = include_bytes!("vectors/acvp-ml-dsa-sigGen-FIPS204-internalProjection.subset.json");
const SIGGEN_SHA256: &str = "ca1f1697d78b2280d854bbe0f8e86d3601695013f14e7bb4ce0604bc80ed2b4e";
const SIGVER: &[u8] = include_bytes!("vectors/acvp-ml-dsa-sigVer-FIPS204-internalProjection.subset.json");
const SIGVER_SHA256: &str = "d005dfeee9039f751299a6430fdac509b97ad9ab7d25b0b502dc9a2b59b7fb0c";
const WP_SIGN: &[u8] = include_bytes!("vectors/wycheproof-mldsa_65_sign_seed_test.json");
const WP_SIGN_SHA256: &str = "e26b2bb9ab8d45ed570ba6828c7e40b6fa3e1545bb8bc2c449c77531760133e0";
const WP_VERIFY: &[u8] = include_bytes!("vectors/wycheproof-mldsa_65_verify_test.subset.json");
const WP_VERIFY_SHA256: &str = "47fc788c0913dc41cfd0ef5bc9ed44c779a6bdeeb8b3700077fd572527c33870";
const ZERO_RND: [u8; 32] = [0; 32];
fn json(file: &[u8]) -> Value {
serde_json::from_slice(file).expect("vector json")
}
/// The ML-DSA-65 groups, without HashML-DSA.
fn groups(file: &[u8]) -> Vec<Value> {
json(file)["testGroups"]
.as_array()
.expect("testGroups")
.iter()
.filter(|g| g["parameterSet"] == "ML-DSA-65" && g["preHash"].as_str().unwrap_or("none") != "preHash")
.cloned()
.collect()
}
fn field(t: &Value, name: &str) -> Vec<u8> {
hex(t[name].as_str().unwrap_or_else(|| panic!("field {name}")))
}
fn opt_field(t: &Value, name: &str) -> Option<Vec<u8>> {
t.get(name).and_then(Value::as_str).map(hex)
}
fn vk_from(bytes: &[u8]) -> Option<VerifyingKey<MlDsa65>> {
Array::try_from(bytes).ok().map(|a| VerifyingKey::<MlDsa65>::decode(&a))
}
fn sig_from(bytes: &[u8]) -> Option<Signature<MlDsa65>> {
Signature::<MlDsa65>::try_from(bytes).ok()
}
#[allow(deprecated)]
fn sk_from_expanded(bytes: &[u8]) -> ExpandedSigningKey<MlDsa65> {
// ACVP's sigGen gives the FIPS 204 expanded key, not the seed. `from_expanded` is deprecated
// (it does not validate), which is fine for official vectors; Arcanum itself uses seeds.
ExpandedSigningKey::<MlDsa65>::from_expanded(&Array::try_from(bytes).expect("sk length"))
}
#[test]
fn vector_files_are_the_pinned_ones() {
assert_sha256(KEYGEN, KEYGEN_SHA256, "ACVP ML-DSA keyGen");
assert_sha256(SIGGEN, SIGGEN_SHA256, "ACVP ML-DSA sigGen subset");
assert_sha256(SIGVER, SIGVER_SHA256, "ACVP ML-DSA sigVer subset");
assert_sha256(WP_SIGN, WP_SIGN_SHA256, "Wycheproof mldsa_65_sign_seed");
assert_sha256(WP_VERIFY, WP_VERIFY_SHA256, "Wycheproof mldsa_65_verify subset");
}
#[test]
#[allow(deprecated)]
fn acvp_keygen_65() {
let groups = groups(KEYGEN);
assert_eq!(groups.len(), 1, "one ML-DSA-65 keyGen group");
let mut n = 0;
for t in groups[0]["tests"].as_array().unwrap() {
let seed = Seed::try_from(field(t, "seed").as_slice()).expect("seed length");
let sk = ExpandedSigningKey::<MlDsa65>::from_seed(&seed);
assert_eq!(sk.verifying_key().encode().as_slice(), field(t, "pk").as_slice(), "pk, tcId {}", t["tcId"]);
assert_eq!(sk.to_expanded().as_slice(), field(t, "sk").as_slice(), "sk, tcId {}", t["tcId"]);
n += 1;
}
assert_eq!(n, 25);
}
/// sigGen, byte for byte: deterministic groups (tgId 3, 9, 10) and hedged groups (15, 21, 22).
#[test]
fn acvp_siggen_65() {
let groups = groups(SIGGEN);
assert_eq!(groups.len(), 6);
let mut n = 0;
for g in &groups {
let interface = g["signatureInterface"].as_str().unwrap();
let external_mu = g["externalMu"].as_bool().unwrap();
let deterministic = g["deterministic"].as_bool().unwrap();
for t in g["tests"].as_array().unwrap() {
let id = &t["tcId"];
let sk = sk_from_expanded(&field(t, "sk"));
let rnd = if deterministic { ZERO_RND.to_vec() } else { field(t, "rnd") };
let mut rng = FixedRng::new(&rnd);
let sig = match (interface, external_mu) {
("external", false) => {
let ctx = field(t, "context");
sk.sign_randomized(&field(t, "message"), &ctx, &mut rng).expect("sign")
}
("internal", true) => {
let mu = Array::try_from(field(t, "mu").as_slice()).expect("mu length");
sk.sign_mu_randomized(&mu, &mut rng).expect("sign")
}
("internal", false) => {
// ML-DSA.Sign_internal (FIPS 204 Algorithm 7) on M' = the message as given.
// `sign_internal` takes rnd directly (and is never called by Arcanum).
let rnd: ml_dsa::B32 = Array::try_from(rnd.as_slice()).unwrap();
sk.sign_internal(&[field(t, "message").as_slice()], &rnd)
}
other => panic!("unexpected group {other:?}"),
};
assert_eq!(
sig.encode().as_slice(),
field(t, "signature").as_slice(),
"signature, tgId {} tcId {id}",
g["tgId"]
);
if interface == "external" || external_mu {
// The hedged path must consume the vector's rnd: no more, no less.
assert_eq!(rng.used(), 32, "the hedged path draws exactly 32 bytes of rnd, tcId {id}");
}
n += 1;
}
}
assert_eq!(n, 18);
}
/// sigVer: accept and reject, on the corrected (a7f283cd) file.
#[test]
fn acvp_sigver_65() {
let groups = groups(SIGVER);
assert_eq!(groups.len(), 3);
let (mut accepted, mut rejected) = (0, 0);
for g in &groups {
let interface = g["signatureInterface"].as_str().unwrap();
let external_mu = g["externalMu"].as_bool().unwrap();
for t in g["tests"].as_array().unwrap() {
let vk = vk_from(&field(t, "pk")).expect("pk length");
let ok = sig_from(&field(t, "signature")).is_some_and(|sig| match (interface, external_mu) {
("external", false) => vk.verify_with_context(&field(t, "message"), &field(t, "context"), &sig),
("internal", true) => vk.verify_mu(&Array::try_from(field(t, "mu").as_slice()).unwrap(), &sig),
("internal", false) => vk.verify_internal(&field(t, "message"), &sig),
other => panic!("unexpected group {other:?}"),
});
let want = t["testPassed"].as_bool().unwrap();
assert_eq!(ok, want, "tgId {} tcId {} ({})", g["tgId"], t["tcId"], t["reason"]);
if want { accepted += 1 } else { rejected += 1 }
}
}
assert_eq!((accepted, rejected), (3, 12));
}
/// Wycheproof signing from a seed: deterministic unless the case gives `rnd`, byte for byte; an
/// over-long context and a seed of the wrong length are refused.
#[test]
fn wycheproof_sign_seed_65() {
let (mut valid, mut invalid) = (0, 0);
for g in json(WP_SIGN)["testGroups"].as_array().unwrap() {
let seed_bytes = field(g, "privateSeed");
for t in g["tests"].as_array().unwrap() {
let id = &t["tcId"];
let want_valid = t["result"] == "valid";
let Ok(seed) = Seed::try_from(seed_bytes.as_slice()) else {
assert!(!want_valid, "tcId {id}: a seed of {} bytes must be refused", seed_bytes.len());
invalid += 1;
continue;
};
let sk = ExpandedSigningKey::<MlDsa65>::from_seed(&seed);
if let Some(pk) = opt_field(g, "publicKey") {
assert_eq!(sk.verifying_key().encode().as_slice(), pk.as_slice(), "public key, tcId {id}");
}
let rnd = opt_field(t, "rnd").unwrap_or_else(|| ZERO_RND.to_vec());
let mut rng = FixedRng::new(&rnd);
let ctx = opt_field(t, "ctx").unwrap_or_default();
let result = match opt_field(t, "msg") {
Some(msg) => sk.sign_randomized(&msg, &ctx, &mut rng),
None => sk.sign_mu_randomized(&Array::try_from(field(t, "mu").as_slice()).unwrap(), &mut rng),
};
if want_valid {
let sig = result.unwrap_or_else(|e| panic!("tcId {id}: {e}"));
assert_eq!(sig.encode().as_slice(), field(t, "sig").as_slice(), "signature, tcId {id}");
let vk = sk.verifying_key();
let verified = match opt_field(t, "msg") {
Some(msg) => vk.verify_with_context(&msg, &ctx, &sig),
None => vk.verify_mu(&Array::try_from(field(t, "mu").as_slice()).unwrap(), &sig),
};
assert!(verified, "tcId {id}: own signature does not verify");
valid += 1;
} else {
assert!(result.is_err(), "tcId {id} ({}) must be refused", t["comment"]);
invalid += 1;
}
}
}
assert_eq!((valid, invalid), (101, 4));
}
/// Wycheproof verification, including bad hint encodings, infinity-norm violations, wrong lengths
/// and an over-long context.
#[test]
fn wycheproof_verify_65() {
let (mut valid, mut invalid) = (0, 0);
for g in json(WP_VERIFY)["testGroups"].as_array().unwrap() {
let vk = vk_from(&field(g, "publicKey"));
for t in g["tests"].as_array().unwrap() {
let ctx = opt_field(t, "ctx").unwrap_or_default();
let ok = match (&vk, sig_from(&field(t, "sig"))) {
(Some(vk), Some(sig)) => vk.verify_with_context(&field(t, "msg"), &ctx, &sig),
_ => false,
};
let want = t["result"] == "valid";
assert_eq!(ok, want, "tcId {} ({}) {:?}", t["tcId"], t["comment"], t["flags"]);
if want { valid += 1 } else { invalid += 1 }
}
}
assert_eq!(valid + invalid, 70);
assert!(valid > 0 && invalid > 0);
}
+130
View File
@@ -0,0 +1,130 @@
//! Mandatory test 1a: ML-KEM-768 known-answer tests from NIST ACVP (FIPS 203).
//!
//! Runs the vetted `ml-kem` crate, exactly as Arcanum uses it, against the official vectors.
//! Provenance and sha256 pins: tests/vectors/SOURCES.md.
mod common;
use common::{assert_sha256, hex};
#[allow(deprecated)]
use ml_kem::ExpandedKeyEncoding;
use ml_kem::array::Array;
use ml_kem::{B32, Decapsulate, DecapsulationKey, EncapsulationKey, KeyExport, MlKem768, Seed};
use serde_json::Value;
const KEYGEN: &[u8] = include_bytes!("vectors/acvp-ml-kem-keyGen-FIPS203-internalProjection.json");
const KEYGEN_SHA256: &str = "d7a62a2c3476957f56dd8d24f9004ea6776ccfe995ffe71a65bb9506dc9c7b1b";
const ENCDEC: &[u8] = include_bytes!("vectors/acvp-ml-kem-encapDecap-FIPS203-internalProjection.json");
const ENCDEC_SHA256: &str = "a556952ce869bb89c3a3196a701dad89647c193a34c86eafb61a9d710d5b810f";
/// The ML-KEM-768 test groups for one `function` ("" for keyGen, which has none).
fn groups(file: &[u8], function: &str) -> Vec<Value> {
let v: Value = serde_json::from_slice(file).expect("ACVP json");
v["testGroups"]
.as_array()
.expect("testGroups")
.iter()
.filter(|g| g["parameterSet"] == "ML-KEM-768")
.filter(|g| g["function"].as_str().unwrap_or("") == function)
.cloned()
.collect()
}
fn tests_of(groups: &[Value]) -> Vec<Value> {
groups.iter().flat_map(|g| g["tests"].as_array().expect("tests").clone()).collect()
}
fn field(t: &Value, name: &str) -> Vec<u8> {
hex(t[name].as_str().unwrap_or_else(|| panic!("field {name}")))
}
fn ek_from(bytes: &[u8]) -> Result<EncapsulationKey<MlKem768>, ml_kem::InvalidKey> {
let arr = Array::try_from(bytes).expect("ek length");
EncapsulationKey::<MlKem768>::new(&arr)
}
#[allow(deprecated)]
fn dk_from_expanded(bytes: &[u8]) -> Result<DecapsulationKey<MlKem768>, ml_kem::InvalidKey> {
let arr = Array::try_from(bytes).expect("dk length");
DecapsulationKey::<MlKem768>::from_expanded_bytes(&arr)
}
#[test]
fn vector_files_are_the_pinned_ones() {
assert_sha256(KEYGEN, KEYGEN_SHA256, "ACVP keyGen");
assert_sha256(ENCDEC, ENCDEC_SHA256, "ACVP encapDecap");
}
#[test]
#[allow(deprecated)]
fn acvp_keygen_768() {
let tests = tests_of(&groups(KEYGEN, ""));
assert_eq!(tests.len(), 25, "ACVP keyGen ML-KEM-768 has 25 cases");
for t in &tests {
let mut seed = field(t, "d");
seed.extend(field(t, "z"));
let dk = DecapsulationKey::<MlKem768>::from_seed(Seed::try_from(seed.as_slice()).unwrap());
assert_eq!(dk.encapsulation_key().to_bytes().as_slice(), field(t, "ek").as_slice(), "tcId {}", t["tcId"]);
assert_eq!(dk.to_expanded_bytes().as_slice(), field(t, "dk").as_slice(), "tcId {}", t["tcId"]);
}
}
#[test]
fn acvp_encapsulation_768() {
let tests = tests_of(&groups(ENCDEC, "encapsulation"));
assert_eq!(tests.len(), 25);
for t in &tests {
let ek = ek_from(&field(t, "ek")).expect("valid ek");
let m = B32::try_from(field(t, "m").as_slice()).unwrap();
let (c, k) = ek.encapsulate_deterministic(&m);
assert_eq!(c.as_slice(), field(t, "c").as_slice(), "tcId {}", t["tcId"]);
assert_eq!(k.as_slice(), field(t, "k").as_slice(), "tcId {}", t["tcId"]);
}
}
/// Includes "modified ciphertext" cases: implicit rejection must return the vector's K-bar.
#[test]
fn acvp_decapsulation_768_including_implicit_rejection() {
let tests = tests_of(&groups(ENCDEC, "decapsulation"));
assert_eq!(tests.len(), 10);
let mut modified = 0;
for t in &tests {
let dk = dk_from_expanded(&field(t, "dk")).expect("valid dk");
let c = Array::try_from(field(t, "c").as_slice()).unwrap();
let k = dk.decapsulate(&c);
assert_eq!(k.as_slice(), field(t, "k").as_slice(), "tcId {}", t["tcId"]);
if t["reason"] == "modified ciphertext" {
modified += 1;
}
}
assert!(modified > 0, "the set must exercise implicit rejection");
}
/// FIPS 203 §7.2 encapsulation key check: the modulus check must reject the bad keys.
#[test]
fn acvp_encapsulation_key_check_768() {
let tests = tests_of(&groups(ENCDEC, "encapsulationKeyCheck"));
assert_eq!(tests.len(), 10);
let mut rejected = 0;
for t in &tests {
let expected = t["testPassed"].as_bool().unwrap();
assert_eq!(ek_from(&field(t, "ek")).is_ok(), expected, "tcId {} ({})", t["tcId"], t["reason"]);
// Arcanum's own parser must agree: a hybrid key built on a bad ML-KEM key is refused.
let mut hybrid = field(t, "ek");
hybrid.extend([9u8; 32]);
assert_eq!(arcanum::xwing::PublicKey::from_bytes(&hybrid).is_ok(), expected, "tcId {}", t["tcId"]);
rejected += usize::from(!expected);
}
assert!(rejected > 0, "the set must contain keys that fail the check");
}
/// FIPS 203 §7.3 decapsulation key check (hash of ek inside dk).
#[test]
fn acvp_decapsulation_key_check_768() {
let tests = tests_of(&groups(ENCDEC, "decapsulationKeyCheck"));
assert_eq!(tests.len(), 10);
for t in &tests {
let expected = t["testPassed"].as_bool().unwrap();
assert_eq!(dk_from_expanded(&field(t, "dk")).is_ok(), expected, "tcId {} ({})", t["tcId"], t["reason"]);
}
}
+66
View File
@@ -0,0 +1,66 @@
//! Mandatory test 1b: X25519 known-answer tests from RFC 7748 (§5.2 and §6.1).
//!
//! Runs the vetted `x25519-dalek` crate, exactly as Arcanum uses it. The bytes are the RFC's; the
//! same values are in x25519-dalek 3.0.0's own tests (tests/vectors/SOURCES.md).
mod common;
use common::arr;
use x25519_dalek::{PublicKey, StaticSecret, X25519_BASEPOINT_BYTES, x25519};
#[test]
fn rfc7748_5_2_vector_1() {
let k = arr("a546e36bf0527c9d3b16154b82465edd62144c0ac1fc5a18506a2244ba449ac4");
let u = arr("e6db6867583030db3594c1a424b15f7c726624ec26b3353b10a903a6d0ab1c4c");
let out: [u8; 32] = arr("c3da55379de9c6908e94ea4df28d084f32eccf03491c71f754b4075577a28552");
assert_eq!(x25519(k, u), out);
}
#[test]
fn rfc7748_5_2_vector_2() {
let k = arr("4b66e9d4d1b4673c5ad22691957d6af5c11b6421e0ea01d42ca4169e7918ba0d");
let u = arr("e5210f12786811d3f4b7959d0538ae2c31dbe7106fc03c3efc4cd549c715a493");
let out: [u8; 32] = arr("95cbde9476e8907d7aade45cb4b873f88b595a68799fa152e6f8f7647aac7957");
assert_eq!(x25519(k, u), out);
}
/// RFC 7748 §5.2 iteration: k = u = 9; each step u <- k, k <- X25519(k, u).
fn iterate(n: usize) -> [u8; 32] {
let mut k = X25519_BASEPOINT_BYTES;
let mut u = X25519_BASEPOINT_BYTES;
for _ in 0..n {
let next = x25519(k, u);
u = k;
k = next;
}
k
}
#[test]
fn rfc7748_5_2_iterated_once() {
let expected: [u8; 32] = arr("422c8e7a6227d7bca1350b3e2bb7279f7897b87bb6854b783c60e80311ae3079");
assert_eq!(iterate(1), expected);
}
#[test]
fn rfc7748_5_2_iterated_1000() {
let expected: [u8; 32] = arr("684cf59ba83309552800ef566f2f4d3c1c3887c49360e3875f2eb94d99532c51");
assert_eq!(iterate(1000), expected);
}
/// RFC 7748 §6.1, through the same `StaticSecret` / `PublicKey` types Arcanum uses.
#[test]
fn rfc7748_6_1_diffie_hellman() {
let alice_sk: [u8; 32] = arr("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a");
let alice_pk: [u8; 32] = arr("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a");
let bob_sk: [u8; 32] = arr("5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb");
let bob_pk: [u8; 32] = arr("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f");
let shared: [u8; 32] = arr("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742");
let a = StaticSecret::from(alice_sk);
let b = StaticSecret::from(bob_sk);
assert_eq!(PublicKey::from(&a).as_bytes(), &alice_pk);
assert_eq!(PublicKey::from(&b).as_bytes(), &bob_pk);
assert_eq!(a.diffie_hellman(&PublicKey::from(bob_pk)).as_bytes(), &shared);
assert_eq!(b.diffie_hellman(&PublicKey::from(alice_pk)).as_bytes(), &shared);
}
+82
View File
@@ -0,0 +1,82 @@
//! Mandatory test 1c: X-Wing known-answer tests (draft-connolly-cfrg-xwing-kem-11, Appendix C)
//! through Arcanum's own composition, plus a differential test against RustCrypto `x-wing` 0.1.1.
mod common;
use arcanum::xwing::{Ciphertext, PublicKey, SecretKey};
use common::{assert_sha256, hex, rng};
use rand_core::Rng;
use serde::Deserialize;
use x_wing::{Decapsulate, Decapsulator, KeyExport};
const VECTORS: &[u8] = include_bytes!("vectors/xwing-test-vectors.json");
const VECTORS_SHA256: &str = "409efe197550b22985b4a0419418a0c5f2c2b193426c55bd998399ec8d3e614d";
#[derive(Deserialize)]
struct Vector {
seed: String,
sk: String,
pk: String,
eseed: String,
ct: String,
ss: String,
}
fn vectors() -> Vec<Vector> {
assert_sha256(VECTORS, VECTORS_SHA256, "X-Wing vectors");
serde_json::from_slice(VECTORS).expect("X-Wing json")
}
#[test]
fn draft_11_vectors() {
let vs = vectors();
assert_eq!(vs.len(), 3, "draft -11 Appendix C has three vectors");
for (i, v) in vs.iter().enumerate() {
let seed: [u8; 32] = hex(&v.seed).try_into().unwrap();
let sk = SecretKey::from_seed(seed);
assert_eq!(sk.to_seed().as_slice(), hex(&v.sk).as_slice(), "vector {i}: sk");
assert_eq!(sk.public_key().as_bytes().as_slice(), hex(&v.pk).as_slice(), "vector {i}: pk");
let pk = PublicKey::from_bytes(&hex(&v.pk)).expect("vector pk parses");
let eseed: [u8; 64] = hex(&v.eseed).try_into().unwrap();
let (ct, ss) = pk.encapsulate_derand(&eseed).expect("vector encapsulates");
assert_eq!(ct.as_bytes().as_slice(), hex(&v.ct).as_slice(), "vector {i}: ct");
assert_eq!(ss.as_bytes().as_slice(), hex(&v.ss).as_slice(), "vector {i}: ss (encaps)");
let ct = Ciphertext::from_bytes(&hex(&v.ct)).expect("vector ct parses");
let ss = sk.decapsulate(&ct).expect("vector decapsulates");
assert_eq!(ss.as_bytes().as_slice(), hex(&v.ss).as_slice(), "vector {i}: ss (decaps)");
}
}
/// Arcanum and the RustCrypto reference must agree on keys, ciphertexts and secrets for random
/// inputs, and on the implicit-rejection output for random (garbage) ML-KEM ciphertexts.
#[test]
fn differential_against_rustcrypto_x_wing() {
let mut r = rng(7);
for round in 0..64 {
let mut seed = [0u8; 32];
r.fill_bytes(&mut seed);
let mut eseed = [0u8; 64];
r.fill_bytes(&mut eseed);
let ours = SecretKey::from_seed(seed);
let theirs = x_wing::DecapsulationKey::from(seed);
let their_pk = theirs.encapsulation_key().to_bytes();
assert_eq!(ours.public_key().as_bytes().as_slice(), their_pk.as_slice(), "round {round}: pk");
let (our_ct, our_ss) = ours.public_key().encapsulate_derand(&eseed).unwrap();
let their_ek = x_wing::EncapsulationKey::try_from(their_pk.as_slice()).unwrap();
let (their_ct, their_ss) = their_ek.encapsulate_deterministic(&eseed.into());
assert_eq!(our_ct.as_bytes().as_slice(), their_ct.as_slice(), "round {round}: ct");
assert_eq!(our_ss.as_bytes().as_slice(), their_ss.as_slice(), "round {round}: ss");
// A ciphertext whose ML-KEM part is random bytes, with an honest X25519 part.
let mut garbage = *our_ct.as_bytes();
r.fill_bytes(&mut garbage[..1088]);
let ours_ss = ours.decapsulate(&Ciphertext::from_bytes(&garbage).unwrap()).unwrap();
let theirs_ss = theirs.decapsulate(&garbage.into());
assert_eq!(ours_ss.as_bytes().as_slice(), theirs_ss.as_slice(), "round {round}: implicit rejection");
assert_ne!(ours_ss.as_bytes(), our_ss.as_bytes(), "round {round}: garbage must not decapsulate");
}
}
+181
View File
@@ -0,0 +1,181 @@
//! Mandatory test 5: malformed ciphertexts and keys of the wrong length are rejected with typed
//! errors, never a panic. The same entry points are fuzzed by fuzz/fuzz_targets/untrusted_input.rs.
mod common;
use arcanum::xwing::{CIPHERTEXT_LEN, Ciphertext, PUBLIC_KEY_LEN, PublicKey, SECRET_KEY_LEN, SecretKey};
use arcanum::{Error, Input, exchange, seal};
use common::rng;
use rand_core::Rng;
const LENGTHS: [usize; 12] = [0, 1, 31, 32, 33, 64, 1087, 1088, 1119, 1121, 1215, 1217];
#[test]
fn public_key_of_the_wrong_length_is_a_typed_error() {
for len in LENGTHS.into_iter().chain([PUBLIC_KEY_LEN * 2]) {
let err = PublicKey::from_bytes(&vec![0u8; len]).unwrap_err();
assert_eq!(err, Error::InvalidLength { input: Input::PublicKey, expected: PUBLIC_KEY_LEN, actual: len });
}
}
#[test]
fn ciphertext_of_the_wrong_length_is_a_typed_error() {
for len in LENGTHS.into_iter().filter(|&l| l != CIPHERTEXT_LEN).chain([CIPHERTEXT_LEN * 2]) {
let err = Ciphertext::from_bytes(&vec![0u8; len]).unwrap_err();
assert_eq!(err, Error::InvalidLength { input: Input::Ciphertext, expected: CIPHERTEXT_LEN, actual: len });
}
}
#[test]
fn secret_key_of_the_wrong_length_is_a_typed_error() {
for len in LENGTHS.into_iter().filter(|&l| l != SECRET_KEY_LEN) {
let err = SecretKey::from_bytes(&vec![0u8; len]).unwrap_err();
assert_eq!(err, Error::InvalidLength { input: Input::SecretKey, expected: SECRET_KEY_LEN, actual: len });
}
assert!(SecretKey::from_bytes(&[7u8; SECRET_KEY_LEN]).is_ok(), "any 32 bytes are a valid seed");
}
/// An ML-KEM key whose coefficients are not reduced mod q fails FIPS 203 §7.2: all-0xff bytes
/// encode 12-bit values of 4095 > q = 3329.
#[test]
fn ml_kem_key_failing_the_modulus_check_is_a_typed_error() {
let mut bad = [0xffu8; PUBLIC_KEY_LEN];
bad[1184..].copy_from_slice(&[9u8; 32]);
assert_eq!(PublicKey::from_bytes(&bad).unwrap_err(), Error::InvalidPublicKey);
}
#[test]
fn random_bytes_never_panic() {
let mut r = rng(9);
let sk = SecretKey::from_seed([0x01; 32]);
let peer = SecretKey::from_seed([0x02; 32]);
let (honest_ct, _) = peer.public_key().encapsulate(&mut r).unwrap();
for round in 0..512 {
let len = [PUBLIC_KEY_LEN, CIPHERTEXT_LEN, seal::OVERHEAD, seal::OVERHEAD + 40, 0, 17][round % 6];
let mut buf = vec![0u8; len];
r.fill_bytes(&mut buf);
if let Ok(pk) = PublicKey::from_bytes(&buf) {
let _ = exchange::initiate(&sk, &pk, b"ctx", &mut r);
let _ = exchange::respond(&sk, &pk, &honest_ct, b"ctx", &mut r);
}
if let Ok(ct) = Ciphertext::from_bytes(&buf) {
// Random ML-KEM ciphertexts decapsulate (implicit rejection) to some unrelated secret.
let _ = exchange::respond(&sk, peer.public_key(), &ct, b"ctx", &mut r);
let _ = exchange::initiate(&sk, peer.public_key(), b"ctx", &mut r).unwrap().finish(&ct);
}
assert!(seal::open(&sk, &buf, b"aad").is_err(), "random bytes must never open");
}
}
#[test]
fn sealed_box_round_trips() {
let mut r = rng(10);
let sk = SecretKey::generate(&mut r);
for len in [0usize, 1, 15, 16, 17, 1000, 70_000] {
let msg: Vec<u8> = (0..len).map(|i| (i * 31 % 251) as u8).collect();
let sealed = seal::seal(sk.public_key(), &msg, b"custos/v1 item 42", &mut r).unwrap();
assert_eq!(sealed.len(), msg.len() + seal::OVERHEAD);
let opened = seal::open(&sk, &sealed, b"custos/v1 item 42").unwrap();
assert_eq!(opened.as_slice(), msg.as_slice());
}
}
#[test]
fn sealed_box_too_short_is_a_typed_error() {
let sk = SecretKey::from_seed([0x02; 32]);
for len in [0, 1, seal::OVERHEAD - 1] {
let err = seal::open(&sk, &vec![1u8; len], b"").unwrap_err();
assert_eq!(err, Error::TooShort { input: Input::SealedBox, minimum: seal::OVERHEAD, actual: len });
}
}
#[test]
fn sealed_box_with_an_unknown_version_is_a_typed_error() {
let mut r = rng(11);
let sk = SecretKey::generate(&mut r);
let mut sealed = seal::seal(sk.public_key(), b"hello", b"", &mut r).unwrap();
for v in [0u8, 2, 0xff] {
sealed[0] = v;
assert_eq!(seal::open(&sk, &sealed, b"").unwrap_err(), Error::UnsupportedVersion(v));
}
}
#[test]
fn every_tampered_or_truncated_sealed_box_is_refused() {
let mut r = rng(12);
let sk = SecretKey::generate(&mut r);
let sealed = seal::seal(sk.public_key(), b"the household photo key", b"aad", &mut r).unwrap();
for i in 1..sealed.len() {
let mut bad = sealed.clone();
bad[i] ^= 0x80;
let err = seal::open(&sk, &bad, b"aad").unwrap_err();
assert!(matches!(err, Error::DecryptionFailed | Error::NonContributory), "byte {i}: {err:?}");
}
for len in seal::OVERHEAD..sealed.len() {
assert_eq!(seal::open(&sk, &sealed[..len], b"aad").unwrap_err(), Error::DecryptionFailed, "length {len}");
}
}
#[test]
fn sealed_box_needs_the_right_key_and_aad() {
let mut r = rng(13);
let sk = SecretKey::generate(&mut r);
let other = SecretKey::generate(&mut r);
let sealed = seal::seal(sk.public_key(), b"secret", b"aad", &mut r).unwrap();
assert_eq!(seal::open(&other, &sealed, b"aad").unwrap_err(), Error::DecryptionFailed);
assert_eq!(seal::open(&sk, &sealed, b"aaD").unwrap_err(), Error::DecryptionFailed);
assert_eq!(seal::open(&sk, &sealed, b"").unwrap_err(), Error::DecryptionFailed);
}
#[test]
fn errors_display_without_secrets() {
let e = Error::InvalidLength { input: Input::Ciphertext, expected: 1120, actual: 3 };
assert_eq!(e.to_string(), "ciphertext has the wrong length: expected 1120 bytes, got 3");
let _: &dyn std::error::Error = &e;
}
/// QA A-20: the modulus check is not over-eager. The last 32 bytes of the ML-KEM key are the
/// seed rho, where any value is legal.
#[test]
fn ml_kem_key_check_accepts_any_rho() {
let sk = SecretKey::from_seed([0x03; 32]);
let mut ok = *sk.public_key().as_bytes();
ok[1183] ^= 1;
assert!(PublicKey::from_bytes(&ok).is_ok());
}
/// QA A-21: the only stored private-key form is the 32-byte seed; an expanded ML-KEM key or an
/// X-Wing key plus anything else is refused by length.
#[test]
fn only_the_32_byte_seed_is_a_secret_key() {
for len in [64, 96, 2400, 2432] {
assert!(matches!(SecretKey::from_bytes(&vec![0u8; len]), Err(Error::InvalidLength { .. })), "{len}");
}
}
/// QA A-24: a one-byte extension and a splice (header of one box, body of another) are refused.
#[test]
fn sealed_box_extension_and_splice_are_refused() {
let mut r = rng(14);
let sk = SecretKey::generate(&mut r);
let b1 = seal::seal(sk.public_key(), b"one", b"", &mut r).unwrap();
let b2 = seal::seal(sk.public_key(), b"two", b"", &mut r).unwrap();
let mut ext = b1.clone();
ext.push(0);
assert_eq!(seal::open(&sk, &ext, b"").unwrap_err(), Error::DecryptionFailed);
let mut spliced = b1[..1121].to_vec();
spliced.extend_from_slice(&b2[1121..]);
assert_eq!(seal::open(&sk, &spliced, b"").unwrap_err(), Error::DecryptionFailed);
}
/// QA A-26: all randomness comes from the RNG parameter: the same seed gives the same box, a
/// different seed a different one.
#[test]
fn seal_randomness_comes_only_from_the_rng() {
let sk = SecretKey::from_seed([0x04; 32]);
let a = seal::seal(sk.public_key(), b"m", b"", &mut rng(1)).unwrap();
let b = seal::seal(sk.public_key(), b"m", b"", &mut rng(1)).unwrap();
let c = seal::seal(sk.public_key(), b"m", b"", &mut rng(2)).unwrap();
assert_eq!(a, b);
assert_ne!(a, c);
}
+38
View File
@@ -0,0 +1,38 @@
//! Mandatory test 6 (the part a test can check; `cargo deny` and `cargo audit` are run separately,
//! see docs/01_arcanum.md). The compiler enforces `#![forbid(unsafe_code)]`; this guardrail makes
//! sure the attribute itself is never removed and no source file opts back in.
use std::fs;
use std::path::Path;
fn rust_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
for entry in fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
rust_files(&path, out);
} else if path.extension().is_some_and(|e| e == "rs") {
out.push(path);
}
}
}
#[test]
fn the_crate_forbids_unsafe_code() {
let lib = fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("src/lib.rs")).unwrap();
assert!(lib.lines().any(|l| l.trim() == "#![forbid(unsafe_code)]"), "src/lib.rs must forbid unsafe code");
}
#[test]
fn no_source_file_contains_unsafe() {
let mut files = Vec::new();
rust_files(&Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut files);
assert!(!files.is_empty());
for f in files {
let text = fs::read_to_string(&f).unwrap();
for (n, line) in text.lines().enumerate() {
let code = line.split("//").next().unwrap_or("");
let opts_in = code.contains("unsafe") && code.trim() != "#![forbid(unsafe_code)]";
assert!(!opts_in, "{}:{}: {line}", f.display(), n + 1);
}
}
}
+99
View File
@@ -0,0 +1,99 @@
//! Mandatory test 4: WireGuard PSK epochs. Successive epochs differ, the same epoch is reproducible
//! from the same inputs, and the epoch helper follows the 120-second Rosenpass-style interval.
use arcanum::exchange;
use arcanum::xwing::SecretKey;
use arcanum::{RECOMMENDED_EPOCH_SECONDS, WIREGUARD_PSK_LEN, epoch_at};
use std::collections::HashSet;
const CONTEXT: &[u8] = b"via/test: epochs";
fn exchange_with(eseed_i: [u8; 64]) -> (exchange::Session, exchange::Session) {
let i = SecretKey::from_seed([0x01; 32]);
let r = SecretKey::from_seed([0x04; 32]);
let init = exchange::initiate_derand(&i, r.public_key(), CONTEXT, &eseed_i).unwrap();
let (ct_ri, rs) = exchange::respond_derand(&r, i.public_key(), init.ciphertext(), CONTEXT, &[0x05; 64]).unwrap();
(init.finish(&ct_ri).unwrap(), rs)
}
fn sessions() -> (exchange::Session, exchange::Session) {
exchange_with([0x02; 64])
}
#[test]
fn successive_epochs_differ() {
let (a, _) = sessions();
let mut seen = HashSet::new();
for epoch in 0..2048u64 {
assert!(seen.insert(*a.wireguard_psk(epoch).as_bytes()), "epoch {epoch} repeats an earlier PSK");
}
// The ends of the range and neighbours that differ only in the high bytes.
for epoch in [u64::MAX, u64::MAX - 1, 1 << 32, (1 << 32) + 1, 1 << 63] {
assert!(seen.insert(*a.wireguard_psk(epoch).as_bytes()), "epoch {epoch} repeats");
}
}
#[test]
fn the_same_epoch_is_reproducible_from_the_same_inputs() {
let (a1, b1) = sessions();
let (a2, b2) = sessions();
for epoch in [0, 1, 719, 720, u64::MAX] {
let p = *a1.wireguard_psk(epoch).as_bytes();
assert_eq!(&p, a1.wireguard_psk(epoch).as_bytes(), "same session, asked twice");
assert_eq!(&p, a2.wireguard_psk(epoch).as_bytes(), "rebuilt from the same inputs");
assert_eq!(&p, b1.wireguard_psk(epoch).as_bytes(), "the other peer");
assert_eq!(&p, b2.wireguard_psk(epoch).as_bytes(), "the other peer, rebuilt");
}
}
#[test]
fn a_different_exchange_gives_different_psks_for_the_same_epoch() {
let (a, _) = exchange_with([0x02; 64]);
let (c, _) = exchange_with([0x03; 64]);
for epoch in 0..16 {
assert_ne!(a.wireguard_psk(epoch).as_bytes(), c.wireguard_psk(epoch).as_bytes());
}
}
#[test]
fn a_psk_is_32_bytes_and_not_trivial() {
let (a, _) = sessions();
let p = a.wireguard_psk(0);
assert_eq!(WIREGUARD_PSK_LEN, 32);
assert_eq!(p.as_bytes().len(), 32);
assert_ne!(p.as_bytes(), &[0u8; 32]);
}
#[test]
fn the_psk_never_prints() {
let (a, _) = sessions();
let p = a.wireguard_psk(0);
let shown = format!("{p:?} {a:?}");
assert!(shown.contains("redacted"), "{shown}");
let k = p.as_bytes();
// Neither a hex dump nor a derived `[1, 2, 3, ...]` array may appear.
assert!(!shown.contains(&hex::encode(&k[..4])), "{shown}");
assert!(!shown.contains(&format!("{}, {}, {}", k[0], k[1], k[2])), "{shown}");
}
#[test]
fn epoch_helper_uses_two_minute_epochs() {
assert_eq!(RECOMMENDED_EPOCH_SECONDS, 120, "Rosenpass REKEY_AFTER_TIME_RESPONDER is 120 s");
assert_eq!(epoch_at(0), 0);
assert_eq!(epoch_at(119), 0);
assert_eq!(epoch_at(120), 1);
assert_eq!(epoch_at(239), 1);
assert_eq!(epoch_at(240), 2);
assert_eq!(epoch_at(1_764_000_000), 1_764_000_000 / 120);
assert_eq!(epoch_at(u64::MAX), u64::MAX / 120);
}
/// QA A-11: the epoch is encoded at its full 64-bit width; nothing truncates it.
#[test]
fn the_epoch_is_not_truncated() {
let (a, _) = sessions();
let p = |e: u64| *a.wireguard_psk(e).as_bytes();
assert_ne!(p(0), p(1 << 32));
assert_ne!(p(1), p(1 << 8));
assert_ne!(p(u64::MAX), p(u64::MAX >> 1));
}
+196
View File
@@ -0,0 +1,196 @@
//! QA second review (PR #1): what a **consumer** of Arcanum can and cannot write, checked by
//! compiling small programs against the crate with **default features**, as via-core and via will.
//!
//! The test suite itself always builds Arcanum with `hazmat` (the self-dev-dependency), so no
//! in-process test can see the release API. This one writes a throwaway crate under
//! `CARGO_TARGET_TMPDIR` that depends on Arcanum by path without features, and runs
//! `cargo check --offline` on it. A program that must not compile is a compile-fail test (QA A-33,
//! A-34); a control program proves the harness is not blind.
//!
//! Cases:
//! - control: the safe API (generate, mutual exchange, seal/open) compiles;
//! - A-33: an RNG that is `Rng` but not `CryptoRng` is refused by the type system;
//! - A-34: none of the deterministic `_derand` / `from_seed` entry points is reachable;
//! - QA-R2-01: the raw X-Wing shared secret must not be reachable without the key schedule.
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;
/// All cases share one crate (so the dependencies are checked once); they must not run at once.
static LOCK: Mutex<()> = Mutex::new(());
const PRELUDE: &str = r#"
#![allow(unused)]
use core::convert::Infallible;
use rand_core::{TryCryptoRng, TryRng};
/// A counter: deterministic, and therefore NOT a cryptographic RNG.
pub struct Counter(pub u64);
impl TryRng for Counter {
type Error = Infallible;
fn try_next_u32(&mut self) -> Result<u32, Infallible> { self.0 += 1; Ok(self.0 as u32) }
fn try_next_u64(&mut self) -> Result<u64, Infallible> { self.0 += 1; Ok(self.0) }
fn try_fill_bytes(&mut self, d: &mut [u8]) -> Result<(), Infallible> {
for b in d { self.0 += 1; *b = self.0 as u8; }
Ok(())
}
}
/// The same counter, *claiming* to be cryptographic (a stand-in for a real CSPRNG in the control).
pub struct Claimed(pub Counter);
impl TryRng for Claimed {
type Error = Infallible;
fn try_next_u32(&mut self) -> Result<u32, Infallible> { self.0.try_next_u32() }
fn try_next_u64(&mut self) -> Result<u64, Infallible> { self.0.try_next_u64() }
fn try_fill_bytes(&mut self, d: &mut [u8]) -> Result<(), Infallible> { self.0.try_fill_bytes(d) }
}
impl TryCryptoRng for Claimed {}
"#;
fn consumer_dir() -> PathBuf {
let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("qa-consumer-api");
std::fs::create_dir_all(dir.join("src")).unwrap();
let arcanum = env!("CARGO_MANIFEST_DIR").replace('\\', "/");
let manifest = format!(
"[package]\nname = \"qa-consumer-api\"\nversion = \"0.0.0\"\nedition = \"2024\"\npublish = false\n\n\
[dependencies]\narcanum = {{ path = \"{arcanum}\" }}\n\
rand_core = {{ version = \"0.10\", default-features = false }}\n\n[workspace]\n"
);
std::fs::write(dir.join("Cargo.toml"), manifest).unwrap();
// Same dependency versions as Arcanum itself; cargo prunes what the consumer does not use.
if !dir.join("Cargo.lock").exists() {
std::fs::copy(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.lock"), dir.join("Cargo.lock")).unwrap();
}
dir
}
/// `cargo check` a consumer whose `main` body is `body`. Returns (compiled, compiler output).
fn check(body: &str) -> (bool, String) {
let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = consumer_dir();
std::fs::write(dir.join("src/main.rs"), format!("{PRELUDE}\nfn main() {{\n{body}\n}}\n")).unwrap();
let out = Command::new(env!("CARGO"))
.current_dir(&dir)
.args(["check", "--offline", "--quiet", "--message-format", "short"])
.env_remove("CARGO_TARGET_DIR")
.output()
.expect("run cargo check");
(out.status.success(), String::from_utf8_lossy(&out.stderr).into_owned())
}
fn assert_compiles(what: &str, body: &str) {
let (ok, err) = check(body);
assert!(ok, "{what}: the control program must compile, or the harness is blind:\n{err}");
}
fn assert_refused(what: &str, body: &str, needles: &[&str]) {
let (ok, err) = check(body);
assert!(!ok, "{what}: compiled against Arcanum with default features, and must not");
assert!(
needles.iter().any(|n| err.contains(n)),
"{what}: refused, but not for the expected reason ({needles:?}):\n{err}"
);
}
#[test]
fn control_the_safe_api_compiles_without_hazmat() {
assert_compiles(
"control",
r#"
let mut rng = Claimed(Counter(0));
let a = arcanum::xwing::SecretKey::generate(&mut rng);
let b = arcanum::xwing::SecretKey::generate(&mut rng);
let init = arcanum::exchange::initiate(&a, b.public_key(), b"ctx", &mut rng).unwrap();
let (ct, rs) = arcanum::exchange::respond(&b, a.public_key(), init.ciphertext(), b"ctx", &mut rng).unwrap();
let is = init.finish(&ct).unwrap();
let _ = (is.wireguard_psk(1), rs.wireguard_psk(1));
let sealed = arcanum::seal::seal(b.public_key(), b"m", b"", &mut rng).unwrap();
let _ = arcanum::seal::open(&b, &sealed, b"").unwrap();
"#,
);
}
/// QA A-33: `R: CryptoRng`, not `R: Rng`. A counter is refused everywhere randomness enters.
#[test]
fn a33_a_non_crypto_rng_does_not_compile() {
let calls = [
("SecretKey::generate", "let _ = arcanum::xwing::SecretKey::generate(&mut Counter(0));"),
// Builder, with the R2-01 fix: `PublicKey::encapsulate` is hazmat-only now, so it no longer
// exists for a consumer (qa_r2_01 checks that). Its place is taken by the other release
// function that takes an RNG, `exchange::respond`.
(
"exchange::respond",
"let k = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap(); \
let ct = arcanum::xwing::Ciphertext::from_bytes(&[0; 1120]).unwrap(); \
let _ = arcanum::exchange::respond(&k, k.public_key(), &ct, b\"\", &mut Counter(0));",
),
(
"exchange::initiate",
"let k = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap(); \
let _ = arcanum::exchange::initiate(&k, k.public_key(), b\"\", &mut Counter(0));",
),
(
"seal::seal",
"let k = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap(); \
let _ = arcanum::seal::seal(k.public_key(), b\"\", b\"\", &mut Counter(0));",
),
];
for (what, body) in calls {
assert_refused(what, body, &["CryptoRng"]);
}
}
/// QA A-34: with default features, no deterministic entry point exists in the public API.
#[test]
fn a34_deterministic_entry_points_are_not_reachable_without_hazmat() {
let k = "let k = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap();";
let calls = [
("SecretKey::from_seed", "let _ = arcanum::xwing::SecretKey::from_seed([1; 32]);".to_string()),
("PublicKey::encapsulate_derand", format!("{k} let _ = k.public_key().encapsulate_derand(&[0; 64]);")),
(
"exchange::initiate_derand",
format!("{k} let _ = arcanum::exchange::initiate_derand(&k, k.public_key(), b\"\", &[0; 64]);"),
),
(
"exchange::respond_derand",
format!(
"{k} let ct = arcanum::xwing::Ciphertext::from_bytes(&[0; 1120]).unwrap(); \
let _ = arcanum::exchange::respond_derand(&k, k.public_key(), &ct, b\"\", &[0; 64]);"
),
),
(
"seal::seal_derand",
format!("{k} let _ = arcanum::seal::seal_derand(k.public_key(), b\"\", b\"\", &[0; 64]);"),
),
];
for (what, body) in calls {
// E0425: no such function; E0599: no such method or associated function.
assert_refused(what, &body, &["E0425", "E0599"]);
}
}
/// QA-R2-01 (major): a release consumer can take the raw X-Wing shared secret of a **one-way**
/// encapsulation and use it as a key, skipping the mutual exchange, the transcript, the context
/// and the `domi/arcanum/v1` labels. That is exactly the single-direction PSK that QA A-15 (and the
/// crate's own `exchange` docs) say lets a quantum attacker who impersonates the initiator choose
/// the responder's PSK. Fails while `PublicKey::encapsulate` / `SecretKey::decapsulate` hand out a
/// `SharedSecret` whose bytes are public without `hazmat`.
#[test]
fn qa_r2_01_raw_shared_secret_is_not_reachable_without_hazmat() {
let (ok, err) = check(
r#"
let mut rng = Claimed(Counter(0));
let peer = arcanum::xwing::SecretKey::generate(&mut rng);
let (_ct, ss) = peer.public_key().encapsulate(&mut rng).unwrap();
let one_way_psk: [u8; 32] = *ss.as_bytes();
let _ = one_way_psk;
"#,
);
assert!(
!ok,
"the raw one-way X-Wing secret is reachable in a release build: \
`PublicKey::encapsulate(..).1.as_bytes()` compiles without `hazmat`"
);
let _ = err;
}
+213
View File
@@ -0,0 +1,213 @@
//! QA second review (PR #1): the cases of `qa/01_arcanum_attacks.md` that the builder listed as
//! partial or not done and that can be done honestly here, plus regression tests for the review's
//! own findings (QA-R2-nn, see `qa/review-arcanum-pr1.md` outside this repository and the PR
//! comments).
mod common;
use arcanum::exchange::{self, Initiation, Session, WireGuardPsk};
use arcanum::xwing::{CIPHERTEXT_LEN, Ciphertext, PublicKey, SecretKey, SharedSecret};
use common::rng;
use std::collections::HashSet;
use zeroize::ZeroizeOnDrop;
// ---------------------------------------------------------------------------------------------
// A-28 and A-31, at compile time. A hand-rolled `assert_not_impl` (the `static_assertions` trick:
// if `$t` implements `$tr`, the call below is ambiguous and the crate does not compile), so no new
// dev-dependency is needed. Checked by adding `#[derive(Clone, Copy, PartialEq)]` to a secret type:
// this file then fails to compile.
// ---------------------------------------------------------------------------------------------
macro_rules! assert_not_impl {
($t:ty : $($tr:path),+ $(,)?) => {
$(
const _: fn() = || {
#[allow(dead_code)]
trait AmbiguousIfImpl<A> {
fn some_item() {}
}
impl<T: ?Sized> AmbiguousIfImpl<()> for T {}
#[allow(dead_code)]
struct Invalid;
impl<T: ?Sized + $tr> AmbiguousIfImpl<Invalid> for T {}
let _ = <$t as AmbiguousIfImpl<_>>::some_item;
};
)+
};
}
fn assert_zeroize_on_drop<T: ZeroizeOnDrop + ?Sized>() {}
// A secret that is `Copy` can never be wiped; `Clone` multiplies what must be wiped; `PartialEq`
// on secret bytes is a variable-time comparison (A-31); `Display` is one `{}` away from a log line.
assert_not_impl!(SecretKey: Copy, Clone, PartialEq, core::fmt::Display);
assert_not_impl!(SharedSecret: Copy, Clone, PartialEq, core::fmt::Display);
assert_not_impl!(Session: Copy, Clone, PartialEq, core::fmt::Display);
assert_not_impl!(WireGuardPsk: Copy, Clone, PartialEq, core::fmt::Display);
assert_not_impl!(Initiation<'static>: Copy, Clone, PartialEq, core::fmt::Display);
/// QA A-28: the secret types promise `ZeroizeOnDrop`. (`Initiation` wipes its fields but does not
/// carry the marker; noted in the review as a nit, not asserted here.)
#[test]
fn a28_secret_types_are_zeroize_on_drop() {
assert_zeroize_on_drop::<SecretKey>();
assert_zeroize_on_drop::<SharedSecret>();
assert_zeroize_on_drop::<Session>();
assert_zeroize_on_drop::<WireGuardPsk>();
assert_zeroize_on_drop::<exchange::Initiation<'static>>(); // R2-05, added by the builder with the fix
}
/// QA A-28: `Debug` of every secret type is redacted (the PSK and Session case is already in
/// `psk_epochs.rs`; this adds the key, the X-Wing secret and the half-finished exchange).
#[test]
fn a28_debug_of_secret_types_is_redacted() {
let seed = [0xab; 32];
let sk = SecretKey::from_seed(seed);
let peer = SecretKey::from_seed([0xcd; 32]);
let (ct, ss) = peer.public_key().encapsulate(&mut rng(1)).unwrap();
let init = exchange::initiate(&sk, peer.public_key(), b"ctx", &mut rng(2)).unwrap();
let ss_hex = hex::encode(ss.as_bytes());
let shown = format!("{sk:?} {ss:?} {init:?} {ct:?}");
for needle in ["abab", "171, 171", &ss_hex[..8], &format!("{}, {}", ss.as_bytes()[0], ss.as_bytes()[1])] {
assert!(!shown.to_lowercase().contains(needle), "{needle} in {shown}");
}
assert_eq!(shown.matches("redacted").count(), 3, "{shown}");
}
/// QA A-31, the rung-1 guardrail: no variable-time comparison of secret bytes in `src/`.
#[test]
fn a31_no_variable_time_comparison_of_secrets_in_src() {
for file in ["xwing.rs", "exchange.rs", "schedule.rs", "seal.rs"] {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src").join(file);
let text = std::fs::read_to_string(&path).unwrap();
for (n, line) in text.lines().enumerate() {
let code = line.split("//").next().unwrap_or("");
for bad in ["== [0", "as_bytes() ==", "as_bytes() !=", "ss_x.as_bytes() ==", "== *"] {
assert!(!code.contains(bad), "src/{file}:{}: `{bad}` in `{line}`", n + 1);
}
}
}
}
// ---------------------------------------------------------------------------------------------
// Partial cases completed.
// ---------------------------------------------------------------------------------------------
/// QA A-03 (the missing half): every one of the 1120 single-byte flips gives a different secret
/// from the honest one **and from every other flip**.
#[test]
fn a03_every_ciphertext_flip_gives_a_distinct_secret() {
let r = SecretKey::from_seed([0x31; 32]);
let (ct, ss) = r.public_key().encapsulate(&mut rng(3)).unwrap();
let mut seen = HashSet::new();
seen.insert(*ss.as_bytes());
let mut refused = 0;
for i in 0..CIPHERTEXT_LEN {
let mut b = *ct.as_bytes();
b[i] ^= 0x01;
match r.decapsulate(&Ciphertext::from_bytes(&b).unwrap()) {
Ok(out) => {
assert!(seen.insert(*out.as_bytes()), "byte {i}: collides with the honest secret or another flip")
}
Err(_) => refused += 1, // a flip that lands on a low-order ct_X
}
}
assert!(refused <= 1, "{refused} flips refused");
}
/// QA A-06 (the missing half): a "hybrid" key spliced from A's ML-KEM half and B's X25519 half
/// matches neither A nor B.
#[test]
fn a06_a_spliced_public_key_matches_neither_owner() {
let a = SecretKey::from_seed([0x61; 32]);
let b = SecretKey::from_seed([0x62; 32]);
let mut spliced = *a.public_key().as_bytes();
spliced[1184..].copy_from_slice(&b.public_key().as_bytes()[1184..]);
let pk = PublicKey::from_bytes(&spliced).unwrap();
let (ct, ss) = pk.encapsulate(&mut rng(4)).unwrap();
assert_ne!(a.decapsulate(&ct).unwrap().as_bytes(), ss.as_bytes());
assert_ne!(b.decapsulate(&ct).unwrap().as_bytes(), ss.as_bytes());
// And through the exchange: a responder given the spliced key as "A's" cannot agree with A.
let init = exchange::initiate(&a, b.public_key(), b"ctx", &mut rng(5)).unwrap();
let (ct_ri, rs) = exchange::respond(&b, &pk, init.ciphertext(), b"ctx", &mut rng(6)).unwrap();
let is = init.finish(&ct_ri).unwrap();
assert_ne!(is.wireguard_psk(0).as_bytes(), rs.wireguard_psk(0).as_bytes());
}
/// QA A-18 (the missing half): implicit rejection is `Ok`, deterministic for one ciphertext,
/// different for two tamperings, and recipient-specific.
#[test]
fn a18_implicit_rejection_is_ok_deterministic_and_recipient_specific() {
let r = SecretKey::from_seed([0x71; 32]);
let other = SecretKey::from_seed([0x72; 32]);
let (ct, ss) = r.public_key().encapsulate(&mut rng(7)).unwrap();
let flip = |i: usize| {
let mut b = *ct.as_bytes();
b[i] ^= 0x08;
Ciphertext::from_bytes(&b).unwrap()
};
let (c1, c2) = (flip(10), flip(11));
let k1a = r.decapsulate(&c1).expect("implicit rejection must not be an Err");
let k1b = r.decapsulate(&c1).unwrap();
assert_eq!(k1a.as_bytes(), k1b.as_bytes(), "J(z || c) must be deterministic");
assert_ne!(k1a.as_bytes(), r.decapsulate(&c2).unwrap().as_bytes());
assert_ne!(k1a.as_bytes(), ss.as_bytes());
assert_ne!(k1a.as_bytes(), other.decapsulate(&c1).unwrap().as_bytes(), "z differs per recipient");
}
/// QA A-30: every error a hostile input can produce displays only lengths and variants. Feeds
/// recognisable bytes (0xab) to every parser and checks that no Debug or Display shows them.
#[test]
fn a30_errors_from_hostile_input_carry_no_input_bytes() {
let sk = SecretKey::from_seed([0x01; 32]);
let mut errors = Vec::new();
for len in [0usize, 31, 33, 1119, 1121, 1215, 1217, 1136, 1137, 2000] {
let junk = vec![0xab; len];
errors.extend(PublicKey::from_bytes(&junk).err());
errors.extend(Ciphertext::from_bytes(&junk).err());
errors.extend(SecretKey::from_bytes(&junk).err());
// Byte 0 is the public version byte, which `UnsupportedVersion(v)` echoes by design
// (A-37); give it the valid value so the rest of the box reaches the parser.
let mut boxed = junk.clone();
if let Some(v) = boxed.first_mut() {
*v = arcanum::seal::VERSION;
}
errors.extend(arcanum::seal::open(&sk, &boxed, b"").err());
}
errors.extend(PublicKey::from_bytes(&[0xab; 1216]).err());
assert!(errors.len() > 30);
for e in errors {
let shown = format!("{e} {e:?}").to_lowercase();
assert!(!shown.contains("abab") && !shown.contains("171"), "{shown}");
}
}
// ---------------------------------------------------------------------------------------------
// Regression tests for this review's findings.
// ---------------------------------------------------------------------------------------------
/// QA-R2-02 (minor): `PublicKey::from_bytes` accepts a non-canonical X25519 half. X25519 ignores
/// bit 255 (RFC 7748 §5), so `pk_X` and `pk_X | 0x80..` are the same key to the DH but different
/// bytes to the X-Wing combiner and to Arcanum's transcript. An initiator handed the variant
/// "succeeds" and silently derives a PSK the real owner can never match, and one secret key has
/// two public encodings that compare unequal. Arcanum already refuses low-order points as stricter
/// than the draft; refusing a non-canonical encoding is the same kind of check and changes no
/// vector (honest keys are canonical). Fails while the variant parses.
#[test]
fn qa_r2_02_non_canonical_x25519_public_key_is_refused() {
let i = SecretKey::from_seed([0x81; 32]);
let r = SecretKey::from_seed([0x82; 32]);
let mut variant = *r.public_key().as_bytes();
assert_eq!(variant[1215] & 0x80, 0, "an honest pk_X is canonical");
variant[1215] |= 0x80;
if let Ok(pk) = PublicKey::from_bytes(&variant) {
// Show the consequence before failing: the exchange "works" and the PSKs disagree.
let init = exchange::initiate(&i, &pk, b"ctx", &mut rng(8)).unwrap();
let (ct_ri, rs) = exchange::respond(&r, i.public_key(), init.ciphertext(), b"ctx", &mut rng(9)).unwrap();
let is = init.finish(&ct_ri).unwrap();
assert_ne!(is.wireguard_psk(0).as_bytes(), rs.wireguard_psk(0).as_bytes());
assert_ne!(&pk, r.public_key(), "two encodings of one key compare unequal");
panic!("PublicKey::from_bytes accepted a non-canonical X25519 half (bit 255 set)");
}
}
+210
View File
@@ -0,0 +1,210 @@
//! Mandatory test 3 (v0.2.0): the composite is RFC 10073 `id-MLDSA65-Ed25519-SHA512`, byte for byte.
//!
//! - The RFC's own signatures (`s`, empty ctx; `sWithContext`) verify, from Appendix E as
//! published in `lamps-wg/draft-composite-sigs` `testvectors.json` at `f0627ab`, and the RFC's
//! 64-byte private key derives the RFC's 1984-byte public key.
//! - Arcanum's own signatures verify under an **independent rebuild** of M' written here, against
//! the component crates directly: ML-DSA-65 with ctx = Label, and Ed25519 `verify_strict`.
//! - The ML-DSA half is hedged (two signatures of the same message differ) and the Ed25519 half
//! is pure Ed25519 (deterministic, so equal).
//!
//! The RFC vectors are hedged, so there is no byte-exact composite signing KAT (docs gap).
mod common;
use arcanum::Error;
use arcanum::sign::{
self, AppContext, SIGNATURE_LEN, SIGNING_KEY_LEN, Signature, SigningKey, VERIFYING_KEY_LEN, VerifyingKey,
};
use common::{assert_sha256, b64, rng};
use ml_dsa::MlDsa65;
use ml_dsa::common::array::Array;
use serde_json::Value;
use sha2::{Digest, Sha512};
const VECTORS: &[u8] = include_bytes!("vectors/composite-sigs-testvectors-MLDSA65-Ed25519.subset.json");
const VECTORS_SHA256: &str = "33311f63d2c5a21d5dd4b05eb864de38bd7572108b38de713a40312d2b893b34";
/// RFC 10073 §2.2 and §6, written out here independently of `src/sign.rs`.
const PREFIX: &[u8] = b"CompositeAlgorithmSignatures2025";
const LABEL: &[u8] = b"COMPSIG-MLDSA65-Ed25519-SHA512";
const ML_DSA_SIG_LEN: usize = 3309;
const ML_DSA_PK_LEN: usize = 1952;
/// M' = Prefix || Label || u8(len(ctx)) || ctx || SHA-512(M) (RFC 10073 §3.2)
fn m_prime(msg: &[u8], ctx: &[u8]) -> Vec<u8> {
assert!(ctx.len() <= 255);
let mut m = Vec::new();
m.extend_from_slice(PREFIX);
m.extend_from_slice(LABEL);
m.push(ctx.len() as u8);
m.extend_from_slice(ctx);
m.extend_from_slice(&Sha512::digest(msg));
m
}
/// Verify a composite signature with the component crates only, not with Arcanum.
fn independent_verify(pk: &[u8], msg: &[u8], ctx: &[u8], sig: &[u8]) -> (bool, bool) {
assert_eq!(pk.len(), ML_DSA_PK_LEN + 32);
assert_eq!(sig.len(), ML_DSA_SIG_LEN + 64);
let mp = m_prime(msg, ctx);
let ml_vk = ml_dsa::VerifyingKey::<MlDsa65>::decode(&Array::try_from(&pk[..ML_DSA_PK_LEN]).unwrap());
let ml_ok = ml_dsa::Signature::<MlDsa65>::try_from(&sig[..ML_DSA_SIG_LEN])
.is_ok_and(|s| ml_vk.verify_with_context(&mp, LABEL, &s));
let ed_vk = ed25519_dalek::VerifyingKey::from_bytes(pk[ML_DSA_PK_LEN..].try_into().unwrap()).unwrap();
let ed_sig = ed25519_dalek::Signature::from_slice(&sig[ML_DSA_SIG_LEN..]).unwrap();
let ed_ok = ed_vk.verify_strict(&mp, &ed_sig).is_ok();
(ml_ok, ed_ok)
}
struct Rfc {
m: Vec<u8>,
ctx: Vec<u8>,
pk: Vec<u8>,
sk: Vec<u8>,
s: Vec<u8>,
s_with_context: Vec<u8>,
}
fn rfc() -> Rfc {
assert_sha256(VECTORS, VECTORS_SHA256, "RFC 10073 composite vectors subset");
let v: Value = serde_json::from_slice(VECTORS).unwrap();
let tests = v["tests"].as_array().unwrap();
assert_eq!(tests.len(), 1);
let t = &tests[0];
assert_eq!(t["tcId"], "id-MLDSA65-Ed25519-SHA512");
let f = |name: &str| b64(t[name].as_str().unwrap());
Rfc {
m: b64(v["m"].as_str().unwrap()),
ctx: b64(v["ctx"].as_str().unwrap()),
pk: f("pk"),
sk: f("sk"),
s: f("s"),
s_with_context: f("sWithContext"),
}
}
#[test]
fn sizes_are_the_rfcs() {
let r = rfc();
assert_eq!((VERIFYING_KEY_LEN, SIGNATURE_LEN, SIGNING_KEY_LEN), (1984, 3373, 64));
assert_eq!((r.pk.len(), r.s.len(), r.s_with_context.len(), r.sk.len()), (1984, 3373, 3373, 64));
assert_eq!(sign::PREFIX, PREFIX);
assert_eq!(sign::LABEL, LABEL);
}
#[test]
fn rfc_private_key_derives_the_rfc_public_key() {
let r = rfc();
let sk = SigningKey::from_bytes(&r.sk).unwrap();
assert_eq!(sk.verifying_key().as_bytes().as_slice(), r.pk.as_slice());
assert_eq!(sk.to_bytes().as_slice(), r.sk.as_slice(), "the private key round-trips (mldsaSeed || edSK)");
}
/// The gap in docs/02_signatures.md: does `verify_strict` accept the RFC's vectors? This answers it.
#[test]
fn rfc_signatures_verify() {
let r = rfc();
let vk = VerifyingKey::from_bytes(&r.pk).unwrap();
let s = Signature::from_bytes(&r.s).unwrap();
let swc = Signature::from_bytes(&r.s_with_context).unwrap();
// Arcanum's raw (hazmat) interface, with the RFC's bare ctx.
assert_eq!(sign::verify_composite_raw(&vk, &r.m, b"", &s), Ok(()), "s (empty ctx)");
assert_eq!(sign::verify_composite_raw(&vk, &r.m, &r.ctx, &swc), Ok(()), "sWithContext");
// The contexts are not interchangeable.
assert_eq!(sign::verify_composite_raw(&vk, &r.m, &r.ctx, &s), Err(Error::InvalidSignature));
assert_eq!(sign::verify_composite_raw(&vk, &r.m, b"", &swc), Err(Error::InvalidSignature));
// The independent rebuild agrees, half by half.
assert_eq!(independent_verify(&r.pk, &r.m, b"", &r.s), (true, true));
assert_eq!(independent_verify(&r.pk, &r.m, &r.ctx, &r.s_with_context), (true, true));
}
#[test]
fn own_signatures_verify_under_an_independent_rebuild_of_m_prime() {
let mut rng = rng(30);
let sk = SigningKey::generate(&mut rng);
let pk = sk.verifying_key().as_bytes().to_vec();
let msg = b"a plan, signed by its author";
// Release API: the ctx is Arcanum's app prefix plus the caller's label.
let ctx = AppContext::new(b"plans").unwrap();
assert_eq!(ctx.as_bytes(), b"domi/arcanum/v2/sig/app/plans");
let sig = sk.sign(msg, &ctx, &mut rng).unwrap();
assert_eq!(independent_verify(&pk, msg, ctx.as_bytes(), sig.as_bytes()), (true, true));
assert_eq!(sk.verifying_key().verify(msg, &ctx, &sig), Ok(()));
// Raw interface: an empty ctx and the longest ctx, 255 bytes.
for ctx in [&b""[..], &[0xa5; 255][..]] {
let sig = sign::sign_composite_raw(&sk, msg, ctx, &mut rng).unwrap();
assert_eq!(independent_verify(&pk, msg, ctx, sig.as_bytes()), (true, true), "ctx of {} bytes", ctx.len());
assert_eq!(sign::verify_composite_raw(sk.verifying_key(), msg, ctx, &sig), Ok(()));
}
// The RFC's own private key, signing the RFC's message: verifies under the RFC's public key.
let r = rfc();
let rfc_sk = SigningKey::from_bytes(&r.sk).unwrap();
let sig = sign::sign_composite_raw(&rfc_sk, &r.m, &r.ctx, &mut rng).unwrap();
assert_eq!(independent_verify(&r.pk, &r.m, &r.ctx, sig.as_bytes()), (true, true));
}
#[test]
fn ml_dsa_half_is_hedged_and_ed25519_half_is_pure() {
let sk = SigningKey::generate(&mut rng(31));
let ctx = AppContext::new(b"hedge").unwrap();
let a = sk.sign(b"same message", &ctx, &mut rng(32)).unwrap();
let b = sk.sign(b"same message", &ctx, &mut rng(33)).unwrap();
let (a, b) = (a.as_bytes(), b.as_bytes());
assert_ne!(a[..ML_DSA_SIG_LEN], b[..ML_DSA_SIG_LEN], "ML-DSA must be hedged: fresh rnd per signature");
assert_eq!(a[ML_DSA_SIG_LEN..], b[ML_DSA_SIG_LEN..], "Ed25519 over the same M' is deterministic");
// The same RNG state gives the same signature: the RNG is the only source of randomness.
let c = sk.sign(b"same message", &ctx, &mut rng(32)).unwrap();
assert_eq!(a, c.as_bytes());
}
#[test]
fn ml_dsa_half_uses_the_label_as_its_context() {
let mut rng = rng(34);
let sk = SigningKey::generate(&mut rng);
let pk = sk.verifying_key().as_bytes().to_vec();
let ctx = AppContext::new(b"label").unwrap();
let sig = sk.sign(b"m", &ctx, &mut rng).unwrap();
let mp = m_prime(b"m", ctx.as_bytes());
let ml_vk = ml_dsa::VerifyingKey::<MlDsa65>::decode(&Array::try_from(&pk[..ML_DSA_PK_LEN]).unwrap());
let ml_sig = ml_dsa::Signature::<MlDsa65>::try_from(&sig.as_bytes()[..ML_DSA_SIG_LEN]).unwrap();
assert!(ml_vk.verify_with_context(&mp, LABEL, &ml_sig), "ctx = Label");
assert!(!ml_vk.verify_with_context(&mp, b"", &ml_sig), "not the empty ctx");
assert!(!ml_vk.verify_with_context(&mp, ctx.as_bytes(), &ml_sig), "not the application ctx");
}
/// An RNG that records what it hands out (backed by the test ChaCha20).
struct Recording(chacha20::ChaCha20Rng, Vec<u8>);
impl rand_core::TryRng for Recording {
type Error = core::convert::Infallible;
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
unimplemented!("signing draws bytes, not words")
}
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
unimplemented!("signing draws bytes, not words")
}
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
rand_core::Rng::fill_bytes(&mut self.0, dst);
self.1.extend_from_slice(dst);
Ok(())
}
}
impl rand_core::TryCryptoRng for Recording {}
/// QA S-03 (their `qa_s05`), RFC 10073 §3.1: `generate` draws 64 fresh bytes, the ML-DSA seed then
/// the Ed25519 seed, independently. Kills deriving one seed from the other, or drawing only 32.
#[test]
fn generate_draws_two_independent_seeds() {
let mut rec = Recording(rng(35), Vec::new());
let sk = SigningKey::generate(&mut rec);
assert_eq!(rec.1.len(), 64, "exactly 64 bytes drawn");
assert_eq!(sk.to_bytes().as_slice(), rec.1.as_slice(), "the seeds are the RNG output, in order");
assert_ne!(rec.1[..32], rec.1[32..], "two different seeds");
let again = SigningKey::from_bytes(&rec.1).unwrap();
assert_eq!(again.verifying_key(), sk.verifying_key());
}
+214
View File
@@ -0,0 +1,214 @@
//! Mandatory test 5 (v0.2.0): every byte matters. Flipping any byte of the message, the context,
//! the public key or the signature fails verification. Contexts are prefix-free (the length of
//! ctx is inside M'), and a key-binding signature never verifies as an application message, nor
//! the other way round.
mod common;
use arcanum::Error;
use arcanum::sign::{
self, AppContext, KEM_KEY_CONTEXT, SIGNATURE_LEN, Signature, SigningKey, VERIFYING_KEY_LEN, VerifyingKey,
};
use arcanum::xwing;
use common::rng;
const MSG: &[u8] = b"Built on Domi: every byte of this message is signed.";
fn setup(tag: u8) -> (SigningKey, AppContext, Signature) {
let mut r = rng(tag);
let sk = SigningKey::generate(&mut r);
let c = AppContext::new(b"every-byte").unwrap();
let sig = sk.sign(MSG, &c, &mut r).unwrap();
assert_eq!(sk.verifying_key().verify(MSG, &c, &sig), Ok(()), "control");
(sk, c, sig)
}
#[test]
fn flipping_any_byte_of_the_message_fails() {
let (sk, c, sig) = setup(50);
for i in 0..MSG.len() {
for mask in [0x01, 0x80] {
let mut m = MSG.to_vec();
m[i] ^= mask;
assert_eq!(sk.verifying_key().verify(&m, &c, &sig), Err(Error::InvalidSignature), "byte {i}");
}
}
let mut longer = MSG.to_vec();
longer.push(0);
assert_eq!(sk.verifying_key().verify(&longer, &c, &sig), Err(Error::InvalidSignature), "appended byte");
assert_eq!(sk.verifying_key().verify(&MSG[..MSG.len() - 1], &c, &sig), Err(Error::InvalidSignature));
}
#[test]
fn flipping_any_byte_of_the_context_fails() {
let (sk, c, sig) = setup(51);
let vk = sk.verifying_key();
// Through the release API: every byte of the caller's label. Labels are `&'static` (QA S-09);
// a test may leak a few to build them at run time, which a consumer must not do.
let label = b"every-byte";
for i in 0..label.len() {
let mut l = label.to_vec();
l[i] ^= 0x01;
let l: &'static [u8] = Box::leak(l.into_boxed_slice());
assert_eq!(vk.verify(MSG, &AppContext::new(l).unwrap(), &sig), Err(Error::InvalidSignature), "label byte {i}");
}
// Through the raw interface: every byte of the whole ctx, Arcanum's prefix included.
let full = c.as_bytes().to_vec();
assert_eq!(sign::verify_composite_raw(vk, MSG, &full, &sig), Ok(()), "control");
for i in 0..full.len() {
let mut f = full.clone();
f[i] ^= 0x01;
assert_eq!(sign::verify_composite_raw(vk, MSG, &f, &sig), Err(Error::InvalidSignature), "ctx byte {i}");
}
}
#[test]
fn flipping_any_byte_of_the_public_key_fails() {
let (sk, c, sig) = setup(52);
let pk = *sk.verifying_key().as_bytes();
let (mut refused_at_parse, mut refused_at_verify) = (0, 0);
for i in 0..VERIFYING_KEY_LEN {
let mut b = pk;
b[i] ^= 0x01;
match VerifyingKey::from_bytes(&b) {
Err(e) => {
assert_eq!(e, Error::InvalidVerifyingKey, "byte {i}");
assert!(i >= VERIFYING_KEY_LEN - 32, "byte {i}: only the Ed25519 point can fail to parse");
refused_at_parse += 1;
}
Ok(vk) => {
assert_eq!(vk.verify(MSG, &c, &sig), Err(Error::InvalidSignature), "byte {i}");
refused_at_verify += 1;
}
}
}
assert_eq!(refused_at_parse + refused_at_verify, VERIFYING_KEY_LEN);
assert!(refused_at_verify >= 1952, "every ML-DSA byte reaches verification");
}
#[test]
fn flipping_any_byte_of_the_signature_fails() {
let (sk, c, sig) = setup(53);
for i in 0..SIGNATURE_LEN {
let mut b = *sig.as_bytes();
b[i] ^= 0x01;
let bad = Signature::from_bytes(&b).unwrap();
assert_eq!(sk.verifying_key().verify(MSG, &c, &bad), Err(Error::InvalidSignature), "byte {i}");
}
}
#[test]
fn contexts_are_prefix_free() {
let mut r = rng(54);
let sk = SigningKey::generate(&mut r);
let vk = sk.verifying_key();
let a = AppContext::new(b"a").unwrap();
let ab = AppContext::new(b"ab").unwrap();
let sig_a = sk.sign(MSG, &a, &mut r).unwrap();
let sig_ab = sk.sign(MSG, &ab, &mut r).unwrap();
assert_eq!(vk.verify(MSG, &ab, &sig_a), Err(Error::InvalidSignature), "a is a prefix of ab");
assert_eq!(vk.verify(MSG, &a, &sig_ab), Err(Error::InvalidSignature), "ab extends a");
assert_eq!(vk.verify(MSG, &AppContext::new(b"a\0").unwrap(), &sig_a), Err(Error::InvalidSignature));
// Moving a byte between ctx and message: M' holds SHA-512(M), and u8(len ctx) fixes the split.
assert_eq!(vk.verify(b"bBuilt", &a, &sk.sign(b"Built", &ab, &mut r).unwrap()), Err(Error::InvalidSignature));
// The raw interface: the empty ctx, Arcanum's prefixes and the RFC's empty ctx are all distinct.
let raw_empty = sign::sign_composite_raw(&sk, MSG, b"", &mut r).unwrap();
assert_eq!(sign::verify_composite_raw(vk, MSG, b"\0", &raw_empty), Err(Error::InvalidSignature));
assert_eq!(vk.verify(MSG, &a, &raw_empty), Err(Error::InvalidSignature));
let app_prefix_only = sign::sign_composite_raw(&sk, MSG, b"domi/arcanum/v2/sig/app/", &mut r).unwrap();
assert_eq!(vk.verify(MSG, &a, &app_prefix_only), Err(Error::InvalidSignature));
// Arcanum's fixed contexts: neither is a prefix of the other.
let app = b"domi/arcanum/v2/sig/app/";
assert_eq!(KEM_KEY_CONTEXT, b"domi/arcanum/v2/sig/kem-key");
assert!(!app.starts_with(KEM_KEY_CONTEXT) && !KEM_KEY_CONTEXT.starts_with(app));
}
/// The key-binding message, written out here from docs/02_signatures.md, independently of the code:
/// u8(1) || u64be(not_before) || u64be(not_after) || u16be(len id) || id || xwing_pk.
fn binding_message(id: &[u8], kem: &xwing::PublicKey, (nb, na): (u64, u64)) -> Vec<u8> {
let mut m = vec![1u8];
m.extend_from_slice(&nb.to_be_bytes());
m.extend_from_slice(&na.to_be_bytes());
m.extend_from_slice(&(id.len() as u16).to_be_bytes());
m.extend_from_slice(id);
m.extend_from_slice(kem.as_bytes());
m
}
#[test]
fn a_key_binding_never_verifies_as_an_app_message_and_back() {
let mut r = rng(55);
let sk = SigningKey::generate(&mut r);
let vk = sk.verifying_key();
let kem = xwing::SecretKey::generate(&mut r);
let (id, valid, now) = (b"device-7".as_slice(), (1_000, 2_000), 1_500);
let binding = sign::bind_kem_key(&sk, id, kem.public_key(), valid, &mut r).unwrap();
assert_eq!(sign::verify_binding(vk, id, kem.public_key(), valid, now, &binding), Ok(()), "control");
// The binding is exactly the documented message under the kem-key ctx.
let msg = binding_message(id, kem.public_key(), valid);
assert_eq!(sign::verify_composite_raw(vk, &msg, KEM_KEY_CONTEXT, &binding), Ok(()), "documented encoding");
// As an application message, under any application label: refused.
for label in [b"kem-key".as_slice(), b"", b"domi/arcanum/v2/sig/kem-key", b"x"] {
if let Ok(c) = AppContext::new(label) {
assert_eq!(vk.verify(&msg, &c, &binding), Err(Error::InvalidSignature), "label {label:?}");
}
}
// The other way round: an application signature over the very same bytes is no binding.
let app_sig = sk.sign(&msg, &AppContext::new(b"kem-key").unwrap(), &mut r).unwrap();
assert_eq!(sign::verify_binding(vk, id, kem.public_key(), valid, now, &app_sig), Err(Error::InvalidSignature));
}
#[test]
fn every_field_of_a_key_binding_matters() {
let mut r = rng(56);
let sk = SigningKey::generate(&mut r);
let vk = sk.verifying_key();
let kem = xwing::SecretKey::generate(&mut r);
let other_kem = xwing::SecretKey::generate(&mut r);
let (id, valid) = (b"device-7".as_slice(), (1_000u64, 2_000u64));
let sig = sign::bind_kem_key(&sk, id, kem.public_key(), valid, &mut r).unwrap();
let check =
|id: &[u8], k: &xwing::PublicKey, v: (u64, u64), now: u64| sign::verify_binding(vk, id, k, v, now, &sig);
assert_eq!(check(id, kem.public_key(), valid, 1_000), Ok(()), "not_before is inclusive");
assert_eq!(check(id, kem.public_key(), valid, 2_000), Ok(()), "not_after is inclusive");
assert_eq!(check(id, kem.public_key(), valid, 999), Err(Error::OutsideValidity));
assert_eq!(check(id, kem.public_key(), valid, 2_001), Err(Error::OutsideValidity));
assert_eq!(check(b"device-8", kem.public_key(), valid, 1_500), Err(Error::InvalidSignature), "id");
assert_eq!(check(b"device-7\0", kem.public_key(), valid, 1_500), Err(Error::InvalidSignature), "id length");
assert_eq!(check(id, other_kem.public_key(), valid, 1_500), Err(Error::InvalidSignature), "X-Wing key");
assert_eq!(check(id, kem.public_key(), (1_000, 2_001), 1_500), Err(Error::InvalidSignature), "not_after");
assert_eq!(check(id, kem.public_key(), (999, 2_000), 1_500), Err(Error::InvalidSignature), "not_before");
// A forged window is refused as a bad signature before its dates are looked at.
assert_eq!(check(id, kem.public_key(), (0, u64::MAX), 5_000), Err(Error::InvalidSignature));
// An inverted window is refused when binding and when verifying.
assert_eq!(sign::bind_kem_key(&sk, id, kem.public_key(), (2, 1), &mut r), Err(Error::InvalidValidity));
assert_eq!(check(id, kem.public_key(), (2_000, 1_000), 1_500), Err(Error::InvalidValidity));
// Every byte of the X-Wing key matters (its encoding is fixed-width and signed whole).
let mut flipped = *kem.public_key().as_bytes();
for i in [0, 600, 1183, 1184, 1215] {
flipped[i] ^= 0x01;
if let Ok(k) = xwing::PublicKey::from_bytes(&flipped) {
assert_eq!(check(id, &k, valid, 1_500), Err(Error::InvalidSignature), "X-Wing byte {i}");
}
flipped[i] ^= 0x01;
}
}
/// QA S-02 (their `qa_s04`): `OutsideValidity` only ever means "authentic, but not now". A forged
/// window that also excludes `now` is `InvalidSignature`. Kills checking `now` before the signature.
#[test]
fn a_forged_window_that_excludes_now_is_invalid_signature_not_outside_validity() {
let mut r = rng(57);
let sk = SigningKey::generate(&mut r);
let kem = xwing::SecretKey::generate(&mut r);
let sig = sign::bind_kem_key(&sk, b"dev", kem.public_key(), (1_000, 2_000), &mut r).unwrap();
let check =
|v: (u64, u64), now: u64| sign::verify_binding(sk.verifying_key(), b"dev", kem.public_key(), v, now, &sig);
assert_eq!(check((1_000, 2_000), 1_500), Ok(()), "control");
assert_eq!(check((1_000, 2_000), 2_500), Err(Error::OutsideValidity), "control: authentic, expired");
assert_eq!(check((1_000, 2_001), 2_500), Err(Error::InvalidSignature), "forged window, now after it");
assert_eq!(check((3_000, 4_000), 2_500), Err(Error::InvalidSignature), "forged window, now before it");
}
+190
View File
@@ -0,0 +1,190 @@
//! Mandatory test 4 (v0.2.0): both halves of a composite signature are bound. A signature is
//! accepted only when **both** the ML-DSA-65 half and the Ed25519 half verify over this M'.
//!
//! Refused: either half replaced by a valid half of another signature (another message, another
//! key or another context), either half zeroed, the halves swapped. And the ML-DSA half alone is
//! no ordinary ML-DSA signature: an empty-ctx ML-DSA verifier refuses it, on M' and on M.
//!
//! Pinned, not a bug: the composite is not SUF-CMA (RFC 10073 §9.2). Two hedged signatures of the
//! same message by the same key under the same context can trade ML-DSA halves and still verify.
mod common;
use arcanum::Error;
use arcanum::sign::{AppContext, SIGNATURE_LEN, Signature, SigningKey};
use common::rng;
use ml_dsa::MlDsa65;
use ml_dsa::common::array::Array;
use sha2::{Digest, Sha512};
const ML: usize = 3309; // the ML-DSA-65 half comes first
const ML_PK: usize = 1952;
fn ctx(label: &'static [u8]) -> AppContext {
AppContext::new(label).unwrap()
}
fn splice(ml_from: &Signature, ed_from: &Signature) -> Signature {
let mut b = [0u8; SIGNATURE_LEN];
b[..ML].copy_from_slice(&ml_from.as_bytes()[..ML]);
b[ML..].copy_from_slice(&ed_from.as_bytes()[ML..]);
Signature::from_bytes(&b).unwrap()
}
fn refused(sk: &SigningKey, msg: &[u8], c: &AppContext, sig: &Signature, what: &str) {
assert_eq!(sk.verifying_key().verify(msg, c, sig), Err(Error::InvalidSignature), "{what}");
}
#[test]
fn a_half_from_another_signature_is_refused() {
let mut r = rng(40);
let sk = SigningKey::generate(&mut r);
let other_key = SigningKey::generate(&mut r);
let c = ctx(b"halves");
let msg = b"the message";
let good = sk.sign(msg, &c, &mut r).unwrap();
assert_eq!(sk.verifying_key().verify(msg, &c, &good), Ok(()), "control");
let other_msg = sk.sign(b"another message", &c, &mut r).unwrap();
let other_ctx = sk.sign(msg, &ctx(b"another context"), &mut r).unwrap();
let other_signer = other_key.sign(msg, &c, &mut r).unwrap();
for (donor, what) in
[(&other_msg, "another message"), (&other_ctx, "another context"), (&other_signer, "another key")]
{
refused(&sk, msg, &c, &splice(donor, &good), &format!("ML-DSA half from {what}"));
refused(&sk, msg, &c, &splice(&good, donor), &format!("Ed25519 half from {what}"));
}
}
#[test]
fn a_zeroed_or_missing_half_is_refused() {
let mut r = rng(41);
let sk = SigningKey::generate(&mut r);
let c = ctx(b"halves");
let good = sk.sign(b"m", &c, &mut r).unwrap();
let mut b = *good.as_bytes();
b[..ML].fill(0);
refused(&sk, b"m", &c, &Signature::from_bytes(&b).unwrap(), "ML-DSA half zeroed");
let mut b = *good.as_bytes();
b[ML..].fill(0);
refused(&sk, b"m", &c, &Signature::from_bytes(&b).unwrap(), "Ed25519 half zeroed");
let mut b = *good.as_bytes();
b[ML..].fill(0xff);
refused(&sk, b"m", &c, &Signature::from_bytes(&b).unwrap(), "Ed25519 half all ones");
// A signature with one half cut off is the wrong length, a typed error at parse time.
assert!(Signature::from_bytes(&good.as_bytes()[..ML]).is_err(), "ML-DSA half alone");
assert!(Signature::from_bytes(&good.as_bytes()[ML..]).is_err(), "Ed25519 half alone");
}
#[test]
fn swapped_halves_are_refused() {
let mut r = rng(42);
let sk = SigningKey::generate(&mut r);
let c = ctx(b"halves");
let good = sk.sign(b"m", &c, &mut r).unwrap();
let g = good.as_bytes();
let mut swapped = Vec::with_capacity(SIGNATURE_LEN);
swapped.extend_from_slice(&g[ML..]);
swapped.extend_from_slice(&g[..ML]);
refused(&sk, b"m", &c, &Signature::from_bytes(&swapped).unwrap(), "Ed25519 || ML-DSA");
}
#[test]
fn the_ml_dsa_half_alone_is_not_an_ordinary_ml_dsa_signature() {
let mut r = rng(43);
let sk = SigningKey::generate(&mut r);
let c = ctx(b"halves");
let msg = b"m";
let sig = sk.sign(msg, &c, &mut r).unwrap();
let pk = sk.verifying_key().as_bytes();
let vk = ml_dsa::VerifyingKey::<MlDsa65>::decode(&Array::try_from(&pk[..ML_PK]).unwrap());
let half = ml_dsa::Signature::<MlDsa65>::try_from(&sig.as_bytes()[..ML]).unwrap();
let mut mp = Vec::new();
mp.extend_from_slice(b"CompositeAlgorithmSignatures2025COMPSIG-MLDSA65-Ed25519-SHA512");
mp.push(c.as_bytes().len() as u8);
mp.extend_from_slice(c.as_bytes());
mp.extend_from_slice(&Sha512::digest(msg));
// An application that verifies ML-DSA with the empty ctx (as the crate's `Verifier` trait does)
// refuses the half, whether it is shown M' or the message itself.
assert!(!vk.verify_with_context(&mp, b"", &half), "empty ctx over M'");
assert!(!vk.verify_with_context(msg, b"", &half), "empty ctx over M");
assert!(!vk.verify_with_context(msg, b"COMPSIG-MLDSA65-Ed25519-SHA512", &half), "Label ctx over M");
// Control: it is a valid ML-DSA signature over M' under ctx = Label, and nothing else.
assert!(vk.verify_with_context(&mp, b"COMPSIG-MLDSA65-Ed25519-SHA512", &half));
// Likewise the Ed25519 half: it signs M', never the message.
let ed = ed25519_dalek::VerifyingKey::from_bytes(pk[ML_PK..].try_into().unwrap()).unwrap();
let ed_half = ed25519_dalek::Signature::from_slice(&sig.as_bytes()[ML..]).unwrap();
assert!(ed.verify_strict(msg, &ed_half).is_err(), "Ed25519 over M");
assert!(ed.verify_strict(&mp, &ed_half).is_ok(), "control: Ed25519 over M'");
}
/// RFC 10073 §9.2: not SUF-CMA. Pinned so a change in this property is noticed, not hidden.
#[test]
fn halves_of_two_signatures_of_the_same_message_combine_as_the_rfc_says() {
let mut r = rng(44);
let sk = SigningKey::generate(&mut r);
let c = ctx(b"halves");
let a = sk.sign(b"m", &c, &mut r).unwrap();
let b = sk.sign(b"m", &c, &mut r).unwrap();
assert_ne!(a, b, "hedged ML-DSA");
assert_eq!(sk.verifying_key().verify(b"m", &c, &splice(&a, &b)), Ok(()));
assert_eq!(sk.verifying_key().verify(b"m", &c, &splice(&b, &a)), Ok(()));
}
/// QA S-01 (PR #2 review, their `qa_s03`): the Ed25519 half is checked with `verify_strict`, not
/// plain `verify`. A signer who knows its own Ed25519 scalar `a` can make a half with R = the
/// identity (a small-order point) and s = H(R || A || M')·a. Plain `verify` accepts it,
/// `verify_strict` refuses it, and so must Arcanum. Kills `verify_strict` -> `verify`.
#[test]
fn a_small_order_r_in_the_ed25519_half_is_refused() {
use curve25519_dalek::scalar::Scalar;
use ed25519_dalek::Verifier as _;
let seeds = [0x11u8; 64]; // a throwaway key
let sk = SigningKey::from_bytes(&seeds).unwrap();
let vk = sk.verifying_key();
let c = ctx(b"small-order-r");
let msg = b"m";
let good = sk.sign(msg, &c, &mut rng(45)).unwrap();
// a = clamp(SHA-512(Ed25519 seed)[..32]) (RFC 8032 §5.1.5).
let h = Sha512::digest(&seeds[32..]);
let mut a = [0u8; 32];
a.copy_from_slice(&h[..32]);
a[0] &= 248;
a[31] &= 127;
a[31] |= 64;
let a = Scalar::from_bytes_mod_order(a);
let mut mp = Vec::new();
mp.extend_from_slice(b"CompositeAlgorithmSignatures2025COMPSIG-MLDSA65-Ed25519-SHA512");
mp.push(c.as_bytes().len() as u8);
mp.extend_from_slice(c.as_bytes());
mp.extend_from_slice(&Sha512::digest(msg));
let mut r = [0u8; 32];
r[0] = 1; // the identity, canonically encoded: order 1
let a_bytes = &vk.as_bytes()[ML_PK..];
let mut kh = Sha512::new();
kh.update(r);
kh.update(a_bytes);
kh.update(&mp);
let k = Scalar::from_bytes_mod_order_wide(&kh.finalize().into());
let mut ed_half = [0u8; 64];
ed_half[..32].copy_from_slice(&r);
ed_half[32..].copy_from_slice((k * a).as_bytes());
// Controls: this is the one difference between the two Ed25519 checks.
let ed_vk = ed25519_dalek::VerifyingKey::from_bytes(a_bytes.try_into().unwrap()).unwrap();
let ed_sig = ed25519_dalek::Signature::from_bytes(&ed_half);
assert!(ed_vk.verify(&mp, &ed_sig).is_ok(), "control: plain verify accepts a small-order R");
assert!(ed_vk.verify_strict(&mp, &ed_sig).is_err(), "control: verify_strict refuses it");
let mut b = [0u8; SIGNATURE_LEN];
b[..ML].copy_from_slice(&good.as_bytes()[..ML]);
b[ML..].copy_from_slice(&ed_half);
refused(&sk, msg, &c, &Signature::from_bytes(&b).unwrap(), "small-order R in the Ed25519 half");
}
+205
View File
@@ -0,0 +1,205 @@
//! Mandatory test 7 (v0.2.0): hygiene of the signature API.
//!
//! - What a **default-features consumer** can and cannot write, by compiling small programs against
//! Arcanum without `hazmat`, the way `qa_consumer_api.rs` does for v0.1.0 (QA A-33, A-34). The
//! raw RFC interface is `hazmat` only, and none of `ml-dsa`'s own signing internals
//! (`sign_internal` with caller-chosen randomness, `sign_mu_deterministic`, `sign_deterministic`,
//! the `Signer` trait with its empty context) can be reached through Arcanum's types.
//! - The secret types are `ZeroizeOnDrop`, including the component crates' keys (which proves their
//! `zeroize` features are on), and `Debug` never prints key material.
//!
//! The feature graph (no `hazmat` anywhere, `zeroize` on) is checked in `feature_hygiene.rs`, and
//! the heap wiping by the allocator probe in `zeroize-probe/`.
mod common;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;
use arcanum::sign::{AppContext, SigningKey};
use common::rng;
use zeroize::ZeroizeOnDrop;
/// The cases share one crate (its dependencies are checked once), so they must not run at once.
static LOCK: Mutex<()> = Mutex::new(());
const PRELUDE: &str = r#"
#![allow(unused)]
use core::convert::Infallible;
use rand_core::{TryCryptoRng, TryRng};
/// A counter: deterministic, and therefore NOT a cryptographic RNG.
pub struct Counter(pub u64);
impl TryRng for Counter {
type Error = Infallible;
fn try_next_u32(&mut self) -> Result<u32, Infallible> { self.0 += 1; Ok(self.0 as u32) }
fn try_next_u64(&mut self) -> Result<u64, Infallible> { self.0 += 1; Ok(self.0) }
fn try_fill_bytes(&mut self, d: &mut [u8]) -> Result<(), Infallible> {
for b in d { self.0 += 1; *b = self.0 as u8; }
Ok(())
}
}
/// The same counter, *claiming* to be cryptographic (a stand-in for a real CSPRNG in the control).
pub struct Claimed(pub Counter);
impl TryRng for Claimed {
type Error = Infallible;
fn try_next_u32(&mut self) -> Result<u32, Infallible> { self.0.try_next_u32() }
fn try_next_u64(&mut self) -> Result<u64, Infallible> { self.0.try_next_u64() }
fn try_fill_bytes(&mut self, d: &mut [u8]) -> Result<(), Infallible> { self.0.try_fill_bytes(d) }
}
impl TryCryptoRng for Claimed {}
fn key() -> arcanum::sign::SigningKey { arcanum::sign::SigningKey::generate(&mut Claimed(Counter(0))) }
fn ctx() -> arcanum::sign::AppContext { arcanum::sign::AppContext::new(b"consumer").unwrap() }
"#;
fn consumer_dir() -> PathBuf {
let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("sig-consumer-api");
std::fs::create_dir_all(dir.join("src")).unwrap();
let arcanum = env!("CARGO_MANIFEST_DIR").replace('\\', "/");
let manifest = format!(
"[package]\nname = \"sig-consumer-api\"\nversion = \"0.0.0\"\nedition = \"2024\"\npublish = false\n\n\
[dependencies]\narcanum = {{ path = \"{arcanum}\" }}\n\
rand_core = {{ version = \"0.10\", default-features = false }}\n\n[workspace]\n"
);
std::fs::write(dir.join("Cargo.toml"), manifest).unwrap();
if !dir.join("Cargo.lock").exists() {
std::fs::copy(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.lock"), dir.join("Cargo.lock")).unwrap();
}
dir
}
/// `cargo check` a consumer whose `main` body is `body`. Returns (compiled, compiler output).
fn check(body: &str) -> (bool, String) {
let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
let dir = consumer_dir();
std::fs::write(dir.join("src/main.rs"), format!("{PRELUDE}\nfn main() {{\n{body}\n}}\n")).unwrap();
let out = Command::new(env!("CARGO"))
.current_dir(&dir)
.args(["check", "--offline", "--quiet", "--message-format", "short"])
.env_remove("CARGO_TARGET_DIR")
.output()
.expect("run cargo check");
(out.status.success(), String::from_utf8_lossy(&out.stderr).into_owned())
}
fn assert_refused(what: &str, body: &str, needles: &[&str]) {
let (ok, err) = check(body);
assert!(!ok, "{what}: compiled against Arcanum with default features, and must not");
assert!(
needles.iter().any(|n| err.contains(n)),
"{what}: refused, but not for the expected reason ({needles:?}):\n{err}"
);
}
#[test]
fn control_the_release_signature_api_compiles_without_hazmat() {
let (ok, err) = check(
r#"
let mut rng = Claimed(Counter(0));
let sk = key();
let sig = sk.sign(b"plan", &ctx(), &mut rng).unwrap();
sk.verifying_key().verify(b"plan", &ctx(), &sig).unwrap();
let vk = arcanum::sign::VerifyingKey::from_bytes(sk.verifying_key().as_bytes()).unwrap();
let sig = arcanum::sign::Signature::from_bytes(sig.as_bytes()).unwrap();
vk.verify(b"plan", &ctx(), &sig).unwrap();
let stored = sk.to_bytes();
let _again = arcanum::sign::SigningKey::from_bytes(stored.as_slice()).unwrap();
let kem = arcanum::xwing::SecretKey::generate(&mut rng);
let b = arcanum::sign::bind_kem_key(&sk, b"id", kem.public_key(), (1, 2), &mut rng).unwrap();
arcanum::sign::verify_binding(&vk, b"id", kem.public_key(), (1, 2), 1, &b).unwrap();
"#,
);
assert!(ok, "the control program must compile, or the harness is blind:\n{err}");
}
/// Like QA A-33: randomness must be `CryptoRng`; a counter is refused everywhere it enters.
#[test]
fn a_non_crypto_rng_does_not_compile() {
let calls = [
("SigningKey::generate", "let _ = arcanum::sign::SigningKey::generate(&mut Counter(0));"),
("SigningKey::sign", "let _ = key().sign(b\"m\", &ctx(), &mut Counter(0));"),
(
"bind_kem_key",
"let kem = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap(); \
let _ = arcanum::sign::bind_kem_key(&key(), b\"id\", kem.public_key(), (1, 2), &mut Counter(0));",
),
];
for (what, body) in calls {
assert_refused(what, body, &["CryptoRng"]);
}
}
/// Like QA A-34: the raw RFC 10073 interface (any ctx, including empty) is `hazmat` only.
#[test]
fn the_raw_interface_is_not_reachable_without_hazmat() {
let calls = [
(
"sign_composite_raw",
"let _ = arcanum::sign::sign_composite_raw(&key(), b\"m\", b\"\", &mut Claimed(Counter(0)));",
),
(
"verify_composite_raw",
"let k = key(); let s = k.sign(b\"m\", &ctx(), &mut Claimed(Counter(0))).unwrap(); \
let _ = arcanum::sign::verify_composite_raw(k.verifying_key(), b\"m\", b\"\", &s);",
),
];
for (what, body) in calls {
assert_refused(what, body, &["E0425"]);
}
}
/// `ml-dsa` 0.1.2 makes `ExpandedSigningKey::sign_internal` (caller-chosen randomness) and
/// `sign_mu_deterministic` (panics on failure) public, and its `Signer` trait signs with an
/// empty context. None may be reachable through Arcanum: no re-export, no public field, no
/// `Deref`/`AsRef` to the component keys, and an `AppContext` only from the Arcanum prefix.
#[test]
fn ml_dsa_internals_are_not_reachable() {
let calls: [(&str, &str, &[&str]); 9] = [
("re-export of ml_dsa", "use arcanum::ml_dsa;", &["E0432"]),
("re-export in sign", "use arcanum::sign::ml_dsa;", &["E0432"]),
("sign_internal through the key", "let _ = key().sign_internal(&[b\"m\"], &Default::default());", &["E0599"]),
(
"sign_mu_deterministic through the key",
"let _ = key().sign_mu_deterministic(&Default::default());",
&["E0599"],
),
("sign_deterministic through the key", "let _ = key().sign_deterministic(b\"m\", b\"\");", &["E0599"]),
("a component key field", "let k = key(); let _ = &k.ml;", &["E0609", "E0616"]),
("a foreign or empty context", "let _ = arcanum::sign::AppContext::from_raw(b\"\");", &["E0599"]),
("cloning a signing key", "let k = key(); let _ = k.clone();", &["E0599"]),
(
"a label built at run time (QA S-09)",
"let l = std::env::args().next().unwrap().into_bytes(); let _ = arcanum::sign::AppContext::new(&l);",
&["E0597", "E0716"],
),
];
for (what, body, needles) in calls {
assert_refused(what, body, needles);
}
}
fn assert_zeroize_on_drop<T: ZeroizeOnDrop + ?Sized>() {}
#[test]
fn secret_types_are_zeroize_on_drop() {
assert_zeroize_on_drop::<SigningKey>();
// The component keys Arcanum holds: these bounds hold only with each crate's `zeroize` feature.
assert_zeroize_on_drop::<ml_dsa::ExpandedSigningKey<ml_dsa::MlDsa65>>();
assert_zeroize_on_drop::<ml_dsa::SigningKey<ml_dsa::MlDsa65>>();
assert_zeroize_on_drop::<ed25519_dalek::SigningKey>();
}
#[test]
fn debug_never_prints_key_material() {
let sk = SigningKey::from_bytes(&[0xab; 64]).unwrap();
let dbg = format!("{sk:?}");
assert!(!dbg.contains("ab, ab") && !dbg.contains("abab") && !dbg.contains("171"), "{dbg}");
let seeds = sk.to_bytes();
assert_eq!(seeds.as_slice(), [0xab; 64].as_slice());
let ctx = AppContext::new(b"debug").unwrap();
let sig = sk.sign(b"m", &ctx, &mut rng(70)).unwrap();
let _ = format!("{sig:?} {:?} {ctx:?}", sk.verifying_key());
}
+215
View File
@@ -0,0 +1,215 @@
//! Mandatory test 6 (v0.2.0): malformed signature input gives typed errors, never a panic.
//! Wrong lengths, weak and non-canonical Ed25519 keys, contexts of 0 and 256 bytes, an over-long
//! key id, random bytes. The same entry points are fuzzed by fuzz/fuzz_targets/signatures.rs.
mod common;
use arcanum::sign::{
self, AppContext, MAX_APP_LABEL_LEN, SIGNATURE_LEN, SIGNING_KEY_LEN, Signature, SigningKey, VERIFYING_KEY_LEN,
VerifyingKey,
};
use arcanum::{Error, Input, xwing};
use common::{hex, rng};
use rand_core::Rng;
const LENGTHS: [usize; 14] = [0, 1, 31, 32, 33, 63, 64, 65, 1952, 1983, 1985, 3309, 3372, 3374];
#[test]
fn wrong_lengths_are_typed_errors() {
for len in LENGTHS {
let b = vec![0u8; len];
if len != VERIFYING_KEY_LEN {
assert_eq!(
VerifyingKey::from_bytes(&b).unwrap_err(),
Error::InvalidLength { input: Input::VerifyingKey, expected: VERIFYING_KEY_LEN, actual: len }
);
}
if len != SIGNATURE_LEN {
assert_eq!(
Signature::from_bytes(&b).unwrap_err(),
Error::InvalidLength { input: Input::Signature, expected: SIGNATURE_LEN, actual: len }
);
}
if len != SIGNING_KEY_LEN {
assert_eq!(
SigningKey::from_bytes(&b).unwrap_err(),
Error::InvalidLength { input: Input::SigningKey, expected: SIGNING_KEY_LEN, actual: len }
);
}
}
assert!(SigningKey::from_bytes(&[7u8; SIGNING_KEY_LEN]).is_ok(), "any two 32-byte seeds are a key");
assert!(Signature::from_bytes(&[0u8; SIGNATURE_LEN]).is_ok(), "any 3373 bytes parse; verify decides");
}
/// The small-order points of edwards25519 (the 8-torsion), canonical and non-canonical
/// encodings, and encodings of y >= p. All must be refused as an Ed25519 half.
const WEAK_OR_NON_CANONICAL: [&str; 10] = [
"0100000000000000000000000000000000000000000000000000000000000000", // identity
"ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", // order 2
"0000000000000000000000000000000000000000000000000000000000000000", // order 4
"0000000000000000000000000000000000000000000000000000000000000080", // order 4
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05", // order 8
"26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85", // order 8
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a", // order 8
"c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa", // order 8
"0100000000000000000000000000000000000000000000000000000000000080", // identity, sign bit set
"eeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", // y = p + 1 (non-canonical 1)
];
fn with_ed_half(base: &[u8; VERIFYING_KEY_LEN], ed: &[u8]) -> [u8; VERIFYING_KEY_LEN] {
let mut b = *base;
b[VERIFYING_KEY_LEN - 32..].copy_from_slice(ed);
b
}
#[test]
fn weak_and_non_canonical_ed25519_keys_are_refused() {
let base = *SigningKey::generate(&mut rng(60)).verifying_key().as_bytes();
for h in WEAK_OR_NON_CANONICAL {
let b = with_ed_half(&base, &hex(h));
assert_eq!(VerifyingKey::from_bytes(&b).unwrap_err(), Error::InvalidVerifyingKey, "{h}");
}
// Every y >= p (19 values, sign bit clear and set) is a non-canonical encoding.
for low in 0xedu8..=0xff {
for top in [0x7f, 0xff] {
let mut e = [0xffu8; 32];
e[0] = low;
e[31] = top;
assert_eq!(VerifyingKey::from_bytes(&with_ed_half(&base, &e)).unwrap_err(), Error::InvalidVerifyingKey);
}
}
// An honest key with its sign bit flipped is another valid point: it parses, but cannot verify.
let sk = SigningKey::generate(&mut rng(61));
let c = AppContext::new(b"t").unwrap();
let sig = sk.sign(b"m", &c, &mut rng(62)).unwrap();
let mut b = *sk.verifying_key().as_bytes();
b[VERIFYING_KEY_LEN - 1] ^= 0x80;
if let Ok(vk) = VerifyingKey::from_bytes(&b) {
assert_eq!(vk.verify(b"m", &c, &sig), Err(Error::InvalidSignature));
}
}
#[test]
fn contexts_of_the_wrong_length_are_typed_errors() {
let sk = SigningKey::generate(&mut rng(63));
let vk = sk.verifying_key();
assert_eq!(MAX_APP_LABEL_LEN, 255 - b"domi/arcanum/v2/sig/app/".len());
assert!(AppContext::new(&[b'x'; MAX_APP_LABEL_LEN]).is_ok());
assert_eq!(AppContext::new(&[b'x'; MAX_APP_LABEL_LEN]).unwrap().as_bytes().len(), 255);
assert_eq!(
AppContext::new(&[b'x'; MAX_APP_LABEL_LEN + 1]).unwrap_err(),
Error::TooLong { input: Input::Context, maximum: MAX_APP_LABEL_LEN, actual: MAX_APP_LABEL_LEN + 1 }
);
assert_eq!(AppContext::new(b"").unwrap_err(), Error::TooShort { input: Input::Context, minimum: 1, actual: 0 });
// QA S-09: the constructor is a `const fn`, so a bad label can fail the consumer's build.
const OK: Result<AppContext, Error> = AppContext::new(b"const");
const EMPTY: Result<AppContext, Error> = AppContext::new(b"");
assert_eq!(OK.unwrap().as_bytes(), b"domi/arcanum/v2/sig/app/const");
assert!(EMPTY.is_err());
// The raw RFC interface: 255 bytes is the most, 256 is a typed error (sign and verify).
let sig = sign::sign_composite_raw(&sk, b"m", &[1; 255], &mut rng(64)).unwrap();
assert_eq!(sign::verify_composite_raw(vk, b"m", &[1; 255], &sig), Ok(()));
let too_long = Error::TooLong { input: Input::Context, maximum: 255, actual: 256 };
assert_eq!(sign::sign_composite_raw(&sk, b"m", &[1; 256], &mut rng(65)).unwrap_err(), too_long);
assert_eq!(sign::verify_composite_raw(vk, b"m", &[1; 256], &sig), Err(too_long));
}
#[test]
fn an_over_long_key_id_is_a_typed_error() {
let mut r = rng(66);
let sk = SigningKey::generate(&mut r);
let kem = xwing::SecretKey::generate(&mut r);
let id = vec![0u8; 65_536];
let err = Error::TooLong { input: Input::KeyId, maximum: 65_535, actual: 65_536 };
assert_eq!(sign::bind_kem_key(&sk, &id, kem.public_key(), (0, 1), &mut r), Err(err.clone()));
let sig = sign::bind_kem_key(&sk, &id[..65_535], kem.public_key(), (0, 1), &mut r).unwrap();
assert_eq!(sign::verify_binding(sk.verifying_key(), &id[..65_535], kem.public_key(), (0, 1), 0, &sig), Ok(()));
assert_eq!(sign::verify_binding(sk.verifying_key(), &id, kem.public_key(), (0, 1), 0, &sig), Err(err));
// The empty id is allowed (a key bound to "no name" is still bound to this signer).
let sig = sign::bind_kem_key(&sk, b"", kem.public_key(), (0, 1), &mut r).unwrap();
assert_eq!(sign::verify_binding(sk.verifying_key(), b"", kem.public_key(), (0, 1), 1, &sig), Ok(()));
}
#[test]
fn random_bytes_never_panic() {
let mut r = rng(67);
let sk = SigningKey::generate(&mut r);
let c = AppContext::new(b"random").unwrap();
let good = sk.sign(b"m", &c, &mut r).unwrap();
let kem = xwing::SecretKey::generate(&mut r);
for round in 0..256 {
let len = [VERIFYING_KEY_LEN, SIGNATURE_LEN, SIGNING_KEY_LEN, 0, 17][round % 5];
let mut buf = vec![0u8; len];
r.fill_bytes(&mut buf);
if let Ok(vk) = VerifyingKey::from_bytes(&buf) {
assert!(vk.verify(b"m", &c, &good).is_err());
assert!(sign::verify_binding(&vk, b"id", kem.public_key(), (0, 9), 1, &good).is_err());
}
if let Ok(sig) = Signature::from_bytes(&buf) {
assert_eq!(sk.verifying_key().verify(b"m", &c, &sig), Err(Error::InvalidSignature));
let _ = sign::verify_composite_raw(sk.verifying_key(), &buf, &buf[..len.min(255)], &sig);
}
if let Ok(k) = SigningKey::from_bytes(&buf) {
let sig = k.sign(&buf, &c, &mut r).unwrap();
assert_eq!(k.verifying_key().verify(&buf, &c, &sig), Ok(()));
}
}
}
/// QA S-05 (their `qa_s07`, inverted): an ML-DSA-65 public key with t1 = 0 is the ML-DSA analogue
/// of a weak Ed25519 key. The component crate accepts it, and its ML-DSA half can be computed by
/// anyone, with no secret (s1 = s2 = t0 = 0); Arcanum refuses the key at parse.
#[test]
#[allow(deprecated)]
fn an_ml_dsa_key_with_zero_t1_is_refused() {
use ml_dsa::common::array::Array;
use shake::Update as _;
let rho = [0x5au8; 32];
let mut ml_pk = rho.to_vec();
ml_pk.extend_from_slice(&[0u8; 1920]); // t1 = 0
let ed = ed25519_dalek::SigningKey::from_bytes(&[0x22; 32]); // a throwaway Ed25519 key
let mut pk = ml_pk.clone();
pk.extend_from_slice(ed.verifying_key().as_bytes());
assert_eq!(VerifyingKey::from_bytes(&pk).unwrap_err(), Error::InvalidVerifyingKey);
// Control: one non-zero t1 byte, anywhere, and the key parses.
for i in [32, 1000, 1951] {
let mut p = pk.clone();
p[i] = 1;
assert!(VerifyingKey::from_bytes(&p).is_ok(), "t1 byte {i} set");
}
// rho alone may be anything, including zero: only t1 = 0 is weak.
let mut p = pk.clone();
p[..32].fill(0);
p[100] = 1;
assert!(VerifyingKey::from_bytes(&p).is_ok());
// Why: with the component crate alone, a secret-free key signs for this public key. The expanded
// key packs eta - 0 = 4 into 4 bits (0x44 per byte) for s1 and s2, and 2^12 - 0 into 13 bits for
// t0; K is public (zero) and tr is unused by sign_mu.
let mut sk = rho.to_vec();
sk.extend_from_slice(&[0u8; 32 + 64]);
sk.extend(std::iter::repeat_n(0x44u8, 640 + 768));
let mut t0 = vec![0u8; 2496];
for i in 0..(6 * 256) {
let bit = 13 * i + 12;
t0[bit / 8] |= 1 << (bit % 8);
}
sk.extend_from_slice(&t0);
assert_eq!(sk.len(), 4032);
let ml_sk = ml_dsa::ExpandedSigningKey::<ml_dsa::MlDsa65>::from_expanded(&Array::try_from(sk.as_slice()).unwrap());
let ml_vk = ml_dsa::VerifyingKey::<ml_dsa::MlDsa65>::decode(&Array::try_from(ml_pk.as_slice()).unwrap());
let mu = ml_vk
.compute_mu(
|h| {
h.update(b"any message at all");
Ok(())
},
b"",
)
.unwrap();
let half = ml_sk.sign_mu_randomized(&mu, &mut rng(68)).unwrap();
assert!(ml_vk.verify_mu(&mu, &half), "the component crate accepts a secret-free signature");
}
+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);
}
+74
View File
@@ -0,0 +1,74 @@
# Known-answer vector sources
Every v0.1.0 file here is kept byte-for-byte as published; v0.2.0 adds three subsets and one
extraction, each made by a script in this folder (below). `.gitattributes` marks the folder `-text`.
The tests check each file's sha256 before using it, so a changed file fails the test instead of
silently changing what is verified. Fetched 2026-11-25.
| File | sha256 | Source |
|:--|:--|:--|
| `acvp-ml-kem-keyGen-FIPS203-internalProjection.json` | `d7a62a2c3476957f56dd8d24f9004ea6776ccfe995ffe71a65bb9506dc9c7b1b` | NIST ACVP-Server, `gen-val/json-files/ML-KEM-keyGen-FIPS203/internalProjection.json` at commit `975de31eb83d87039ec88934fdc47d8c312b892d` (2026-08-12). Git blob `99973426c8dd03f227ace6d7ac917ba4443e2f27` matches the GitHub API listing. |
| `acvp-ml-kem-encapDecap-FIPS203-internalProjection.json` | `a556952ce869bb89c3a3196a701dad89647c193a34c86eafb61a9d710d5b810f` | NIST ACVP-Server, `gen-val/json-files/ML-KEM-encapDecap-FIPS203/internalProjection.json` at the same commit. Git blob `73692fe52abe2f937b7884baa46475c77c68a1d3` matches. |
| `xwing-test-vectors.json` | `409efe197550b22985b4a0419418a0c5f2c2b193426c55bd998399ec8d3e614d` | The X-Wing draft authors' repository, `dconnolly/draft-connolly-cfrg-xwing-kem`, `spec/test-vectors.json` at commit `984c2f7a93b8f8d8f8073ebb53f9f4ce50b5babd` (2026-09-23, the day draft -11 was posted). The same three vectors are in Appendix C of draft -11 (spot-checked: seed and ss of vectors 1–2, ss of vector 3), and, pretty-printed, in RustCrypto `x-wing` 0.1.1 `tests/test-vectors.json` (identical after removing whitespace). |
URLs:
- <https://github.com/usnistgov/ACVP-Server/tree/975de31eb83d87039ec88934fdc47d8c312b892d/gen-val/json-files>
- <https://github.com/dconnolly/draft-connolly-cfrg-xwing-kem/blob/984c2f7a93b8f8d8f8073ebb53f9f4ce50b5babd/spec/test-vectors.json>
- <https://www.ietf.org/archive/id/draft-connolly-cfrg-xwing-kem-11.txt>, Appendix C
Only the ML-KEM-768 groups of the ACVP files are used (the files also hold 512 and 1024).
## v0.2.0: signatures (ML-DSA-65, Ed25519, the RFC 10073 composite)
Fetched 2026-11-25 with curl from `raw.githubusercontent.com` (RFC 8032 from `www.rfc-editor.org`),
each into its own empty directory, and handled as data. Every git blob id below matches the GitHub
API tree listing of the named commit. The tests check the sha256 of the file **in this folder**.
**Kept whole, byte for byte** (each under about 1 MB):
| File | sha256 (= the original) | Source |
|:--|:--|:--|
| `acvp-ml-dsa-keyGen-FIPS204-internalProjection.json` | `e67ee6540d40e11506c3c4e3b1f79fc1cefcd49820db99fc61f87cc8ba463baf` | NIST ACVP-Server `gen-val/json-files/ML-DSA-keyGen-FIPS204/internalProjection.json` at `2972def23bf9f3680c2c531561ed9bdd0f1086ad` (2026-07-20); 882,437 bytes, blob `ebf2104da140b725675aea4cc47676c0536421f7` |
| `wycheproof-ed25519_test.json` | `752d2ea7d7c6cf4736381b6cbacb61f8182b126ab7cd9b058f00c50084975536` | C2SP Wycheproof `testvectors_v1/ed25519_test.json` at `20b256949ea8f21a11375619b1825027ca0668bd` (2026-10-12); 126,699 bytes, blob `42d44cd7eca6003c7de611b6487c9cc57a124b38` |
| `wycheproof-mldsa_65_sign_seed_test.json` | `e26b2bb9ab8d45ed570ba6828c7e40b6fa3e1545bb8bc2c449c77531760133e0` | Wycheproof `testvectors_v1/mldsa_65_sign_seed_test.json` at the same commit; 886,331 bytes, blob `ff302e20c0b847e66fdcc7444cd63fc1cd7bf634` |
**Reduced subsets** (the original is larger than about 1 MB, or holds other algorithms). Made by
`make_subsets.py` in this folder, which refuses an original whose sha256 is not the one below,
keeps every selected test case and group header unchanged (whole cases and whole groups are
dropped, never fields), and writes two-space-indented JSON with LF endings; two runs gave identical
bytes. Command: `python -I make_subsets.py --acvp-siggen ... --acvp-sigver ... --wycheproof-mldsa-verify ... --composite ... --out .`
| File here (sha256) | Original (sha256, size, blob) | Selection |
|:--|:--|:--|
| `acvp-ml-dsa-sigGen-FIPS204-internalProjection.subset.json` (`ca1f1697d78b2280d854bbe0f8e86d3601695013f14e7bb4ce0604bc80ed2b4e`) | ACVP-Server `gen-val/json-files/ML-DSA-sigGen-FIPS204/internalProjection.json` at `2972def23bf9f3680c2c531561ed9bdd0f1086ad`: `72dcaf5f69853ca267ccd16af9cb40949786aca0fcfbf05d1ebeba132b93af22`, 8,971,659 bytes, blob `c090942249958e2071d56bf458b19e31256ded3e` | ML-DSA-65 groups without HashML-DSA (`preHash`): tgId 3, 9, 10 (deterministic) and 15, 21, 22 (hedged, with `rnd`); the first 3 cases of each by tcId (31-33, 121-123, 136-138, 211-213, 301-303, 316-318), 18 cases |
| `acvp-ml-dsa-sigVer-FIPS204-internalProjection.subset.json` (`d005dfeee9039f751299a6430fdac509b97ad9ab7d25b0b502dc9a2b59b7fb0c`) | ACVP-Server `gen-val/json-files/ML-DSA-sigVer-FIPS204/internalProjection.json` at **`a7f283cdc87d2d6dd93c1bac59e5622c5f9f8324`** (2026-07-31, after the ModifyZ correction): `47cdd6314c7f746d02421ffcba89d4dbc7bb875ac49e07a029fdfc26fba55437`, 4,533,178 bytes, blob `4c8caf12220e44dfa711fefe20e0285aaad844be` | ML-DSA-65 groups without `preHash`: tgId 3, 9, 10; the first case of each (testPassed, reason) pair, so one valid case and one of each of the four modifications (message, commitment, z, hint) per group, 15 cases |
| `wycheproof-mldsa_65_verify_test.subset.json` (`47fc788c0913dc41cfd0ef5bc9ed44c779a6bdeeb8b3700077fd572527c33870`) | Wycheproof `testvectors_v1/mldsa_65_verify_test.json` at `20b256949ea8f21a11375619b1825027ca0668bd`: `1ca235f61928421a173a171780beb00264ae9155dc33c52a11e1766cc7979034`, 1,664,284 bytes, blob `fa871a3c8c76b0cf871879243ad34fa2cbd79000` | All 25 groups; in each, at most 4 cases per (result, set of flags), first by tcId: 70 of 210 cases, every flag kept (most of the dropped ones are 40 `ManySteps` valid signatures and 44 `InfinityNormViolation` cases); `numberOfTests` is updated to 70 |
| `composite-sigs-testvectors-MLDSA65-Ed25519.subset.json` (`33311f63d2c5a21d5dd4b05eb864de38bd7572108b38de713a40312d2b893b34`) | `lamps-wg/draft-composite-sigs` `src/testvectors.json` at `f0627ab34acfe1aee0abce4bee91ed2b577eab76` (2026-01-07): `a60f697f9fd94c3cd5e4501a40c4396d9a9ffc7cf0f8a1ddd87dedbb46a7abf0`, 491,883 bytes, blob `eac3df25ca915882d3bcb3062835555787b02f5a` | The top-level `m` and `ctx`, and only the `tcId = "id-MLDSA65-Ed25519-SHA512"` entry of `tests` (unchanged, with its `x5c`) |
**Extracted from a text RFC** by `extract_rfc8032.py` in this folder (it checks the RFC's sha256,
skips page breaks, joins the hex lines and checks each stated length):
| File here (sha256) | Original | Selection |
|:--|:--|:--|
| `rfc8032-7.1-ed25519.json` (`fad8e499cdc3e0324a5b4a93cdbabb33f8aed1df73ecacfdb364f433b0fdf12b`) | <https://www.rfc-editor.org/rfc/rfc8032.txt>: `ed63657ff389301282b169b0abde9b5dd2c7e4d524fdfa5da6ff3094fc93c4c3`, 103,210 bytes | §7.1, the five Ed25519 vectors: TEST 1, 2, 3, 1024 and SHA(abc) |
URLs, with `<commit>` as in the tables:
- `https://raw.githubusercontent.com/usnistgov/ACVP-Server/<commit>/gen-val/json-files/ML-DSA-{keyGen,sigGen,sigVer}-FIPS204/internalProjection.json`
- `https://raw.githubusercontent.com/C2SP/wycheproof/<commit>/testvectors_v1/{ed25519_test,mldsa_65_sign_seed_test,mldsa_65_verify_test}.json`
- `https://raw.githubusercontent.com/lamps-wg/draft-composite-sigs/<commit>/src/testvectors.json`
Not used: the HashML-DSA (`preHash`) groups (Arcanum signs pure ML-DSA only); the ML-DSA-44 and
ML-DSA-87 groups; the full sigGen/sigVer/verify files (their sha256 above lets anyone check the
subsets against them by rerunning the script).
## Vectors kept in test source
| Test | Source |
|:--|:--|
| X25519 scalar multiplication, two vectors (RFC 7748 §5.2) | RFC 7748, <https://www.rfc-editor.org/rfc/rfc7748.txt>; the same bytes are in `x25519-dalek` 3.0.0 `tests/x25519_tests.rs` |
| X25519 iterated, 1 and 1,000 iterations (RFC 7748 §5.2) | RFC 7748 §5.2 |
| X25519 Diffie–Hellman, Alice and Bob (RFC 7748 §6.1) | RFC 7748 §6.1; also in `x25519-dalek` 3.0.0 `tests/x25519_tests.rs` |
Not run: the RFC 7748 1,000,000-iteration vector (minutes in a debug build).
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+73
View File
@@ -0,0 +1,73 @@
"""Extract the five Ed25519 test vectors of RFC 8032 section 7.1 into JSON.
Usage: python -I extract_rfc8032.py PATH/rfc8032.txt OUT.json
PATH/rfc8032.txt is https://www.rfc-editor.org/rfc/rfc8032.txt, unchanged (its sha256 is pinned
below and in SOURCES.md). Page breaks are skipped; every hex field is joined as printed, and the
message length is checked against the "(length N bytes)" the RFC states.
"""
import hashlib
import json
import re
import sys
PINNED = "ed63657ff389301282b169b0abde9b5dd2c7e4d524fdfa5da6ff3094fc93c4c3"
FIELDS = {"SECRET KEY:": "secret_key", "PUBLIC KEY:": "public_key", "SIGNATURE:": "signature"}
def main():
src, out = sys.argv[1], sys.argv[2]
raw = open(src, "rb").read()
got = hashlib.sha256(raw).hexdigest()
if got != PINNED:
raise SystemExit(f"{src}: sha256 {got} is not the pinned {PINNED}")
lines = raw.decode("ascii").splitlines()
start = lines.index("7.1. Test Vectors for Ed25519")
end = lines.index("7.2. Test Vectors for Ed25519ctx")
tests, cur, field, declared = [], None, None, None
for line in lines[start:end]:
s = line.strip()
if s.startswith("Josefsson & Liusvaara") or s.startswith("RFC 8032 ") or s == "\f" or s == "":
continue
if s.startswith("-----TEST "):
cur = {"name": s[len("-----TEST "):], "secret_key": "", "public_key": "", "message": "",
"signature": ""}
tests.append(cur)
field = None
continue
if cur is None or s == "-----":
continue
m = re.fullmatch(r"MESSAGE \(length (\d+) bytes?\):", s)
if m:
field, declared = "message", int(m.group(1))
cur["_declared"] = declared
continue
if s in FIELDS:
field = FIELDS[s]
continue
if s in ("ALGORITHM:", "Ed25519"):
field = None
continue
if field and re.fullmatch(r"[0-9a-f]+", s):
cur[field] += s
continue
raise SystemExit(f"unexpected line in section 7.1: {line!r}")
for t in tests:
n = t.pop("_declared")
if len(t["message"]) != 2 * n:
raise SystemExit(f"TEST {t['name']}: message is {len(t['message']) // 2} bytes, RFC says {n}")
for k, size in (("secret_key", 32), ("public_key", 32), ("signature", 64)):
if len(t[k]) != 2 * size:
raise SystemExit(f"TEST {t['name']}: {k} is not {size} bytes")
if [t["name"] for t in tests] != ["1", "2", "3", "1024", "SHA(abc)"]:
raise SystemExit(f"unexpected tests: {[t['name'] for t in tests]}")
doc = {"source": "RFC 8032 section 7.1, https://www.rfc-editor.org/rfc/rfc8032.txt", "tests": tests}
with open(out, "w", encoding="utf-8", newline="\n") as f:
json.dump(doc, f, indent=2)
f.write("\n")
print(f"{out}: {len(tests)} vectors")
if __name__ == "__main__":
main()
+131
View File
@@ -0,0 +1,131 @@
"""Reduce the large official vector files to the subsets kept in this folder.
Usage (each argument is the path to the ORIGINAL file, downloaded unchanged from the URL and
commit listed in SOURCES.md):
python -I make_subsets.py --acvp-siggen PATH --acvp-sigver PATH \
--wycheproof-mldsa-verify PATH --composite PATH --out DIR
The script refuses an original whose sha256 is not the pinned one, keeps every field of every
test case it selects unchanged (only whole test cases and whole groups are dropped), and writes
JSON with two-space indentation and LF line endings. Running it twice gives identical bytes.
"""
import argparse
import collections
import hashlib
import json
import os
PINNED = {
"acvp_siggen": "72dcaf5f69853ca267ccd16af9cb40949786aca0fcfbf05d1ebeba132b93af22",
"acvp_sigver": "47cdd6314c7f746d02421ffcba89d4dbc7bb875ac49e07a029fdfc26fba55437",
"wycheproof_mldsa_verify": "1ca235f61928421a173a171780beb00264ae9155dc33c52a11e1766cc7979034",
"composite": "a60f697f9fd94c3cd5e4501a40c4396d9a9ffc7cf0f8a1ddd87dedbb46a7abf0",
}
# ACVP sigGen: ML-DSA-65 only, no HashML-DSA (preHash) groups, the first N cases of each group.
SIGGEN_PER_GROUP = 3
# Wycheproof verify: per group, at most N cases for each (result, set of flags).
WYCHEPROOF_PER_KIND = 4
COMPOSITE_ENTRY = "id-MLDSA65-Ed25519-SHA512"
def load(path, key):
with open(path, "rb") as f:
raw = f.read()
got = hashlib.sha256(raw).hexdigest()
if got != PINNED[key]:
raise SystemExit(f"{path}: sha256 {got} is not the pinned {PINNED[key]}")
return json.loads(raw.decode("utf-8"))
def write(out_dir, name, obj):
path = os.path.join(out_dir, name)
with open(path, "w", encoding="utf-8", newline="\n") as f:
json.dump(obj, f, indent=2, ensure_ascii=False)
f.write("\n")
n = sum(len(g["tests"]) for g in obj["testGroups"]) if "testGroups" in obj else len(obj["tests"])
print(f"{name}: {n} cases")
def acvp_siggen(d):
groups = []
for g in d["testGroups"]:
if g["parameterSet"] != "ML-DSA-65" or g["preHash"] == "preHash":
continue
g = dict(g)
g["tests"] = sorted(g["tests"], key=lambda t: t["tcId"])[:SIGGEN_PER_GROUP]
groups.append(g)
d = dict(d)
d["testGroups"] = groups
return d
def acvp_sigver(d):
# One case for each (testPassed, reason) in each ML-DSA-65 non-preHash group.
groups = []
for g in d["testGroups"]:
if g["parameterSet"] != "ML-DSA-65" or g["preHash"] == "preHash":
continue
seen = set()
kept = []
for t in sorted(g["tests"], key=lambda t: t["tcId"]):
kind = (t["testPassed"], t.get("reason"))
if kind not in seen:
seen.add(kind)
kept.append(t)
g = dict(g)
g["tests"] = kept
groups.append(g)
d = dict(d)
d["testGroups"] = groups
return d
def wycheproof_verify(d):
groups = []
for g in d["testGroups"]:
count = collections.Counter()
kept = []
for t in sorted(g["tests"], key=lambda t: t["tcId"]):
kind = (t["result"], frozenset(t.get("flags", [])))
if count[kind] < WYCHEPROOF_PER_KIND:
count[kind] += 1
kept.append(t)
g = dict(g)
g["tests"] = kept
groups.append(g)
d = dict(d)
d["testGroups"] = groups
d["numberOfTests"] = sum(len(g["tests"]) for g in groups)
return d
def composite(d):
entries = [t for t in d["tests"] if t["tcId"] == COMPOSITE_ENTRY]
if len(entries) != 1:
raise SystemExit(f"expected exactly one {COMPOSITE_ENTRY} entry, found {len(entries)}")
return {"m": d["m"], "ctx": d["ctx"], "tests": entries}
def main():
p = argparse.ArgumentParser()
p.add_argument("--acvp-siggen", required=True)
p.add_argument("--acvp-sigver", required=True)
p.add_argument("--wycheproof-mldsa-verify", required=True)
p.add_argument("--composite", required=True)
p.add_argument("--out", required=True)
a = p.parse_args()
write(a.out, "acvp-ml-dsa-sigGen-FIPS204-internalProjection.subset.json",
acvp_siggen(load(a.acvp_siggen, "acvp_siggen")))
write(a.out, "acvp-ml-dsa-sigVer-FIPS204-internalProjection.subset.json",
acvp_sigver(load(a.acvp_sigver, "acvp_sigver")))
write(a.out, "wycheproof-mldsa_65_verify_test.subset.json",
wycheproof_verify(load(a.wycheproof_mldsa_verify, "wycheproof_mldsa_verify")))
write(a.out, "composite-sigs-testvectors-MLDSA65-Ed25519.subset.json",
composite(load(a.composite, "composite")))
if __name__ == "__main__":
main()
+40
View File
@@ -0,0 +1,40 @@
{
"source": "RFC 8032 section 7.1, https://www.rfc-editor.org/rfc/rfc8032.txt",
"tests": [
{
"name": "1",
"secret_key": "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
"public_key": "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a",
"message": "",
"signature": "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"
},
{
"name": "2",
"secret_key": "4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb",
"public_key": "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c",
"message": "72",
"signature": "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"
},
{
"name": "3",
"secret_key": "c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7",
"public_key": "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025",
"message": "af82",
"signature": "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a"
},
{
"name": "1024",
"secret_key": "f5e5767cf153319517630f226876b86c8160cc583bc013744c6bf255f5cc0ee5",
"public_key": "278117fc144c72340f67d0f2316e8386ceffbf2b2428c9c51fef7c597f1d426e",
"message": "08b8b2b733424243760fe426a4b54908632110a66c2f6591eabd3345e3e4eb98fa6e264bf09efe12ee50f8f54e9f77b1e355f6c50544e23fb1433ddf73be84d879de7c0046dc4996d9e773f4bc9efe5738829adb26c81b37c93a1b270b20329d658675fc6ea534e0810a4432826bf58c941efb65d57a338bbd2e26640f89ffbc1a858efcb8550ee3a5e1998bd177e93a7363c344fe6b199ee5d02e82d522c4feba15452f80288a821a579116ec6dad2b3b310da903401aa62100ab5d1a36553e06203b33890cc9b832f79ef80560ccb9a39ce767967ed628c6ad573cb116dbefefd75499da96bd68a8a97b928a8bbc103b6621fcde2beca1231d206be6cd9ec7aff6f6c94fcd7204ed3455c68c83f4a41da4af2b74ef5c53f1d8ac70bdcb7ed185ce81bd84359d44254d95629e9855a94a7c1958d1f8ada5d0532ed8a5aa3fb2d17ba70eb6248e594e1a2297acbbb39d502f1a8c6eb6f1ce22b3de1a1f40cc24554119a831a9aad6079cad88425de6bde1a9187ebb6092cf67bf2b13fd65f27088d78b7e883c8759d2c4f5c65adb7553878ad575f9fad878e80a0c9ba63bcbcc2732e69485bbc9c90bfbd62481d9089beccf80cfe2df16a2cf65bd92dd597b0707e0917af48bbb75fed413d238f5555a7a569d80c3414a8d0859dc65a46128bab27af87a71314f318c782b23ebfe808b82b0ce26401d2e22f04d83d1255dc51addd3b75a2b1ae0784504df543af8969be3ea7082ff7fc9888c144da2af58429ec96031dbcad3dad9af0dcbaaaf268cb8fcffead94f3c7ca495e056a9b47acdb751fb73e666c6c655ade8297297d07ad1ba5e43f1bca32301651339e22904cc8c42f58c30c04aafdb038dda0847dd988dcda6f3bfd15c4b4c4525004aa06eeff8ca61783aacec57fb3d1f92b0fe2fd1a85f6724517b65e614ad6808d6f6ee34dff7310fdc82aebfd904b01e1dc54b2927094b2db68d6f903b68401adebf5a7e08d78ff4ef5d63653a65040cf9bfd4aca7984a74d37145986780fc0b16ac451649de6188a7dbdf191f64b5fc5e2ab47b57f7f7276cd419c17a3ca8e1b939ae49e488acba6b965610b5480109c8b17b80e1b7b750dfc7598d5d5011fd2dcc5600a32ef5b52a1ecc820e308aa342721aac0943bf6686b64b2579376504ccc493d97e6aed3fb0f9cd71a43dd497f01f17c0e2cb3797aa2a2f256656168e6c496afc5fb93246f6b1116398a346f1a641f3b041e989f7914f90cc2c7fff357876e506b50d334ba77c225bc307ba537152f3f1610e4eafe595f6d9d90d11faa933a15ef1369546868a7f3a45a96768d40fd9d03412c091c6315cf4fde7cb68606937380db2eaaa707b4c4185c32eddcdd306705e4dc1ffc872eeee475a64dfac86aba41c0618983f8741c5ef68d3a101e8a3b8cac60c905c15fc910840b94c00a0b9d0",
"signature": "0aab4c900501b3e24d7cdf4663326a3a87df5e4843b2cbdb67cbf6e460fec350aa5371b1508f9f4528ecea23c436d94b5e8fcd4f681e30a6ac00a9704a188a03"
},
{
"name": "SHA(abc)",
"secret_key": "833fe62409237b9d62ec77587520911e9a759cec1d19755b7da901b96dca3d42",
"public_key": "ec172b93ad5e563bf4932c70e1245034c35467ef2efd4d64ebf819683467e2bf",
"message": "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
"signature": "dc2a4459e7369633a52b1bf277839a00201009a3efbf3ecb69bea2186c26b58909351fc9ac90b3ecfdfbc7c66431e0303dca179c138ac17ad9bef1177331a704"
}
]
}
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+531
View File
@@ -0,0 +1,531 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aead"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "arcanum"
version = "0.2.0"
dependencies = [
"chacha20poly1305",
"ed25519-dalek",
"hkdf",
"hmac",
"ml-dsa",
"ml-kem",
"rand_core",
"sha2",
"sha3",
"shake",
"x25519-dalek",
"zeroize",
]
[[package]]
name = "arcanum-zeroize-probe"
version = "0.0.0"
dependencies = [
"arcanum",
"chacha20",
"ml-dsa",
"rand_core",
"zeroize",
]
[[package]]
name = "autocfg"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64ct"
version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
"zeroize",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cipher",
"cpufeatures",
"rand_core",
"zeroize",
]
[[package]]
name = "chacha20poly1305"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"
dependencies = [
"aead",
"chacha20",
"cipher",
"poly1305",
"zeroize",
]
[[package]]
name = "cipher"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
"block-buffer",
"crypto-common",
"inout",
]
[[package]]
name = "cmov"
version = "0.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
[[package]]
name = "const-oid"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
"rand_core",
]
[[package]]
name = "ctutils"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
dependencies = [
"cmov",
]
[[package]]
name = "curve25519-dalek"
version = "5.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23"
dependencies = [
"cfg-if",
"cpufeatures",
"curve25519-dalek-derive",
"digest",
"fiat-crypto",
"rustc_version",
"subtle",
"zeroize",
]
[[package]]
name = "curve25519-dalek-derive"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "der"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004"
dependencies = [
"const-oid",
"zeroize",
]
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"crypto-common",
"ctutils",
"zeroize",
]
[[package]]
name = "ed25519"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a"
dependencies = [
"signature",
]
[[package]]
name = "ed25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"
dependencies = [
"curve25519-dalek",
"ed25519",
"sha2",
"subtle",
"zeroize",
]
[[package]]
name = "fiat-crypto"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24"
[[package]]
name = "hkdf"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"
dependencies = [
"hmac",
]
[[package]]
name = "hmac"
version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
dependencies = [
"digest",
]
[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
"ctutils",
"typenum",
"zeroize",
]
[[package]]
name = "inout"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
dependencies = [
"hybrid-array",
]
[[package]]
name = "keccak"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d8f198d1db720e4940b5a493201d199d9f24f568f8f746bd13706243a2f71598"
dependencies = [
"cfg-if",
"cpufeatures",
]
[[package]]
name = "kem"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "01737161ba802849cfd486b5bd209d38ba4943494c249a8126005170c7621edd"
dependencies = [
"crypto-common",
"rand_core",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "ml-dsa"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f6d49c3f3f0e10e18ca975ffda66f8da0ec36521c1d911adcbc521bf0743f5c"
dependencies = [
"crypto-common",
"ctutils",
"hybrid-array",
"module-lattice",
"pkcs8",
"shake",
"signature",
"zeroize",
]
[[package]]
name = "ml-kem"
version = "0.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84ca78b66f46050d49fa21693ae8adab2081d8101b65d8067316b6b70b64a0d1"
dependencies = [
"hybrid-array",
"kem",
"module-lattice",
"rand_core",
"sha3",
"shake",
"zeroize",
]
[[package]]
name = "module-lattice"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4a1e412c8ee83a1c678f427806219c49c96b2511b9f07497514f0e43fb26155"
dependencies = [
"ctutils",
"hybrid-array",
"num-traits",
"zeroize",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "pkcs8"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7"
dependencies = [
"der",
"spki",
]
[[package]]
name = "poly1305"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"
dependencies = [
"cpufeatures",
"universal-hash",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rustc_version"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
dependencies = [
"semver",
]
[[package]]
name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
[[package]]
name = "sha2"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "sha3"
version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc9bad02c26382724b2d2692c6f179285e4b54eeecd7968f52a50059c3c11759"
dependencies = [
"digest",
"keccak",
"sponge-cursor",
]
[[package]]
name = "shake"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09057cb2149ad4cbd2da1e26b351f9a4c354219421229c69c3063e6f61947c4a"
dependencies = [
"digest",
"keccak",
"sponge-cursor",
]
[[package]]
name = "signature"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5"
dependencies = [
"digest",
"rand_core",
]
[[package]]
name = "spki"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9"
dependencies = [
"base64ct",
"der",
]
[[package]]
name = "sponge-cursor"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620"
dependencies = [
"zeroize",
]
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "universal-hash"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
dependencies = [
"crypto-common",
"ctutils",
]
[[package]]
name = "x25519-dalek"
version = "3.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6"
dependencies = [
"curve25519-dalek",
"rand_core",
"zeroize",
]
[[package]]
name = "zeroize"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "arcanum-zeroize-probe"
version = "0.0.0"
edition = "2024"
license = "CPAL-1.0"
publish = false
description = "QA A-29: a counting allocator that checks Arcanum's secrets are wiped before their heap memory is freed. Test-only; never a dependency of anything."
[dependencies]
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 }
# Its own workspace, like fuzz/: the probe needs `unsafe` (a GlobalAlloc), and Arcanum itself
# keeps `#![forbid(unsafe_code)]`. Nothing depends on this crate.
[workspace]
members = ["."]
+93
View File
@@ -0,0 +1,93 @@
//! 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, [`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, AtomicU8, AtomicUsize, Ordering};
/// The marker. Exactly 32 bytes, the size of every Arcanum secret.
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);
ARMED.store(true, Ordering::SeqCst);
}
/// Stop watching; true if a freed block held the canary since [`arm`].
pub fn disarm() -> bool {
ARMED.store(false, Ordering::SeqCst);
SEEN.load(Ordering::SeqCst)
}
struct Probe;
// SAFETY: forwards every call to `System` unchanged; `dealloc` only reads the block it is about
// to free, which is valid for `layout.size()` bytes by the `GlobalAlloc` contract.
unsafe impl GlobalAlloc for Probe {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
unsafe { System.alloc(layout) }
}
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 holds_secret(block) {
SEEN.store(true, Ordering::SeqCst);
}
}
unsafe { System.dealloc(ptr, layout) }
}
// `realloc` is deliberately not overridden: the default moves the data with `self.alloc` and
// frees the old block with `self.dealloc`, so a growing buffer's old copy is scanned too.
}
#[global_allocator]
static GLOBAL: Probe = Probe;
+145
View File
@@ -0,0 +1,145 @@
//! QA A-29: heap memory that held Arcanum secret bytes is wiped before it is freed.
//!
//! One test function, run sequentially, because the probe is process-global. The controls come
//! first and prove the probe is not blind: an unwiped `Vec` and a `Zeroizing<Vec>` that grows
//! (the reallocation case) are both caught; a `Zeroizing<Vec>` that does not grow is not.
//!
//! Run: `cargo test --manifest-path zeroize-probe/Cargo.toml -- --test-threads=1`
use arcanum::exchange;
use arcanum::seal;
use arcanum::sign::{self, AppContext, SigningKey};
use arcanum::xwing::SecretKey;
use arcanum_zeroize_probe::{CANARY, arm, disarm, watch};
use chacha20::ChaCha20Rng;
use rand_core::SeedableRng;
use zeroize::{Zeroize, Zeroizing};
fn rng(tag: u8) -> ChaCha20Rng {
ChaCha20Rng::from_seed([tag; 32])
}
#[test]
fn secrets_are_wiped_before_their_heap_memory_is_freed() {
// --- controls: the probe sees what it should ---
arm();
drop(std::hint::black_box(CANARY.to_vec()));
assert!(disarm(), "control: an unwiped Vec holding the canary must be seen");
arm();
drop(std::hint::black_box(Zeroizing::new(CANARY.to_vec())));
assert!(!disarm(), "control: a Zeroizing<Vec> that never grows must not be seen");
arm();
let mut grows = Zeroizing::new(CANARY.to_vec());
grows.extend_from_slice(&[0u8; 4096]); // reallocates: the old block is freed unwiped
drop(std::hint::black_box(grows));
assert!(disarm(), "control: the reallocation case (A-29's typical bug) must be seen");
// --- Arcanum ---
// The seed (= the stored secret key) inside a heap-allocated SecretKey.
arm();
drop(std::hint::black_box(Box::new(SecretKey::from_bytes(&CANARY).unwrap())));
assert!(!disarm(), "a boxed SecretKey was freed with its seed still in memory");
// The exported seed.
arm();
let sk = SecretKey::from_bytes(&CANARY).unwrap();
drop(std::hint::black_box(Box::new(sk.to_seed())));
assert!(!disarm(), "a boxed to_seed() copy was freed unwiped");
// seal: the plaintext is copied into the output buffer and encrypted in place.
let recipient = SecretKey::generate(&mut rng(1));
arm();
let sealed = seal::seal(recipient.public_key(), &CANARY, b"aad", &mut rng(2)).unwrap();
let sealed_copy = sealed.clone();
drop(std::hint::black_box(sealed));
assert!(!disarm(), "seal freed a buffer that held the plaintext");
// open: the returned plaintext, dropped by the caller.
arm();
let opened = seal::open(&recipient, &sealed_copy, b"aad").unwrap();
assert_eq!(opened.as_slice(), CANARY);
drop(std::hint::black_box(opened));
assert!(!disarm(), "an opened plaintext was freed unwiped");
// open with the wrong aad: the failure path frees its buffer.
arm();
assert!(seal::open(&recipient, &sealed_copy, b"wrong").is_err());
assert!(!disarm(), "a failed open freed a buffer that held plaintext");
// A plaintext large enough to be split across many blocks by nobody but us.
let big: Vec<u8> = CANARY.iter().copied().cycle().take(70_000).collect();
arm();
let sealed_big = seal::seal(recipient.public_key(), &big, b"", &mut rng(3)).unwrap();
let opened_big = seal::open(&recipient, &sealed_big, b"").unwrap();
assert_eq!(opened_big.as_slice(), big.as_slice());
drop(opened_big);
drop(sealed_big);
assert!(!disarm(), "a 70 kB seal/open freed plaintext unwiped");
drop(Zeroizing::new(big));
// A whole exchange on the heap, with the canary as context.
let a = SecretKey::from_bytes(&[7; 32]).unwrap();
let b = SecretKey::from_bytes(&[8; 32]).unwrap();
arm();
let init = Box::new(exchange::initiate(&a, b.public_key(), &CANARY, &mut rng(4)).unwrap());
let (ct, rs) = exchange::respond(&b, a.public_key(), init.ciphertext(), &CANARY, &mut rng(5)).unwrap();
let is = Box::new(init.finish(&ct).unwrap());
let psk = Box::new(is.wireguard_psk(1));
drop((psk, is, rs));
assert!(!disarm(), "an exchange freed its context unwiped");
// --- v0.2.0: signatures ---
// Both seeds are the canary. Building the key runs `ml-dsa`'s `SigningKey::from_seed`, which
// keeps a copy of the ML-DSA seed in a heap box (`alloc`) and wipes it on drop (`zeroize`).
let seeds: Zeroizing<Vec<u8>> = Zeroizing::new([CANARY, CANARY].concat());
arm();
drop(std::hint::black_box(Box::new(SigningKey::from_bytes(&seeds).unwrap())));
assert!(!disarm(), "a boxed signing key (or ml-dsa's seed box) was freed with a seed in memory");
// The exported seeds.
let sk = SigningKey::from_bytes(&seeds).unwrap();
arm();
drop(std::hint::black_box(Box::new(sk.to_bytes())));
assert!(!disarm(), "a boxed to_bytes() copy was freed unwiped");
// Signing, an app message and a key binding, with the canary key; then the key is dropped.
let ctx = AppContext::new(b"probe").unwrap();
let kem = SecretKey::from_bytes(&[9; 32]).unwrap();
arm();
let sk = Box::new(SigningKey::from_bytes(&seeds).unwrap());
let sig = sk.sign(b"message", &ctx, &mut rng(6)).unwrap();
assert_eq!(sk.verifying_key().verify(b"message", &ctx, &sig), Ok(()));
let bound = sign::bind_kem_key(&sk, b"id", kem.public_key(), (0, 1), &mut rng(7)).unwrap();
assert_eq!(sign::verify_binding(sk.verifying_key(), b"id", kem.public_key(), (0, 1), 0, &bound), Ok(()));
drop((sig, bound, sk));
assert!(!disarm(), "signing freed a buffer that held a seed");
// --- QA S-04: the expanded ML-DSA key, which never contains the canary ---
// FIPS 204 skEncode of the canary key: rho (0..32), K (32..64), tr (64..128), s1 (128..768), ...
// Watch K (held raw in ml-dsa's ExpandedSigningKey) and a window of the encoded s1 (in any
// encoded copy of the key, the shape QA's mutation Q15 leaked).
#[allow(deprecated)]
let mut expanded = ml_dsa::ExpandedSigningKey::<ml_dsa::MlDsa65>::from_seed(&CANARY.into()).to_expanded();
let k: [u8; 32] = expanded[32..64].try_into().unwrap();
let s1: [u8; 32] = expanded[128..160].try_into().unwrap();
watch(&[k, s1]);
// Controls: an unwiped copy of the encoded expanded key is seen, a wiped one is not.
arm();
drop(std::hint::black_box(expanded.to_vec()));
assert!(disarm(), "control: an unwiped copy of the expanded key must be seen");
arm();
drop(std::hint::black_box(Zeroizing::new(expanded.to_vec())));
assert!(!disarm(), "control: a Zeroizing copy must not be seen");
expanded.as_mut_slice().zeroize();
// Arcanum: build, sign, bind and drop with the canary key, watching the expanded key's bytes.
arm();
let sk = Box::new(SigningKey::from_bytes(&seeds).unwrap());
let sig = sk.sign(b"message", &ctx, &mut rng(8)).unwrap();
let bound = sign::bind_kem_key(&sk, b"id", kem.public_key(), (0, 1), &mut rng(9)).unwrap();
drop((sig, bound, sk));
assert!(!disarm(), "a signing key was freed with expanded ML-DSA key material (K or s1) in memory");
watch(&[]);
}