Compare commits
4 Commits
f3e17f3d5c
...
v0.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 2fae9ad3eb | |||
| 9f8d1161ad | |||
| 96086be4b3 | |||
| 6780abc0c2 |
+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
|
||||
(QA A-16, A-17). RustCrypto ships the same option as `DecapsulationKeyRejectNonContrib`.
|
||||
|
||||
**Canonical X25519 public keys only (QA R2-02).** Draft -11 says nothing about the encoding of
|
||||
`pk_X` beyond "the 32 byte string representing the u-coordinate" (§4), and its Python reference
|
||||
decodes with `% p`, so it would accept aliases. RFC 7748 decoders mask bit 255 and reduce mod p,
|
||||
which means `pk_X`, `pk_X` with bit 255 set, and `pk_X + p` (where that fits) are the same key to
|
||||
X25519 but different bytes to the combiner and the transcript: a peer given an alias "succeeds" and
|
||||
silently derives a PSK the owner never matches. `PublicKey::from_bytes` therefore refuses an
|
||||
X25519 half with bit 255 set or a value of at least 2^255 - 19, as `Error::InvalidPublicKey`.
|
||||
X25519 outputs are always canonical, so no honest key and no official vector is affected. A
|
||||
ciphertext's `ct_X` is not checked this way: it is single-use, and its raw bytes are bound by the
|
||||
combiner (QA A-04), so an alias only gives a different secret.
|
||||
|
||||
**ML-KEM key check.** The draft requires the FIPS 203 §7.2 encapsulation key check.
|
||||
`ml-kem`'s `EncapsulationKey::new` performs it; Arcanum maps its failure to
|
||||
`Error::InvalidPublicKey`, and the NIST ACVP `encapsulationKeyCheck` vectors check that.
|
||||
@@ -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.
|
||||
- Roles are bound by position (initiator first), so a reflected exchange gives a different PSK
|
||||
(QA A-14).
|
||||
- Every field before the context is fixed-width and the context is length-prefixed, so the
|
||||
encoding is injective (QA A-08). Labels are unique, versioned and prefix-free (QA A-07, a unit
|
||||
- Every transcript field before the context is fixed-width and the context is length-prefixed, so
|
||||
the transcript encoding is injective (QA A-08). The HKDF-Expand helper takes exactly one label
|
||||
and one fixed-width field array (QA R2-03), so its `info` is injective by its signature, not by
|
||||
the discipline of its callers; this did not change any v1 byte (the golden vectors are unchanged). Labels are unique, versioned and prefix-free (QA A-07, a unit
|
||||
test). The epoch is a full 64-bit big-endian value (QA A-11).
|
||||
- `ctx` is the caller's binding (for Via: both Tessera device ids, the protocol name, the version).
|
||||
- A v2 changes the labels and never reuses these. The v1 outputs are frozen by golden vectors
|
||||
@@ -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
|
||||
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`,
|
||||
`PublicKey::encapsulate_derand`, `exchange::{initiate,respond}_derand`, `seal::seal_derand`)
|
||||
used by the known-answer tests. It is off by default. The tests turn it on through a
|
||||
self-dev-dependency, which never reaches a normal build; `tests/feature_hygiene.rs` asserts that
|
||||
neither `arcanum/hazmat` nor `ml-kem/hazmat` is in the normal-edge feature graph, and proves the
|
||||
check can see the feature when it is on (QA A-34, A-35). 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
|
||||
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.
|
||||
|
||||
## 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)]` |
|
||||
|
||||
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.
|
||||
|
||||
## 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).
|
||||
- **Zeroisation residuals:** HKDF/HMAC and SHA-3 internal states are wiped only as far as those
|
||||
crates' `zeroize` features go; values moved by the compiler may leave copies on the stack;
|
||||
`PublicKey` copies are not secret. QA 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.
|
||||
- **X25519 RFC 7748 1,000,000-iteration vector** is not run (minutes in a debug build); the
|
||||
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.
|
||||
#[must_use]
|
||||
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>>,
|
||||
}
|
||||
|
||||
// The secret fields wipe themselves: `ss_ir` is a `ZeroizeOnDrop` `SharedSecret` and `context` is
|
||||
// `Zeroizing`; `me` is a borrow and `peer`/`ct_ir` are public (QA R2-05).
|
||||
impl ZeroizeOnDrop for Initiation<'_> {}
|
||||
|
||||
impl fmt::Debug for Initiation<'_> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("Initiation([redacted])")
|
||||
@@ -104,7 +108,7 @@ impl Initiation<'_> {
|
||||
/// is not reported; it yields a session that does not match the responder's, and the
|
||||
/// WireGuard handshake then fails.
|
||||
pub fn finish(self, ct_ri: &Ciphertext) -> Result<Session, Error> {
|
||||
let ss_ri = self.me.decapsulate(ct_ri)?;
|
||||
let ss_ri = self.me.decapsulate_inner(ct_ri)?;
|
||||
let t = Transcript {
|
||||
initiator: self.me.public_key(),
|
||||
responder: &self.peer,
|
||||
@@ -118,6 +122,10 @@ impl Initiation<'_> {
|
||||
|
||||
/// Start an exchange as the initiator: encapsulate to the responder and keep the state.
|
||||
///
|
||||
/// **`rng` must be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it
|
||||
/// once per process; never a fixed, derived or configured seed. `CryptoRng` is only a marker: a
|
||||
/// CSPRNG with a constant seed satisfies it and makes this call fully deterministic (QA R2-04).
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::NonContributory`] if the responder's X25519 key is a low-order point.
|
||||
pub fn initiate<'a, R: CryptoRng + ?Sized>(
|
||||
@@ -134,6 +142,10 @@ pub fn initiate<'a, R: CryptoRng + ?Sized>(
|
||||
/// Answer an exchange as the responder: decapsulate the initiator's ciphertext, encapsulate back,
|
||||
/// and return the ciphertext to send together with the finished session.
|
||||
///
|
||||
/// **`rng` must be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it
|
||||
/// once per process; never a fixed, derived or configured seed. `CryptoRng` is only a marker: a
|
||||
/// CSPRNG with a constant seed satisfies it and makes this call fully deterministic (QA R2-04).
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::NonContributory`] if the initiator's ciphertext or public key has a low-order X25519
|
||||
/// part.
|
||||
@@ -196,7 +208,7 @@ fn respond_inner(
|
||||
context: &[u8],
|
||||
eseed: &[u8; ENCAPSULATION_SEED_LEN],
|
||||
) -> 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 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) };
|
||||
|
||||
+13
-6
@@ -28,9 +28,16 @@ fn psk_info(epoch: u64) -> Vec<u8> {
|
||||
#[test]
|
||||
fn a08_kdf_info_encodings_in_use_are_injective() {
|
||||
let prk: Prk = Zeroizing::new([9u8; 32]);
|
||||
// (1) The helper is raw concatenation. If this ever fails, the helper became length-prefixed:
|
||||
// update this test and the golden vectors together.
|
||||
assert_eq!(*expand::<32>(&prk, &[b"ab", b"c"]), *expand::<32>(&prk, &[b"a", b"bc"]));
|
||||
// (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();
|
||||
@@ -83,15 +90,15 @@ fn a09_one_secret_never_yields_the_same_key_for_two_purposes() {
|
||||
|
||||
let mut keys: HashSet<[u8; 32]> = HashSet::new();
|
||||
for prk in [&seal, &session] {
|
||||
let key = *expand::<32>(prk, &[LABEL_SEAL_KEY]);
|
||||
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>(prk, &[LABEL_SEAL_NONCE]));
|
||||
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>(prk, &[LABEL_WIREGUARD_PSK, &e.to_be_bytes()])), "epoch {e}");
|
||||
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.
|
||||
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.
|
||||
@@ -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);
|
||||
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.
|
||||
pub(crate) fn expand<const N: usize>(prk: &Prk, info: &[&[u8]]) -> Zeroizing<[u8; N]> {
|
||||
/// HKDF-Expand to `N` bytes with `info = label || field`.
|
||||
///
|
||||
/// The signature is what makes the encoding injective (QA R2-03): exactly one label, which must be
|
||||
/// one of the `LABEL_*` constants above (unique and prefix-free, tested in `binding_tests`), and
|
||||
/// exactly one fixed-width field. If two calls give the same `info`, their labels are equal (in a
|
||||
/// prefix-free set a label is determined by the string it starts), so their fields are equal too.
|
||||
/// Several values go into one fixed-width array, never into separate parts. This is byte for byte
|
||||
/// the v1 encoding (`tests/golden_v1.rs` is unchanged).
|
||||
pub(crate) fn expand<const N: usize, const K: usize>(
|
||||
prk: &Prk,
|
||||
label: &'static [u8],
|
||||
field: &[u8; K],
|
||||
) -> Zeroizing<[u8; N]> {
|
||||
// Infallible: a 32-byte PRK is the SHA-256 output size, and N <= 32 is far below 255 * 32.
|
||||
let hk = Hkdf::<Sha256>::from_prk(prk.as_slice()).expect("PRK is 32 bytes");
|
||||
let mut out = Zeroizing::new([0u8; N]);
|
||||
hk.expand_multi_info(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
|
||||
}
|
||||
|
||||
+13
-6
@@ -33,8 +33,8 @@ const HEADER_LEN: usize = 1 + CIPHERTEXT_LEN;
|
||||
pub const OVERHEAD: usize = HEADER_LEN + TAG_LEN;
|
||||
|
||||
fn cipher(prk: &Prk) -> (ChaCha20Poly1305, Nonce) {
|
||||
let key = expand::<32>(prk, &[LABEL_SEAL_KEY]);
|
||||
let nonce = expand::<12>(prk, &[LABEL_SEAL_NONCE]);
|
||||
let key = expand::<32, 0>(prk, LABEL_SEAL_KEY, &[]);
|
||||
let nonce = expand::<12, 0>(prk, LABEL_SEAL_NONCE, &[]);
|
||||
// Infallible: the key is exactly 32 bytes.
|
||||
let aead = ChaCha20Poly1305::new_from_slice(key.as_slice()).expect("32-byte key");
|
||||
(aead, Nonce::from(*nonce))
|
||||
@@ -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
|
||||
/// to open).
|
||||
///
|
||||
/// **`rng` must be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it
|
||||
/// once per process; never a fixed, derived or configured seed. `CryptoRng` is only a marker: a
|
||||
/// CSPRNG with a constant seed satisfies it and makes this call fully deterministic (QA R2-04).
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::NonContributory`] if the recipient's X25519 key is a low-order point.
|
||||
pub fn seal<R: CryptoRng + ?Sized>(
|
||||
@@ -80,8 +84,10 @@ fn seal_inner(
|
||||
let (ct, ss) = recipient.encapsulate_inner(eseed)?;
|
||||
let (aead, nonce) = cipher(&seal_prk(&ss, recipient, &ct, aad));
|
||||
|
||||
// Allocated once at its final size, so no buffer that held plaintext is ever reallocated.
|
||||
let mut out = Vec::with_capacity(plaintext.len() + OVERHEAD);
|
||||
// Allocated once at its final size, so no buffer that held plaintext is ever reallocated. It is
|
||||
// `Zeroizing` until the plaintext has been encrypted in place, so an early return (the
|
||||
// `MessageTooLong` path) wipes the copy instead of freeing it unwiped (QA R2-05).
|
||||
let mut out = Zeroizing::new(Vec::with_capacity(plaintext.len() + OVERHEAD));
|
||||
out.push(VERSION);
|
||||
out.extend_from_slice(ct.as_bytes());
|
||||
out.extend_from_slice(plaintext);
|
||||
@@ -90,7 +96,8 @@ fn seal_inner(
|
||||
.encrypt_inout_detached(&nonce, &[VERSION], (&mut out[HEADER_LEN..]).into())
|
||||
.map_err(|_| Error::MessageTooLong)?;
|
||||
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`.
|
||||
@@ -108,7 +115,7 @@ pub fn open(recipient: &SecretKey, sealed: &[u8], aad: &[u8]) -> Result<Zeroizin
|
||||
return Err(Error::UnsupportedVersion(version));
|
||||
}
|
||||
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 (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
|
||||
//! 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
|
||||
//! refused with [`Error::NonContributory`]. Honest keys and ciphertexts are never low-order, so no
|
||||
//! honest exchange and no official vector is affected (docs/01_arcanum.md).
|
||||
//! Two deliberate differences from the draft, both stricter and both invisible to honest peers and
|
||||
//! to the official vectors: a low-order X25519 public key or ciphertext part is refused with
|
||||
//! [`Error::NonContributory`], and a public key whose X25519 half is not the canonical encoding
|
||||
//! (bit 255 set, or a value of at least 2^255 - 19) is refused with [`Error::InvalidPublicKey`]
|
||||
//! (docs/01_arcanum.md).
|
||||
//!
|
||||
//! **The raw one-way KEM is not part of the release API** (QA R2-01). Without the `hazmat` feature
|
||||
//! a consumer can parse keys and ciphertexts and generate a key pair, but cannot encapsulate,
|
||||
//! decapsulate or read an X-Wing secret: a PSK must come from [`crate::exchange`], which needs both
|
||||
//! directions and binds the transcript, and sealing goes through [`crate::seal`].
|
||||
|
||||
use core::{array, fmt};
|
||||
|
||||
@@ -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]>);
|
||||
|
||||
impl SharedSecret {
|
||||
/// The raw 32 bytes, for interoperating with other X-Wing users. Prefer [`crate::exchange`],
|
||||
/// which binds the secret to the transcript and a context.
|
||||
/// The raw 32 bytes. **Hazmat** (feature `hazmat`): a one-way X-Wing secret authenticates only
|
||||
/// the receiver and is bound to no transcript, so it must never be used as a key directly.
|
||||
#[cfg(feature = "hazmat")]
|
||||
#[must_use]
|
||||
pub fn as_bytes(&self) -> &[u8; SHARED_SECRET_LEN] {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub(crate) fn bytes(&self) -> &[u8; SHARED_SECRET_LEN] {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for SharedSecret {
|
||||
@@ -84,12 +96,15 @@ impl PublicKey {
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::InvalidLength`] if it is not 1216 bytes; [`Error::InvalidPublicKey`] if the ML-KEM
|
||||
/// part fails the FIPS 203 §7.2 encapsulation key check.
|
||||
/// part fails the FIPS 203 §7.2 encapsulation key check, or the X25519 part is not canonical.
|
||||
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
|
||||
let bytes: &[u8; PUBLIC_KEY_LEN] = exact(Input::PublicKey, bytes)?;
|
||||
let m: [u8; ML_KEM_PUBLIC_KEY_LEN] = array::from_fn(|i| bytes[i]);
|
||||
let pk_m = MlKemEncapsulationKey::new(&Array::from(m)).map_err(|_| Error::InvalidPublicKey)?;
|
||||
let x: [u8; 32] = array::from_fn(|i| bytes[ML_KEM_PUBLIC_KEY_LEN + i]);
|
||||
if !is_canonical_x25519(&x) {
|
||||
return Err(Error::InvalidPublicKey);
|
||||
}
|
||||
Ok(Self { bytes: *bytes, pk_m, pk_x: X25519Public::from(x) })
|
||||
}
|
||||
|
||||
@@ -99,10 +114,12 @@ impl PublicKey {
|
||||
&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
|
||||
/// [`Error::NonContributory`] if the X25519 part of the key is a low-order point.
|
||||
#[cfg(feature = "hazmat")]
|
||||
pub fn encapsulate<R: CryptoRng + ?Sized>(&self, rng: &mut R) -> Result<(Ciphertext, SharedSecret), Error> {
|
||||
let mut eseed = Zeroizing::new([0u8; ENCAPSULATION_SEED_LEN]);
|
||||
rng.fill_bytes(eseed.as_mut_slice());
|
||||
@@ -205,6 +222,10 @@ pub struct SecretKey {
|
||||
|
||||
impl SecretKey {
|
||||
/// Generate a new key pair from the caller's RNG.
|
||||
///
|
||||
/// **`rng` must be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it
|
||||
/// once per process; never a fixed, derived or configured seed. `CryptoRng` is only a marker: a
|
||||
/// CSPRNG with a constant seed satisfies it and makes this call fully deterministic (QA R2-04).
|
||||
pub fn generate<R: CryptoRng + ?Sized>(rng: &mut R) -> Self {
|
||||
let mut seed = Zeroizing::new([0u8; SECRET_KEY_LEN]);
|
||||
rng.fill_bytes(seed.as_mut_slice());
|
||||
@@ -241,12 +262,17 @@ impl SecretKey {
|
||||
&self.public
|
||||
}
|
||||
|
||||
/// X-Wing `Decapsulate` (draft -11 §5.5).
|
||||
/// X-Wing `Decapsulate` (draft -11 §5.5). **Hazmat** (feature `hazmat`), see the module docs.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Error::NonContributory`] if the X25519 part of the ciphertext is a low-order point. A
|
||||
/// tampered ML-KEM part is not an error: ML-KEM's implicit rejection returns an unrelated secret.
|
||||
#[cfg(feature = "hazmat")]
|
||||
pub fn decapsulate(&self, ct: &Ciphertext) -> Result<SharedSecret, Error> {
|
||||
self.decapsulate_inner(ct)
|
||||
}
|
||||
|
||||
pub(crate) fn decapsulate_inner(&self, ct: &Ciphertext) -> Result<SharedSecret, Error> {
|
||||
let ct_x: [u8; 32] = array::from_fn(|i| ct.0[ML_KEM_CIPHERTEXT_LEN + i]);
|
||||
let ss_x = self.sk_x.diffie_hellman(&X25519Public::from(ct_x));
|
||||
if !ss_x.was_contributory() {
|
||||
@@ -296,6 +322,18 @@ impl fmt::Debug for SecretKey {
|
||||
// (their `zeroize` features are enabled in Cargo.toml).
|
||||
impl ZeroizeOnDrop for SecretKey {}
|
||||
|
||||
/// RFC 7748 encodes a u-coordinate as 32 little-endian bytes of a value below p = 2^255 - 19, with
|
||||
/// bit 255 clear; X25519 outputs (every honest public key) are always in that form. Decoders mask
|
||||
/// bit 255 and reduce mod p, so other encodings alias a canonical key: refuse them (QA R2-02).
|
||||
fn is_canonical_x25519(u: &[u8; 32]) -> bool {
|
||||
if u[31] & 0x80 != 0 {
|
||||
return false;
|
||||
}
|
||||
// With bit 255 clear, u >= p only for 2^255 - 19 ..= 2^255 - 1: ed..ff, then 30 x ff, then 7f.
|
||||
let at_least_p = u[31] == 0x7f && u[1..31].iter().all(|&b| b == 0xff) && u[0] >= 0xed;
|
||||
!at_least_p
|
||||
}
|
||||
|
||||
/// Copy a 32-byte ML-KEM shared key into a stack array that is wiped on drop.
|
||||
fn as32(k: &ml_kem::SharedKey) -> Zeroizing<[u8; 32]> {
|
||||
let mut out = Zeroizing::new([0u8; 32]);
|
||||
|
||||
+42
-1
@@ -68,14 +68,55 @@ fn low_order_x25519_ciphertext_is_refused() {
|
||||
fn low_order_x25519_public_key_is_refused() {
|
||||
let i = SecretKey::from_seed([0x43; 32]);
|
||||
let r = SecretKey::from_seed([0x44; 32]);
|
||||
let mut refused_at_parse = 0;
|
||||
for point in low_order_points() {
|
||||
let mut bad = *r.public_key().as_bytes();
|
||||
bad[1184..].copy_from_slice(&point);
|
||||
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!(exchange::initiate_derand(&i, &pk, b"ctx", &[0x55; 64]).err(), Some(Error::NonContributory));
|
||||
assert_eq!(arcanum::seal::seal(&pk, b"x", b"", &mut rng(1)).err(), Some(Error::NonContributory));
|
||||
}
|
||||
// 7 points with bit 255 set, plus p and p + 1.
|
||||
assert_eq!(refused_at_parse, 9);
|
||||
}
|
||||
|
||||
/// QA R2-02 boundary: p - 1 is the largest canonical u-coordinate (and low order), p is the
|
||||
/// smallest non-canonical one, and an honest key is always canonical.
|
||||
#[test]
|
||||
fn the_canonical_boundary_is_exactly_p() {
|
||||
let r = SecretKey::from_seed([0x44; 32]);
|
||||
let with_x = |x: [u8; 32]| {
|
||||
let mut b = *r.public_key().as_bytes();
|
||||
b[1184..].copy_from_slice(&x);
|
||||
PublicKey::from_bytes(&b)
|
||||
};
|
||||
let mut p_minus_1 = [0xff; 32];
|
||||
p_minus_1[0] = 0xec;
|
||||
p_minus_1[31] = 0x7f;
|
||||
let mut p = p_minus_1;
|
||||
p[0] = 0xed;
|
||||
let mut below = [0xff; 32];
|
||||
below[31] = 0x7f;
|
||||
below[1] = 0xfe; // 2^255 - 1 - 2^8: below p although its first byte is 0xff
|
||||
assert!(with_x(p_minus_1).is_ok());
|
||||
assert_eq!(with_x(p).err(), Some(Error::InvalidPublicKey));
|
||||
assert!(with_x(below).is_ok());
|
||||
assert!(PublicKey::from_bytes(r.public_key().as_bytes()).is_ok());
|
||||
}
|
||||
|
||||
/// QA A-04: X25519 ignores bit 255 of ct_X, so ct_X and ct_X ^ 0x80 give the same ss_X. The
|
||||
|
||||
@@ -116,10 +116,14 @@ fn control_the_safe_api_compiles_without_hazmat() {
|
||||
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`.
|
||||
(
|
||||
"PublicKey::encapsulate",
|
||||
"exchange::respond",
|
||||
"let k = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap(); \
|
||||
let _ = k.public_key().encapsulate(&mut Counter(0));",
|
||||
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",
|
||||
|
||||
@@ -54,6 +54,7 @@ fn a28_secret_types_are_zeroize_on_drop() {
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user