rencfs 0.14.11

WARNING! UNDER ACTIVE DEVELOPMENT. An encrypted file system that is mounted with FUSE on Linux. It can be used to create encrypted directories.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
use std::any::Any;
use std::io;
use std::io::{Read, Seek, SeekFrom, Write};
use std::sync::{Arc, Mutex};

use bytes::Buf;
use rand_chacha::rand_core::RngCore;
use ring::aead::{
    Aad, Algorithm, BoundKey, Nonce, NonceSequence, OpeningKey, SealingKey, UnboundKey, NONCE_LEN,
};
use ring::error::Unspecified;
use shush_rs::{ExposeSecret, SecretVec};
use tracing::error;

use crate::crypto::buf_mut::BufMut;
use crate::crypto::read::ExistingNonceSequence;
use crate::{crypto, decrypt_block, stream_util};

mod bench;
mod test;

#[cfg(test)]
pub(crate) const BLOCK_SIZE: usize = 100; // round value easier for debugging
#[cfg(not(test))]
pub(crate) const BLOCK_SIZE: usize = 256 * 1024; // 256 KB block size

/// If you have your custom [Write] + [Seek] you want to pass to [`CryptoWrite`] it needs to implement this trait.
/// It has a blanket implementation for [Write] + [Seek] + [Read].
pub trait WriteSeekRead: Write + Seek + Read {}

impl<T: Write + Seek + Read> WriteSeekRead for T {}

/// If you have your custom implementation for [Write] you want to pass to [`CryptoWrite`] it needs to implement this trait.
///
/// It has a blanket implementation for [Write] + [Seek] + [Read] + [`'static`] but in case your implementation is only [Write] it needs to implement this.
pub trait CryptoInnerWriter: Write + Any {
    fn into_any(self) -> Box<dyn Any>;
    fn as_write(&mut self) -> Option<&mut dyn Write>;
    fn as_write_seek_read(&mut self) -> Option<&mut dyn WriteSeekRead>;
}

impl<T: Write + Seek + Read + 'static> CryptoInnerWriter for T {
    fn into_any(self) -> Box<dyn Any> {
        Box::new(self)
    }
    fn as_write(&mut self) -> Option<&mut dyn Write> {
        Some(self)
    }

    fn as_write_seek_read(&mut self) -> Option<&mut dyn WriteSeekRead> {
        Some(self)
    }
}

/// Writes encrypted content to the wrapped Writer.
#[allow(clippy::module_name_repetitions)]
pub trait CryptoWrite<W: CryptoInnerWriter + Send + Sync>: Write + Send + Sync {
    /// You must call this after the last writing to make sure we write the last block.
    /// This handles the flush also.
    #[allow(clippy::missing_errors_doc)]
    fn finish(&mut self) -> io::Result<W>;
}

/// Write with Seek
pub trait CryptoWriteSeek<W: CryptoInnerWriter + Send + Sync>: CryptoWrite<W> + Seek {}

/// ring
#[allow(clippy::module_name_repetitions)]
pub struct RingCryptoWrite<W: CryptoInnerWriter + Send + Sync> {
    writer: Option<W>,
    seek: bool,
    sealing_key: SealingKey<RandomNonceSequenceWrapper>,
    buf: BufMut,
    nonce_sequence: Arc<Mutex<RandomNonceSequence>>,
    ciphertext_block_size: usize,
    plaintext_block_size: usize,
    block_index: u64,
    opening_key: Option<OpeningKey<ExistingNonceSequence>>,
    last_nonce: Option<Arc<Mutex<Option<Vec<u8>>>>>,
    decrypt_buf: Option<BufMut>,
}

impl<W: CryptoInnerWriter + Send + Sync> RingCryptoWrite<W> {
    #[allow(clippy::missing_panics_doc)]
    #[allow(clippy::needless_pass_by_value)]
    pub fn new(
        mut writer: W,
        seek: bool,
        algorithm: &'static Algorithm,
        key: &SecretVec<u8>,
    ) -> Self {
        let unbound_key = UnboundKey::new(algorithm, &key.expose_secret()).expect("unbound key");
        let nonce_sequence = Arc::new(Mutex::new(RandomNonceSequence::default()));
        let wrapping_nonce_sequence = RandomNonceSequenceWrapper::new(nonce_sequence.clone());
        let sealing_key = SealingKey::new(unbound_key, wrapping_nonce_sequence);
        let buf = BufMut::new(vec![0; BLOCK_SIZE]);

        let (last_nonce, opening_key, decrypt_buf) = if writer.as_write_seek_read().is_some() {
            let last_nonce = Arc::new(Mutex::new(None));
            let unbound_key = UnboundKey::new(algorithm, &key.expose_secret()).unwrap();
            let nonce_sequence2 = ExistingNonceSequence::new(last_nonce.clone());
            let opening_key = OpeningKey::new(unbound_key, nonce_sequence2);
            let ciphertext_block_size = NONCE_LEN + BLOCK_SIZE + algorithm.tag_len();
            let decrypt_buf = BufMut::new(vec![0; ciphertext_block_size]);

            (Some(last_nonce), Some(opening_key), Some(decrypt_buf))
        } else {
            (None, None, None)
        };
        Self {
            writer: Some(writer),
            seek,
            sealing_key,
            buf,
            nonce_sequence,
            ciphertext_block_size: NONCE_LEN + BLOCK_SIZE + algorithm.tag_len(),
            plaintext_block_size: BLOCK_SIZE,
            block_index: 0,
            opening_key,
            last_nonce,
            decrypt_buf,
        }
    }

    fn encrypt_and_write(&mut self) -> io::Result<()> {
        let data = self.buf.as_mut();
        let aad = Aad::from(self.block_index.to_le_bytes());
        let tag = self
            .sealing_key
            .seal_in_place_separate_tag(aad, data)
            .map_err(|err| {
                error!("error sealing in place: {}", err);
                io::Error::new(
                    io::ErrorKind::Other,
                    format!("error sealing in place: {err}"),
                )
            })?;
        let nonce_sequence = self.nonce_sequence.lock().unwrap();
        let nonce = &nonce_sequence.last_nonce;
        let writer = self
            .writer
            .as_mut()
            .ok_or(io::Error::new(io::ErrorKind::NotConnected, "no writer"))?;
        writer.write_all(nonce)?;
        writer.write_all(data)?;
        self.buf.clear();
        writer.write_all(tag.as_ref())?;
        writer.flush()?;
        self.block_index += 1;
        Ok(())
    }

    const fn pos(&self) -> u64 {
        self.block_index * self.plaintext_block_size as u64 + self.buf.pos_write() as u64
    }

    fn decrypt_block(&mut self) -> io::Result<bool> {
        let old_block_index = self.block_index;
        let writer = self
            .writer
            .as_mut()
            .ok_or(io::Error::new(io::ErrorKind::NotConnected, "no writer"))?
            .as_write_seek_read()
            .ok_or(io::Error::new(
                io::ErrorKind::NotConnected,
                "downcast failed",
            ))?;
        decrypt_block!(
            self.block_index,
            self.decrypt_buf.as_mut().unwrap(),
            writer,
            self.last_nonce.as_ref().unwrap(),
            self.opening_key.as_mut().unwrap()
        );
        if old_block_index == self.block_index {
            // no decryption happened
            Ok(false)
        } else {
            // decryption happened
            self.buf.clear();
            // bring back block index to current block, it's incremented by decrypt_block if it can decrypt something
            self.block_index -= 1;
            // bring back file pos also so the next writing will write to the same block
            let writer = self
                .writer
                .as_mut()
                .ok_or(io::Error::new(io::ErrorKind::NotConnected, "no writer"))?
                .as_write_seek_read()
                .ok_or(io::Error::new(
                    io::ErrorKind::NotConnected,
                    "downcast failed",
                ))?;
            writer.seek(SeekFrom::Start(
                self.block_index * self.ciphertext_block_size as u64,
            ))?;
            // copy plaintext
            self.buf.seek_available(SeekFrom::Start(
                self.decrypt_buf.as_ref().unwrap().available_read() as u64,
            ))?;
            self.decrypt_buf
                .as_ref()
                .unwrap()
                .as_ref_read_available()
                .copy_to_slice(
                    &mut self.buf.as_mut()[..self.decrypt_buf.as_ref().unwrap().available_read()],
                );
            Ok(true)
        }
    }
}

impl<W: CryptoInnerWriter + Send + Sync> Write for RingCryptoWrite<W> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        if self.writer.is_none() {
            return Err(io::Error::new(
                io::ErrorKind::Other,
                "write called on already finished writer",
            ));
        }
        if self.pos() == 0 && self.buf.available() == 0 {
            if self.seek {
                // first write since we opened the writer, try to load the first block
                let writer = self
                    .writer
                    .as_mut()
                    .ok_or(io::Error::new(io::ErrorKind::NotConnected, "no writer"))?
                    .as_write_seek_read()
                    .ok_or(io::Error::new(
                        io::ErrorKind::NotConnected,
                        "downcast failed",
                    ))?;
                writer.seek(SeekFrom::Start(0))?;
                self.block_index = 0;
                self.decrypt_block()?;
            }
        } else if self.buf.is_dirty() && self.buf.remaining() == 0 {
            self.flush()?;
            // try to decrypt the next block if we have any
            let block_index = self.pos() / self.plaintext_block_size as u64;
            let writer = self
                .writer
                .as_mut()
                .ok_or(io::Error::new(io::ErrorKind::NotConnected, "no writer"))?
                .as_write_seek_read()
                .ok_or(io::Error::new(
                    io::ErrorKind::NotConnected,
                    "downcast failed",
                ))?;
            let stream_len = writer.stream_len()?;
            if stream_len > block_index * self.ciphertext_block_size as u64 {
                self.decrypt_block()?;
            }
        }
        if self.buf.is_dirty() && self.buf.remaining() == 0 {
            self.flush()?;
        }
        let len = self.buf.write(buf)?;
        Ok(len)
    }

    fn flush(&mut self) -> io::Result<()> {
        if !self.buf.is_dirty() {
            return Ok(());
        }
        // encrypt and write when we have a full buffer
        if self.buf.remaining() == 0 {
            self.encrypt_and_write()?;
        }

        Ok(())
    }
}

impl<W: CryptoInnerWriter + Send + Sync> CryptoWrite<W> for RingCryptoWrite<W> {
    fn finish(&mut self) -> io::Result<W> {
        if self.buf.is_dirty() {
            // encrypt and write last block, use as many bytes as we have
            self.encrypt_and_write()?;
        }
        let boxed = self
            .writer
            .take()
            .ok_or(io::Error::new(io::ErrorKind::NotConnected, "no writer"))?
            .into_any()
            .downcast::<W>()
            .map_err(|_| io::Error::new(io::ErrorKind::Other, "downcast failed"))?;
        Ok(Box::into_inner(boxed))
    }
}

struct RandomNonceSequence {
    rng: Mutex<Box<dyn RngCore + Send + Sync>>,
    last_nonce: Vec<u8>,
}

impl Default for RandomNonceSequence {
    fn default() -> Self {
        Self {
            rng: Mutex::new(Box::new(crypto::create_rng())),
            last_nonce: vec![0; NONCE_LEN],
        }
    }
}

impl NonceSequence for RandomNonceSequence {
    // called once for each seal operation
    fn advance(&mut self) -> Result<Nonce, Unspecified> {
        self.rng.lock().unwrap().fill_bytes(&mut self.last_nonce);
        Nonce::try_assume_unique_for_key(&self.last_nonce)
    }
}

struct RandomNonceSequenceWrapper {
    inner: Arc<Mutex<RandomNonceSequence>>,
}

impl RandomNonceSequenceWrapper {
    pub const fn new(inner: Arc<Mutex<RandomNonceSequence>>) -> Self {
        Self { inner }
    }
}

impl NonceSequence for RandomNonceSequenceWrapper {
    fn advance(&mut self) -> Result<Nonce, Unspecified> {
        self.inner.lock().unwrap().advance()
    }
}

impl<W: CryptoInnerWriter + Send + Sync> RingCryptoWrite<W> {
    fn get_plaintext_len(&mut self) -> io::Result<u64> {
        let writer = self
            .writer
            .as_mut()
            .ok_or(io::Error::new(io::ErrorKind::NotConnected, "no writer"))?
            .as_write_seek_read()
            .ok_or(io::Error::new(
                io::ErrorKind::NotConnected,
                "downcast failed",
            ))?;
        let ciphertext_len = writer.stream_len()?;
        if ciphertext_len == 0 && self.buf.available() == 0 {
            return Ok(0);
        }
        let stream_last_block_index = ciphertext_len / self.ciphertext_block_size as u64;
        let plaintext_len = if self.block_index == stream_last_block_index && self.buf.is_dirty() {
            // we are at the last block, we consider what we have in buffer,
            // as we might have additional content that is not written yet
            self.block_index * self.plaintext_block_size as u64 + self.buf.available() as u64
        } else {
            ciphertext_len
                - ((ciphertext_len / self.ciphertext_block_size as u64) + 1)
                    * (self.ciphertext_block_size - self.plaintext_block_size) as u64
        };
        Ok(plaintext_len)
    }
}

impl<W: CryptoInnerWriter + Send + Sync> Seek for RingCryptoWrite<W> {
    #[allow(clippy::cast_possible_wrap)]
    #[allow(clippy::cast_sign_loss)]
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        let new_pos = match pos {
            SeekFrom::Start(pos) => pos as i64,
            SeekFrom::End(pos) => self.get_plaintext_len()? as i64 + pos,
            SeekFrom::Current(pos) => self.pos() as i64 + pos,
        };
        if new_pos < 0 {
            return Err(io::Error::new(io::ErrorKind::InvalidInput, "position < 0"));
        }
        let new_pos = new_pos as u64;
        if new_pos == self.pos() {
            return Ok(new_pos);
        }
        let current_block_index = self.pos() / self.plaintext_block_size as u64;
        let new_block_index = new_pos / self.plaintext_block_size as u64;
        if current_block_index == new_block_index {
            if self.pos() == 0 && self.buf.available() == 0 {
                // first write since we opened the writer, try to load the first block
                let writer = self
                    .writer
                    .as_mut()
                    .ok_or(io::Error::new(io::ErrorKind::NotConnected, "no writer"))?
                    .as_write_seek_read()
                    .ok_or(io::Error::new(
                        io::ErrorKind::NotConnected,
                        "downcast failed",
                    ))?;
                writer.seek(SeekFrom::Start(0))?;
                self.block_index = 0;
                self.decrypt_block()?;
            }
            let at_full_block_end = self.pos() % self.plaintext_block_size as u64 == 0
                && self.buf.pos_write() == self.buf.available();
            if self.buf.available() == 0
                // this checks if we are at the end of the current block,
                // which is the start boundary of next block
                // in that case we need to seek inside the next block
                || at_full_block_end
            {
                // write current block
                if self.buf.is_dirty() {
                    self.encrypt_and_write()?;
                }
                // decrypt the next block
                self.decrypt_block()?;
            }
            // seek inside the block as much as we can
            let desired_offset = new_pos % self.plaintext_block_size as u64;
            self.buf.seek_write(SeekFrom::Start(
                desired_offset.min(self.buf.available() as u64),
            ))?;
        } else {
            // we need to seek to a new block

            // write current block
            if self.buf.is_dirty() {
                self.encrypt_and_write()?;
            }
            // seek to new block, or until the last block in stream
            let writer = self
                .writer
                .as_mut()
                .ok_or(io::Error::new(io::ErrorKind::NotConnected, "no writer"))?
                .as_write_seek_read()
                .ok_or(io::Error::new(
                    io::ErrorKind::NotConnected,
                    "downcast failed",
                ))?;
            let last_block_index = writer.stream_len()? / self.ciphertext_block_size as u64;
            let target_block_index = new_block_index.min(last_block_index);
            writer.seek(SeekFrom::Start(
                target_block_index * self.ciphertext_block_size as u64,
            ))?;
            // try to decrypt target block
            self.block_index = target_block_index;
            self.decrypt_block()?;
            if self.block_index == new_block_index {
                // seek inside new block as much as we can
                let desired_offset = new_pos % self.plaintext_block_size as u64;
                self.buf.seek_write(SeekFrom::Start(
                    desired_offset.min(self.buf.available() as u64),
                ))?;
            } else {
                // we don't have this block, seek as much in target block
                self.buf
                    .seek_write(SeekFrom::Start(self.buf.available() as u64))?;
            }
        }
        // if we couldn't seek until new pos, write zeros until new position
        if self.pos() < new_pos {
            let len = new_pos - self.pos();
            stream_util::fill_zeros(self, len)?;
        }
        Ok(self.pos())
    }
}

impl<W: CryptoInnerWriter + Send + Sync> CryptoWriteSeek<W> for RingCryptoWrite<W> {}