cascade: add CCC v2 seal and open with suite policy
Independent HKDF-SHA-512 key and nonce per layer per round, AAD bound to suite and layout, at most 16 rounds, fail closed on policy or self-test. Refs: R3-2, R3-3, R3-6
This commit is contained in:
parent
7776380a93
commit
7058c5ffa4
|
|
@ -0,0 +1,157 @@
|
||||||
|
//! The CCC v2 cascade (R3-2, D-8).
|
||||||
|
//!
|
||||||
|
//! For round `r` (0-based, up to [`MAX_ROUNDS`]) and layer `i` of a suite:
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! okm(r,i) = HKDF-SHA-512(ikm = root key,
|
||||||
|
//! salt = per-message or per-record salt (32 bytes),
|
||||||
|
//! info = u16be(len(domain)) || domain || "ccc2"
|
||||||
|
//! || u8(r) || u8(i) || u32be(alg_id(i)))
|
||||||
|
//! key(r,i) || nonce(r,i) = okm(r,i)
|
||||||
|
//! aad(r,i) = u16be(len(aad)) || aad || u16be(suite_id) || u8(rounds) || u8(r) || u8(i)
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! Sealing runs round 0 layer 0 first and the last layer of the last round
|
||||||
|
//! last; opening runs the reverse. Every layer of every round has an
|
||||||
|
//! independent key and nonce (S4). Nonces are derived, never random, and the
|
||||||
|
//! salt is fresh per message or record, so nonce reuse cannot happen. The AAD
|
||||||
|
//! binds the caller's context (S5) plus the suite, the round count and the
|
||||||
|
//! layer position, so a ciphertext cannot be opened under another suite or
|
||||||
|
//! layout. Any failure while opening is reported as one
|
||||||
|
//! [`CascadeError::AuthenticationFailed`]: the caller never learns which layer
|
||||||
|
//! failed.
|
||||||
|
|
||||||
|
use ccc_crypto_core::{AeadAlgorithm, KdfAlgorithm};
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
use crate::suite::{ResolvedSuite, MAX_ROUNDS};
|
||||||
|
use crate::CascadeError;
|
||||||
|
|
||||||
|
/// Salt length for every message and record.
|
||||||
|
pub const SALT_LEN: usize = 32;
|
||||||
|
/// Shortest accepted root key.
|
||||||
|
pub const MIN_ROOT_KEY_LEN: usize = 32;
|
||||||
|
|
||||||
|
/// What a cascade seal or open is about: the caller's domain label and AAD.
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub struct Context<'a> {
|
||||||
|
/// Domain label, e.g. `b"lum/v1/rec"` or `b"lum/lgp/msg"`.
|
||||||
|
pub domain: &'a [u8],
|
||||||
|
/// Associated data binding the ciphertext to its place.
|
||||||
|
pub aad: &'a [u8],
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn layer_info(domain: &[u8], round: u8, layer: u8, alg: AeadAlgorithm) -> Vec<u8> {
|
||||||
|
let mut info = Vec::with_capacity(domain.len() + 12);
|
||||||
|
info.extend_from_slice(&(domain.len() as u16).to_be_bytes());
|
||||||
|
info.extend_from_slice(domain);
|
||||||
|
info.extend_from_slice(b"ccc2");
|
||||||
|
info.push(round);
|
||||||
|
info.push(layer);
|
||||||
|
info.extend_from_slice(&(alg as u32).to_be_bytes());
|
||||||
|
info
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn layer_aad(aad: &[u8], suite: u16, rounds: u8, round: u8, layer: u8) -> Vec<u8> {
|
||||||
|
let mut out = Vec::with_capacity(aad.len() + 7);
|
||||||
|
out.extend_from_slice(&(aad.len() as u16).to_be_bytes());
|
||||||
|
out.extend_from_slice(aad);
|
||||||
|
out.extend_from_slice(&suite.to_be_bytes());
|
||||||
|
out.push(rounds);
|
||||||
|
out.push(round);
|
||||||
|
out.push(layer);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn check_inputs(root_key: &[u8], salt: &[u8], ctx: &Context<'_>) -> Result<(), CascadeError> {
|
||||||
|
if root_key.len() < MIN_ROOT_KEY_LEN {
|
||||||
|
return Err(CascadeError::InvalidInput("root key shorter than 32 bytes"));
|
||||||
|
}
|
||||||
|
if salt.len() != SALT_LEN {
|
||||||
|
return Err(CascadeError::InvalidInput("salt must be 32 bytes"));
|
||||||
|
}
|
||||||
|
if ctx.domain.len() > u16::MAX as usize || ctx.aad.len() > u16::MAX as usize {
|
||||||
|
return Err(CascadeError::InvalidInput("domain or aad too long"));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wiped-on-drop bytes.
|
||||||
|
pub(crate) type SecretVec = Zeroizing<Vec<u8>>;
|
||||||
|
|
||||||
|
/// Derive `(key, nonce)` for one layer.
|
||||||
|
pub(crate) fn layer_key(
|
||||||
|
suite: &ResolvedSuite,
|
||||||
|
root_key: &[u8],
|
||||||
|
salt: &[u8],
|
||||||
|
info: &[u8],
|
||||||
|
alg: AeadAlgorithm,
|
||||||
|
) -> Result<(SecretVec, SecretVec), CascadeError> {
|
||||||
|
let okm = suite.kdf.derive_key(KdfAlgorithm::Sha512, root_key, salt, info, alg.key_len() + alg.nonce_len())?;
|
||||||
|
let key = Zeroizing::new(okm[..alg.key_len()].to_vec());
|
||||||
|
let nonce = Zeroizing::new(okm[alg.key_len()..].to_vec());
|
||||||
|
Ok((key, nonce))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_rounds(rounds: u8) -> Result<(), CascadeError> {
|
||||||
|
if rounds == 0 || rounds > MAX_ROUNDS {
|
||||||
|
return Err(CascadeError::Policy(format!("rounds must be 1..={MAX_ROUNDS}, got {rounds}")));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seal `plaintext` with `rounds` passes of `suite`.
|
||||||
|
///
|
||||||
|
/// The output is the bare cascade ciphertext (plaintext length plus one tag
|
||||||
|
/// per layer per round); the caller frames it (version, suite, salt).
|
||||||
|
pub fn seal(
|
||||||
|
suite: &ResolvedSuite,
|
||||||
|
rounds: u8,
|
||||||
|
root_key: &[u8],
|
||||||
|
salt: &[u8],
|
||||||
|
ctx: Context<'_>,
|
||||||
|
plaintext: &[u8],
|
||||||
|
) -> Result<Vec<u8>, CascadeError> {
|
||||||
|
check_rounds(rounds)?;
|
||||||
|
check_inputs(root_key, salt, &ctx)?;
|
||||||
|
let mut data = Zeroizing::new(plaintext.to_vec());
|
||||||
|
for r in 0..rounds {
|
||||||
|
for (i, (alg, provider)) in suite.layers.iter().enumerate() {
|
||||||
|
let i = i as u8;
|
||||||
|
let (key, nonce) = layer_key(suite, root_key, salt, &layer_info(ctx.domain, r, i, *alg), *alg)?;
|
||||||
|
let aad = layer_aad(ctx.aad, suite.id, rounds, r, i);
|
||||||
|
data = Zeroizing::new(provider.encrypt_aead(*alg, &key, &nonce, &data, &aad)?);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(data.to_vec())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Open a cascade ciphertext sealed by [`seal`] with the same inputs.
|
||||||
|
pub fn open(
|
||||||
|
suite: &ResolvedSuite,
|
||||||
|
rounds: u8,
|
||||||
|
root_key: &[u8],
|
||||||
|
salt: &[u8],
|
||||||
|
ctx: Context<'_>,
|
||||||
|
ciphertext: &[u8],
|
||||||
|
) -> Result<Zeroizing<Vec<u8>>, CascadeError> {
|
||||||
|
check_rounds(rounds)?;
|
||||||
|
check_inputs(root_key, salt, &ctx)?;
|
||||||
|
if ciphertext.len() < suite.overhead_per_round() * rounds as usize {
|
||||||
|
return Err(CascadeError::AuthenticationFailed);
|
||||||
|
}
|
||||||
|
let mut data = Zeroizing::new(ciphertext.to_vec());
|
||||||
|
for r in (0..rounds).rev() {
|
||||||
|
for (i, (alg, provider)) in suite.layers.iter().enumerate().rev() {
|
||||||
|
let i = i as u8;
|
||||||
|
let (key, nonce) = layer_key(suite, root_key, salt, &layer_info(ctx.domain, r, i, *alg), *alg)?;
|
||||||
|
let aad = layer_aad(ctx.aad, suite.id, rounds, r, i);
|
||||||
|
data = Zeroizing::new(
|
||||||
|
provider
|
||||||
|
.decrypt_aead(*alg, &key, &nonce, &data, &aad)
|
||||||
|
.map_err(|_| CascadeError::AuthenticationFailed)?,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(data)
|
||||||
|
}
|
||||||
|
|
@ -1,20 +1,57 @@
|
||||||
//! # ccc-cascade
|
//! # ccc-cascade
|
||||||
//!
|
//!
|
||||||
//! CCC v2 (design: "Cascade encryption: CCC v2", D-8, D-25). Nothing here is
|
//! CCC v2 (design: "Cascade encryption: CCC v2", D-8, D-25): a cascade of
|
||||||
//! specific to LetUsMsg and nothing does I/O.
|
//! AEAD layers from several providers, with an independent HKDF-SHA-512 key
|
||||||
|
//! and nonce for every layer of every round, a random 32-byte salt per message
|
||||||
|
//! or record, AAD binding, bucket padding and a STREAM mode for blobs. Plus the
|
||||||
|
//! suite registry and the policy checks (at least one vetted layer, FIPS vetted
|
||||||
|
//! layer in release builds, adjacent provider diversity, self-tests passed).
|
||||||
|
//!
|
||||||
|
//! Nothing here is specific to LetUsMsg and nothing does I/O.
|
||||||
#![forbid(unsafe_code)]
|
#![forbid(unsafe_code)]
|
||||||
#![warn(missing_docs)]
|
#![warn(missing_docs)]
|
||||||
|
|
||||||
|
pub mod cascade;
|
||||||
pub mod padding;
|
pub mod padding;
|
||||||
pub mod secret;
|
pub mod secret;
|
||||||
|
pub mod suite;
|
||||||
|
pub mod suites;
|
||||||
|
|
||||||
|
pub use cascade::{open, seal, Context, SALT_LEN};
|
||||||
pub use padding::{pad, unpad, Bucketing};
|
pub use padding::{pad, unpad, Bucketing};
|
||||||
pub use secret::{Key32, SecretBytes};
|
pub use secret::{Key32, SecretBytes};
|
||||||
|
pub use suite::{Layer, Policy, ProviderSet, ResolvedSuite, Suite, MAX_ROUNDS};
|
||||||
|
|
||||||
|
use ccc_crypto_core::CryptoError;
|
||||||
|
|
||||||
/// Errors from the cascade.
|
/// Errors from the cascade.
|
||||||
#[derive(Debug, Clone, thiserror::Error)]
|
#[derive(Debug, Clone, thiserror::Error)]
|
||||||
pub enum CascadeError {
|
pub enum CascadeError {
|
||||||
|
/// A suite, round count or layout breaks the policy (fail closed).
|
||||||
|
#[error("policy: {0}")]
|
||||||
|
Policy(String),
|
||||||
|
/// An algorithm failed its provider's self-test; no fallback (D-28).
|
||||||
|
#[error("self-test failed: {0}")]
|
||||||
|
SelfTestFailed(String),
|
||||||
|
/// Opening failed. Never says which layer.
|
||||||
|
#[error("authentication failed")]
|
||||||
|
AuthenticationFailed,
|
||||||
/// Malformed input.
|
/// Malformed input.
|
||||||
#[error("invalid input: {0}")]
|
#[error("invalid input: {0}")]
|
||||||
InvalidInput(&'static str),
|
InvalidInput(&'static str),
|
||||||
|
/// A provider error while sealing or deriving keys.
|
||||||
|
#[error("crypto: {0}")]
|
||||||
|
Crypto(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<CryptoError> for CascadeError {
|
||||||
|
fn from(e: CryptoError) -> Self {
|
||||||
|
match e {
|
||||||
|
CryptoError::AuthenticationFailed => Self::AuthenticationFailed,
|
||||||
|
other => Self::Crypto(other.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,179 @@
|
||||||
|
//! Cascade suites, providers and policy (R3-3, R3-6, R3-7).
|
||||||
|
//!
|
||||||
|
//! A suite is an ordered list of layers, each an AEAD from a named provider.
|
||||||
|
//! Before a suite is used it is *resolved* against the providers this build
|
||||||
|
//! has, and checked against a [`Policy`]:
|
||||||
|
//!
|
||||||
|
//! - at least one vetted layer (S4);
|
||||||
|
//! - in release builds, a vetted layer from a FIPS-mode provider (D-26);
|
||||||
|
//! - optionally, adjacent layers from different providers;
|
||||||
|
//! - experimental layers only when the policy allows them;
|
||||||
|
//! - every layer's algorithm passed its provider's self-test (fail closed, S6,
|
||||||
|
//! D-28): there is no fallback suite.
|
||||||
|
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use ccc_crypto_core::{AeadAlgorithm, CryptoProvider, Tier};
|
||||||
|
|
||||||
|
use crate::CascadeError;
|
||||||
|
|
||||||
|
/// Most rounds any suite may use (D-25).
|
||||||
|
pub const MAX_ROUNDS: u8 = 16;
|
||||||
|
|
||||||
|
/// One layer of a suite.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Layer {
|
||||||
|
/// The AEAD.
|
||||||
|
pub aead: AeadAlgorithm,
|
||||||
|
/// The provider that runs it (`"wolfssl"`, `"rustcrypto"`, ...).
|
||||||
|
pub provider: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A named, versioned suite.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Suite {
|
||||||
|
/// Stable suite ID; part of every envelope and of the AAD.
|
||||||
|
pub id: u16,
|
||||||
|
/// Name for logs and diagnostics.
|
||||||
|
pub name: &'static str,
|
||||||
|
/// Layers, applied first to last when sealing.
|
||||||
|
pub layers: Vec<Layer>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The rules a suite must meet.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Policy {
|
||||||
|
/// The vetted layer must come from a FIPS-mode provider (release builds).
|
||||||
|
pub require_fips_vetted_layer: bool,
|
||||||
|
/// Adjacent layers must come from different providers.
|
||||||
|
pub require_distinct_adjacent_providers: bool,
|
||||||
|
/// Experimental-tier layers are allowed.
|
||||||
|
pub allow_experimental: bool,
|
||||||
|
/// Fewest layers allowed.
|
||||||
|
pub min_layers: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Policy {
|
||||||
|
/// Development builds: everything but the FIPS requirement.
|
||||||
|
pub fn development() -> Self {
|
||||||
|
Self {
|
||||||
|
require_fips_vetted_layer: false,
|
||||||
|
require_distinct_adjacent_providers: false,
|
||||||
|
allow_experimental: false,
|
||||||
|
min_layers: 1,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Release builds (D-26): the vetted layer must come from wolfCrypt in
|
||||||
|
/// FIPS mode. A build without the FIPS module cannot resolve any suite.
|
||||||
|
pub fn release() -> Self {
|
||||||
|
Self { require_fips_vetted_layer: true, ..Self::development() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The providers this build has, with the algorithms that failed self-test.
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
pub struct ProviderSet {
|
||||||
|
providers: HashMap<&'static str, Arc<dyn CryptoProvider>>,
|
||||||
|
failed: HashSet<(&'static str, u32)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ProviderSet {
|
||||||
|
/// An empty set.
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add `provider` after running its self-test. Algorithms that fail are
|
||||||
|
/// recorded and every suite using them refuses to resolve.
|
||||||
|
pub fn add(&mut self, provider: Arc<dyn CryptoProvider>) -> &mut Self {
|
||||||
|
let name = provider.provider_name();
|
||||||
|
let report = provider.self_test();
|
||||||
|
for r in report.results.iter().filter(|r| !r.passed) {
|
||||||
|
self.failed.insert((name, r.algo_id));
|
||||||
|
}
|
||||||
|
self.providers.insert(name, provider);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The provider called `name`.
|
||||||
|
pub fn get(&self, name: &str) -> Option<&Arc<dyn CryptoProvider>> {
|
||||||
|
self.providers.get(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `(provider, algorithm)` failed its self-test.
|
||||||
|
pub fn failed_self_test(&self, provider: &str, algo_id: u32) -> bool {
|
||||||
|
self.failed.iter().any(|(p, a)| *p == provider && *a == algo_id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve `suite` under `policy`.
|
||||||
|
pub fn resolve(&self, suite: &Suite, policy: &Policy) -> Result<ResolvedSuite, CascadeError> {
|
||||||
|
let deny = |m: String| Err(CascadeError::Policy(format!("suite {}: {m}", suite.name)));
|
||||||
|
if suite.layers.len() < policy.min_layers.max(1) {
|
||||||
|
return deny(format!("needs at least {} layers", policy.min_layers.max(1)));
|
||||||
|
}
|
||||||
|
let mut layers = Vec::with_capacity(suite.layers.len());
|
||||||
|
for (i, l) in suite.layers.iter().enumerate() {
|
||||||
|
let Some(p) = self.providers.get(l.provider) else {
|
||||||
|
return deny(format!("layer {i}: provider {} is not in this build", l.provider));
|
||||||
|
};
|
||||||
|
if self.failed_self_test(l.provider, l.aead as u32) {
|
||||||
|
return Err(CascadeError::SelfTestFailed(format!("{} in {}", l.aead.name(), l.provider)));
|
||||||
|
}
|
||||||
|
let caps = p.capabilities();
|
||||||
|
if !caps.aead.get(&l.aead).is_some_and(|c| c.available) {
|
||||||
|
return deny(format!("layer {i}: {} not available in {}", l.aead.name(), l.provider));
|
||||||
|
}
|
||||||
|
if l.aead.tier() == Tier::Experimental && !policy.allow_experimental {
|
||||||
|
return deny(format!("layer {i}: experimental {} not allowed", l.aead.name()));
|
||||||
|
}
|
||||||
|
layers.push((l.aead, p.clone()));
|
||||||
|
}
|
||||||
|
let vetted: Vec<_> =
|
||||||
|
suite.layers.iter().filter(|l| l.aead.tier() == Tier::Vetted).map(|l| l.provider).collect();
|
||||||
|
if vetted.is_empty() {
|
||||||
|
return deny("no vetted layer".into());
|
||||||
|
}
|
||||||
|
if policy.require_fips_vetted_layer && !vetted.iter().any(|p| self.providers[p].fips_mode()) {
|
||||||
|
return deny("no vetted layer from a FIPS-mode provider".into());
|
||||||
|
}
|
||||||
|
if policy.require_distinct_adjacent_providers && suite.layers.windows(2).any(|w| w[0].provider == w[1].provider)
|
||||||
|
{
|
||||||
|
return deny("adjacent layers share a provider".into());
|
||||||
|
}
|
||||||
|
// The key schedule uses HKDF-SHA-512 from the first vetted layer's
|
||||||
|
// provider (the FIPS module in release builds).
|
||||||
|
let kdf = self.providers[vetted[0]].clone();
|
||||||
|
Ok(ResolvedSuite { id: suite.id, name: suite.name, layers, kdf })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A suite checked against a policy, with its providers attached.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct ResolvedSuite {
|
||||||
|
/// Suite ID.
|
||||||
|
pub id: u16,
|
||||||
|
/// Suite name.
|
||||||
|
pub name: &'static str,
|
||||||
|
pub(crate) layers: Vec<(AeadAlgorithm, Arc<dyn CryptoProvider>)>,
|
||||||
|
pub(crate) kdf: Arc<dyn CryptoProvider>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ResolvedSuite {
|
||||||
|
/// Number of layers.
|
||||||
|
pub fn layer_count(&self) -> usize {
|
||||||
|
self.layers.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bytes one round adds (one tag per layer).
|
||||||
|
pub fn overhead_per_round(&self) -> usize {
|
||||||
|
self.layers.iter().map(|(a, _)| a.tag_len()).sum()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Debug for ResolvedSuite {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("ResolvedSuite").field("id", &self.id).field("name", &self.name).finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,72 @@
|
||||||
|
//! Built-in suites (R3-1): the registry's named, versioned suites. IDs are
|
||||||
|
//! stable: they are part of every envelope and of the AAD.
|
||||||
|
//!
|
||||||
|
//! LetUsMsg's profiles pick from these in `lum-crypto` (R3-10).
|
||||||
|
|
||||||
|
use ccc_crypto_core::AeadAlgorithm::{AesGcm256, AesGcmSiv256, AsconAead128, ChaCha20Poly1305, XChaCha20Poly1305};
|
||||||
|
|
||||||
|
use crate::suite::{Layer, Suite};
|
||||||
|
|
||||||
|
const fn layer(aead: ccc_crypto_core::AeadAlgorithm, provider: &'static str) -> Layer {
|
||||||
|
Layer { aead, provider }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Floor: one vetted layer (AES-256-GCM from wolfCrypt).
|
||||||
|
pub fn floor_aes() -> Suite {
|
||||||
|
Suite { id: 1, name: "floor-aes", layers: vec![layer(AesGcm256, "wolfssl")] }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Standard+: two layers, two providers, two design families.
|
||||||
|
pub fn standard_2() -> Suite {
|
||||||
|
Suite {
|
||||||
|
id: 2,
|
||||||
|
name: "standard-2",
|
||||||
|
layers: vec![layer(AesGcm256, "wolfssl"), layer(XChaCha20Poly1305, "rustcrypto")],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// High: three layers alternating providers.
|
||||||
|
pub fn high_3() -> Suite {
|
||||||
|
Suite {
|
||||||
|
id: 3,
|
||||||
|
name: "high-3",
|
||||||
|
layers: vec![
|
||||||
|
layer(XChaCha20Poly1305, "rustcrypto"),
|
||||||
|
layer(AesGcm256, "wolfssl"),
|
||||||
|
layer(AesGcmSiv256, "rustcrypto"),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ultra: three layers from two providers including a conservative
|
||||||
|
/// alternative (Ascon-AEAD128), with adjacent layers from different providers.
|
||||||
|
pub fn ultra_3() -> Suite {
|
||||||
|
Suite {
|
||||||
|
id: 4,
|
||||||
|
name: "ultra-3",
|
||||||
|
layers: vec![
|
||||||
|
layer(XChaCha20Poly1305, "rustcrypto"),
|
||||||
|
layer(AesGcm256, "wolfssl"),
|
||||||
|
layer(AsconAead128, "rustcrypto"),
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Storage at rest for Standard: two layers (design: storage cascade row).
|
||||||
|
pub fn storage_2() -> Suite {
|
||||||
|
Suite {
|
||||||
|
id: 5,
|
||||||
|
name: "storage-2",
|
||||||
|
layers: vec![layer(AesGcmSiv256, "rustcrypto"), layer(ChaCha20Poly1305, "wolfssl")],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every built-in suite.
|
||||||
|
pub fn all() -> Vec<Suite> {
|
||||||
|
vec![floor_aes(), standard_2(), high_3(), ultra_3(), storage_2()]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The built-in suite with `id`.
|
||||||
|
pub fn by_id(id: u16) -> Option<Suite> {
|
||||||
|
all().into_iter().find(|s| s.id == id)
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,225 @@
|
||||||
|
//! Cascade tests over the wolfSSL provider, plus a delegating test provider
|
||||||
|
//! that lets the policy checks see other provider names, FIPS mode and
|
||||||
|
//! self-test failures.
|
||||||
|
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use ccc_crypto_core::{
|
||||||
|
AeadAlgorithm::{self, AesGcm256, ChaCha20Poly1305, XChaCha20Poly1305},
|
||||||
|
AeadProvider, AlgoTestResult, BenchmarkReport, CryptoError, CryptoProvider, HashAlgorithm, HashProvider,
|
||||||
|
KdfAlgorithm, KdfProvider, MacAlgorithm, MacProvider, ProviderCapabilities, SelfTestReport,
|
||||||
|
};
|
||||||
|
use ccc_crypto_wolfssl::WolfSslProvider;
|
||||||
|
use zeroize::Zeroizing;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// Delegates to wolfSSL under another name, with a chosen FIPS flag and
|
||||||
|
/// optionally one algorithm failing its self-test.
|
||||||
|
struct TestProvider {
|
||||||
|
name: &'static str,
|
||||||
|
fips: bool,
|
||||||
|
fail: Option<AeadAlgorithm>,
|
||||||
|
inner: WolfSslProvider,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TestProvider {
|
||||||
|
fn arc(name: &'static str, fips: bool, fail: Option<AeadAlgorithm>) -> Arc<dyn CryptoProvider> {
|
||||||
|
Arc::new(Self { name, fips, fail, inner: WolfSslProvider::new() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AeadProvider for TestProvider {
|
||||||
|
fn encrypt_aead(&self, a: AeadAlgorithm, k: &[u8], n: &[u8], p: &[u8], aad: &[u8]) -> Result<Vec<u8>, CryptoError> {
|
||||||
|
self.inner.encrypt_aead(a, k, n, p, aad)
|
||||||
|
}
|
||||||
|
fn decrypt_aead(&self, a: AeadAlgorithm, k: &[u8], n: &[u8], c: &[u8], aad: &[u8]) -> Result<Vec<u8>, CryptoError> {
|
||||||
|
self.inner.decrypt_aead(a, k, n, c, aad)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl KdfProvider for TestProvider {
|
||||||
|
fn derive_key(
|
||||||
|
&self,
|
||||||
|
a: KdfAlgorithm,
|
||||||
|
ikm: &[u8],
|
||||||
|
salt: &[u8],
|
||||||
|
info: &[u8],
|
||||||
|
len: usize,
|
||||||
|
) -> Result<Zeroizing<Vec<u8>>, CryptoError> {
|
||||||
|
self.inner.derive_key(a, ikm, salt, info, len)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl MacProvider for TestProvider {
|
||||||
|
fn compute_mac(&self, a: MacAlgorithm, k: &[u8], d: &[u8]) -> Result<Vec<u8>, CryptoError> {
|
||||||
|
self.inner.compute_mac(a, k, d)
|
||||||
|
}
|
||||||
|
fn verify_mac(&self, a: MacAlgorithm, k: &[u8], d: &[u8], m: &[u8]) -> Result<bool, CryptoError> {
|
||||||
|
self.inner.verify_mac(a, k, d, m)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl HashProvider for TestProvider {
|
||||||
|
fn hash(&self, a: HashAlgorithm, d: &[u8]) -> Result<Vec<u8>, CryptoError> {
|
||||||
|
self.inner.hash(a, d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl CryptoProvider for TestProvider {
|
||||||
|
fn provider_name(&self) -> &'static str {
|
||||||
|
self.name
|
||||||
|
}
|
||||||
|
fn fips_mode(&self) -> bool {
|
||||||
|
self.fips
|
||||||
|
}
|
||||||
|
fn capabilities(&self) -> ProviderCapabilities {
|
||||||
|
self.inner.capabilities()
|
||||||
|
}
|
||||||
|
fn self_test(&self) -> SelfTestReport {
|
||||||
|
let mut r = self.inner.self_test();
|
||||||
|
if let Some(a) = self.fail {
|
||||||
|
r.results.push(AlgoTestResult {
|
||||||
|
algo_id: a as u32,
|
||||||
|
algo_name: a.name().into(),
|
||||||
|
passed: false,
|
||||||
|
error_message: Some("injected".into()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
r
|
||||||
|
}
|
||||||
|
fn benchmark(&self) -> BenchmarkReport {
|
||||||
|
self.inner.benchmark()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn providers() -> ProviderSet {
|
||||||
|
let mut set = ProviderSet::new();
|
||||||
|
set.add(Arc::new(WolfSslProvider::new()));
|
||||||
|
set.add(TestProvider::arc("other", false, None));
|
||||||
|
set.add(TestProvider::arc("fips", true, None));
|
||||||
|
set
|
||||||
|
}
|
||||||
|
|
||||||
|
fn suite(id: u16, layers: &[(AeadAlgorithm, &'static str)]) -> Suite {
|
||||||
|
Suite { id, name: "test", layers: layers.iter().map(|(aead, provider)| Layer { aead: *aead, provider }).collect() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn three() -> ResolvedSuite {
|
||||||
|
let s = suite(9, &[(XChaCha20Poly1305, "other"), (AesGcm256, "wolfssl"), (ChaCha20Poly1305, "other")]);
|
||||||
|
providers().resolve(&s, &Policy::development()).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
const KEY: [u8; 32] = [7; 32];
|
||||||
|
const SALT: [u8; 32] = [3; 32];
|
||||||
|
|
||||||
|
fn ctx(aad: &[u8]) -> Context<'_> {
|
||||||
|
Context { domain: b"test/v1", aad }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_trip_across_rounds() {
|
||||||
|
let s = three();
|
||||||
|
for rounds in [1u8, 3, 16] {
|
||||||
|
let ct = seal(&s, rounds, &KEY, &SALT, ctx(b"a"), b"hello cascade").unwrap();
|
||||||
|
assert_eq!(ct.len(), 13 + 16 * 3 * rounds as usize, "one tag per layer per round");
|
||||||
|
assert_eq!(open(&s, rounds, &KEY, &SALT, ctx(b"a"), &ct).unwrap().as_slice(), b"hello cascade");
|
||||||
|
}
|
||||||
|
// Ultra's 16 rounds of 3 layers add 768 bytes (design figure).
|
||||||
|
assert_eq!(seal(&s, 16, &KEY, &SALT, ctx(b""), b"").unwrap().len(), 768);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn any_change_fails_closed_with_one_error() {
|
||||||
|
let s = three();
|
||||||
|
let ct = seal(&s, 3, &KEY, &SALT, ctx(b"vault|table|key"), b"secret").unwrap();
|
||||||
|
let auth = |r: Result<Zeroizing<Vec<u8>>, CascadeError>| matches!(r, Err(CascadeError::AuthenticationFailed));
|
||||||
|
for i in [0, ct.len() / 2, ct.len() - 1] {
|
||||||
|
let mut t = ct.clone();
|
||||||
|
t[i] ^= 1;
|
||||||
|
assert!(auth(open(&s, 3, &KEY, &SALT, ctx(b"vault|table|key"), &t)), "byte {i}");
|
||||||
|
}
|
||||||
|
assert!(auth(open(&s, 3, &KEY, &SALT, ctx(b"vault|table|other"), &ct)), "aad");
|
||||||
|
assert!(auth(open(&s, 3, &KEY, &[4; 32], ctx(b"vault|table|key"), &ct)), "salt");
|
||||||
|
assert!(auth(open(&s, 3, &[8; 32], &SALT, ctx(b"vault|table|key"), &ct)), "key");
|
||||||
|
assert!(auth(open(&s, 2, &KEY, &SALT, ctx(b"vault|table|key"), &ct)), "rounds");
|
||||||
|
assert!(auth(open(&s, 3, &KEY, &SALT, ctx(b"vault|table|key"), &ct[..10])), "truncated");
|
||||||
|
let other_domain = Context { domain: b"test/v2", aad: b"vault|table|key" };
|
||||||
|
assert!(auth(open(&s, 3, &KEY, &SALT, other_domain, &ct)), "domain");
|
||||||
|
// Same layers under another suite ID do not open (AAD binds the suite).
|
||||||
|
let same_layers = suite(10, &[(XChaCha20Poly1305, "other"), (AesGcm256, "wolfssl"), (ChaCha20Poly1305, "other")]);
|
||||||
|
let s10 = providers().resolve(&same_layers, &Policy::development()).unwrap();
|
||||||
|
assert!(auth(open(&s10, 3, &KEY, &SALT, ctx(b"vault|table|key"), &ct)), "suite id");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn salt_makes_identical_messages_differ() {
|
||||||
|
let s = three();
|
||||||
|
let a = seal(&s, 1, &KEY, &[1; 32], ctx(b""), b"same").unwrap();
|
||||||
|
let b = seal(&s, 1, &KEY, &[2; 32], ctx(b""), b"same").unwrap();
|
||||||
|
assert_ne!(a, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn layer_keys_and_nonces_are_all_distinct() {
|
||||||
|
let s = three();
|
||||||
|
let mut seen = std::collections::HashSet::new();
|
||||||
|
for r in 0..16u8 {
|
||||||
|
for (i, (alg, _)) in s.layers.iter().enumerate() {
|
||||||
|
let (k, n) =
|
||||||
|
cascade::layer_key(&s, &KEY, &SALT, &cascade::layer_info(b"d", r, i as u8, *alg), *alg).unwrap();
|
||||||
|
assert!(seen.insert(k.to_vec()), "key reuse at round {r} layer {i}");
|
||||||
|
assert!(seen.insert(n.to_vec()), "nonce reuse at round {r} layer {i}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rounds_are_capped_at_16() {
|
||||||
|
let s = three();
|
||||||
|
assert!(matches!(seal(&s, 0, &KEY, &SALT, ctx(b""), b"x"), Err(CascadeError::Policy(_))));
|
||||||
|
assert!(matches!(seal(&s, 17, &KEY, &SALT, ctx(b""), b"x"), Err(CascadeError::Policy(_))));
|
||||||
|
assert!(matches!(seal(&s, 1, &[0; 16], &SALT, ctx(b""), b"x"), Err(CascadeError::InvalidInput(_))));
|
||||||
|
assert!(matches!(seal(&s, 1, &KEY, &[0; 16], ctx(b""), b"x"), Err(CascadeError::InvalidInput(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn policy_checks() {
|
||||||
|
let p = providers();
|
||||||
|
let dev = Policy::development();
|
||||||
|
let missing = suite(1, &[(AesGcm256, "absent")]);
|
||||||
|
assert!(matches!(p.resolve(&missing, &dev), Err(CascadeError::Policy(_))));
|
||||||
|
let empty = suite(1, &[]);
|
||||||
|
assert!(matches!(p.resolve(&empty, &dev), Err(CascadeError::Policy(_))));
|
||||||
|
// wolfSSL here is the open-source build: not FIPS, so release refuses it.
|
||||||
|
let wolf = suite(1, &[(AesGcm256, "wolfssl")]);
|
||||||
|
assert!(p.resolve(&wolf, &dev).is_ok());
|
||||||
|
assert!(matches!(p.resolve(&wolf, &Policy::release()), Err(CascadeError::Policy(_))));
|
||||||
|
let fips = suite(1, &[(AesGcm256, "fips"), (XChaCha20Poly1305, "other")]);
|
||||||
|
assert!(p.resolve(&fips, &Policy::release()).is_ok());
|
||||||
|
let distinct = Policy { require_distinct_adjacent_providers: true, ..dev.clone() };
|
||||||
|
let same = suite(1, &[(AesGcm256, "wolfssl"), (ChaCha20Poly1305, "wolfssl")]);
|
||||||
|
assert!(matches!(p.resolve(&same, &distinct), Err(CascadeError::Policy(_))));
|
||||||
|
assert!(p.resolve(&fips, &distinct).is_ok());
|
||||||
|
// Unavailable algorithm in the provider: refused, not substituted.
|
||||||
|
let ascon = suite(1, &[(AesGcm256, "wolfssl"), (AeadAlgorithm::AsconAead128, "wolfssl")]);
|
||||||
|
assert!(matches!(p.resolve(&ascon, &dev), Err(CascadeError::Policy(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn self_test_failure_blocks_every_suite_using_it() {
|
||||||
|
let mut p = providers();
|
||||||
|
p.add(TestProvider::arc("broken", false, Some(ChaCha20Poly1305)));
|
||||||
|
let uses = suite(1, &[(AesGcm256, "wolfssl"), (ChaCha20Poly1305, "broken")]);
|
||||||
|
assert!(matches!(p.resolve(&uses, &Policy::development()), Err(CascadeError::SelfTestFailed(_))));
|
||||||
|
// Other algorithms of that provider still work: the failure is per algorithm.
|
||||||
|
let other = suite(1, &[(AesGcm256, "broken")]);
|
||||||
|
assert!(p.resolve(&other, &Policy::development()).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn builtin_suites_have_unique_ids_and_a_vetted_layer() {
|
||||||
|
let all = suites::all();
|
||||||
|
let ids: std::collections::HashSet<_> = all.iter().map(|s| s.id).collect();
|
||||||
|
assert_eq!(ids.len(), all.len());
|
||||||
|
for s in &all {
|
||||||
|
assert!(s.layers.iter().any(|l| l.aead.tier() == ccc_crypto_core::Tier::Vetted), "{}", s.name);
|
||||||
|
assert_eq!(suites::by_id(s.id).as_ref(), Some(s));
|
||||||
|
}
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue