Skip to main content

redseat_api/
encrypted.rs

1//! Random access to the files of encrypted (`crypt`) libraries, for players that
2//! stream and seek.
3//!
4//! A media file is stored as a header, the encrypted thumbnail, then the encrypted
5//! data (redseat-crypto, AES-256-CBC with PKCS#7 padding and the media's IV). The
6//! server serves the data part with range requests (redseat_rust `docs/MEDIA_FILES.md`).
7//! CBC decrypts any block on its own: plaintext block `i` is `AES-decrypt(C[i]) XOR
8//! C[i-1]`, with the media's IV before block 0. So [`EncryptedMediaReader::read_at`]
9//! fetches only the blocks it needs and the one before them.
10//!
11//! The decryption goes through redseat-crypto's one-shot functions. Those check the
12//! PKCS#7 padding, which only the last block of the data has: blocks from the middle
13//! of the data get a padding block appended, encrypted from their last block with
14//! the key, so they decrypt to exactly their plaintext.
15
16use crate::crypto::{Iv, Key};
17use crate::error::{Error, Result};
18use crate::library::LibraryApi;
19use crate::transport::{Request, Response};
20
21/// AES block size.
22const BLOCK: u64 = 16;
23
24/// Reads the plaintext of an encrypted media by ranges. Get one with
25/// [`LibraryApi::open_encrypted_media`], or for a file kept on this device with
26/// [`Downloads::source`](crate::app::downloads::Downloads::source). Cheap to clone.
27#[derive(Clone)]
28pub struct EncryptedMediaReader {
29    source: DataSource,
30    key: Key,
31    iv: Iv,
32    /// Bytes of encrypted data, a multiple of 16.
33    data_len: u64,
34    /// Bytes of plaintext.
35    len: u64,
36}
37
38/// Where the encrypted data is read: from the server by range requests, or from a
39/// file holding the data part as the server serves it (a download kept offline).
40// One per reader: its size does not matter.
41#[allow(clippy::large_enum_variant)]
42#[derive(Clone)]
43enum DataSource {
44    Server {
45        library: LibraryApi,
46        media_id: String,
47    },
48    /// Read on `runtime`'s blocking threads, so any executor can await the reader.
49    #[cfg(all(feature = "mirror", not(target_arch = "wasm32")))]
50    File {
51        path: std::path::PathBuf,
52        runtime: tokio::runtime::Handle,
53    },
54}
55
56impl std::fmt::Debug for EncryptedMediaReader {
57    // Never print the key.
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        let source = match &self.source {
60            DataSource::Server { media_id, .. } => media_id.clone(),
61            #[cfg(all(feature = "mirror", not(target_arch = "wasm32")))]
62            DataSource::File { path, .. } => path.display().to_string(),
63        };
64        f.debug_struct("EncryptedMediaReader")
65            .field("source", &source)
66            .field("len", &self.len)
67            .finish_non_exhaustive()
68    }
69}
70
71/// A range of the encrypted data to fetch.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73enum DataRange {
74    /// From the first to the last byte, inclusive.
75    Bytes(u64, u64),
76    /// The last bytes.
77    Suffix(u64),
78}
79
80impl DataRange {
81    fn header(self) -> String {
82        match self {
83            DataRange::Bytes(start, end) => format!("bytes={start}-{end}"),
84            DataRange::Suffix(count) => format!("bytes=-{count}"),
85        }
86    }
87}
88
89/// The blocks to fetch to read plaintext `offset..end` of `data_len` bytes of data.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91struct Span {
92    /// The first and last block holding the plaintext.
93    first: u64,
94    last: u64,
95    /// The bytes to fetch: the blocks, and the one before them (their IV) if any.
96    fetch: (u64, u64),
97}
98
99fn span(offset: u64, end: u64) -> Span {
100    let (first, last) = (offset / BLOCK, (end - 1) / BLOCK);
101    Span {
102        first,
103        last,
104        fetch: (first.saturating_sub(1) * BLOCK, (last + 1) * BLOCK - 1),
105    }
106}
107
108fn to_block(bytes: &[u8]) -> Result<Iv> {
109    bytes
110        .try_into()
111        .map_err(|_| Error::malformed("encrypted data is not made of whole blocks", None))
112}
113
114/// Decrypts whole CBC blocks that follow `prev` (the previous ciphertext block, or
115/// the IV). `last_of_data`: they end the data, padding included.
116fn decrypt_blocks(key: &Key, prev: &Iv, blocks: &[u8], last_of_data: bool) -> Result<Vec<u8>> {
117    if blocks.is_empty() || !blocks.len().is_multiple_of(BLOCK as usize) {
118        return Err(Error::malformed(
119            "encrypted data is not made of whole blocks",
120            None,
121        ));
122    }
123    if last_of_data {
124        return Ok(redseat_crypto::decrypt_buffer(key, prev, blocks)?);
125    }
126    // A block encrypted from the last one decrypts to a full padding block.
127    let last = to_block(&blocks[blocks.len() - BLOCK as usize..])?;
128    let mut with_padding = blocks.to_vec();
129    with_padding.extend(redseat_crypto::encrypt_buffer(key, &last, &[]));
130    Ok(redseat_crypto::decrypt_buffer(key, prev, &with_padding)?)
131}
132
133/// The total of a `Content-Range: bytes a-b/total` header.
134fn content_range_total(response: &Response) -> Option<u64> {
135    response
136        .header("content-range")?
137        .rsplit('/')
138        .next()?
139        .trim()
140        .parse()
141        .ok()
142}
143
144impl EncryptedMediaReader {
145    pub(crate) async fn open(
146        library: LibraryApi,
147        media_id: String,
148        key: Key,
149        iv: Iv,
150        size: Option<u64>,
151    ) -> Result<Self> {
152        let source = DataSource::Server { library, media_id };
153        Self::open_source(source, key, iv, size).await
154    }
155
156    /// The data part of an encrypted media in a file of this device, as the server
157    /// serves it by ranges, read on `runtime`.
158    #[cfg(all(feature = "mirror", not(target_arch = "wasm32")))]
159    pub(crate) async fn open_file(
160        path: std::path::PathBuf,
161        runtime: tokio::runtime::Handle,
162        key: Key,
163        iv: Iv,
164    ) -> Result<Self> {
165        Self::open_source(DataSource::File { path, runtime }, key, iv, None).await
166    }
167
168    async fn open_source(source: DataSource, key: Key, iv: Iv, size: Option<u64>) -> Result<Self> {
169        let mut reader = EncryptedMediaReader {
170            source,
171            key,
172            iv,
173            data_len: 0,
174            len: 0,
175        };
176        // The server writes no data for an empty file.
177        if size == Some(0) {
178            return Ok(reader);
179        }
180        // The last two blocks: the data size, and the padding of the last one.
181        let (tail, data_len) = reader.fetch(DataRange::Suffix(2 * BLOCK)).await?;
182        if data_len == 0 || !data_len.is_multiple_of(BLOCK) || tail.len() < BLOCK as usize {
183            return Err(Error::malformed(
184                format!("encrypted data of {data_len} bytes is not made of whole blocks"),
185                None,
186            ));
187        }
188        let (prev, last) = match tail.len() {
189            32 => (to_block(&tail[..16])?, &tail[16..]),
190            _ => (reader.iv, &tail[tail.len() - 16..]),
191        };
192        let last_plain = decrypt_blocks(&reader.key, &prev, last, true)?;
193        reader.data_len = data_len;
194        reader.len = data_len - BLOCK + last_plain.len() as u64;
195        Ok(reader)
196    }
197
198    /// The plaintext size, in bytes.
199    pub fn len(&self) -> u64 {
200        self.len
201    }
202
203    pub fn is_empty(&self) -> bool {
204        self.len == 0
205    }
206
207    /// Up to `len` bytes of plaintext from `offset`: fewer at the end, none past it.
208    pub async fn read_at(&self, offset: u64, len: usize) -> Result<Vec<u8>> {
209        if offset >= self.len || len == 0 {
210            return Ok(Vec::new());
211        }
212        let end = offset.saturating_add(len as u64).min(self.len);
213        let span = span(offset, end);
214        let (fetched, _) = self
215            .fetch(DataRange::Bytes(span.fetch.0, span.fetch.1))
216            .await?;
217        if fetched.len() as u64 != span.fetch.1 - span.fetch.0 + 1 {
218            return Err(Error::malformed(
219                format!(
220                    "asked for {} bytes of encrypted data, got {}",
221                    span.fetch.1 - span.fetch.0 + 1,
222                    fetched.len()
223                ),
224                None,
225            ));
226        }
227        let (prev, blocks) = if span.first == 0 {
228            (self.iv, &fetched[..])
229        } else {
230            (to_block(&fetched[..16])?, &fetched[16..])
231        };
232        let last_of_data = span.last == self.data_len / BLOCK - 1;
233        let plain = decrypt_blocks(&self.key, &prev, blocks, last_of_data)?;
234        let skip = (offset - span.first * BLOCK) as usize;
235        let take = (end - offset) as usize;
236        plain
237            .get(skip..skip + take)
238            .map(<[u8]>::to_vec)
239            .ok_or_else(|| Error::malformed("encrypted data shorter than expected", None))
240    }
241
242    /// Fetches a range of the encrypted data; returns it and the data size.
243    async fn fetch(&self, range: DataRange) -> Result<(Vec<u8>, u64)> {
244        let (library, media_id) = match &self.source {
245            DataSource::Server { library, media_id } => (library, media_id),
246            #[cfg(all(feature = "mirror", not(target_arch = "wasm32")))]
247            DataSource::File { path, runtime } => {
248                let path = path.clone();
249                return (runtime.spawn_blocking(move || read_file_range(&path, range)))
250                    .await
251                    .map_err(|error| Error::Storage {
252                        message: format!("cannot read the downloaded file: {error}"),
253                    })?;
254            }
255        };
256        let request = Request::get(library.media_path(media_id)).header("Range", range.header());
257        let response = library.client().request(request).await?;
258        // An older server ignores the range and sends the whole data.
259        let total = match (response.status, content_range_total(&response)) {
260            (206, Some(total)) => total,
261            _ => {
262                return Err(Error::malformed(
263                    "the server cannot serve parts of encrypted files: it needs an update",
264                    None,
265                ));
266            }
267        };
268        Ok((response.body, total))
269    }
270}
271
272/// A range of a file holding encrypted data, and the file's size.
273#[cfg(all(feature = "mirror", not(target_arch = "wasm32")))]
274fn read_file_range(path: &std::path::Path, range: DataRange) -> Result<(Vec<u8>, u64)> {
275    use std::io::{Read as _, Seek as _};
276    let storage = |error: std::io::Error| Error::Storage {
277        message: format!("cannot read the downloaded file: {error}"),
278    };
279    let mut file = std::fs::File::open(path).map_err(storage)?;
280    let total = file.metadata().map_err(storage)?.len();
281    let (start, end) = match range {
282        DataRange::Bytes(start, end) => (start, end.min(total.saturating_sub(1))),
283        DataRange::Suffix(count) => (total.saturating_sub(count), total.saturating_sub(1)),
284    };
285    if total == 0 || start > end {
286        return Ok((Vec::new(), total));
287    }
288    file.seek(std::io::SeekFrom::Start(start))
289        .map_err(storage)?;
290    let mut bytes = vec![0; (end - start + 1) as usize];
291    file.read_exact(&mut bytes).map_err(storage)?;
292    Ok((bytes, total))
293}
294
295#[cfg(test)]
296mod tests {
297    use std::sync::Arc;
298
299    use base64::Engine;
300
301    use super::span;
302    use crate::client::{ClientOptions, RedseatClient};
303    use crate::cloud::ServerToken;
304    use crate::library::LibraryApi;
305    use crate::test_support::FakeTransport;
306    use crate::transport::{Request, Response};
307    use crate::types::media::Media;
308
309    /// The encrypted data part of a file holding `plain`, as the server stores it.
310    fn encrypted_data(key: &[u8; 32], iv: &[u8; 16], plain: &[u8]) -> Vec<u8> {
311        let file = redseat_crypto::encrypt_file_bytes(
312            key,
313            iv,
314            plain,
315            Some("video/mp4"),
316            Some((b"thumb", "image/jpeg")),
317            None,
318        )
319        .unwrap();
320        let header = redseat_crypto::FileHeader::decode(&file).unwrap();
321        file[header.data_offset() as usize..].to_vec()
322    }
323
324    /// Answers range requests on `data` as the server does since range support:
325    /// 206 with a Content-Range relative to the data.
326    fn serve_ranges(data: &[u8], request: &Request) -> Response {
327        let range = request
328            .headers
329            .iter()
330            .find(|(name, _)| name == "Range")
331            .map(|(_, value)| value.trim_start_matches("bytes=").to_owned())
332            .expect("a range request");
333        let total = data.len() as u64;
334        let (start, end) = match range.split_once('-').unwrap() {
335            ("", count) => (total.saturating_sub(count.parse().unwrap()), total - 1),
336            (start, "") => (start.parse().unwrap(), total - 1),
337            (start, end) => (
338                start.parse().unwrap(),
339                end.parse::<u64>().unwrap().min(total - 1),
340            ),
341        };
342        Response {
343            status: 206,
344            headers: vec![(
345                "content-range".into(),
346                format!("bytes {start}-{end}/{total}"),
347            )],
348            body: data[start as usize..=end as usize].to_vec(),
349        }
350    }
351
352    fn library(fake: Arc<FakeTransport>, key: [u8; 32]) -> LibraryApi {
353        let client = RedseatClient::new(ClientOptions::new(fake));
354        client.set_token(ServerToken {
355            token: "t".into(),
356            expires: i64::MAX,
357        });
358        let library = serde_json::from_value(serde_json::json!({
359            "id": "lib", "name": "Vault", "source": "PathProvider", "type": "photos", "crypt": true
360        }))
361        .unwrap();
362        let api = LibraryApi::new(client, library);
363        api.set_key(key);
364        api
365    }
366
367    fn media(iv: &[u8; 16], size: u64) -> Media {
368        Media {
369            id: "m1".into(),
370            size: Some(size),
371            iv: Some(base64::engine::general_purpose::STANDARD.encode(iv)),
372            ..Default::default()
373        }
374    }
375
376    #[test]
377    fn fetches_the_blocks_and_the_one_before() {
378        // Inside block 0: no block before it.
379        assert_eq!(span(3, 10).fetch, (0, 15));
380        // Across blocks 1 and 2: from block 0, their IV.
381        let crossing = span(20, 40);
382        assert_eq!((crossing.first, crossing.last), (1, 2));
383        assert_eq!(crossing.fetch, (0, 47));
384        assert_eq!(span(160, 161).fetch, (144, 175));
385    }
386
387    #[tokio::test]
388    async fn reads_any_range_of_the_plaintext() {
389        let key = redseat_crypto::derive_key("secret");
390        let iv = redseat_crypto::random_iv().unwrap();
391        for size in [1usize, 15, 16, 17, 31, 32, 1000, 4096] {
392            let plain: Vec<u8> = (0..size).map(|i| (i * 7 % 251) as u8).collect();
393            let data = encrypted_data(&key, &iv, &plain);
394            let served = data.clone();
395            let fake = FakeTransport::new(move |request| {
396                assert_eq!(request.path, "/libraries/lib/medias/m1");
397                Ok(serve_ranges(&served, request))
398            });
399            let api = library(fake.clone(), key);
400            let reader = api
401                .open_encrypted_media(&media(&iv, data.len() as u64))
402                .await
403                .unwrap();
404            assert_eq!(reader.len(), size as u64, "size {size}");
405
406            let reads = [
407                (0, 5),
408                (0, size),
409                (size / 2, 40),
410                (15, 2),
411                (16, 16),
412                (size.saturating_sub(3), 10),
413            ];
414            for (offset, len) in reads {
415                let got = reader.read_at(offset as u64, len).await.unwrap();
416                let end = (offset + len).min(size);
417                let expected = plain.get(offset..end).unwrap_or_default();
418                assert_eq!(got, expected, "size {size}, read {offset}+{len}");
419            }
420            assert!(reader.read_at(size as u64, 10).await.unwrap().is_empty());
421            // Only the blocks needed are fetched: a read of 5 bytes, one block.
422            let requests = fake.requests();
423            let first_read = &requests[1];
424            assert!(
425                first_read
426                    .headers
427                    .contains(&("Range".to_owned(), "bytes=0-15".to_owned())),
428                "{:?}",
429                first_read.headers
430            );
431        }
432    }
433
434    /// A download kept offline holds the data part as the server serves it.
435    #[cfg(feature = "mirror")]
436    #[tokio::test]
437    async fn reads_a_downloaded_file_by_ranges() {
438        let key = redseat_crypto::derive_key("secret");
439        let iv = redseat_crypto::random_iv().unwrap();
440        let path = std::env::temp_dir().join(format!(
441            "redseat-encrypted-file-{}-{}",
442            std::process::id(),
443            crate::client::now_ms()
444        ));
445        for size in [1usize, 16, 17, 1000] {
446            let plain: Vec<u8> = (0..size).map(|i| (i * 7 % 251) as u8).collect();
447            std::fs::write(&path, encrypted_data(&key, &iv, &plain)).unwrap();
448            let reader = super::EncryptedMediaReader::open_file(
449                path.clone(),
450                tokio::runtime::Handle::current(),
451                key,
452                iv,
453            )
454            .await
455            .unwrap();
456            assert_eq!(reader.len(), size as u64);
457            assert_eq!(reader.read_at(0, size).await.unwrap(), plain);
458            let middle = reader.read_at(size as u64 / 2, 20).await.unwrap();
459            let end = (size / 2 + 20).min(size);
460            assert_eq!(middle, plain[size / 2..end]);
461        }
462        std::fs::remove_file(&path).unwrap();
463    }
464
465    #[tokio::test]
466    async fn an_empty_file_needs_no_request() {
467        let fake = FakeTransport::new(|_| panic!("no request"));
468        let key = redseat_crypto::derive_key("secret");
469        let reader = library(fake, key)
470            .open_encrypted_media(&media(&[0; 16], 0))
471            .await
472            .unwrap();
473        assert!(reader.is_empty());
474        assert!(reader.read_at(0, 10).await.unwrap().is_empty());
475    }
476
477    #[tokio::test]
478    async fn says_when_the_server_needs_an_update() {
479        let key = redseat_crypto::derive_key("secret");
480        let iv = [3u8; 16];
481        let data = encrypted_data(&key, &iv, b"a video");
482        // An older server ignores the range: 200 with the whole data.
483        let fake = FakeTransport::new(move |_| Ok(FakeTransport::bytes(data.clone())));
484        let error = library(fake, key)
485            .open_encrypted_media(&media(&iv, 16))
486            .await
487            .unwrap_err();
488        assert!(error.to_string().contains("update"), "{error}");
489    }
490
491    #[tokio::test]
492    async fn a_wrong_key_fails_on_open() {
493        let iv = [5u8; 16];
494        let data = encrypted_data(&redseat_crypto::derive_key("secret"), &iv, &[1u8; 100]);
495        let fake = FakeTransport::new(move |request| Ok(serve_ranges(&data, request)));
496        let error = library(fake, redseat_crypto::derive_key("wrong"))
497            .open_encrypted_media(&media(&iv, 112))
498            .await
499            .unwrap_err();
500        assert_eq!(error.kind(), crate::ErrorKind::Crypto);
501    }
502}