Skip to main content

vector_core/crypto/
stream.rs

1//! Attachment AES-256-GCM over a file, a chunk at a time: the cipher of
2//! [`super::decrypt_data`] (16-byte nonce, 16-byte tag appended) without the file
3//! ever sitting whole in memory.
4//!
5//! GCM is CTR encryption plus a GHASH over the ciphertext, and both run
6//! incrementally. The catch is that the tag only speaks at the end, so plaintext
7//! is written to a file the caller keeps out of sight until this returns Ok.
8
9use std::io::{Read, Write};
10use std::path::Path;
11
12use super::gcm;
13use zeroize::Zeroize;
14use super::sha256::Sha256;
15
16use super::hex;
17
18/// Read size for every streamed pass. A multiple of the 16-byte GHASH block, so
19/// only the final read can leave a partial block.
20const CHUNK: usize = 1 << 20;
21
22/// What one pass over a downloaded file learned.
23#[derive(Debug)]
24pub struct StreamedFile {
25    /// SHA-256 of the file as downloaded: a Blossom URL's content address.
26    pub source_sha256: String,
27    /// SHA-256 of what was written out: the attachment's identity.
28    pub output_sha256: String,
29    pub output_len: u64,
30}
31
32/// What a pass stopped by its caller returns.
33pub const CANCELLED: &str = "Upload cancelled";
34
35/// Tell `progress` when `done` of `total` reaches a new whole percentage; false when
36/// it asks the pass to stop.
37fn report(done: u64, total: u64, reported: &mut u8, progress: &mut dyn FnMut(u8) -> bool) -> bool {
38    let pct = done.saturating_mul(100).checked_div(total).map_or(100, |p| p.min(100) as u8);
39    if pct > *reported {
40        *reported = pct;
41        return progress(pct);
42    }
43    true
44}
45
46fn hex32(bytes: &[u8]) -> String {
47    hex::encode(bytes)
48}
49
50/// Decrypt `src` (ciphertext || tag) into `dst`, hashing both sides on the way.
51/// `dst` holds unauthenticated plaintext until this returns: on any error it is
52/// removed, and a tag mismatch is reported as a decryption failure.
53pub fn decrypt_file(src: &Path, dst: &Path, key_hex: &str, nonce_hex: &str) -> Result<StreamedFile, String> {
54    decrypt_file_with_progress(src, dst, key_hex, nonce_hex, &mut |_| true)
55}
56
57/// [`decrypt_file`], telling `progress` each new whole percentage of the file opened.
58/// `progress` answering false stops the pass, as for [`encrypt_file_with_progress`].
59pub fn decrypt_file_with_progress(src: &Path, dst: &Path, key_hex: &str, nonce_hex: &str, progress: &mut dyn FnMut(u8) -> bool) -> Result<StreamedFile, String> {
60    let result = decrypt_file_inner(src, Some(dst), key_hex, nonce_hex, progress);
61    if result.is_err() {
62        let _ = std::fs::remove_file(dst);
63    }
64    result
65}
66
67/// What [`decrypt_file`] learns about `src`, with no plaintext written anywhere: the tag
68/// verdict, both hashes and the length. For ciphertext that stays ciphertext on disk.
69pub fn verify_file(src: &Path, key_hex: &str, nonce_hex: &str) -> Result<StreamedFile, String> {
70    verify_file_with_progress(src, key_hex, nonce_hex, &mut |_| true)
71}
72
73/// [`verify_file`], reporting progress as [`decrypt_file_with_progress`] does.
74pub fn verify_file_with_progress(src: &Path, key_hex: &str, nonce_hex: &str, progress: &mut dyn FnMut(u8) -> bool) -> Result<StreamedFile, String> {
75    decrypt_file_inner(src, None, key_hex, nonce_hex, progress)
76}
77
78/// Encrypt `src` into `dst` (ciphertext || tag), the counterpart of [`decrypt_file`].
79/// Returns the SHA-256 and length of what was written: the blob a server will hold.
80pub fn encrypt_file(src: &Path, dst: &Path, key_hex: &str, nonce_hex: &str) -> Result<(String, u64), String> {
81    encrypt_file_with_progress(src, dst, key_hex, nonce_hex, &mut |_| true)
82}
83
84/// [`encrypt_file`], telling `progress` each new whole percentage of the file sealed.
85/// `progress` answering false stops the pass: nothing is written and the error says
86/// it was cancelled.
87pub fn encrypt_file_with_progress(src: &Path, dst: &Path, key_hex: &str, nonce_hex: &str, progress: &mut dyn FnMut(u8) -> bool) -> Result<(String, u64), String> {
88    let result = encrypt_file_inner(src, dst, key_hex, nonce_hex, progress);
89    if result.is_err() {
90        let _ = std::fs::remove_file(dst);
91    }
92    result.map(|(blob, len, _)| (blob, len))
93}
94
95/// What opening says when the bytes aren't the ones sealed under that key.
96pub const TAG_MISMATCH: &str = "Decryption failed: aead::Error (authentication tag mismatch)";
97
98/// What a send says when its file changed between being hashed and being sealed.
99pub const CHANGED: &str = "The file changed while it was being sent. Attach it again to send it.";
100
101/// [`encrypt_file_with_progress`] for a file the sender may still change: the bytes sealed
102/// must be the ones hashed as `plain_sha256`, or nothing is written and the send says so.
103pub fn encrypt_file_matching(src: &Path, dst: &Path, key_hex: &str, nonce_hex: &str, plain_sha256: &str, progress: &mut dyn FnMut(u8) -> bool) -> Result<(String, u64), String> {
104    let result = encrypt_file_inner(src, dst, key_hex, nonce_hex, progress).and_then(|(blob, len, plain)| {
105        if plain == plain_sha256 { Ok((blob, len)) } else { Err(CHANGED.to_string()) }
106    });
107    if result.is_err() {
108        let _ = std::fs::remove_file(dst);
109    }
110    result
111}
112
113/// GCM's limit for one message (2^36 - 32 bytes): past it the 32-bit counter wraps and
114/// the keystream repeats.
115const GCM_MAX_PLAINTEXT: u64 = (1 << 36) - 32;
116
117fn encrypt_file_inner(src: &Path, dst: &Path, key_hex: &str, nonce_hex: &str, progress: &mut dyn FnMut(u8) -> bool) -> Result<(String, u64, String), String> {
118    let (mut key, nonce) = super::attachment_params(key_hex, nonce_hex, "Invalid decryption key")?;
119    let mut input = std::fs::File::open(src).map_err(|e| format!("open file: {e}"))?;
120    let total = input.metadata().map(|m| m.len()).unwrap_or(0);
121    if total > GCM_MAX_PLAINTEXT {
122        return Err("File too large to encrypt as one attachment (over 64 GiB)".to_string());
123    }
124    let mut gcm = gcm::Stream::new(&key, &nonce);
125    key.zeroize();
126    let mut reported = 0u8;
127    let mut output = std::io::BufWriter::with_capacity(
128        CHUNK,
129        std::fs::File::create(dst).map_err(|e| format!("create ciphertext: {e}"))?,
130    );
131    let mut blob_hash = Sha256::new();
132    let mut plain_hash = Sha256::new();
133    let mut buf = vec![0u8; CHUNK];
134    let mut len = 0u64;
135    loop {
136        // Fill the buffer before encrypting: GHASH may only pad the final block.
137        let mut n = 0;
138        while n < CHUNK {
139            let got = input.read(&mut buf[n..]).map_err(|e| format!("read file: {e}"))?;
140            if got == 0 {
141                break;
142            }
143            n += got;
144        }
145        if n == 0 {
146            break;
147        }
148        let chunk = &mut buf[..n];
149        plain_hash.update(&*chunk);
150        gcm.encrypt(chunk);
151        blob_hash.update(&*chunk);
152        output.write_all(chunk).map_err(|e| format!("write ciphertext: {e}"))?;
153        len += n as u64;
154        if !report(len, total, &mut reported, progress) {
155            return Err(CANCELLED.to_string());
156        }
157        if n < CHUNK {
158            break;
159        }
160    }
161    let tag = gcm.finish();
162    blob_hash.update(tag);
163    output.write_all(&tag).map_err(|e| format!("write ciphertext: {e}"))?;
164    let file = output.into_inner().map_err(|e| format!("write ciphertext: {e}"))?;
165    file.sync_all().map_err(|e| format!("sync ciphertext: {e}"))?;
166    Ok((hex32(&blob_hash.finalize()), len + 16, hex32(&plain_hash.finalize())))
167}
168
169fn decrypt_file_inner(src: &Path, dst: Option<&Path>, key_hex: &str, nonce_hex: &str, progress: &mut dyn FnMut(u8) -> bool) -> Result<StreamedFile, String> {
170    let (mut key, nonce) = super::attachment_params(key_hex, nonce_hex, "Invalid decryption key")?;
171    let mut input = std::fs::File::open(src).map_err(|e| format!("open download: {e}"))?;
172    let total = input.metadata().map_err(|e| format!("stat download: {e}"))?.len();
173    if total < 16 {
174        return Err(format!("Invalid Input: encrypted data too small ({} bytes, minimum 16 bytes required for authentication tag)", total));
175    }
176    let ciphertext_len = total - 16;
177    if ciphertext_len > GCM_MAX_PLAINTEXT {
178        return Err("Invalid Input: encrypted data exceeds the AES-GCM limit".to_string());
179    }
180    let mut gcm = gcm::Stream::new(&key, &nonce);
181    key.zeroize();
182    let mut reported = 0u8;
183
184    let mut source_hash = Sha256::new();
185    let mut output_hash = Sha256::new();
186    let mut output = match dst {
187        Some(dst) => Some(std::io::BufWriter::with_capacity(
188            CHUNK,
189            std::fs::File::create(dst).map_err(|e| format!("create output: {e}"))?,
190        )),
191        None => None,
192    };
193
194    let mut buf = vec![0u8; CHUNK];
195    let mut remaining = ciphertext_len;
196    while remaining > 0 {
197        let n = remaining.min(CHUNK as u64) as usize;
198        let chunk = &mut buf[..n];
199        input.read_exact(chunk).map_err(|e| format!("read download: {e}"))?;
200        source_hash.update(&*chunk);
201        gcm.decrypt(chunk);
202        output_hash.update(&*chunk);
203        if let Some(output) = output.as_mut() {
204            output.write_all(chunk).map_err(|e| format!("write output: {e}"))?;
205        }
206        remaining -= n as u64;
207        if !report(ciphertext_len - remaining, ciphertext_len, &mut reported, progress) {
208            return Err(CANCELLED.to_string());
209        }
210    }
211
212    let mut tag = [0u8; 16];
213    input.read_exact(&mut tag).map_err(|e| format!("read download: {e}"))?;
214    source_hash.update(tag);
215
216    if !gcm::tags_equal(&gcm.finish(), &tag) {
217        return Err(TAG_MISMATCH.to_string());
218    }
219
220    if let Some(output) = output {
221        let file = output.into_inner().map_err(|e| format!("write output: {e}"))?;
222        file.sync_all().map_err(|e| format!("sync output: {e}"))?;
223    }
224    Ok(StreamedFile {
225        source_sha256: hex32(&source_hash.finalize()),
226        output_sha256: hex32(&output_hash.finalize()),
227        output_len: ciphertext_len,
228    })
229}
230
231/// SHA-256 of a file, read a chunk at a time.
232pub fn hash_file(path: &Path) -> Result<(String, u64), String> {
233    let mut file = std::fs::File::open(path).map_err(|e| format!("open: {e}"))?;
234    let mut hasher = Sha256::new();
235    let mut buf = vec![0u8; CHUNK];
236    let mut len = 0u64;
237    loop {
238        let n = file.read(&mut buf).map_err(|e| format!("read: {e}"))?;
239        if n == 0 {
240            break;
241        }
242        hasher.update(&buf[..n]);
243        len += n as u64;
244    }
245    Ok((hex32(&hasher.finalize()), len))
246}
247
248/// Put a verified download into the download directory under `name`: an identical
249/// file already there (same name, size and hash) is reused and `src` dropped;
250/// otherwise `src` moves to a free spelling of the name. Returns where it landed.
251pub fn place_download(src: &Path, file_hash: &str, len: u64, name: &str, extension: &str) -> Result<std::path::PathBuf, String> {
252    let dir = crate::db::get_download_dir();
253    std::fs::create_dir_all(&dir).map_err(|e| format!("Failed to create directory: {}", e))?;
254    let target_name = if name.is_empty() { format!("{}.{}", file_hash, extension) } else { name.to_string() };
255    // One plain component, or nothing: the name and extension come from the sender.
256    let mut parts = Path::new(&target_name).components();
257    if !matches!((parts.next(), parts.next()), (Some(std::path::Component::Normal(_)), None))
258        || target_name.contains(['/', '\\'])
259    {
260        return Err("Refusing a download name outside the download folder".to_string());
261    }
262
263    let candidate = dir.join(&target_name);
264    let identical = std::fs::metadata(&candidate).map(|m| m.len() == len).unwrap_or(false)
265        && hash_file(&candidate).map(|(h, _)| h == file_hash).unwrap_or(false);
266    if identical {
267        let _ = std::fs::remove_file(src);
268        return Ok(candidate);
269    }
270
271    let dest = crate::crypto::resolve_unique_filename(&dir, &target_name);
272    // A rename can't cross filesystems (app storage to shared storage on Android):
273    // copy beside the destination, then rename that into place.
274    if std::fs::rename(src, &dest).is_err() {
275        let staging = dir.join(format!(".{}.{}.tmp", file_hash, extension));
276        let copied = std::fs::copy(src, &staging)
277            .map_err(|e| format!("Failed to write file: {}", e))
278            .and_then(|_| std::fs::File::open(&staging).and_then(|f| f.sync_all()).map_err(|e| format!("Failed to write file: {}", e)))
279            .and_then(|_| std::fs::rename(&staging, &dest).map_err(|e| format!("Failed to rename file: {}", e)));
280        if let Err(e) = copied {
281            let _ = std::fs::remove_file(&staging);
282            return Err(e);
283        }
284        let _ = std::fs::remove_file(src);
285    }
286    Ok(dest)
287}
288
289#[cfg(test)]
290mod tests {
291    use super::*;
292
293    fn scratch(tag: &str) -> std::path::PathBuf {
294        let dir = std::env::temp_dir().join(format!("vector-stream-{tag}-{}", std::process::id()));
295        let _ = std::fs::remove_dir_all(&dir);
296        std::fs::create_dir_all(&dir).unwrap();
297        dir
298    }
299
300    #[test]
301    fn a_download_never_lands_outside_its_folder() {
302        let dir = scratch("escape");
303        let src = dir.join("plain");
304        std::fs::write(&src, b"x").unwrap();
305        for bad in ["..\\..\\evil.bat", "../evil", "sub/evil", ".."] {
306            assert!(place_download(&src, "abc", 1, bad, "bin").is_err(), "{bad}");
307        }
308        assert!(place_download(&src, "abc", 1, "", "..\\evil").is_err());
309    }
310
311    fn roundtrip(len: usize) {
312        let dir = scratch(&format!("rt{len}"));
313        let plain: Vec<u8> = (0..len).map(|i| (i * 31 % 251) as u8).collect();
314        let params = crate::crypto::generate_encryption_params();
315        let sealed = crate::crypto::encrypt_data(&plain, &params).unwrap();
316        let (src, dst) = (dir.join("in"), dir.join("out"));
317        std::fs::write(&src, &sealed).unwrap();
318
319        let got = decrypt_file(&src, &dst, &params.key, &params.nonce).unwrap();
320        assert_eq!(std::fs::read(&dst).unwrap(), plain, "same plaintext as the one-shot cipher at {len} bytes");
321        assert_eq!(got.output_sha256, crate::crypto::sha256_hex(&plain));
322        assert_eq!(got.source_sha256, crate::crypto::sha256_hex(&sealed));
323        assert_eq!(got.output_len, len as u64);
324    }
325
326    #[test]
327    fn it_matches_the_one_shot_cipher_across_chunk_and_block_edges() {
328        for len in [0, 1, 15, 16, 17, CHUNK - 1, CHUNK, CHUNK + 1, 2 * CHUNK + 7] {
329            roundtrip(len);
330        }
331    }
332
333    #[test]
334    fn a_verify_pass_learns_what_a_decrypt_does_and_writes_nothing() {
335        for len in [0usize, 17, CHUNK + 1] {
336            let dir = scratch(&format!("verify{len}"));
337            let plain: Vec<u8> = (0..len).map(|i| (i * 13 % 241) as u8).collect();
338            let params = crate::crypto::generate_encryption_params();
339            let sealed = crate::crypto::encrypt_data(&plain, &params).unwrap();
340            let src = dir.join("blob");
341            std::fs::write(&src, &sealed).unwrap();
342
343            let got = verify_file(&src, &params.key, &params.nonce).unwrap();
344            assert_eq!(got.output_sha256, crate::crypto::sha256_hex(&plain));
345            assert_eq!(got.source_sha256, crate::crypto::sha256_hex(&sealed));
346            assert_eq!(got.output_len, len as u64);
347            let left: Vec<_> = std::fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).collect();
348            assert_eq!(left, vec![std::ffi::OsString::from("blob")], "nothing beside the blob at {len} bytes");
349        }
350    }
351
352    #[test]
353    fn a_verify_pass_refuses_a_wrong_key_tamper_and_truncation() {
354        let dir = scratch("verifybad");
355        let plain = vec![0x42u8; CHUNK + 33];
356        let params = crate::crypto::generate_encryption_params();
357        let sealed = crate::crypto::encrypt_data(&plain, &params).unwrap();
358        let src = dir.join("blob");
359
360        let mut tampered = sealed.clone();
361        tampered[CHUNK + 3] ^= 1;
362        std::fs::write(&src, &tampered).unwrap();
363        assert!(verify_file(&src, &params.key, &params.nonce).unwrap_err().contains("aead"));
364
365        std::fs::write(&src, &sealed[..sealed.len() - 1]).unwrap();
366        assert!(verify_file(&src, &params.key, &params.nonce).is_err(), "a truncated blob");
367        std::fs::write(&src, &sealed[..10]).unwrap();
368        assert!(verify_file(&src, &params.key, &params.nonce).is_err(), "shorter than its tag");
369
370        std::fs::write(&src, &sealed).unwrap();
371        let other = crate::crypto::generate_encryption_params();
372        assert!(verify_file(&src, &other.key, &params.nonce).unwrap_err().contains("aead"));
373        let mut stop = |pct: u8| pct < 50;
374        assert_eq!(verify_file_with_progress(&src, &params.key, &params.nonce, &mut stop).unwrap_err(), CANCELLED);
375        assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1, "only the blob, whatever happened");
376    }
377
378    #[test]
379    fn a_file_changed_after_hashing_is_never_sealed() {
380        let dir = scratch("matching");
381        let (src, sealed) = (dir.join("plain"), dir.join("sealed"));
382        std::fs::write(&src, b"what was hashed").unwrap();
383        let hash = crate::crypto::sha256_hex(b"what was hashed");
384        let params = crate::crypto::generate_encryption_params();
385        assert!(encrypt_file_matching(&src, &sealed, &params.key, &params.nonce, &hash, &mut |_| true).is_ok());
386        std::fs::write(&src, b"what was hashed, then edited").unwrap();
387        assert_eq!(encrypt_file_matching(&src, &sealed, &params.key, &params.nonce, &hash, &mut |_| true).unwrap_err(), CHANGED);
388        assert!(!sealed.exists(), "nothing is left to upload");
389    }
390
391    #[test]
392    fn a_streamed_seal_opens_with_the_one_shot_cipher() {
393        for len in [0usize, 1, 16, 17, CHUNK - 1, CHUNK, CHUNK + 1, 2 * CHUNK + 7] {
394            let dir = scratch(&format!("enc{len}"));
395            let plain: Vec<u8> = (0..len).map(|i| (i * 7 % 253) as u8).collect();
396            let (src, sealed) = (dir.join("plain"), dir.join("sealed"));
397            std::fs::write(&src, &plain).unwrap();
398            let params = crate::crypto::generate_encryption_params();
399            let (hash, sealed_len) = encrypt_file(&src, &sealed, &params.key, &params.nonce).unwrap();
400            let blob = std::fs::read(&sealed).unwrap();
401            assert_eq!(blob, crate::crypto::encrypt_data(&plain, &params).unwrap(), "byte for byte at {len} bytes");
402            assert_eq!((hash, sealed_len), (crate::crypto::sha256_hex(&blob), blob.len() as u64));
403        }
404    }
405
406    #[test]
407    fn a_stopped_pass_ends_early_and_leaves_nothing() {
408        let dir = scratch("stop");
409        let (src, sealed, opened) = (dir.join("plain"), dir.join("sealed"), dir.join("opened"));
410        std::fs::write(&src, vec![3u8; 4 * CHUNK]).unwrap();
411        let params = crate::crypto::generate_encryption_params();
412        let mut seen = 0;
413        let err = encrypt_file_with_progress(&src, &sealed, &params.key, &params.nonce, &mut |pct| { seen = pct; pct < 25 }).unwrap_err();
414        assert_eq!(err, CANCELLED);
415        assert!(seen < 100 && !sealed.exists(), "stopped at {seen}%, nothing left behind");
416
417        encrypt_file(&src, &sealed, &params.key, &params.nonce).unwrap();
418        let err = decrypt_file_with_progress(&sealed, &opened, &params.key, &params.nonce, &mut |pct| pct < 50).unwrap_err();
419        assert_eq!(err, CANCELLED);
420        assert!(!opened.exists(), "no half-opened plaintext");
421    }
422
423    #[test]
424    fn a_flipped_byte_fails_and_leaves_no_plaintext() {
425        let dir = scratch("tamper");
426        let params = crate::crypto::generate_encryption_params();
427        let mut sealed = crate::crypto::encrypt_data(&vec![7u8; 5000], &params).unwrap();
428        sealed[2500] ^= 1;
429        let (src, dst) = (dir.join("in"), dir.join("out"));
430        std::fs::write(&src, &sealed).unwrap();
431        let err = decrypt_file(&src, &dst, &params.key, &params.nonce).unwrap_err();
432        assert!(err.contains("aead"), "reads as a decryption failure: {err}");
433        assert!(!dst.exists(), "unauthenticated plaintext must not survive");
434    }
435
436    #[test]
437    fn a_wrong_key_fails() {
438        let dir = scratch("key");
439        let params = crate::crypto::generate_encryption_params();
440        let sealed = crate::crypto::encrypt_data(b"hello", &params).unwrap();
441        let (src, dst) = (dir.join("in"), dir.join("out"));
442        std::fs::write(&src, &sealed).unwrap();
443        let other = crate::crypto::generate_encryption_params();
444        assert!(decrypt_file(&src, &dst, &other.key, &params.nonce).is_err());
445    }
446
447    #[test]
448    fn hash_file_matches_the_in_memory_hash() {
449        let dir = scratch("hash");
450        let data: Vec<u8> = (0..(CHUNK + 5)).map(|i| i as u8).collect();
451        std::fs::write(dir.join("f"), &data).unwrap();
452        assert_eq!(hash_file(&dir.join("f")).unwrap(), (crate::crypto::sha256_hex(&data), data.len() as u64));
453    }
454}