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`]. Cheap to clone.
26#[derive(Clone)]
27pub struct EncryptedMediaReader {
28    library: LibraryApi,
29    media_id: String,
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
38impl std::fmt::Debug for EncryptedMediaReader {
39    // Never print the key.
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        f.debug_struct("EncryptedMediaReader")
42            .field("media_id", &self.media_id)
43            .field("len", &self.len)
44            .finish_non_exhaustive()
45    }
46}
47
48/// A range of the encrypted data to fetch.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50enum DataRange {
51    /// From the first to the last byte, inclusive.
52    Bytes(u64, u64),
53    /// The last bytes.
54    Suffix(u64),
55}
56
57impl DataRange {
58    fn header(self) -> String {
59        match self {
60            DataRange::Bytes(start, end) => format!("bytes={start}-{end}"),
61            DataRange::Suffix(count) => format!("bytes=-{count}"),
62        }
63    }
64}
65
66/// The blocks to fetch to read plaintext `offset..end` of `data_len` bytes of data.
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68struct Span {
69    /// The first and last block holding the plaintext.
70    first: u64,
71    last: u64,
72    /// The bytes to fetch: the blocks, and the one before them (their IV) if any.
73    fetch: (u64, u64),
74}
75
76fn span(offset: u64, end: u64) -> Span {
77    let (first, last) = (offset / BLOCK, (end - 1) / BLOCK);
78    Span {
79        first,
80        last,
81        fetch: (first.saturating_sub(1) * BLOCK, (last + 1) * BLOCK - 1),
82    }
83}
84
85fn to_block(bytes: &[u8]) -> Result<Iv> {
86    bytes
87        .try_into()
88        .map_err(|_| Error::malformed("encrypted data is not made of whole blocks", None))
89}
90
91/// Decrypts whole CBC blocks that follow `prev` (the previous ciphertext block, or
92/// the IV). `last_of_data`: they end the data, padding included.
93fn decrypt_blocks(key: &Key, prev: &Iv, blocks: &[u8], last_of_data: bool) -> Result<Vec<u8>> {
94    if blocks.is_empty() || !blocks.len().is_multiple_of(BLOCK as usize) {
95        return Err(Error::malformed(
96            "encrypted data is not made of whole blocks",
97            None,
98        ));
99    }
100    if last_of_data {
101        return Ok(redseat_crypto::decrypt_buffer(key, prev, blocks)?);
102    }
103    // A block encrypted from the last one decrypts to a full padding block.
104    let last = to_block(&blocks[blocks.len() - BLOCK as usize..])?;
105    let mut with_padding = blocks.to_vec();
106    with_padding.extend(redseat_crypto::encrypt_buffer(key, &last, &[]));
107    Ok(redseat_crypto::decrypt_buffer(key, prev, &with_padding)?)
108}
109
110/// The total of a `Content-Range: bytes a-b/total` header.
111fn content_range_total(response: &Response) -> Option<u64> {
112    response
113        .header("content-range")?
114        .rsplit('/')
115        .next()?
116        .trim()
117        .parse()
118        .ok()
119}
120
121impl EncryptedMediaReader {
122    pub(crate) async fn open(
123        library: LibraryApi,
124        media_id: String,
125        key: Key,
126        iv: Iv,
127        size: Option<u64>,
128    ) -> Result<Self> {
129        let mut reader = EncryptedMediaReader {
130            library,
131            media_id,
132            key,
133            iv,
134            data_len: 0,
135            len: 0,
136        };
137        // The server writes no data for an empty file.
138        if size == Some(0) {
139            return Ok(reader);
140        }
141        // The last two blocks: the data size, and the padding of the last one.
142        let (tail, data_len) = reader.fetch(DataRange::Suffix(2 * BLOCK)).await?;
143        if data_len == 0 || !data_len.is_multiple_of(BLOCK) || tail.len() < BLOCK as usize {
144            return Err(Error::malformed(
145                format!("encrypted data of {data_len} bytes is not made of whole blocks"),
146                None,
147            ));
148        }
149        let (prev, last) = match tail.len() {
150            32 => (to_block(&tail[..16])?, &tail[16..]),
151            _ => (reader.iv, &tail[tail.len() - 16..]),
152        };
153        let last_plain = decrypt_blocks(&reader.key, &prev, last, true)?;
154        reader.data_len = data_len;
155        reader.len = data_len - BLOCK + last_plain.len() as u64;
156        Ok(reader)
157    }
158
159    /// The plaintext size, in bytes.
160    pub fn len(&self) -> u64 {
161        self.len
162    }
163
164    pub fn is_empty(&self) -> bool {
165        self.len == 0
166    }
167
168    /// Up to `len` bytes of plaintext from `offset`: fewer at the end, none past it.
169    pub async fn read_at(&self, offset: u64, len: usize) -> Result<Vec<u8>> {
170        if offset >= self.len || len == 0 {
171            return Ok(Vec::new());
172        }
173        let end = offset.saturating_add(len as u64).min(self.len);
174        let span = span(offset, end);
175        let (fetched, _) = self
176            .fetch(DataRange::Bytes(span.fetch.0, span.fetch.1))
177            .await?;
178        if fetched.len() as u64 != span.fetch.1 - span.fetch.0 + 1 {
179            return Err(Error::malformed(
180                format!(
181                    "asked for {} bytes of encrypted data, got {}",
182                    span.fetch.1 - span.fetch.0 + 1,
183                    fetched.len()
184                ),
185                None,
186            ));
187        }
188        let (prev, blocks) = if span.first == 0 {
189            (self.iv, &fetched[..])
190        } else {
191            (to_block(&fetched[..16])?, &fetched[16..])
192        };
193        let last_of_data = span.last == self.data_len / BLOCK - 1;
194        let plain = decrypt_blocks(&self.key, &prev, blocks, last_of_data)?;
195        let skip = (offset - span.first * BLOCK) as usize;
196        let take = (end - offset) as usize;
197        plain
198            .get(skip..skip + take)
199            .map(<[u8]>::to_vec)
200            .ok_or_else(|| Error::malformed("encrypted data shorter than expected", None))
201    }
202
203    /// Fetches a range of the encrypted data; returns it and the data size.
204    async fn fetch(&self, range: DataRange) -> Result<(Vec<u8>, u64)> {
205        let request =
206            Request::get(self.library.media_path(&self.media_id)).header("Range", range.header());
207        let response = self.library.client().request(request).await?;
208        // An older server ignores the range and sends the whole data.
209        let total = match (response.status, content_range_total(&response)) {
210            (206, Some(total)) => total,
211            _ => {
212                return Err(Error::malformed(
213                    "the server cannot serve parts of encrypted files: it needs an update",
214                    None,
215                ));
216            }
217        };
218        Ok((response.body, total))
219    }
220}
221
222#[cfg(test)]
223mod tests {
224    use std::sync::Arc;
225
226    use base64::Engine;
227
228    use super::span;
229    use crate::client::{ClientOptions, RedseatClient};
230    use crate::cloud::ServerToken;
231    use crate::library::LibraryApi;
232    use crate::test_support::FakeTransport;
233    use crate::transport::{Request, Response};
234    use crate::types::media::Media;
235
236    /// The encrypted data part of a file holding `plain`, as the server stores it.
237    fn encrypted_data(key: &[u8; 32], iv: &[u8; 16], plain: &[u8]) -> Vec<u8> {
238        let file = redseat_crypto::encrypt_file_bytes(
239            key,
240            iv,
241            plain,
242            Some("video/mp4"),
243            Some((b"thumb", "image/jpeg")),
244            None,
245        )
246        .unwrap();
247        let header = redseat_crypto::FileHeader::decode(&file).unwrap();
248        file[header.data_offset() as usize..].to_vec()
249    }
250
251    /// Answers range requests on `data` as the server does since range support:
252    /// 206 with a Content-Range relative to the data.
253    fn serve_ranges(data: &[u8], request: &Request) -> Response {
254        let range = request
255            .headers
256            .iter()
257            .find(|(name, _)| name == "Range")
258            .map(|(_, value)| value.trim_start_matches("bytes=").to_owned())
259            .expect("a range request");
260        let total = data.len() as u64;
261        let (start, end) = match range.split_once('-').unwrap() {
262            ("", count) => (total.saturating_sub(count.parse().unwrap()), total - 1),
263            (start, "") => (start.parse().unwrap(), total - 1),
264            (start, end) => (
265                start.parse().unwrap(),
266                end.parse::<u64>().unwrap().min(total - 1),
267            ),
268        };
269        Response {
270            status: 206,
271            headers: vec![(
272                "content-range".into(),
273                format!("bytes {start}-{end}/{total}"),
274            )],
275            body: data[start as usize..=end as usize].to_vec(),
276        }
277    }
278
279    fn library(fake: Arc<FakeTransport>, key: [u8; 32]) -> LibraryApi {
280        let client = RedseatClient::new(ClientOptions::new(fake));
281        client.set_token(ServerToken {
282            token: "t".into(),
283            expires: i64::MAX,
284        });
285        let library = serde_json::from_value(serde_json::json!({
286            "id": "lib", "name": "Vault", "source": "PathProvider", "type": "photos", "crypt": true
287        }))
288        .unwrap();
289        let api = LibraryApi::new(client, library);
290        api.set_key(key);
291        api
292    }
293
294    fn media(iv: &[u8; 16], size: u64) -> Media {
295        Media {
296            id: "m1".into(),
297            size: Some(size),
298            iv: Some(base64::engine::general_purpose::STANDARD.encode(iv)),
299            ..Default::default()
300        }
301    }
302
303    #[test]
304    fn fetches_the_blocks_and_the_one_before() {
305        // Inside block 0: no block before it.
306        assert_eq!(span(3, 10).fetch, (0, 15));
307        // Across blocks 1 and 2: from block 0, their IV.
308        let crossing = span(20, 40);
309        assert_eq!((crossing.first, crossing.last), (1, 2));
310        assert_eq!(crossing.fetch, (0, 47));
311        assert_eq!(span(160, 161).fetch, (144, 175));
312    }
313
314    #[tokio::test]
315    async fn reads_any_range_of_the_plaintext() {
316        let key = redseat_crypto::derive_key("secret");
317        let iv = redseat_crypto::random_iv().unwrap();
318        for size in [1usize, 15, 16, 17, 31, 32, 1000, 4096] {
319            let plain: Vec<u8> = (0..size).map(|i| (i * 7 % 251) as u8).collect();
320            let data = encrypted_data(&key, &iv, &plain);
321            let served = data.clone();
322            let fake = FakeTransport::new(move |request| {
323                assert_eq!(request.path, "/libraries/lib/medias/m1");
324                Ok(serve_ranges(&served, request))
325            });
326            let api = library(fake.clone(), key);
327            let reader = api
328                .open_encrypted_media(&media(&iv, data.len() as u64))
329                .await
330                .unwrap();
331            assert_eq!(reader.len(), size as u64, "size {size}");
332
333            let reads = [
334                (0, 5),
335                (0, size),
336                (size / 2, 40),
337                (15, 2),
338                (16, 16),
339                (size.saturating_sub(3), 10),
340            ];
341            for (offset, len) in reads {
342                let got = reader.read_at(offset as u64, len).await.unwrap();
343                let end = (offset + len).min(size);
344                let expected = plain.get(offset..end).unwrap_or_default();
345                assert_eq!(got, expected, "size {size}, read {offset}+{len}");
346            }
347            assert!(reader.read_at(size as u64, 10).await.unwrap().is_empty());
348            // Only the blocks needed are fetched: a read of 5 bytes, one block.
349            let requests = fake.requests();
350            let first_read = &requests[1];
351            assert!(
352                first_read
353                    .headers
354                    .contains(&("Range".to_owned(), "bytes=0-15".to_owned())),
355                "{:?}",
356                first_read.headers
357            );
358        }
359    }
360
361    #[tokio::test]
362    async fn an_empty_file_needs_no_request() {
363        let fake = FakeTransport::new(|_| panic!("no request"));
364        let key = redseat_crypto::derive_key("secret");
365        let reader = library(fake, key)
366            .open_encrypted_media(&media(&[0; 16], 0))
367            .await
368            .unwrap();
369        assert!(reader.is_empty());
370        assert!(reader.read_at(0, 10).await.unwrap().is_empty());
371    }
372
373    #[tokio::test]
374    async fn says_when_the_server_needs_an_update() {
375        let key = redseat_crypto::derive_key("secret");
376        let iv = [3u8; 16];
377        let data = encrypted_data(&key, &iv, b"a video");
378        // An older server ignores the range: 200 with the whole data.
379        let fake = FakeTransport::new(move |_| Ok(FakeTransport::bytes(data.clone())));
380        let error = library(fake, key)
381            .open_encrypted_media(&media(&iv, 16))
382            .await
383            .unwrap_err();
384        assert!(error.to_string().contains("update"), "{error}");
385    }
386
387    #[tokio::test]
388    async fn a_wrong_key_fails_on_open() {
389        let iv = [5u8; 16];
390        let data = encrypted_data(&redseat_crypto::derive_key("secret"), &iv, &[1u8; 100]);
391        let fake = FakeTransport::new(move |request| Ok(serve_ranges(&data, request)));
392        let error = library(fake, redseat_crypto::derive_key("wrong"))
393            .open_encrypted_media(&media(&iv, 112))
394            .await
395            .unwrap_err();
396        assert_eq!(error.kind(), crate::ErrorKind::Crypto);
397    }
398}