2a432f5d86
The mandatory tests of docs/02_signatures.md, against the API the doc sets out (arcanum::sign). They do not compile yet: the module does not exist. 1 kat_mldsa65: ACVP keyGen, sigGen (deterministic and hedged groups, byte for byte, through sign_randomized/sign_mu_randomized fed the vector's rnd), sigVer on the corrected file; Wycheproof sign_seed and verify. 2 kat_ed25519: RFC 8032 section 7.1 and Wycheproof, with verify_strict. 3 sig_composite: the RFC 10073 vectors s and sWithContext verify, the RFC key derives the RFC public key, own signatures verify under an independent rebuild of M', ML-DSA hedged with ctx = Label. 4 sig_halves: either half swapped in from another signature, zeroed or cut, or the halves swapped, is refused; the ML-DSA half fails an empty-ctx verifier. Not SUF-CMA (RFC 10073 9.2) is pinned. 5 sig_every_byte: any flipped byte of message, ctx, public key or signature fails; contexts are prefix-free; key bindings and app messages never verify as each other; every binding field matters. 6 sig_malformed: wrong lengths, weak and non-canonical Ed25519 keys, 0- and 256-byte contexts, a 65536-byte key id, random bytes. 7 sig_hygiene and feature_hygiene: compile-fail checks against a default-features consumer (hazmat raw interface, ml-dsa internals, non-crypto RNG, Clone), ZeroizeOnDrop, Debug; ml-dsa and ed25519-dalek in the normal graph with zeroize and without hazmat or defaults. The allocator probe covers the signing keys. 8 golden_v1.rs is untouched. Adds ml-dsa =0.1.2 (alloc, rand_core, zeroize) and ed25519-dalek =3.0.0 (zeroize) with default features off, base64 for the tests, and bumps the version to 0.2.0. The fuzz target follows with the code.
201 lines
8.8 KiB
Rust
201 lines
8.8 KiB
Rust
//! Mandatory test 7 (v0.2.0): hygiene of the signature API.
|
|
//!
|
|
//! - What a **default-features consumer** can and cannot write, by compiling small programs against
|
|
//! Arcanum without `hazmat`, the way `qa_consumer_api.rs` does for v0.1.0 (QA A-33, A-34). The
|
|
//! raw RFC interface is `hazmat` only, and none of `ml-dsa`'s own signing internals
|
|
//! (`sign_internal` with caller-chosen randomness, `sign_mu_deterministic`, `sign_deterministic`,
|
|
//! the `Signer` trait with its empty context) can be reached through Arcanum's types.
|
|
//! - The secret types are `ZeroizeOnDrop`, including the component crates' keys (which proves their
|
|
//! `zeroize` features are on), and `Debug` never prints key material.
|
|
//!
|
|
//! The feature graph (no `hazmat` anywhere, `zeroize` on) is checked in `feature_hygiene.rs`, and
|
|
//! the heap wiping by the allocator probe in `zeroize-probe/`.
|
|
|
|
mod common;
|
|
|
|
use std::path::{Path, PathBuf};
|
|
use std::process::Command;
|
|
use std::sync::Mutex;
|
|
|
|
use arcanum::sign::{AppContext, SigningKey};
|
|
use common::rng;
|
|
use zeroize::ZeroizeOnDrop;
|
|
|
|
/// The cases share one crate (its dependencies are checked once), so they must not run at once.
|
|
static LOCK: Mutex<()> = Mutex::new(());
|
|
|
|
const PRELUDE: &str = r#"
|
|
#![allow(unused)]
|
|
use core::convert::Infallible;
|
|
use rand_core::{TryCryptoRng, TryRng};
|
|
|
|
/// A counter: deterministic, and therefore NOT a cryptographic RNG.
|
|
pub struct Counter(pub u64);
|
|
impl TryRng for Counter {
|
|
type Error = Infallible;
|
|
fn try_next_u32(&mut self) -> Result<u32, Infallible> { self.0 += 1; Ok(self.0 as u32) }
|
|
fn try_next_u64(&mut self) -> Result<u64, Infallible> { self.0 += 1; Ok(self.0) }
|
|
fn try_fill_bytes(&mut self, d: &mut [u8]) -> Result<(), Infallible> {
|
|
for b in d { self.0 += 1; *b = self.0 as u8; }
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// The same counter, *claiming* to be cryptographic (a stand-in for a real CSPRNG in the control).
|
|
pub struct Claimed(pub Counter);
|
|
impl TryRng for Claimed {
|
|
type Error = Infallible;
|
|
fn try_next_u32(&mut self) -> Result<u32, Infallible> { self.0.try_next_u32() }
|
|
fn try_next_u64(&mut self) -> Result<u64, Infallible> { self.0.try_next_u64() }
|
|
fn try_fill_bytes(&mut self, d: &mut [u8]) -> Result<(), Infallible> { self.0.try_fill_bytes(d) }
|
|
}
|
|
impl TryCryptoRng for Claimed {}
|
|
|
|
fn key() -> arcanum::sign::SigningKey { arcanum::sign::SigningKey::generate(&mut Claimed(Counter(0))) }
|
|
fn ctx() -> arcanum::sign::AppContext { arcanum::sign::AppContext::new(b"consumer").unwrap() }
|
|
"#;
|
|
|
|
fn consumer_dir() -> PathBuf {
|
|
let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("sig-consumer-api");
|
|
std::fs::create_dir_all(dir.join("src")).unwrap();
|
|
let arcanum = env!("CARGO_MANIFEST_DIR").replace('\\', "/");
|
|
let manifest = format!(
|
|
"[package]\nname = \"sig-consumer-api\"\nversion = \"0.0.0\"\nedition = \"2024\"\npublish = false\n\n\
|
|
[dependencies]\narcanum = {{ path = \"{arcanum}\" }}\n\
|
|
rand_core = {{ version = \"0.10\", default-features = false }}\n\n[workspace]\n"
|
|
);
|
|
std::fs::write(dir.join("Cargo.toml"), manifest).unwrap();
|
|
if !dir.join("Cargo.lock").exists() {
|
|
std::fs::copy(Path::new(env!("CARGO_MANIFEST_DIR")).join("Cargo.lock"), dir.join("Cargo.lock")).unwrap();
|
|
}
|
|
dir
|
|
}
|
|
|
|
/// `cargo check` a consumer whose `main` body is `body`. Returns (compiled, compiler output).
|
|
fn check(body: &str) -> (bool, String) {
|
|
let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
|
let dir = consumer_dir();
|
|
std::fs::write(dir.join("src/main.rs"), format!("{PRELUDE}\nfn main() {{\n{body}\n}}\n")).unwrap();
|
|
let out = Command::new(env!("CARGO"))
|
|
.current_dir(&dir)
|
|
.args(["check", "--offline", "--quiet", "--message-format", "short"])
|
|
.env_remove("CARGO_TARGET_DIR")
|
|
.output()
|
|
.expect("run cargo check");
|
|
(out.status.success(), String::from_utf8_lossy(&out.stderr).into_owned())
|
|
}
|
|
|
|
fn assert_refused(what: &str, body: &str, needles: &[&str]) {
|
|
let (ok, err) = check(body);
|
|
assert!(!ok, "{what}: compiled against Arcanum with default features, and must not");
|
|
assert!(
|
|
needles.iter().any(|n| err.contains(n)),
|
|
"{what}: refused, but not for the expected reason ({needles:?}):\n{err}"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn control_the_release_signature_api_compiles_without_hazmat() {
|
|
let (ok, err) = check(
|
|
r#"
|
|
let mut rng = Claimed(Counter(0));
|
|
let sk = key();
|
|
let sig = sk.sign(b"plan", &ctx(), &mut rng).unwrap();
|
|
sk.verifying_key().verify(b"plan", &ctx(), &sig).unwrap();
|
|
let vk = arcanum::sign::VerifyingKey::from_bytes(sk.verifying_key().as_bytes()).unwrap();
|
|
let sig = arcanum::sign::Signature::from_bytes(sig.as_bytes()).unwrap();
|
|
vk.verify(b"plan", &ctx(), &sig).unwrap();
|
|
let stored = sk.to_bytes();
|
|
let _again = arcanum::sign::SigningKey::from_bytes(stored.as_slice()).unwrap();
|
|
let kem = arcanum::xwing::SecretKey::generate(&mut rng);
|
|
let b = arcanum::sign::bind_kem_key(&sk, b"id", kem.public_key(), (1, 2), &mut rng).unwrap();
|
|
arcanum::sign::verify_binding(&vk, b"id", kem.public_key(), (1, 2), 1, &b).unwrap();
|
|
"#,
|
|
);
|
|
assert!(ok, "the control program must compile, or the harness is blind:\n{err}");
|
|
}
|
|
|
|
/// Like QA A-33: randomness must be `CryptoRng`; a counter is refused everywhere it enters.
|
|
#[test]
|
|
fn a_non_crypto_rng_does_not_compile() {
|
|
let calls = [
|
|
("SigningKey::generate", "let _ = arcanum::sign::SigningKey::generate(&mut Counter(0));"),
|
|
("SigningKey::sign", "let _ = key().sign(b\"m\", &ctx(), &mut Counter(0));"),
|
|
(
|
|
"bind_kem_key",
|
|
"let kem = arcanum::xwing::SecretKey::from_bytes(&[1; 32]).unwrap(); \
|
|
let _ = arcanum::sign::bind_kem_key(&key(), b\"id\", kem.public_key(), (1, 2), &mut Counter(0));",
|
|
),
|
|
];
|
|
for (what, body) in calls {
|
|
assert_refused(what, body, &["CryptoRng"]);
|
|
}
|
|
}
|
|
|
|
/// Like QA A-34: the raw RFC 10073 interface (any ctx, including empty) is `hazmat` only.
|
|
#[test]
|
|
fn the_raw_interface_is_not_reachable_without_hazmat() {
|
|
let calls = [
|
|
(
|
|
"sign_composite_raw",
|
|
"let _ = arcanum::sign::sign_composite_raw(&key(), b\"m\", b\"\", &mut Claimed(Counter(0)));",
|
|
),
|
|
(
|
|
"verify_composite_raw",
|
|
"let k = key(); let s = k.sign(b\"m\", &ctx(), &mut Claimed(Counter(0))).unwrap(); \
|
|
let _ = arcanum::sign::verify_composite_raw(k.verifying_key(), b\"m\", b\"\", &s);",
|
|
),
|
|
];
|
|
for (what, body) in calls {
|
|
assert_refused(what, body, &["E0425"]);
|
|
}
|
|
}
|
|
|
|
/// `ml-dsa` 0.1.2 makes `ExpandedSigningKey::sign_internal` (caller-chosen randomness) and
|
|
/// `sign_mu_deterministic` (panics on failure) public, and its `Signer` trait signs with an
|
|
/// empty context. None may be reachable through Arcanum: no re-export, no public field, no
|
|
/// `Deref`/`AsRef` to the component keys, and an `AppContext` only from the Arcanum prefix.
|
|
#[test]
|
|
fn ml_dsa_internals_are_not_reachable() {
|
|
let calls: [(&str, &str, &[&str]); 8] = [
|
|
("re-export of ml_dsa", "use arcanum::ml_dsa;", &["E0432"]),
|
|
("re-export in sign", "use arcanum::sign::ml_dsa;", &["E0432"]),
|
|
("sign_internal through the key", "let _ = key().sign_internal(&[b\"m\"], &Default::default());", &["E0599"]),
|
|
(
|
|
"sign_mu_deterministic through the key",
|
|
"let _ = key().sign_mu_deterministic(&Default::default());",
|
|
&["E0599"],
|
|
),
|
|
("sign_deterministic through the key", "let _ = key().sign_deterministic(b\"m\", b\"\");", &["E0599"]),
|
|
("a component key field", "let k = key(); let _ = &k.ml;", &["E0609", "E0616"]),
|
|
("a foreign or empty context", "let _ = arcanum::sign::AppContext::from_raw(b\"\");", &["E0599"]),
|
|
("cloning a signing key", "let k = key(); let _ = k.clone();", &["E0599"]),
|
|
];
|
|
for (what, body, needles) in calls {
|
|
assert_refused(what, body, needles);
|
|
}
|
|
}
|
|
|
|
fn assert_zeroize_on_drop<T: ZeroizeOnDrop + ?Sized>() {}
|
|
|
|
#[test]
|
|
fn secret_types_are_zeroize_on_drop() {
|
|
assert_zeroize_on_drop::<SigningKey>();
|
|
// The component keys Arcanum holds: these bounds hold only with each crate's `zeroize` feature.
|
|
assert_zeroize_on_drop::<ml_dsa::ExpandedSigningKey<ml_dsa::MlDsa65>>();
|
|
assert_zeroize_on_drop::<ml_dsa::SigningKey<ml_dsa::MlDsa65>>();
|
|
assert_zeroize_on_drop::<ed25519_dalek::SigningKey>();
|
|
}
|
|
|
|
#[test]
|
|
fn debug_never_prints_key_material() {
|
|
let sk = SigningKey::from_bytes(&[0xab; 64]).unwrap();
|
|
let dbg = format!("{sk:?}");
|
|
assert!(!dbg.contains("ab, ab") && !dbg.contains("abab") && !dbg.contains("171"), "{dbg}");
|
|
let seeds = sk.to_bytes();
|
|
assert_eq!(seeds.as_slice(), [0xab; 64].as_slice());
|
|
let ctx = AppContext::new(b"debug").unwrap();
|
|
let sig = sk.sign(b"m", &ctx, &mut rng(70)).unwrap();
|
|
let _ = format!("{sig:?} {:?} {ctx:?}", sk.verifying_key());
|
|
}
|