Skip to main content

sew_e2ee/
chunk.rs

1//! `open_recording_chunk`: for the admin download of an encrypted recording.
2//!
3//! Opens one chunk of a recorder-sealed segment or mix part: Sew's blob stream format (the
4//! server's side of it is not published), reimplemented on the **open** side only, in pure Rust
5//! (aes-gcm), so it builds for wasm32 and never depends on aws-lc-rs.
6//!
7//! ```text
8//! header (16): "SEWB" | version 0x01 | chunk_size_log2 (16..=24) | reserved 0x0000 | nonce_prefix (8)
9//! nonce(i)  = nonce_prefix ‖ u32be(i)
10//! aad(i)    = "sew-blob-v1" ‖ 0x00 ‖ header ‖ u32be(i) ‖ last (0x01 | 0x00)
11//! ```
12
13use aes_gcm::aead::{Aead, KeyInit, Payload};
14use aes_gcm::{Aes256Gcm, Key, Nonce};
15use zeroize::Zeroizing;
16
17use crate::error::ChunkError;
18
19const MAGIC: [u8; 4] = *b"SEWB";
20const VERSION: u8 = 0x01;
21const HEADER_LEN: u64 = 16;
22const TAG_LEN: u64 = 16;
23const MIN_CHUNK_LOG2: u8 = 16;
24const MAX_CHUNK_LOG2: u8 = 24;
25const AAD_LABEL: &[u8] = b"sew-blob-v1";
26
27fn parse_header(header: &[u8; 16]) -> Result<u8, ChunkError> {
28    if header[0..4] != MAGIC {
29        return Err(ChunkError::Header("magic"));
30    }
31    if header[4] != VERSION {
32        return Err(ChunkError::Header("version"));
33    }
34    if header[6] != 0 || header[7] != 0 {
35        return Err(ChunkError::Header("reserved"));
36    }
37    let log2 = header[5];
38    if !(MIN_CHUNK_LOG2..=MAX_CHUNK_LOG2).contains(&log2) {
39        return Err(ChunkError::Header("chunk_size_log2"));
40    }
41    Ok(log2)
42}
43
44/// Opens chunk `index` (`ct` = ciphertext ‖ tag). A failed tag returns an error and no
45/// plaintext.
46pub fn open_recording_chunk(
47    key: &[u8; 32],
48    header: &[u8; 16],
49    index: u32,
50    last: bool,
51    ct: &[u8],
52) -> Result<Zeroizing<Vec<u8>>, ChunkError> {
53    let log2 = parse_header(header)?;
54    let frame = (1u64 << log2) + TAG_LEN;
55    let len = ct.len() as u64;
56    if len < TAG_LEN || len > frame {
57        return Err(ChunkError::Length);
58    }
59    if !last && len != frame {
60        return Err(ChunkError::Length);
61    }
62    let mut nonce = [0u8; 12];
63    nonce[..8].copy_from_slice(&header[8..16]);
64    nonce[8..].copy_from_slice(&index.to_be_bytes());
65    let mut aad = Vec::with_capacity(AAD_LABEL.len() + 1 + 16 + 4 + 1);
66    aad.extend_from_slice(AAD_LABEL);
67    aad.push(0x00);
68    aad.extend_from_slice(header);
69    aad.extend_from_slice(&index.to_be_bytes());
70    aad.push(u8::from(last));
71    let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));
72    let pt = cipher
73        .decrypt(Nonce::from_slice(&nonce), Payload { msg: ct, aad: &aad })
74        .map_err(|_| ChunkError::Aead)?;
75    let pt = Zeroizing::new(pt);
76    if last && index > 0 && pt.is_empty() {
77        return Err(ChunkError::Length);
78    }
79    Ok(pt)
80}
81
82/// The chunk layout of a sealed file.
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct ChunkLayout {
85    /// Chunks (`N`).
86    pub chunks: u32,
87    /// Plaintext bytes per full chunk (`C`).
88    pub chunk_size: u64,
89    /// Plaintext bytes in all.
90    pub plaintext_len: u64,
91}
92
93impl ChunkLayout {
94    /// Byte offset and length in the file of chunk `index` (the last may be shorter).
95    pub fn chunk_range(&self, index: u32, file_len: u64) -> Option<(u64, u64)> {
96        if index >= self.chunks {
97            return None;
98        }
99        let frame = self.chunk_size + TAG_LEN;
100        let start = HEADER_LEN + u64::from(index) * frame;
101        let end = (start + frame).min(file_len);
102        Some((start, end.saturating_sub(start)))
103    }
104}
105
106/// The layout of a file of `file_len` bytes with `header` (rejects lengths no writer makes).
107pub fn recording_chunk_layout(file_len: u64, header: &[u8; 16]) -> Result<ChunkLayout, ChunkError> {
108    let log2 = parse_header(header)?;
109    let chunk_size = 1u64 << log2;
110    let frame = chunk_size + TAG_LEN;
111    let body = file_len
112        .checked_sub(HEADER_LEN)
113        .ok_or(ChunkError::FileLength)?;
114    if body < TAG_LEN {
115        return Err(ChunkError::FileLength);
116    }
117    let n = body.div_ceil(frame).max(1);
118    let last_frame = body - (n - 1) * frame;
119    if last_frame < TAG_LEN || (n > 1 && last_frame == TAG_LEN) {
120        return Err(ChunkError::FileLength);
121    }
122    let chunks = u32::try_from(n).map_err(|_| ChunkError::FileLength)?;
123    Ok(ChunkLayout {
124        chunks,
125        chunk_size,
126        plaintext_len: body - n * TAG_LEN,
127    })
128}