1use std::io::{Read, Write};
10use std::path::Path;
11
12use super::gcm;
13use zeroize::Zeroize;
14use super::sha256::Sha256;
15
16use super::hex;
17
18const CHUNK: usize = 1 << 20;
21
22#[derive(Debug)]
24pub struct StreamedFile {
25 pub source_sha256: String,
27 pub output_sha256: String,
29 pub output_len: u64,
30}
31
32pub const CANCELLED: &str = "Upload cancelled";
34
35fn 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
50pub 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
57pub 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
67pub 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
73pub 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
78pub 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
84pub 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
95pub const TAG_MISMATCH: &str = "Decryption failed: aead::Error (authentication tag mismatch)";
97
98pub const CHANGED: &str = "The file changed while it was being sent. Attach it again to send it.";
100
101pub 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
113const 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 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
231pub 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
248pub 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 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 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, ¶ms).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, ¶ms.key, ¶ms.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, ¶ms).unwrap();
340 let src = dir.join("blob");
341 std::fs::write(&src, &sealed).unwrap();
342
343 let got = verify_file(&src, ¶ms.key, ¶ms.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, ¶ms).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, ¶ms.key, ¶ms.nonce).unwrap_err().contains("aead"));
364
365 std::fs::write(&src, &sealed[..sealed.len() - 1]).unwrap();
366 assert!(verify_file(&src, ¶ms.key, ¶ms.nonce).is_err(), "a truncated blob");
367 std::fs::write(&src, &sealed[..10]).unwrap();
368 assert!(verify_file(&src, ¶ms.key, ¶ms.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, ¶ms.nonce).unwrap_err().contains("aead"));
373 let mut stop = |pct: u8| pct < 50;
374 assert_eq!(verify_file_with_progress(&src, ¶ms.key, ¶ms.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, ¶ms.key, ¶ms.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, ¶ms.key, ¶ms.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, ¶ms.key, ¶ms.nonce).unwrap();
400 let blob = std::fs::read(&sealed).unwrap();
401 assert_eq!(blob, crate::crypto::encrypt_data(&plain, ¶ms).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, ¶ms.key, ¶ms.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, ¶ms.key, ¶ms.nonce).unwrap();
418 let err = decrypt_file_with_progress(&sealed, &opened, ¶ms.key, ¶ms.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], ¶ms).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, ¶ms.key, ¶ms.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", ¶ms).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, ¶ms.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}