//! 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; use super::{b64, unb64, SealError}; /// The plaintext each part carries (64 KiB). pub const PART: usize = 64 * 1024; /// The bytes a file starts with. pub const MAGIC: &[u8; 4] = b"CTF1"; const PREFIX: usize = 7; const TAG: usize = 16; /// The folder a sealed file's object key sits in: `/sealed/<32 hex>`. pub const FOLDER: &str = "sealed"; /// A per-file key. pub struct FileKey(Zeroizing<[u8; 32]>); impl FileKey { pub fn random() -> FileKey { let mut key = Zeroizing::new([0u8; 32]); rand::thread_rng().fill_bytes(key.as_mut()); FileKey(key) } pub fn from_bytes(bytes: [u8; 32]) -> FileKey { FileKey(Zeroizing::new(bytes)) } /// The key's bytes, for wrapping it to someone (an arrival key, a share). pub fn expose(&self) -> &[u8; 32] { &self.0 } /// As a media entry carries it (inside the sealed blob): base64url. pub fn text(&self) -> String { b64(self.0.as_ref()) } /// Back from [`FileKey::text`]. pub fn read(text: &str) -> Result { 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. pub fn derived_key(bk: &super::keys::Key32, object_key: &str) -> FileKey { use hmac::{Hmac, Mac}; let mut mac = as Mac>::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. pub fn object_key(database_id: &str) -> String { let mut 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. pub fn is_sealed_key(key: &str) -> bool { let mut 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. pub fn 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] { let mut 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 { format!("f1|{path}").into_bytes() } /// Read up to `buf.len()` bytes, as many as the reader has. fn fill(reader: &mut impl Read, buf: &mut [u8]) -> std::io::Result { let mut 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. pub fn seal_file_with(prefix: [u8; PREFIX], fk: &FileKey, object_key: &str, plain: &mut impl Read, out: &mut impl Write) -> Result { let cipher = Aes256Gcm::new(Key::::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)?; let mut written = (MAGIC.len() + PREFIX) as u64; let mut current = Zeroizing::new(vec![0u8; PART]); let mut next = Zeroizing::new(vec![0u8; PART]); let mut have = fill(plain, &mut current).map_err(io)?; let mut 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 { return Ok(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. pub fn seal_file(fk: &FileKey, object_key: &str, plain: &mut impl Read, out: &mut impl Write) -> Result { let mut 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. pub fn open_file(fk: &FileKey, object_key: &str, sealed: &mut impl Read, out: &mut impl Write) -> Result { let cipher = Aes256Gcm::new(Key::::from_slice(fk.0.as_ref())); let aad = aad(object_key); let mut head = [0u8; 4 + PREFIX]; if fill(sealed, &mut head).map_err(io)? != head.len() || &head[..4] != MAGIC { return Err(SealError::DoesNotOpen); } let prefix: [u8; PREFIX] = head[4..].try_into().expect("seven bytes"); let mut current = vec![0u8; PART + TAG]; let mut next = vec![0u8; PART + TAG]; let mut have = fill(sealed, &mut current).map_err(io)?; let mut index: u32 = 0; let mut 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 { return Err(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 { return Ok(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 (`/sealed/`), // 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. pub const HEAD: u64 = (MAGIC.len() + PREFIX) as u64; /// One sealed part's bytes, every part but the last. pub const SEALED_PART: u64 = (PART + TAG) as u64; /// FK of a person's own file: HMAC-SHA256 under FR of `"pf|" || object_key`. pub fn person_file_key(root: &super::keys::Key32, object_key: &str) -> FileKey { use hmac::{Hmac, Mac}; let mut mac = as Mac>::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. pub fn steady_prefix(fk: &FileKey, object_key: &str) -> [u8; PREFIX] { use hmac::{Hmac, Mac}; let mut mac = as Mac>::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. pub fn plain_len(sealed: u64) -> Option { 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. pub struct SealingReader { plain: R, cipher: Aes256Gcm, aad: Vec, prefix: [u8; PREFIX], plain_len: u64, pos: u64, part: Option<(u64, Vec)>, } impl SealingReader { /// `plain` of `plain_len` bytes, sealed for `object_key` under `fk` with its steady prefix. pub fn new(fk: &FileKey, object_key: &str, plain: R, plain_len: u64) -> SealingReader { SealingReader { plain, cipher: Aes256Gcm::new(Key::::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. pub fn sealed_len(&self) -> u64 { sealed_len(self.plain_len) } fn sealed_part(&mut self, index: u64) -> std::io::Result<&[u8]> { if self.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))?; let mut 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 Read for SealingReader { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { let total = self.sealed_len(); if buf.is_empty() || self.pos >= total { return Ok(0); } let n = if self.pos < HEAD { let mut 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 std::io::Seek for SealingReader { fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { 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 { 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. pub struct OpeningReader { sealed: S, cipher: Aes256Gcm, aad: Vec, prefix: Option<[u8; PREFIX]>, sealed_len: u64, plain_len: u64, pos: u64, part: Option<(u64, Zeroizing>)>, } fn does_not_open() -> std::io::Error { std::io::Error::new(std::io::ErrorKind::InvalidData, SealError::DoesNotOpen.code()) } impl OpeningReader { /// The sealed file `sealed`, `sealed_len` bytes long, opened for `object_key` under `fk`. pub fn new(fk: &FileKey, object_key: &str, sealed: S, sealed_len: u64) -> Result, SealError> { let plain_len = plain_len(sealed_len).ok_or(SealError::DoesNotOpen)?; Ok(OpeningReader { sealed, cipher: Aes256Gcm::new(Key::::from_slice(fk.0.as_ref())), aad: aad(object_key), prefix: None, sealed_len, plain_len, pos: 0, part: None, }) } /// The plaintext's length. pub fn plain_len(&self) -> u64 { self.plain_len } fn prefix(&mut self) -> std::io::Result<[u8; PREFIX]> { if let Some(prefix) = self.prefix { return Ok(prefix); } let mut head = [0u8; HEAD as usize]; self.sealed.seek(std::io::SeekFrom::Start(0))?; self.sealed.read_exact(&mut head)?; if &head[..4] != MAGIC { return Err(does_not_open()); } let prefix: [u8; PREFIX] = head[4..].try_into().expect("seven bytes"); self.prefix = Some(prefix); Ok(prefix) } fn opened_part(&mut self, index: u64) -> std::io::Result<&[u8]> { if self.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))?; let mut 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 Read for OpeningReader { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { if buf.is_empty() || self.pos >= self.plain_len { // An empty file is still one part, and it must open. if self.plain_len == 0 && self.part.is_none() { self.opened_part(0)?; } return Ok(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 std::io::Seek for OpeningReader { fn seek(&mut self, to: std::io::SeekFrom) -> std::io::Result { 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. pub fn 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;