Compare commits
3 Commits
853f59ca60
...
f3e17f3d5c
| Author | SHA1 | Date | |
|---|---|---|---|
| f3e17f3d5c | |||
| f31872d0d5 | |||
| 3dfc75075f |
@@ -27,6 +27,8 @@ pub mod xwing;
|
||||
|
||||
#[cfg(test)]
|
||||
mod binding_tests;
|
||||
#[cfg(test)]
|
||||
mod qa_review_tests;
|
||||
|
||||
pub use error::{Error, Input};
|
||||
pub use exchange::{Session, WIREGUARD_PSK_LEN, WireGuardPsk};
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
//! 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) 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"]));
|
||||
|
||||
// (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>(prk, &[LABEL_SEAL_KEY]);
|
||||
assert!(keys.insert(key));
|
||||
let mut nonce = [0u8; 32];
|
||||
nonce[..12].copy_from_slice(&*expand::<12>(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_eq!(keys.len(), 2 * (2 + 1024));
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//! 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));"),
|
||||
(
|
||||
"PublicKey::encapsulate",
|
||||
"let k = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap(); \
|
||||
let _ = k.public_key().encapsulate(&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,212 @@
|
||||
//! 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>();
|
||||
}
|
||||
|
||||
/// 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