Compare commits
7 Commits
853f59ca60
...
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 2fae9ad3eb | |||
| 9f8d1161ad | |||
| 96086be4b3 | |||
| 6780abc0c2 | |||
| f3e17f3d5c | |||
| f31872d0d5 | |||
| 3dfc75075f |
+67
@@ -0,0 +1,67 @@
|
|||||||
|
# Handover — Arcanum
|
||||||
|
|
||||||
|
Newest entry first. Where this file and the code disagree, the code wins and the next entry says so.
|
||||||
|
|
||||||
|
## 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).
|
||||||
+45
-7
@@ -85,6 +85,17 @@ An honest key or ciphertext is never such a point, so this changes no honest exc
|
|||||||
official vector; it removes the case where the classical half silently contributes a known value
|
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`.
|
(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 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
|
`ml-kem`'s `EncapsulationKey::new` performs it; Arcanum maps its failure to
|
||||||
`Error::InvalidPublicKey`, and the NIST ACVP `encapsulationKeyCheck` vectors check that.
|
`Error::InvalidPublicKey`, and the NIST ACVP `encapsulationKeyCheck` vectors check that.
|
||||||
@@ -169,8 +180,10 @@ seal: th = SHA-256("domi/arcanum/v1/transcript/seal" || pk (1216) || ct (11
|
|||||||
(`ct_M || ct_X`), so both public keys and both ciphertexts of each direction are hashed.
|
(`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
|
- Roles are bound by position (initiator first), so a reflected exchange gives a different PSK
|
||||||
(QA A-14).
|
(QA A-14).
|
||||||
- Every field before the context is fixed-width and the context is length-prefixed, so the
|
- Every transcript field before the context is fixed-width and the context is length-prefixed, so
|
||||||
encoding is injective (QA A-08). Labels are unique, versioned and prefix-free (QA A-07, a unit
|
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).
|
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).
|
- `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
|
- A v2 changes the labels and never reuses these. The v1 outputs are frozen by golden vectors
|
||||||
@@ -205,15 +218,37 @@ plaintext is reallocated and freed unwiped (QA A-29). This is a documented const
|
|||||||
|
|
||||||
- `#![no_std]` with `alloc`, `#![forbid(unsafe_code)]`, no I/O, no clock, no OS RNG in the normal
|
- `#![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`).
|
dependency graph (checked by `tests/feature_hygiene.rs`).
|
||||||
- Randomness is a parameter: `&mut R where R: rand_core::CryptoRng` (rand_core 0.10).
|
- 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`,
|
- **The `hazmat` feature** exposes the deterministic entry points (`SecretKey::from_seed`,
|
||||||
`PublicKey::encapsulate_derand`, `exchange::{initiate,respond}_derand`, `seal::seal_derand`)
|
`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
|
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
|
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
|
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). Via and via-core must run the same check.
|
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
|
- Every secret type (`SecretKey`, `SharedSecret`, `Session`, `Initiation`, `WireGuardPsk`) is
|
||||||
zeroised on drop, is not `Copy`, has no `PartialEq`, and prints as `[redacted]` in `Debug`.
|
`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.
|
- Every parser returns `Result<_, arcanum::Error>`; errors carry only lengths and variants.
|
||||||
|
|
||||||
## Tests (written first)
|
## Tests (written first)
|
||||||
@@ -228,7 +263,9 @@ plaintext is reallocated and freed unwiped (QA A-29). This is a documented const
|
|||||||
| 6 | `cargo deny`, `cargo audit` clean; no unsafe | `deny.toml`, `tests/no_unsafe.rs`, `#![forbid(unsafe_code)]` |
|
| 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
|
Also: `tests/golden_v1.rs` (frozen v1 outputs), `tests/feature_hygiene.rs` (no hazmat, no OS RNG
|
||||||
in the release graph). Vector provenance is in `tests/vectors/SOURCES.md`. QA's attack plan
|
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.
|
(`F:\Akce\Via\qa\01_arcanum_attacks.md`) is mapped case by case in the PR's self-review.
|
||||||
|
|
||||||
## Risks
|
## Risks
|
||||||
@@ -256,7 +293,8 @@ in the release graph). Vector provenance is in `tests/vectors/SOURCES.md`. QA's
|
|||||||
own (QA A-32, a dudect run, is not done).
|
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
|
- **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;
|
crates' `zeroize` features go; values moved by the compiler may leave copies on the stack;
|
||||||
`PublicKey` copies are not secret. QA A-29's allocator probe is not built.
|
`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.
|
- **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
|
- **X25519 RFC 7748 1,000,000-iteration vector** is not run (minutes in a debug build); the
|
||||||
1- and 1,000-iteration vectors are.
|
1- and 1,000-iteration vectors are.
|
||||||
|
|||||||
+15
-3
@@ -43,7 +43,7 @@ impl Session {
|
|||||||
/// peers get the same key for the same epoch, and different epochs give different keys.
|
/// peers get the same key for the same epoch, and different epochs give different keys.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn wireguard_psk(&self, epoch: u64) -> WireGuardPsk {
|
pub fn wireguard_psk(&self, epoch: u64) -> WireGuardPsk {
|
||||||
WireGuardPsk(expand(&self.prk, &[LABEL_WIREGUARD_PSK, &epoch.to_be_bytes()]))
|
WireGuardPsk(expand(&self.prk, LABEL_WIREGUARD_PSK, &epoch.to_be_bytes()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -84,6 +84,10 @@ pub struct Initiation<'a> {
|
|||||||
context: Zeroizing<Vec<u8>>,
|
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<'_> {
|
impl fmt::Debug for Initiation<'_> {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.write_str("Initiation([redacted])")
|
f.write_str("Initiation([redacted])")
|
||||||
@@ -104,7 +108,7 @@ impl Initiation<'_> {
|
|||||||
/// is not reported; it yields a session that does not match the responder's, and the
|
/// is not reported; it yields a session that does not match the responder's, and the
|
||||||
/// WireGuard handshake then fails.
|
/// WireGuard handshake then fails.
|
||||||
pub fn finish(self, ct_ri: &Ciphertext) -> Result<Session, Error> {
|
pub fn finish(self, ct_ri: &Ciphertext) -> Result<Session, Error> {
|
||||||
let ss_ri = self.me.decapsulate(ct_ri)?;
|
let ss_ri = self.me.decapsulate_inner(ct_ri)?;
|
||||||
let t = Transcript {
|
let t = Transcript {
|
||||||
initiator: self.me.public_key(),
|
initiator: self.me.public_key(),
|
||||||
responder: &self.peer,
|
responder: &self.peer,
|
||||||
@@ -118,6 +122,10 @@ impl Initiation<'_> {
|
|||||||
|
|
||||||
/// Start an exchange as the initiator: encapsulate to the responder and keep the state.
|
/// 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
|
/// # Errors
|
||||||
/// [`Error::NonContributory`] if the responder's X25519 key is a low-order point.
|
/// [`Error::NonContributory`] if the responder's X25519 key is a low-order point.
|
||||||
pub fn initiate<'a, R: CryptoRng + ?Sized>(
|
pub fn initiate<'a, R: CryptoRng + ?Sized>(
|
||||||
@@ -134,6 +142,10 @@ pub fn initiate<'a, R: CryptoRng + ?Sized>(
|
|||||||
/// Answer an exchange as the responder: decapsulate the initiator's ciphertext, encapsulate back,
|
/// Answer an exchange as the responder: decapsulate the initiator's ciphertext, encapsulate back,
|
||||||
/// and return the ciphertext to send together with the finished session.
|
/// 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
|
/// # Errors
|
||||||
/// [`Error::NonContributory`] if the initiator's ciphertext or public key has a low-order X25519
|
/// [`Error::NonContributory`] if the initiator's ciphertext or public key has a low-order X25519
|
||||||
/// part.
|
/// part.
|
||||||
@@ -196,7 +208,7 @@ fn respond_inner(
|
|||||||
context: &[u8],
|
context: &[u8],
|
||||||
eseed: &[u8; ENCAPSULATION_SEED_LEN],
|
eseed: &[u8; ENCAPSULATION_SEED_LEN],
|
||||||
) -> Result<(Ciphertext, Session), Error> {
|
) -> Result<(Ciphertext, Session), Error> {
|
||||||
let ss_ir = me.decapsulate(ct_ir)?;
|
let ss_ir = me.decapsulate_inner(ct_ir)?;
|
||||||
let (ct_ri, ss_ri) = initiator.encapsulate_inner(eseed)?;
|
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 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) };
|
let session = Session { prk: session_prk(&ss_ir, &ss_ri, &t) };
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ pub mod xwing;
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod binding_tests;
|
mod binding_tests;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod qa_review_tests;
|
||||||
|
|
||||||
pub use error::{Error, Input};
|
pub use error::{Error, Input};
|
||||||
pub use exchange::{Session, WIREGUARD_PSK_LEN, WireGuardPsk};
|
pub use exchange::{Session, WIREGUARD_PSK_LEN, WireGuardPsk};
|
||||||
|
|||||||
@@ -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));
|
||||||
|
}
|
||||||
+16
-5
@@ -82,7 +82,7 @@ fn extract(secrets: &[&[u8; 32]], th: &[u8; 32]) -> Prk {
|
|||||||
|
|
||||||
/// The PRK of a mutual exchange: both directions' X-Wing secrets and the whole transcript.
|
/// 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 {
|
pub(crate) fn session_prk(ss_ir: &SharedSecret, ss_ri: &SharedSecret, t: &Transcript<'_>) -> Prk {
|
||||||
extract(&[ss_ir.as_bytes(), ss_ri.as_bytes()], &t.hash())
|
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.
|
/// The PRK of one sealed box: the X-Wing secret, the recipient key, the ciphertext and the aad.
|
||||||
@@ -94,14 +94,25 @@ pub(crate) fn seal_prk(ss: &SharedSecret, recipient: &PublicKey, ct: &Ciphertext
|
|||||||
h.update((aad.len() as u64).to_be_bytes());
|
h.update((aad.len() as u64).to_be_bytes());
|
||||||
h.update(aad);
|
h.update(aad);
|
||||||
let th: [u8; 32] = h.finalize().into();
|
let th: [u8; 32] = h.finalize().into();
|
||||||
extract(&[ss.as_bytes()], &th)
|
extract(&[ss.bytes()], &th)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// HKDF-Expand to `N` bytes with the info parts concatenated.
|
/// HKDF-Expand to `N` bytes with `info = label || field`.
|
||||||
pub(crate) fn expand<const N: usize>(prk: &Prk, info: &[&[u8]]) -> Zeroizing<[u8; N]> {
|
///
|
||||||
|
/// 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.
|
// 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 hk = Hkdf::<Sha256>::from_prk(prk.as_slice()).expect("PRK is 32 bytes");
|
||||||
let mut out = Zeroizing::new([0u8; N]);
|
let mut out = Zeroizing::new([0u8; N]);
|
||||||
hk.expand_multi_info(info, out.as_mut_slice()).expect("N is at most 255 * 32");
|
hk.expand_multi_info(&[label, field.as_slice()], out.as_mut_slice()).expect("N is at most 255 * 32");
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|||||||
+13
-6
@@ -33,8 +33,8 @@ const HEADER_LEN: usize = 1 + CIPHERTEXT_LEN;
|
|||||||
pub const OVERHEAD: usize = HEADER_LEN + TAG_LEN;
|
pub const OVERHEAD: usize = HEADER_LEN + TAG_LEN;
|
||||||
|
|
||||||
fn cipher(prk: &Prk) -> (ChaCha20Poly1305, Nonce) {
|
fn cipher(prk: &Prk) -> (ChaCha20Poly1305, Nonce) {
|
||||||
let key = expand::<32>(prk, &[LABEL_SEAL_KEY]);
|
let key = expand::<32, 0>(prk, LABEL_SEAL_KEY, &[]);
|
||||||
let nonce = expand::<12>(prk, &[LABEL_SEAL_NONCE]);
|
let nonce = expand::<12, 0>(prk, LABEL_SEAL_NONCE, &[]);
|
||||||
// Infallible: the key is exactly 32 bytes.
|
// Infallible: the key is exactly 32 bytes.
|
||||||
let aead = ChaCha20Poly1305::new_from_slice(key.as_slice()).expect("32-byte key");
|
let aead = ChaCha20Poly1305::new_from_slice(key.as_slice()).expect("32-byte key");
|
||||||
(aead, Nonce::from(*nonce))
|
(aead, Nonce::from(*nonce))
|
||||||
@@ -43,6 +43,10 @@ fn cipher(prk: &Prk) -> (ChaCha20Poly1305, Nonce) {
|
|||||||
/// Seal `plaintext` to `recipient`, bound to `aad` (which is not encrypted and must be given again
|
/// Seal `plaintext` to `recipient`, bound to `aad` (which is not encrypted and must be given again
|
||||||
/// to open).
|
/// 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
|
/// # Errors
|
||||||
/// [`Error::NonContributory`] if the recipient's X25519 key is a low-order point.
|
/// [`Error::NonContributory`] if the recipient's X25519 key is a low-order point.
|
||||||
pub fn seal<R: CryptoRng + ?Sized>(
|
pub fn seal<R: CryptoRng + ?Sized>(
|
||||||
@@ -80,8 +84,10 @@ fn seal_inner(
|
|||||||
let (ct, ss) = recipient.encapsulate_inner(eseed)?;
|
let (ct, ss) = recipient.encapsulate_inner(eseed)?;
|
||||||
let (aead, nonce) = cipher(&seal_prk(&ss, recipient, &ct, aad));
|
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.
|
// Allocated once at its final size, so no buffer that held plaintext is ever reallocated. It is
|
||||||
let mut out = Vec::with_capacity(plaintext.len() + OVERHEAD);
|
// `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.push(VERSION);
|
||||||
out.extend_from_slice(ct.as_bytes());
|
out.extend_from_slice(ct.as_bytes());
|
||||||
out.extend_from_slice(plaintext);
|
out.extend_from_slice(plaintext);
|
||||||
@@ -90,7 +96,8 @@ fn seal_inner(
|
|||||||
.encrypt_inout_detached(&nonce, &[VERSION], (&mut out[HEADER_LEN..]).into())
|
.encrypt_inout_detached(&nonce, &[VERSION], (&mut out[HEADER_LEN..]).into())
|
||||||
.map_err(|_| Error::MessageTooLong)?;
|
.map_err(|_| Error::MessageTooLong)?;
|
||||||
out.extend_from_slice(tag.as_slice());
|
out.extend_from_slice(tag.as_slice());
|
||||||
Ok(out)
|
// 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`.
|
/// Open a sealed box with the recipient's secret key and the same `aad`.
|
||||||
@@ -108,7 +115,7 @@ pub fn open(recipient: &SecretKey, sealed: &[u8], aad: &[u8]) -> Result<Zeroizin
|
|||||||
return Err(Error::UnsupportedVersion(version));
|
return Err(Error::UnsupportedVersion(version));
|
||||||
}
|
}
|
||||||
let ct = Ciphertext::from_bytes(ct)?;
|
let ct = Ciphertext::from_bytes(ct)?;
|
||||||
let ss = recipient.decapsulate(&ct)?;
|
let ss = recipient.decapsulate_inner(&ct)?;
|
||||||
let (aead, nonce) = cipher(&seal_prk(&ss, recipient.public_key(), &ct, aad));
|
let (aead, nonce) = cipher(&seal_prk(&ss, recipient.public_key(), &ct, aad));
|
||||||
|
|
||||||
let (body, tag) = rest.split_at(rest.len() - TAG_LEN);
|
let (body, tag) = rest.split_at(rest.len() - TAG_LEN);
|
||||||
|
|||||||
+46
-8
@@ -4,9 +4,16 @@
|
|||||||
//! `x25519-dalek` (RFC 7748), SHAKE256 from `shake` and SHA3-256 from `sha3` (FIPS 202). It is pinned
|
//! `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.
|
//! by the draft's three test vectors and a differential test against RustCrypto's `x-wing` crate.
|
||||||
//!
|
//!
|
||||||
//! One deliberate difference from the draft: a low-order X25519 public key or ciphertext part is
|
//! Two deliberate differences from the draft, both stricter and both invisible to honest peers and
|
||||||
//! refused with [`Error::NonContributory`]. Honest keys and ciphertexts are never low-order, so no
|
//! to the official vectors: a low-order X25519 public key or ciphertext part is refused with
|
||||||
//! honest exchange and no official vector is affected (docs/01_arcanum.md).
|
//! [`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 core::{array, fmt};
|
||||||
|
|
||||||
@@ -55,12 +62,17 @@ pub(crate) fn combiner(ss_m: &[u8; 32], ss_x: &[u8; 32], ct_x: &[u8; 32], pk_x:
|
|||||||
pub struct SharedSecret(pub(crate) Zeroizing<[u8; SHARED_SECRET_LEN]>);
|
pub struct SharedSecret(pub(crate) Zeroizing<[u8; SHARED_SECRET_LEN]>);
|
||||||
|
|
||||||
impl SharedSecret {
|
impl SharedSecret {
|
||||||
/// The raw 32 bytes, for interoperating with other X-Wing users. Prefer [`crate::exchange`],
|
/// The raw 32 bytes. **Hazmat** (feature `hazmat`): a one-way X-Wing secret authenticates only
|
||||||
/// which binds the secret to the transcript and a context.
|
/// the receiver and is bound to no transcript, so it must never be used as a key directly.
|
||||||
|
#[cfg(feature = "hazmat")]
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn as_bytes(&self) -> &[u8; SHARED_SECRET_LEN] {
|
pub fn as_bytes(&self) -> &[u8; SHARED_SECRET_LEN] {
|
||||||
&self.0
|
&self.0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn bytes(&self) -> &[u8; SHARED_SECRET_LEN] {
|
||||||
|
&self.0
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Debug for SharedSecret {
|
impl fmt::Debug for SharedSecret {
|
||||||
@@ -84,12 +96,15 @@ impl PublicKey {
|
|||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`Error::InvalidLength`] if it is not 1216 bytes; [`Error::InvalidPublicKey`] if the ML-KEM
|
/// [`Error::InvalidLength`] if it is not 1216 bytes; [`Error::InvalidPublicKey`] if the ML-KEM
|
||||||
/// part fails the FIPS 203 §7.2 encapsulation key check.
|
/// 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> {
|
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
|
||||||
let bytes: &[u8; PUBLIC_KEY_LEN] = exact(Input::PublicKey, bytes)?;
|
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 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 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]);
|
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) })
|
Ok(Self { bytes: *bytes, pk_m, pk_x: X25519Public::from(x) })
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,10 +114,12 @@ impl PublicKey {
|
|||||||
&self.bytes
|
&self.bytes
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Encapsulate a fresh shared secret to this key.
|
/// Encapsulate a fresh shared secret to this key. **Hazmat** (feature `hazmat`), see the module
|
||||||
|
/// docs; release code uses [`crate::exchange`] or [`crate::seal`].
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`Error::NonContributory`] if the X25519 part of the key is a low-order point.
|
/// [`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> {
|
pub fn encapsulate<R: CryptoRng + ?Sized>(&self, rng: &mut R) -> Result<(Ciphertext, SharedSecret), Error> {
|
||||||
let mut eseed = Zeroizing::new([0u8; ENCAPSULATION_SEED_LEN]);
|
let mut eseed = Zeroizing::new([0u8; ENCAPSULATION_SEED_LEN]);
|
||||||
rng.fill_bytes(eseed.as_mut_slice());
|
rng.fill_bytes(eseed.as_mut_slice());
|
||||||
@@ -205,6 +222,10 @@ pub struct SecretKey {
|
|||||||
|
|
||||||
impl SecretKey {
|
impl SecretKey {
|
||||||
/// Generate a new key pair from the caller's RNG.
|
/// 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 {
|
pub fn generate<R: CryptoRng + ?Sized>(rng: &mut R) -> Self {
|
||||||
let mut seed = Zeroizing::new([0u8; SECRET_KEY_LEN]);
|
let mut seed = Zeroizing::new([0u8; SECRET_KEY_LEN]);
|
||||||
rng.fill_bytes(seed.as_mut_slice());
|
rng.fill_bytes(seed.as_mut_slice());
|
||||||
@@ -241,12 +262,17 @@ impl SecretKey {
|
|||||||
&self.public
|
&self.public
|
||||||
}
|
}
|
||||||
|
|
||||||
/// X-Wing `Decapsulate` (draft -11 §5.5).
|
/// X-Wing `Decapsulate` (draft -11 §5.5). **Hazmat** (feature `hazmat`), see the module docs.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`Error::NonContributory`] if the X25519 part of the ciphertext is a low-order point. A
|
/// [`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.
|
/// 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> {
|
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 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));
|
let ss_x = self.sk_x.diffie_hellman(&X25519Public::from(ct_x));
|
||||||
if !ss_x.was_contributory() {
|
if !ss_x.was_contributory() {
|
||||||
@@ -296,6 +322,18 @@ impl fmt::Debug for SecretKey {
|
|||||||
// (their `zeroize` features are enabled in Cargo.toml).
|
// (their `zeroize` features are enabled in Cargo.toml).
|
||||||
impl ZeroizeOnDrop for SecretKey {}
|
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.
|
/// 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]> {
|
fn as32(k: &ml_kem::SharedKey) -> Zeroizing<[u8; 32]> {
|
||||||
let mut out = Zeroizing::new([0u8; 32]);
|
let mut out = Zeroizing::new([0u8; 32]);
|
||||||
|
|||||||
+42
-1
@@ -68,14 +68,55 @@ fn low_order_x25519_ciphertext_is_refused() {
|
|||||||
fn low_order_x25519_public_key_is_refused() {
|
fn low_order_x25519_public_key_is_refused() {
|
||||||
let i = SecretKey::from_seed([0x43; 32]);
|
let i = SecretKey::from_seed([0x43; 32]);
|
||||||
let r = SecretKey::from_seed([0x44; 32]);
|
let r = SecretKey::from_seed([0x44; 32]);
|
||||||
|
let mut refused_at_parse = 0;
|
||||||
for point in low_order_points() {
|
for point in low_order_points() {
|
||||||
let mut bad = *r.public_key().as_bytes();
|
let mut bad = *r.public_key().as_bytes();
|
||||||
bad[1184..].copy_from_slice(&point);
|
bad[1184..].copy_from_slice(&point);
|
||||||
let pk = PublicKey::from_bytes(&bad).expect("the ML-KEM part is still valid");
|
// 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!(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!(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));
|
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
|
/// QA A-04: X25519 ignores bit 255 of ct_X, so ct_X and ct_X ^ 0x80 give the same ss_X. The
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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)");
|
||||||
|
}
|
||||||
|
}
|
||||||
Generated
+437
@@ -0,0 +1,437 @@
|
|||||||
|
# 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.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"chacha20poly1305",
|
||||||
|
"hkdf",
|
||||||
|
"hmac",
|
||||||
|
"ml-kem",
|
||||||
|
"rand_core",
|
||||||
|
"sha2",
|
||||||
|
"sha3",
|
||||||
|
"shake",
|
||||||
|
"x25519-dalek",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "arcanum-zeroize-probe"
|
||||||
|
version = "0.0.0"
|
||||||
|
dependencies = [
|
||||||
|
"arcanum",
|
||||||
|
"chacha20",
|
||||||
|
"rand_core",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "autocfg"
|
||||||
|
version = "1.5.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||||
|
|
||||||
|
[[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 = "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",
|
||||||
|
"fiat-crypto",
|
||||||
|
"rustc_version",
|
||||||
|
"subtle",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "curve25519-dalek-derive"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "digest"
|
||||||
|
version = "0.11.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
|
||||||
|
dependencies = [
|
||||||
|
"block-buffer",
|
||||||
|
"crypto-common",
|
||||||
|
"ctutils",
|
||||||
|
"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-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 = "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 = "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",
|
||||||
|
]
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
[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]
|
||||||
|
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 = ["."]
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
//! QA A-29: a global allocator that, in `dealloc`, scans every block for a 32-byte canary before
|
||||||
|
//! handing it back to the system allocator. If a secret built from the canary is freed without
|
||||||
|
//! being wiped first, [`seen`] turns true.
|
||||||
|
//!
|
||||||
|
//! `unsafe` lives here only, in a crate that is not published and that nothing depends on;
|
||||||
|
//! Arcanum itself keeps `#![forbid(unsafe_code)]`. Limits: the probe sees the heap only. Stack
|
||||||
|
//! copies made by moves are invisible to it (and to `zeroize`), see docs/THREAT_MODEL.md.
|
||||||
|
|
||||||
|
use std::alloc::{GlobalAlloc, Layout, System};
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
|
||||||
|
/// 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);
|
||||||
|
|
||||||
|
/// 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 block.windows(CANARY.len()).any(|w| w == CANARY) {
|
||||||
|
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;
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
//! 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::xwing::SecretKey;
|
||||||
|
use arcanum_zeroize_probe::{CANARY, arm, disarm};
|
||||||
|
use chacha20::ChaCha20Rng;
|
||||||
|
use rand_core::SeedableRng;
|
||||||
|
use 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");
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user