//! A sealed table's file, encrypted before it leaves the device (sealing plan//! §2.5, L8): the object keeps it under a random key, so neither its bytes//! nor its hash say anything; the per-file key (FK) travels inside the row's//! sealed blob, beside the media entry that names the object key.//!//! The format, `f1`, is streamed in parts so a 2 GB WhatsApp document is never//! held whole://!//! ```text//! "CTF1" || prefix(7) || part_0 || part_1 || … || part_n//! part_i = AES-256-GCM(FK, nonce = prefix || be32(i) || last_i, aad = "f1|" || object_key, plaintext_i)//! ```//!//! Every part but the last carries [`PART`] bytes of plaintext (the last//! carries 0 to [`PART`]); `last_i` is 1 on the final part only, so a file cut//! short at a part boundary, parts reordered, or a part moved into another//! object's file does not open. One answer for every way it does not open//! ([`SealError::DoesNotOpen`]).use std::io::{Read, Write};use aes_gcm::aead::{Aead, KeyInit, Payload};use aes_gcm::{Aes256Gcm, Key, Nonce};use rand::RngCore;use zeroize::Zeroizing;usesuper::{b64, unb64, SealError};/// The plaintext each part carries (64 KiB).pubconst PART: usize = 64 * 1024;/// The bytes a file starts with.pubconst MAGIC: &[u8; 4] = b"CTF1";const PREFIX: usize = 7;const TAG: usize = 16;/// The folder a sealed file's object key sits in: `<database id>/sealed/<32 hex>`.pubconst FOLDER: &str = "sealed";/// A per-file key.pubstructFileKey(Zeroizing<[u8; 32]>);implFileKey {pubfn random() -> FileKey {letmut key = Zeroizing::new([0u8; 32]); rand::thread_rng().fill_bytes(key.as_mut());FileKey(key) }pubfn from_bytes(bytes: [u8; 32]) -> FileKey {FileKey(Zeroizing::new(bytes)) }/// The key's bytes, for wrapping it to someone (an arrival key, a share).pubfn expose(&self) -> &[u8; 32] { &self.0 }/// As a media entry carries it (inside the sealed blob): base64url.pubfn text(&self) -> String { b64(self.0.as_ref()) }/// Back from [`FileKey::text`].pubfn read(text: &str) -> Result<FileKey, SealError> {let bytes = unb64(text).ok_or_else(|| SealError::BadInput("a file key is base64url".into()))?;let bytes: [u8; 32] = bytes.try_into().map_err(|_| SealError::BadInput("a file key is 32 bytes".into()))?;Ok(FileKey::from_bytes(bytes)) }}/// The file key of a sealed file whose row keeps no key of its own (a story's/// picture: its row holds one `media_key`, no media entry to carry a/// `fileKey`): HMAC-SHA256 under the table's blind key `bk` (sealing plan/// §2.1, made from the DK) of `"f|" || object_key`. Only a holder of the DK/// makes it, the object key is random, and the `f` domain is apart from every/// token's and id's.pubfn derived_key(bk: &super::keys::Key32, object_key: &str) -> FileKey {use hmac::{Hmac, Mac};letmut mac = <Hmac<sha2::Sha256> asMac>::new_from_slice(bk.as_slice()).expect("HMAC takes any key length"); mac.update(b"f|"); mac.update(object_key.as_bytes());FileKey::from_bytes(mac.finalize().into_bytes().into())}/// A fresh object key for a sealed file of `database_id`: random, so it names/// nothing of the file.pubfn object_key(database_id: &str) -> String {letmut bytes = [0u8; 16]; rand::thread_rng().fill_bytes(&mut bytes); format!("{database_id}/{FOLDER}/{}", hex::encode(bytes))}/// Whether `key` is a sealed file's object key.pubfn is_sealed_key(key: &str) -> bool {letmut parts = key.split('/'); matches!((parts.next(), parts.next(), parts.next(), parts.next()), (Some(db), Some(FOLDER), Some(name), None)if !db.is_empty() && name.len() == 32 && name.bytes().all(|b| b.is_ascii_hexdigit()))}/// The size `plain` bytes take sealed.pubfn sealed_len(plain: u64) -> u64 {let parts = plain.div_ceil(PART as u64).max(1); (MAGIC.len() + PREFIX) as u64 + plain + parts * TAG as u64}fn nonce(prefix: &[u8; PREFIX], index: u32, last: bool) -> [u8; 12] {letmut n = [0u8; 12]; n[..PREFIX].copy_from_slice(prefix); n[PREFIX..PREFIX + 4].copy_from_slice(&index.to_be_bytes()); n[11] = u8::from(last); n}/// The aad: the file's object key, the R2 path it is stored at (a name, never key material).fn aad(path: &str) -> Vec<u8> { format!("f1|{path}").into_bytes()}/// Read up to `buf.len()` bytes, as many as the reader has.fn fill(reader: &mutimplRead, buf: &mut [u8]) -> std::io::Result<usize> {letmut got = 0;while got < buf.len() {match reader.read(&mut buf[got..])? {0 => break, n => got += n, } }Ok(got)}fn io(error: std::io::Error) -> SealError {SealError::BadInput(format!("the file could not be read or written ({error})"))}/// Seal `plain` for `object_key` under `fk` into `out`, with `prefix` as the/// nonce prefix (vectors); [`seal_file`] draws it at random.pubfn seal_file_with(prefix: [u8; PREFIX], fk: &FileKey, object_key: &str, plain: &mutimplRead, out: &mutimplWrite) -> Result<u64, SealError> {let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(fk.0.as_ref()));let aad = aad(object_key); out.write_all(MAGIC).map_err(io)?; out.write_all(&prefix).map_err(io)?;letmut written = (MAGIC.len() + PREFIX) as u64;letmut current = Zeroizing::new(vec![0u8; PART]);letmut next = Zeroizing::new(vec![0u8; PART]);letmut have = fill(plain, &mut current).map_err(io)?;letmut index: u32 = 0;loop {// A full part may still be the last: look one part ahead.let ahead = if have == PART { fill(plain, &mut next).map_err(io)? } else { 0 };let last = ahead == 0;let part = cipher .encrypt(Nonce::from_slice(&nonce(&prefix, index, last)), Payload { msg: ¤t[..have], aad: &aad }) .map_err(|_| SealError::Failed)?; out.write_all(&part).map_err(io)?; written += part.len() as u64;if last {returnOk(written); } std::mem::swap(&mut current, &mut next); have = ahead; index = index.checked_add(1).ok_or_else(|| SealError::BadInput("a file of more than 2^32 parts".into()))?; }}/// Seal `plain` for `object_key` under `fk` into `out`; the bytes written.pubfn seal_file(fk: &FileKey, object_key: &str, plain: &mutimplRead, out: &mutimplWrite) -> Result<u64, SealError> {letmut prefix = [0u8; PREFIX]; rand::thread_rng().fill_bytes(&mut prefix); seal_file_with(prefix, fk, object_key, plain, out)}/// Open a sealed file for `object_key` under `fk` from `sealed` into `out`;/// the plaintext bytes written. Nothing past a part that does not open is/// written, and a file cut short does not open.pubfn open_file(fk: &FileKey, object_key: &str, sealed: &mutimplRead, out: &mutimplWrite) -> Result<u64, SealError> {let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(fk.0.as_ref()));let aad = aad(object_key);letmut head = [0u8; 4 + PREFIX];if fill(sealed, &mut head).map_err(io)? != head.len() || &head[..4] != MAGIC {returnErr(SealError::DoesNotOpen); }let prefix: [u8; PREFIX] = head[4..].try_into().expect("seven bytes");letmut current = vec![0u8; PART + TAG];letmut next = vec![0u8; PART + TAG];letmut have = fill(sealed, &mut current).map_err(io)?;letmut index: u32 = 0;letmut written = 0u64;loop {let ahead = if have == PART + TAG { fill(sealed, &mut next).map_err(io)? } else { 0 };let last = ahead == 0;if have < TAG {returnErr(SealError::DoesNotOpen); }let plain = Zeroizing::new( cipher .decrypt(Nonce::from_slice(&nonce(&prefix, index, last)), Payload { msg: ¤t[..have], aad: &aad }) .map_err(|_| SealError::DoesNotOpen)?, ); out.write_all(&plain).map_err(io)?; written += plain.len() as u64;if last {returnOk(written); } std::mem::swap(&mut current, &mut next); have = ahead; index = index.checked_add(1).ok_or(SealError::DoesNotOpen)?; }}// ── a person's own files (R6) ─────────────────────────────//// A picture, a book, a song or a film a person keeps is sealed on their device// before the drain sends it, under a random object key (`<db>/sealed/<hex>`),// so the object holds neither its bytes nor a hash of them. Its key is the// file's own, made from the person's file root FR (`keys::file_root`, from// the DK) and the object key, so every device holding the DK opens it, the// row needs no column for it, and handing one file's key to someone else// (e2e-share's seam) hands nothing of any other file.//// Every part is sealed on its own, so a range of the plaintext opens from the// parts it covers alone (a film seeks without coming down whole), and with// the steady nonce prefix a part sealed again is the same bytes (an upload in// parts resumes at any part without a sealed copy on disk)./// The head every f1 file starts with: the magic and the nonce prefix.pubconst HEAD: u64 = (MAGIC.len() + PREFIX) as u64;/// One sealed part's bytes, every part but the last.pubconst SEALED_PART: u64 = (PART + TAG) as u64;/// FK of a person's own file: HMAC-SHA256 under FR of `"pf|" || object_key`.pubfn person_file_key(root: &super::keys::Key32, object_key: &str) -> FileKey {use hmac::{Hmac, Mac};letmut mac = <Hmac<sha2::Sha256> asMac>::new_from_slice(root.as_slice()).expect("HMAC takes any key length"); mac.update(b"pf|"); mac.update(object_key.as_bytes());FileKey::from_bytes(mac.finalize().into_bytes().into())}/// The nonce prefix a resumable seal uses: the first seven bytes of/// HMAC-SHA256 under FK of `"p|" || object_key`. An object key is fresh for/// every file and names one plaintext, so the same prefix never seals two.pubfn steady_prefix(fk: &FileKey, object_key: &str) -> [u8; PREFIX] {use hmac::{Hmac, Mac};letmut mac = <Hmac<sha2::Sha256> asMac>::new_from_slice(fk.0.as_ref()).expect("HMAC takes any key length"); mac.update(b"p|"); mac.update(object_key.as_bytes());let full = mac.finalize().into_bytes(); full[..PREFIX].try_into().expect("seven bytes")}/// The plaintext a sealed file of `sealed` bytes carries; None when no f1 file is that long.pubfn plain_len(sealed: u64) -> Option<u64> {let body = sealed.checked_sub(HEAD)?;let full = body / SEALED_PART;let rest = body % SEALED_PART;if rest == 0 {// Whole parts only: the last of them is full (or the file is empty: one bare tag).return (full > 0).then(|| full * PART as u64); } (rest >= TAG as u64).then(|| full * PART as u64 + rest - TAG as u64)}fn parts_of(plain: u64) -> u64 { plain.div_ceil(PART as u64).max(1)}/// Plaintext bytes in, sealed bytes out, any range of them: what an upload in/// parts reads from (`Seek` to a part's start, then `Read` it). Nothing is/// written to disk; each sealed part is made when it is read.pubstructSealingReader<R: Read + std::io::Seek> { plain: R, cipher: Aes256Gcm, aad: Vec<u8>, prefix: [u8; PREFIX], plain_len: u64, pos: u64, part: Option<(u64, Vec<u8>)>,}impl<R: Read + std::io::Seek> SealingReader<R> {/// `plain` of `plain_len` bytes, sealed for `object_key` under `fk` with its steady prefix.pubfn new(fk: &FileKey, object_key: &str, plain: R, plain_len: u64) -> SealingReader<R> {SealingReader { plain, cipher: Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(fk.0.as_ref())), aad: aad(object_key), prefix: steady_prefix(fk, object_key), plain_len, pos: 0, part: None, } }/// The sealed file's length.pubfn sealed_len(&self) -> u64 { sealed_len(self.plain_len) }fn sealed_part(&mutself, index: u64) -> std::io::Result<&[u8]> {ifself.part.as_ref().map(|(i, _)| *i) != Some(index) {let start = index * PART as u64;let take = (self.plain_len - start).min(PART as u64) as usize;self.plain.seek(std::io::SeekFrom::Start(start))?;letmut plain = Zeroizing::new(vec![0u8; take]);self.plain.read_exact(&mut plain)?;let last = index + 1 == parts_of(self.plain_len);let index32 = u32::try_from(index).map_err(|_| std::io::Error::other("a file of more than 2^32 parts"))?;let sealed = self .cipher .encrypt(Nonce::from_slice(&nonce(&self.prefix, index32, last)), Payload { msg: &plain, aad: &self.aad }) .map_err(|_| std::io::Error::other("seal_failed"))?;self.part = Some((index, sealed)); }Ok(&self.part.as_ref().expect("made above").1) }}impl<R: Read + std::io::Seek> ReadforSealingReader<R> {fn read(&mutself, buf: &mut [u8]) -> std::io::Result<usize> {let total = self.sealed_len();if buf.is_empty() || self.pos >= total {returnOk(0); }let n = ifself.pos < HEAD {letmut head = [0u8; HEAD as usize]; head[..4].copy_from_slice(MAGIC); head[4..].copy_from_slice(&self.prefix);let from = &head[self.pos as usize..];let n = from.len().min(buf.len()); buf[..n].copy_from_slice(&from[..n]); n } else {let index = (self.pos - HEAD) / SEALED_PART;let within = ((self.pos - HEAD) % SEALED_PART) as usize;let part = self.sealed_part(index)?;let n = (part.len() - within).min(buf.len()); buf[..n].copy_from_slice(&part[within..within + n]); n };self.pos += n as u64;Ok(n) }}impl<R: Read + std::io::Seek> std::io::SeekforSealingReader<R> {fn seek(&mutself, to: std::io::SeekFrom) -> std::io::Result<u64> {self.pos = seek_to(to, self.pos, self.sealed_len())?;Ok(self.pos) }}fn seek_to(to: std::io::SeekFrom, pos: u64, len: u64) -> std::io::Result<u64> {let at = match to { std::io::SeekFrom::Start(n) => Some(n), std::io::SeekFrom::End(d) => len.checked_add_signed(d), std::io::SeekFrom::Current(d) => pos.checked_add_signed(d), }; at.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "a seek before the start"))}/// Sealed bytes in, plaintext out, any range of it: a reader seeks into the/// middle of a film and only the parts it covers are read and opened. A part/// that does not open is an error (`InvalidData`, "seal_does_not_open"),/// never bytes.pubstructOpeningReader<S: Read + std::io::Seek> { sealed: S, cipher: Aes256Gcm, aad: Vec<u8>, prefix: Option<[u8; PREFIX]>, sealed_len: u64, plain_len: u64, pos: u64, part: Option<(u64, Zeroizing<Vec<u8>>)>,}fn does_not_open() -> std::io::Error { std::io::Error::new(std::io::ErrorKind::InvalidData, SealError::DoesNotOpen.code())}impl<S: Read + std::io::Seek> OpeningReader<S> {/// The sealed file `sealed`, `sealed_len` bytes long, opened for `object_key` under `fk`.pubfn new(fk: &FileKey, object_key: &str, sealed: S, sealed_len: u64) -> Result<OpeningReader<S>, SealError> {let plain_len = plain_len(sealed_len).ok_or(SealError::DoesNotOpen)?;Ok(OpeningReader { sealed, cipher: Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(fk.0.as_ref())), aad: aad(object_key), prefix: None, sealed_len, plain_len, pos: 0, part: None, }) }/// The plaintext's length.pubfn plain_len(&self) -> u64 {self.plain_len }fn prefix(&mutself) -> std::io::Result<[u8; PREFIX]> {ifletSome(prefix) = self.prefix {returnOk(prefix); }letmut head = [0u8; HEAD as usize];self.sealed.seek(std::io::SeekFrom::Start(0))?;self.sealed.read_exact(&mut head)?;if &head[..4] != MAGIC {returnErr(does_not_open()); }let prefix: [u8; PREFIX] = head[4..].try_into().expect("seven bytes");self.prefix = Some(prefix);Ok(prefix) }fn opened_part(&mutself, index: u64) -> std::io::Result<&[u8]> {ifself.part.as_ref().map(|(i, _)| *i) != Some(index) {let prefix = self.prefix()?;let start = HEAD + index * SEALED_PART;let take = (self.sealed_len - start).min(SEALED_PART) as usize;self.sealed.seek(std::io::SeekFrom::Start(start))?;letmut sealed = vec![0u8; take];self.sealed.read_exact(&mut sealed)?;let last = index + 1 == parts_of(self.plain_len);let index32 = u32::try_from(index).map_err(|_| does_not_open())?;let plain = self .cipher .decrypt(Nonce::from_slice(&nonce(&prefix, index32, last)), Payload { msg: &sealed, aad: &self.aad }) .map_err(|_| does_not_open())?;self.part = Some((index, Zeroizing::new(plain))); }Ok(&self.part.as_ref().expect("opened above").1) }}impl<S: Read + std::io::Seek> ReadforOpeningReader<S> {fn read(&mutself, buf: &mut [u8]) -> std::io::Result<usize> {if buf.is_empty() || self.pos >= self.plain_len {// An empty file is still one part, and it must open.ifself.plain_len == 0 && self.part.is_none() {self.opened_part(0)?; }returnOk(0); }let index = self.pos / PART as u64;let within = (self.pos % PART as u64) as usize;let part = self.opened_part(index)?;let n = (part.len() - within).min(buf.len()); buf[..n].copy_from_slice(&part[within..within + n]);self.pos += n as u64;Ok(n) }}impl<S: Read + std::io::Seek> std::io::SeekforOpeningReader<S> {fn seek(&mutself, to: std::io::SeekFrom) -> std::io::Result<u64> {self.pos = seek_to(to, self.pos, self.plain_len)?;Ok(self.pos) }}/// The sealed bytes a plaintext range `[start, start + len)` needs, as one/// sealed range `(offset, len)`: the parts it covers, whole. With the head/// (`0..HEAD`) that is all a ranged read fetches.pubfn sealed_range_for(plain_total: u64, start: u64, len: u64) -> (u64, u64) {if plain_total == 0 || len == 0 {return (HEAD, sealed_len(plain_total) - HEAD); }let first = start.min(plain_total - 1) / PART as u64;let last = (start + len - 1).min(plain_total - 1) / PART as u64;let from = HEAD + first * SEALED_PART;let to = (HEAD + (last + 1) * SEALED_PART).min(sealed_len(plain_total)); (from, to - from)}#[cfg(test)]#[path = "file_tests.rs"]mod tests;