//! 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":"<check>"}\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::Engineas _;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;usesuper::key::BackupKey;usecrate::vault::recovery_code::Problem;/// The magic line.pubconst MAGIC: &[u8] = b"COTTON-BACKUP\n";/// The format this build writes, and the newest it reads.pubconst FORMAT: u32 = 1;/// A chunk's plain size.pubconst CHUNK: usize = 1 << 20;/// The longest open header taken.pubconst MAX_HEADER: usize = 64 * 1024;/// The longest manifest taken.pubconst 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)]pubstructOuter {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)]pubstructPart {/// 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)]pubstructManifest {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<Part>,/// How many of each kind of thing (`notes: 412`), as the person counts them. #[serde(default)]pub counts: BTreeMap<String, u64>,}/// What a made file is.#[derive(Debug, Clone, PartialEq, Eq)]pubstructMade {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)]pubstructOpened {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)]pubenumRefusal {/// 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),}implRefusal {/// The refusal's code: its line is `backup` `refused.<code>`.pubfn code(&self) -> &'static str {matchself {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", } }}implFrom<io::Error> forRefusal {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.pubenumUnlock<'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.pubstructSource<'a> {pub name: String,pub bytes: u64,pub read: &'a mutdynRead,}/// Make a file. `made_at` is the phone's clock; the random id comes from the OS.pubfn make( out: &mutdynWrite, key: &BackupKey, manifest: &Manifest, sources: &mut [Source<'_>],) -> Result<Made, Refusal> {letmut id = [0u8; ID_LEN]; rand::rngs::OsRng.fill_bytes(&mut id); make_with(out, key, manifest, sources, &id)}/// [`make`] with the file id given.pubfn make_with( out: &mutdynWrite, key: &BackupKey, manifest: &Manifest, sources: &mut [Source<'_>], id: &[u8; ID_LEN],) -> Result<Made, Refusal> {let parts: Vec<Part> = sources.iter().map(|s| Part { name: s.name.clone(), bytes: s.bytes }).collect();if parts.iter().any(|p| !plain_name(&p.name)) {returnErr(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()))?;letmut 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);letmut 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)?;letmut 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 {returnErr(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.pubfn read_outer(input: &mutdynRead) -> Result<(Outer, Vec<u8>), Refusal> {letmut magic = [0u8; MAGIC.len()];letmut got = 0;while got < magic.len() {match input.read(&mut magic[got..])? {0 => returnErr(Refusal::NotABackup), n => got += n, } }if magic != MAGIC {returnErr(Refusal::NotABackup); }letmut header = Vec::new();letmut byte = [0u8; 1];loop {if input.read(&mut byte)? == 0 {returnErr(Refusal::Cut); }if byte[0] == b'\n' {break; } header.push(byte[0]);if header.len() > MAX_HEADER {returnErr(Refusal::Damaged); } } #[derive(Deserialize)]structFormat { format: u32, }let format: Format = serde_json::from_slice(&header).map_err(|_| Refusal::Damaged)?;if format.format > FORMAT {returnErr(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) {returnErr(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`.pubfn open( input: &mutdynRead, app: &str, unlock: Unlock<'_>, sink: &mutdynFnMut(&Part, &[u8]) -> io::Result<()>,) -> Result<Opened, Refusal> {let (outer, header) = read_outer(input)?;if outer.app != app {returnErr(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);letmut body = DeflateDecoder::new(io::BufReader::new(opener));letmut len = [0u8; 4]; body.read_exact(&mut len)?;let len = u32::from_be_bytes(len) as usize;if len > MAX_MANIFEST {returnErr(Refusal::Damaged); }letmut 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)) {returnErr(Refusal::Damaged); }letmut buf = vec![0u8; 64 * 1024];for part in &manifest.parts {letmut 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.letmut rest = [0u8; 1];if body.read(&mut rest)? != 0 {returnErr(Refusal::Damaged); }let buffered = body.into_inner();if !buffered.buffer().is_empty() {returnErr(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<BackupKey, Refusal> {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)), };ifletSome(key) = held {if key.check() == outer.key {returnOk(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] {letmut 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}structCounting<'a> { inner: &'a mutdynWrite, bytes: u64,}implWriteforCounting<'_> {fn write(&mutself, buf: &[u8]) -> io::Result<usize> {let n = self.inner.write(buf)?;self.bytes += n as u64;Ok(n) }fn flush(&mutself) -> io::Result<()> {self.inner.flush() }}/// Seals what is written into chunks; [`finish`](Sealer::finish) writes the last one (empty if need be).structSealer<W: Write> { out: W, cipher: Aes256Gcm, id: [u8; ID_LEN], aad: [u8; 32], buf: Vec<u8>, index: u32,}impl<W: Write> Sealer<W> {fn new(out: W, key: Zeroizing<[u8; 32]>, id: &[u8; ID_LEN], header: &[u8]) -> Self {let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key.as_ref()));Sealer { out, cipher, id: *id, aad: Sha256::digest(header).into(), buf: Vec::with_capacity(CHUNK), index: 0 } }fn seal(&mutself, 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"))?;letmut 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(mutself) -> io::Result<W> {self.seal(true)?;self.out.flush()?;Ok(self.out) }}impl<W: Write> WriteforSealer<W> {fn write(&mutself, data: &[u8]) -> io::Result<usize> {let room = CHUNK - self.buf.len();let take = room.min(data.len());self.buf.extend_from_slice(&data[..take]);ifself.buf.len() == CHUNK {self.seal(false)?; }Ok(take) }fn flush(&mutself) -> 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`.structOpener<'a> { input: &'a mutdynRead, cipher: Aes256Gcm, id: [u8; ID_LEN], aad: [u8; 32], chunk: usize, plain: Zeroizing<Vec<u8>>, at: usize, index: u32, ended: bool,}impl<'a> Opener<'a> {fn new(input: &'a mutdynRead, key: Zeroizing<[u8; 32]>, id: &[u8; ID_LEN], header: &[u8], chunk: usize) -> Self {let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::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(&mutself) -> io::Result<()> {letmut 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) {returnErr(io::Error::new(io::ErrorKind::InvalidData, "a chunk's length is wrong")); }letmut 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(mutself) -> io::Result<()> {loop {ifself.at != self.plain.len() {returnErr(io::Error::new(io::ErrorKind::InvalidData, "bytes after the end")); }ifself.ended {break; }self.next()?; }letmut more = [0u8; 1];ifself.input.read(&mut more)? != 0 {returnErr(io::Error::new(io::ErrorKind::InvalidData, "bytes after the last chunk")); }Ok(()) }}implReadforOpener<'_> {fn read(&mutself, out: &mut [u8]) -> io::Result<usize> {whileself.at == self.plain.len() {ifself.ended {returnOk(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;