//! THE SEALED FILE. One per app, named by the phone (`Story.cottonbackup`). //! //! ```text //! COTTON-BACKUP\n the magic line //! {"format":1,"app":"story","made_at":…,"id":…, the open header: one line of JSON, at most 64 KiB. //! "chunk":1048576,"key":""}\n It says which app, when, and which code opens it. //! [u32 BE: length | 1<<31 on the last][sealed chunk]… the body, chunk by chunk //! ``` //! //! **The body**, before sealing: a u32 BE length, the manifest (JSON: what is inside, each part's size, the counts //! per kind of thing), then each part's bytes in the manifest's order; all of it deflated. Nothing about what a //! person keeps (not even how many notes) stands in the open header: Apple or Google, holding the file, read only //! the app's name, when it was made and which key opens it. //! //! **The seal**: AES-256-GCM under the file's own key ([`BackupKey::file_key`]), each chunk's nonce the file id's //! first seven bytes, the chunk's index and whether it is the last, and every chunk bound to the whole open header //! (its SHA-256 as associated data). A chunk changed, moved, dropped or added, a header edited, or a file cut short //! is caught: [`Refusal::Damaged`] or [`Refusal::Cut`], never a part restored. use std::collections::BTreeMap; use std::io::{self, Read, Write}; use aes_gcm::aead::{Aead, KeyInit, Payload}; use aes_gcm::{Aes256Gcm, Key, Nonce}; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use base64::Engine as _; use flate2::bufread::DeflateDecoder; use flate2::write::DeflateEncoder; use flate2::Compression; use rand::RngCore; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use zeroize::Zeroizing; use super::key::BackupKey; use crate::vault::recovery_code::Problem; /// The magic line. pub const MAGIC: &[u8] = b"COTTON-BACKUP\n"; /// The format this build writes, and the newest it reads. pub const FORMAT: u32 = 1; /// A chunk's plain size. pub const CHUNK: usize = 1 << 20; /// The longest open header taken. pub const MAX_HEADER: usize = 64 * 1024; /// The longest manifest taken. pub const MAX_MANIFEST: usize = 4 * 1024 * 1024; const LAST: u32 = 1 << 31; const TAG_LEN: usize = 16; const ID_LEN: usize = 16; /// The open header. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Outer { pub format: u32, /// The app's slug (`story`, `notes`, `days`, `keys`…). pub app: String, /// When it was made, as the phone said (RFC 3339). pub made_at: String, /// The file's random id, base64. pub id: String, pub chunk: usize, /// Which backup key seals it ([`BackupKey::check`]). pub key: String, } /// One part of what is inside. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Part { /// A plain name (`data.sqlite`, `files/ab12.jpg`): no folder above it, no `..`. pub name: String, pub bytes: u64, } /// What is inside, sealed. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Manifest { pub app: String, pub made_at: String, /// The core that made it. pub made_by: String, /// The phone's own word for where it was made (`iPhone`, `Android phone`). #[serde(default)] pub device: String, pub parts: Vec, /// How many of each kind of thing (`notes: 412`), as the person counts them. #[serde(default)] pub counts: BTreeMap, } /// What a made file is. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Made { pub outer: Outer, /// The sealed file's size. pub bytes: u64, /// What was put in, before deflating. pub plain_bytes: u64, } /// A file opened and checked whole. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Opened { pub outer: Outer, pub manifest: Manifest, /// The key that opened it: kept by a phone that opened with a typed code, so its next backups need no code. pub key: BackupKey, } /// Why a file was not made or not opened: each has its words (`backup` `refused.*`). #[derive(Debug, Clone, PartialEq, Eq)] pub enum Refusal { /// Not a Cotton backup at all. NotABackup, /// Made by a newer Cotton: update the app. Newer, /// Another app's backup. OtherApp(String), /// Made with another code than the one given (or the one the key store holds). OtherKey, /// The code as typed is not a code. CodeTyped(Problem), /// The file was changed or broken after it was made. Damaged, /// The file ends early: it was not copied whole. Cut, /// Reading or writing failed underneath (the disk), with its own sentence. Io(String), } impl Refusal { /// The refusal's code: its line is `backup` `refused.`. pub fn code(&self) -> &'static str { match self { Refusal::NotABackup => "not_a_backup", Refusal::Newer => "newer", Refusal::OtherApp(_) => "other_app", Refusal::OtherKey => "other_key", Refusal::CodeTyped(_) => "code_typed", Refusal::Damaged => "damaged", Refusal::Cut => "cut", Refusal::Io(_) => "io", } } } impl From for Refusal { fn from(err: io::Error) -> Refusal { match err.kind() { io::ErrorKind::UnexpectedEof => Refusal::Cut, io::ErrorKind::InvalidData => Refusal::Damaged, _ => Refusal::Io(err.to_string()), } } } /// How the person opens a file: the keys to try, the key store's first, then a typed code's. pub enum Unlock<'a> { /// The key the phone's key store holds. Key(&'a BackupKey), /// The recovery code, as typed. Code(&'a str), /// Either: the key store's first, then the typed code. Both(&'a BackupKey, &'a str), } /// A part to put in: its name and where its bytes come from, with their length. pub struct Source<'a> { pub name: String, pub bytes: u64, pub read: &'a mut dyn Read, } /// Make a file. `made_at` is the phone's clock; the random id comes from the OS. pub fn make( out: &mut dyn Write, key: &BackupKey, manifest: &Manifest, sources: &mut [Source<'_>], ) -> Result { let mut id = [0u8; ID_LEN]; rand::rngs::OsRng.fill_bytes(&mut id); make_with(out, key, manifest, sources, &id) } /// [`make`] with the file id given. pub fn make_with( out: &mut dyn Write, key: &BackupKey, manifest: &Manifest, sources: &mut [Source<'_>], id: &[u8; ID_LEN], ) -> Result { let parts: Vec = sources.iter().map(|s| Part { name: s.name.clone(), bytes: s.bytes }).collect(); if parts.iter().any(|p| !plain_name(&p.name)) { return Err(Refusal::Io("a part's name must be a plain name".into())); } let manifest = Manifest { parts, ..manifest.clone() }; let outer = Outer { format: FORMAT, app: manifest.app.clone(), made_at: manifest.made_at.clone(), id: URL_SAFE_NO_PAD.encode(id), chunk: CHUNK, key: key.check(), }; let header = serde_json::to_vec(&outer).map_err(|e| Refusal::Io(e.to_string()))?; let mut counted = Counting { inner: out, bytes: 0 }; counted.write_all(MAGIC)?; counted.write_all(&header)?; counted.write_all(b"\n")?; let sealer = Sealer::new(&mut counted, key.file_key(id), id, &header); let mut deflate = DeflateEncoder::new(sealer, Compression::default()); let manifest_bytes = serde_json::to_vec(&manifest).map_err(|e| Refusal::Io(e.to_string()))?; deflate.write_all(&(manifest_bytes.len() as u32).to_be_bytes())?; deflate.write_all(&manifest_bytes)?; let mut plain = 4 + manifest_bytes.len() as u64; for source in sources.iter_mut() { let copied = io::copy(&mut (&mut source.read).take(source.bytes), &mut deflate)?; if copied != source.bytes { return Err(Refusal::Io(format!("{} was shorter than said", source.name))); } plain += copied; } deflate.finish()?.finish()?; Ok(Made { outer, bytes: counted.bytes, plain_bytes: plain }) } /// Read only the open header: which app, when, which key, whether a code can open it. Opens nothing. pub fn read_outer(input: &mut dyn Read) -> Result<(Outer, Vec), Refusal> { let mut magic = [0u8; MAGIC.len()]; let mut got = 0; while got < magic.len() { match input.read(&mut magic[got..])? { 0 => return Err(Refusal::NotABackup), n => got += n, } } if magic != MAGIC { return Err(Refusal::NotABackup); } let mut header = Vec::new(); let mut byte = [0u8; 1]; loop { if input.read(&mut byte)? == 0 { return Err(Refusal::Cut); } if byte[0] == b'\n' { break; } header.push(byte[0]); if header.len() > MAX_HEADER { return Err(Refusal::Damaged); } } #[derive(Deserialize)] struct Format { format: u32, } let format: Format = serde_json::from_slice(&header).map_err(|_| Refusal::Damaged)?; if format.format > FORMAT { return Err(Refusal::Newer); } let outer: Outer = serde_json::from_slice(&header).map_err(|_| Refusal::Damaged)?; if outer.chunk == 0 || outer.chunk > 16 * CHUNK || URL_SAFE_NO_PAD.decode(&outer.id).map(|id| id.len()) != Ok(ID_LEN) { return Err(Refusal::Damaged); } Ok((outer, header)) } /// Open a file whole for the app `app`, handing each part's bytes to `sink` as they come. A refusal may come after /// some bytes were handed over (the damage is found where it is): the caller writes them aside and keeps them only /// on `Ok`. pub fn open( input: &mut dyn Read, app: &str, unlock: Unlock<'_>, sink: &mut dyn FnMut(&Part, &[u8]) -> io::Result<()>, ) -> Result { let (outer, header) = read_outer(input)?; if outer.app != app { return Err(Refusal::OtherApp(outer.app)); } let key = choose_key(&outer, unlock)?; let id: [u8; ID_LEN] = URL_SAFE_NO_PAD.decode(&outer.id).ok().and_then(|id| id.try_into().ok()).ok_or(Refusal::Damaged)?; let opener = Opener::new(input, key.file_key(&id), &id, &header, outer.chunk); let mut body = DeflateDecoder::new(io::BufReader::new(opener)); let mut len = [0u8; 4]; body.read_exact(&mut len)?; let len = u32::from_be_bytes(len) as usize; if len > MAX_MANIFEST { return Err(Refusal::Damaged); } let mut manifest_bytes = vec![0u8; len]; body.read_exact(&mut manifest_bytes)?; let manifest: Manifest = serde_json::from_slice(&manifest_bytes).map_err(|_| Refusal::Damaged)?; if manifest.app != outer.app || manifest.parts.iter().any(|p| !plain_name(&p.name)) { return Err(Refusal::Damaged); } let mut buf = vec![0u8; 64 * 1024]; for part in &manifest.parts { let mut left = part.bytes; while left > 0 { let want = buf.len().min(left as usize); body.read_exact(&mut buf[..want])?; sink(part, &buf[..want]).map_err(|e| Refusal::Io(e.to_string()))?; left -= want as u64; } } // Nothing may follow the last part, and the sealed stream must end on its last chunk. let mut rest = [0u8; 1]; if body.read(&mut rest)? != 0 { return Err(Refusal::Damaged); } let buffered = body.into_inner(); if !buffered.buffer().is_empty() { return Err(Refusal::Damaged); } buffered.into_inner().finish()?; Ok(Opened { outer, manifest, key }) } /// Which key opens `outer`, given what the person has. fn choose_key(outer: &Outer, unlock: Unlock<'_>) -> Result { let (held, code) = match unlock { Unlock::Key(key) => (Some(key), None), Unlock::Code(code) => (None, Some(code)), Unlock::Both(key, code) => (Some(key), Some(code)), }; if let Some(key) = held { if key.check() == outer.key { return Ok(key.clone()); } } match code.map(BackupKey::from_code) { Some(Ok(typed)) if typed.check() == outer.key => Ok(typed), Some(Err(problem)) => Err(Refusal::CodeTyped(problem)), _ => Err(Refusal::OtherKey), } } fn plain_name(name: &str) -> bool { !name.is_empty() && name.len() <= 255 && !name.starts_with('/') && !name.contains('\\') && !name.contains('\0') && name.split('/').all(|seg| !seg.is_empty() && seg != "." && seg != "..") } fn nonce(id: &[u8; ID_LEN], index: u32, last: bool) -> [u8; 12] { let mut n = [0u8; 12]; n[..7].copy_from_slice(&id[..7]); n[7..11].copy_from_slice(&index.to_be_bytes()); n[11] = last as u8; n } struct Counting<'a> { inner: &'a mut dyn Write, bytes: u64, } impl Write for Counting<'_> { fn write(&mut self, buf: &[u8]) -> io::Result { let n = self.inner.write(buf)?; self.bytes += n as u64; Ok(n) } fn flush(&mut self) -> io::Result<()> { self.inner.flush() } } /// Seals what is written into chunks; [`finish`](Sealer::finish) writes the last one (empty if need be). struct Sealer { out: W, cipher: Aes256Gcm, id: [u8; ID_LEN], aad: [u8; 32], buf: Vec, index: u32, } impl Sealer { fn new(out: W, key: Zeroizing<[u8; 32]>, id: &[u8; ID_LEN], header: &[u8]) -> Self { let cipher = Aes256Gcm::new(Key::::from_slice(key.as_ref())); Sealer { out, cipher, id: *id, aad: Sha256::digest(header).into(), buf: Vec::with_capacity(CHUNK), index: 0 } } fn seal(&mut self, last: bool) -> io::Result<()> { let sealed = self .cipher .encrypt(Nonce::from_slice(&nonce(&self.id, self.index, last)), Payload { msg: &self.buf, aad: &self.aad }) .map_err(|_| io::Error::other("the chunk could not be sealed"))?; let mut len = sealed.len() as u32; if last { len |= LAST; } self.out.write_all(&len.to_be_bytes())?; self.out.write_all(&sealed)?; self.buf.clear(); self.index = self.index.checked_add(1).ok_or_else(|| io::Error::other("the file is too large"))?; Ok(()) } fn finish(mut self) -> io::Result { self.seal(true)?; self.out.flush()?; Ok(self.out) } } impl Write for Sealer { fn write(&mut self, data: &[u8]) -> io::Result { let room = CHUNK - self.buf.len(); let take = room.min(data.len()); self.buf.extend_from_slice(&data[..take]); if self.buf.len() == CHUNK { self.seal(false)?; } Ok(take) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } /// Opens chunk after chunk; a chunk that does not open is `InvalidData`, a file that ends before its last chunk is /// `UnexpectedEof`. struct Opener<'a> { input: &'a mut dyn Read, cipher: Aes256Gcm, id: [u8; ID_LEN], aad: [u8; 32], chunk: usize, plain: Zeroizing>, at: usize, index: u32, ended: bool, } impl<'a> Opener<'a> { fn new(input: &'a mut dyn Read, key: Zeroizing<[u8; 32]>, id: &[u8; ID_LEN], header: &[u8], chunk: usize) -> Self { let cipher = Aes256Gcm::new(Key::::from_slice(key.as_ref())); Opener { input, cipher, id: *id, aad: Sha256::digest(header).into(), chunk, plain: Zeroizing::new(Vec::new()), at: 0, index: 0, ended: false, } } fn next(&mut self) -> io::Result<()> { let mut len = [0u8; 4]; self.input.read_exact(&mut len)?; let len = u32::from_be_bytes(len); let last = len & LAST != 0; let len = (len & !LAST) as usize; if len < TAG_LEN || len > self.chunk + TAG_LEN || (!last && len != self.chunk + TAG_LEN) { return Err(io::Error::new(io::ErrorKind::InvalidData, "a chunk's length is wrong")); } let mut sealed = vec![0u8; len]; self.input.read_exact(&mut sealed)?; let plain = self .cipher .decrypt(Nonce::from_slice(&nonce(&self.id, self.index, last)), Payload { msg: &sealed, aad: &self.aad }) .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "a chunk does not open"))?; self.plain = Zeroizing::new(plain); self.at = 0; self.index += 1; self.ended = last; Ok(()) } /// Everything read: the chunks left (the empty last one, at most) hold nothing, and nothing follows the last. fn finish(mut self) -> io::Result<()> { loop { if self.at != self.plain.len() { return Err(io::Error::new(io::ErrorKind::InvalidData, "bytes after the end")); } if self.ended { break; } self.next()?; } let mut more = [0u8; 1]; if self.input.read(&mut more)? != 0 { return Err(io::Error::new(io::ErrorKind::InvalidData, "bytes after the last chunk")); } Ok(()) } } impl Read for Opener<'_> { fn read(&mut self, out: &mut [u8]) -> io::Result { while self.at == self.plain.len() { if self.ended { return Ok(0); } self.next()?; } let n = out.len().min(self.plain.len() - self.at); out[..n].copy_from_slice(&self.plain[self.at..self.at + n]); self.at += n; Ok(n) } } #[cfg(test)] #[path = "file_tests.rs"] mod tests;