cascade: add STREAM mode for blobs
64 KiB segments with counter and last-flag nonces, so blobs cannot be reordered or truncated, with memory bounded by one segment. Refs: R3-2
This commit is contained in:
parent
7058c5ffa4
commit
743e9ee00e
|
|
@ -14,12 +14,14 @@
|
|||
pub mod cascade;
|
||||
pub mod padding;
|
||||
pub mod secret;
|
||||
pub mod stream;
|
||||
pub mod suite;
|
||||
pub mod suites;
|
||||
|
||||
pub use cascade::{open, seal, Context, SALT_LEN};
|
||||
pub use padding::{pad, unpad, Bucketing};
|
||||
pub use secret::{Key32, SecretBytes};
|
||||
pub use stream::{StreamOpener, StreamSealer, SEGMENT_LEN};
|
||||
pub use suite::{Layer, Policy, ProviderSet, ResolvedSuite, Suite, MAX_ROUNDS};
|
||||
|
||||
use ccc_crypto_core::CryptoError;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,128 @@
|
|||
//! STREAM mode for blobs (R3-2, attachments): 64 KiB segments, one cascade
|
||||
//! round, per-segment nonces and a final-segment flag (the STREAM construction
|
||||
//! of Hoang, Reyhanitabar, Rogaway and Vizár).
|
||||
//!
|
||||
//! Per layer `i` the key and a nonce prefix come from the same schedule as
|
||||
//! [`crate::cascade`] (round 0, domain suffixed `/stream`). Segment `n`'s
|
||||
//! nonce is `prefix || u32be(n) || u8(last)`, so segments cannot be reordered,
|
||||
//! dropped, duplicated or truncated without failing authentication. Memory is
|
||||
//! bounded by one segment.
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::cascade::{check_inputs, layer_aad, layer_info, layer_key, Context};
|
||||
use crate::suite::ResolvedSuite;
|
||||
use crate::CascadeError;
|
||||
|
||||
/// Plaintext bytes per segment (the last may be shorter, even empty).
|
||||
pub const SEGMENT_LEN: usize = 64 * 1024;
|
||||
|
||||
struct LayerState {
|
||||
key: Zeroizing<Vec<u8>>,
|
||||
prefix: Zeroizing<Vec<u8>>,
|
||||
}
|
||||
|
||||
/// Shared state of a sealer or opener.
|
||||
struct Stream {
|
||||
suite: ResolvedSuite,
|
||||
aad: Vec<u8>,
|
||||
layers: Vec<LayerState>,
|
||||
next: u32,
|
||||
finished: bool,
|
||||
}
|
||||
|
||||
impl Stream {
|
||||
fn new(suite: &ResolvedSuite, root_key: &[u8], salt: &[u8], ctx: Context<'_>) -> Result<Self, CascadeError> {
|
||||
check_inputs(root_key, salt, &ctx)?;
|
||||
let mut domain = ctx.domain.to_vec();
|
||||
domain.extend_from_slice(b"/stream");
|
||||
let mut layers = Vec::with_capacity(suite.layers.len());
|
||||
for (i, (alg, _)) in suite.layers.iter().enumerate() {
|
||||
if alg.nonce_len() < 12 {
|
||||
return Err(CascadeError::InvalidInput("STREAM needs nonces of at least 12 bytes"));
|
||||
}
|
||||
let (key, nonce) = layer_key(suite, root_key, salt, &layer_info(&domain, 0, i as u8, *alg), *alg)?;
|
||||
let prefix = Zeroizing::new(nonce[..alg.nonce_len() - 5].to_vec());
|
||||
layers.push(LayerState { key, prefix });
|
||||
}
|
||||
Ok(Self { suite: suite.clone(), aad: ctx.aad.to_vec(), layers, next: 0, finished: false })
|
||||
}
|
||||
|
||||
fn nonce(&self, layer: usize, last: bool) -> Vec<u8> {
|
||||
let mut n = self.layers[layer].prefix.to_vec();
|
||||
n.extend_from_slice(&self.next.to_be_bytes());
|
||||
n.push(u8::from(last));
|
||||
n
|
||||
}
|
||||
|
||||
fn advance(&mut self, last: bool) -> Result<(), CascadeError> {
|
||||
self.finished = last;
|
||||
self.next = self.next.checked_add(1).ok_or(CascadeError::InvalidInput("too many segments"))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Seals a blob segment by segment.
|
||||
pub struct StreamSealer(Stream);
|
||||
|
||||
impl StreamSealer {
|
||||
/// Start sealing under `root_key` and a fresh 32-byte `salt`.
|
||||
pub fn new(suite: &ResolvedSuite, root_key: &[u8], salt: &[u8], ctx: Context<'_>) -> Result<Self, CascadeError> {
|
||||
Ok(Self(Stream::new(suite, root_key, salt, ctx)?))
|
||||
}
|
||||
|
||||
/// Seal the next segment (at most [`SEGMENT_LEN`] bytes). Mark the final
|
||||
/// one with `last`; nothing can be sealed after it.
|
||||
pub fn seal_segment(&mut self, segment: &[u8], last: bool) -> Result<Vec<u8>, CascadeError> {
|
||||
let s = &mut self.0;
|
||||
if s.finished {
|
||||
return Err(CascadeError::InvalidInput("stream already finished"));
|
||||
}
|
||||
if segment.len() > SEGMENT_LEN || (!last && segment.len() != SEGMENT_LEN) {
|
||||
return Err(CascadeError::InvalidInput("segments are SEGMENT_LEN bytes, except the last"));
|
||||
}
|
||||
let mut data = Zeroizing::new(segment.to_vec());
|
||||
for (i, (alg, provider)) in s.suite.layers.iter().enumerate() {
|
||||
let aad = layer_aad(&s.aad, s.suite.id, 1, 0, i as u8);
|
||||
data = Zeroizing::new(provider.encrypt_aead(*alg, &s.layers[i].key, &s.nonce(i, last), &data, &aad)?);
|
||||
}
|
||||
s.advance(last)?;
|
||||
Ok(data.to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens a blob segment by segment.
|
||||
pub struct StreamOpener(Stream);
|
||||
|
||||
impl StreamOpener {
|
||||
/// Start opening a blob sealed with these inputs.
|
||||
pub fn new(suite: &ResolvedSuite, root_key: &[u8], salt: &[u8], ctx: Context<'_>) -> Result<Self, CascadeError> {
|
||||
Ok(Self(Stream::new(suite, root_key, salt, ctx)?))
|
||||
}
|
||||
|
||||
/// Open the next sealed segment. `last` must say whether it is the final
|
||||
/// one; a wrong claim fails authentication.
|
||||
pub fn open_segment(&mut self, sealed: &[u8], last: bool) -> Result<Zeroizing<Vec<u8>>, CascadeError> {
|
||||
let s = &mut self.0;
|
||||
if s.finished {
|
||||
return Err(CascadeError::AuthenticationFailed);
|
||||
}
|
||||
let mut data = Zeroizing::new(sealed.to_vec());
|
||||
for (i, (alg, provider)) in s.suite.layers.iter().enumerate().rev() {
|
||||
let aad = layer_aad(&s.aad, s.suite.id, 1, 0, i as u8);
|
||||
data = Zeroizing::new(
|
||||
provider
|
||||
.decrypt_aead(*alg, &s.layers[i].key, &s.nonce(i, last), &data, &aad)
|
||||
.map_err(|_| CascadeError::AuthenticationFailed)?,
|
||||
);
|
||||
}
|
||||
s.advance(last)?;
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// Whether the final segment has been opened. A blob that ends without it
|
||||
/// was truncated and must be rejected.
|
||||
pub fn is_finished(&self) -> bool {
|
||||
self.0.finished
|
||||
}
|
||||
}
|
||||
|
|
@ -213,6 +213,39 @@ fn self_test_failure_blocks_every_suite_using_it() {
|
|||
assert!(p.resolve(&other, &Policy::development()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_round_trip_and_tamper() {
|
||||
let s = three();
|
||||
let blob: Vec<u8> = (0..(SEGMENT_LEN * 2 + 100)).map(|i| (i % 251) as u8).collect();
|
||||
let mut sealer = StreamSealer::new(&s, &KEY, &SALT, ctx(b"blob-1")).unwrap();
|
||||
let chunks: Vec<&[u8]> = blob.chunks(SEGMENT_LEN).collect();
|
||||
let sealed: Vec<Vec<u8>> =
|
||||
chunks.iter().enumerate().map(|(i, c)| sealer.seal_segment(c, i == chunks.len() - 1).unwrap()).collect();
|
||||
assert!(sealer.seal_segment(b"", true).is_err(), "nothing after the last segment");
|
||||
|
||||
let open_all = |segs: &[Vec<u8>], lasts: &[bool]| -> Result<Vec<u8>, CascadeError> {
|
||||
let mut o = StreamOpener::new(&s, &KEY, &SALT, ctx(b"blob-1"))?;
|
||||
let mut out = vec![];
|
||||
for (seg, last) in segs.iter().zip(lasts) {
|
||||
out.extend_from_slice(&o.open_segment(seg, *last)?);
|
||||
}
|
||||
if !o.is_finished() {
|
||||
return Err(CascadeError::AuthenticationFailed);
|
||||
}
|
||||
Ok(out)
|
||||
};
|
||||
assert_eq!(open_all(&sealed, &[false, false, true]).unwrap(), blob);
|
||||
let swapped = vec![sealed[1].clone(), sealed[0].clone(), sealed[2].clone()];
|
||||
assert!(open_all(&swapped, &[false, false, true]).is_err(), "reordered");
|
||||
assert!(open_all(&sealed[..2], &[false, false]).is_err(), "truncated");
|
||||
assert!(open_all(&sealed[..2], &[false, true]).is_err(), "early end claimed");
|
||||
let mut flipped = sealed.clone();
|
||||
flipped[2][0] ^= 1;
|
||||
assert!(open_all(&flipped, &[false, false, true]).is_err(), "tampered");
|
||||
let mut o = StreamOpener::new(&s, &KEY, &SALT, ctx(b"blob-2")).unwrap();
|
||||
assert!(o.open_segment(&sealed[0], false).is_err(), "other blob's AAD");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builtin_suites_have_unique_ids_and_a_vetted_layer() {
|
||||
let all = suites::all();
|
||||
|
|
|
|||
Loading…
Reference in New Issue