Skip to main content

smb_server/encrypted/
builder.rs

1//! The settings of an [`EncryptedBackend`] and the check that the inner
2//! backend holds a share they fit.
3
4use std::fmt;
5use std::time::Duration;
6
7use zeroize::Zeroizing;
8
9use super::backend::{EncryptedBackend, Settings};
10use super::error::EncryptionError;
11use super::format::{BlockShift, MIN_LONG_NAME_THRESHOLD};
12use super::keys::KeySchedule;
13use super::setup::{Requested, establish};
14use crate::backend::ShareBackend;
15use crate::utils::fill_random;
16
17const DEFAULT_NAME_CACHE_TTL: Duration = Duration::from_secs(30);
18
19/// Settings of an [`EncryptedBackend`], set through the methods below and
20/// applied by [`build`](EncryptedBackendBuilder::build).
21///
22/// `encrypt_names`, `block_size` and `long_name_threshold` are stored in the
23/// share's marker. One that is left alone takes the share's value, or for a
24/// new share the default named on its method. `case_insensitive` and
25/// `name_cache_ttl` are not stored and default to the values named on their
26/// methods.
27pub struct EncryptedBackendBuilder<B> {
28    inner: B,
29    key: Zeroizing<[u8; 32]>,
30    encrypt_names: Option<bool>,
31    case_insensitive: bool,
32    block_size: Option<u32>,
33    long_name_threshold: Option<u8>,
34    name_cache_ttl: Duration,
35    restore_marker: bool,
36}
37
38impl<B> fmt::Debug for EncryptedBackendBuilder<B> {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.debug_struct("EncryptedBackendBuilder")
41            .field("key", &format_args!("<redacted>"))
42            .field("encrypt_names", &self.encrypt_names)
43            .field("case_insensitive", &self.case_insensitive)
44            .field("block_size", &self.block_size)
45            .field("long_name_threshold", &self.long_name_threshold)
46            .field("name_cache_ttl", &self.name_cache_ttl)
47            .field("restore_marker", &self.restore_marker)
48            .finish_non_exhaustive()
49    }
50}
51
52impl<B: ShareBackend> EncryptedBackend<B> {
53    /// Settings for an encrypted view of `inner` under `key`.
54    ///
55    /// `build` wipes the builder's buffer for `key` once the keys are derived,
56    /// and dropping the builder wipes it too. Copies of `key` that the caller
57    /// keeps are the caller's to wipe. The `hmac` and `sha2` crates keep
58    /// key-derived bytes in internal state that they do not wipe. The GHASH
59    /// subkey of `aes-gcm` is not wiped either: it sits in each cipher and in
60    /// copies made during setup and for every operation, and `aes-gcm` wipes
61    /// only one temporary copy.
62    pub fn builder(inner: B, key: [u8; 32]) -> EncryptedBackendBuilder<B> {
63        EncryptedBackendBuilder {
64            inner,
65            key: Zeroizing::new(key),
66            encrypt_names: None,
67            case_insensitive: true,
68            block_size: None,
69            long_name_threshold: None,
70            name_cache_ttl: DEFAULT_NAME_CACHE_TTL,
71            restore_marker: false,
72        }
73    }
74}
75
76impl<B: ShareBackend> EncryptedBackendBuilder<B> {
77    /// Sets whether the names of files and directories are stored encrypted.
78    /// On for a new share unless set. A value that differs from the share's
79    /// fails [`build`](Self::build) with
80    /// [`SettingMismatch`](EncryptionError::SettingMismatch).
81    #[must_use]
82    pub fn encrypt_names(mut self, on: bool) -> Self {
83        self.encrypt_names = Some(on);
84        self
85    }
86
87    /// Sets whether names match without regard to case. On by default. It
88    /// applies to encrypted names; with names in the clear the inner
89    /// backend's rule decides and this has no effect.
90    #[must_use]
91    pub fn case_insensitive(mut self, on: bool) -> Self {
92        self.case_insensitive = on;
93        self
94    }
95
96    /// Sets the number of plaintext bytes in a block: a power of two from
97    /// 8192 to 1048576. The default for a new share is 65536. Another value
98    /// fails [`build`](Self::build) with
99    /// [`InvalidSetting`](EncryptionError::InvalidSetting), and one that
100    /// differs from the share's with
101    /// [`SettingMismatch`](EncryptionError::SettingMismatch).
102    #[must_use]
103    pub fn block_size(mut self, bytes: u32) -> Self {
104        self.block_size = Some(bytes);
105        self
106    }
107
108    /// Sets the longest stored name in characters, from 62 to 255. A name
109    /// whose encrypted form is longer is stored under a short name made from
110    /// a hash, with the encrypted form in a second object beside it. The
111    /// default for a new share is 255. Another value, or any value together
112    /// with [`encrypt_names(false)`](Self::encrypt_names), fails
113    /// [`build`](Self::build) with
114    /// [`InvalidSetting`](EncryptionError::InvalidSetting), and one that
115    /// differs from the share's with
116    /// [`SettingMismatch`](EncryptionError::SettingMismatch).
117    #[must_use]
118    pub fn long_name_threshold(mut self, chars: u8) -> Self {
119        self.long_name_threshold = Some(chars);
120        self
121    }
122
123    /// Sets how long the decrypted names of a directory are trusted for
124    /// changes made outside this backend. The default is 30 seconds;
125    /// `Duration::ZERO` lists the directory again on every lookup that needs
126    /// it. The setting applies only to encrypted names that match without
127    /// regard to case.
128    #[must_use]
129    pub fn name_cache_ttl(mut self, ttl: Duration) -> Self {
130        self.name_cache_ttl = ttl;
131        self
132    }
133
134    /// Lets [`build`](Self::build) write a new marker into a root that has
135    /// entries and no marker. Without it that root fails with
136    /// [`MarkerMissing`](EncryptionError::MarkerMissing).
137    ///
138    /// The new marker takes the settings set on the builder, else the
139    /// defaults, so a share made with other settings has to be restored with
140    /// them. Before it writes the marker, `build` checks the key and the
141    /// block size against what the share holds. It does not check
142    /// `encrypt_names` or `long_name_threshold`, so keep a record of them.
143    /// With encrypted names, at least one entry of the root has to decode
144    /// under the key, and entries whose names do not decode are passed over.
145    /// Of the files, the first that holds data, found breadth first among at
146    /// most 10,000 entries, has to have a header of the chosen block size
147    /// and a first block that is a hole or verifies under the key. A share
148    /// with no such file passes. A failed check is
149    /// [`KeyMismatch`](EncryptionError::KeyMismatch), or
150    /// [`SettingMismatch`](EncryptionError::SettingMismatch) for the block
151    /// size.
152    ///
153    /// With names in the clear, a stray file such as `.DS_Store` can be the
154    /// file that is checked, and fails with `KeyMismatch` until it is
155    /// removed.
156    #[must_use]
157    pub fn restore_marker(mut self) -> Self {
158        self.restore_marker = true;
159        self
160    }
161
162    /// Checks the settings and the root of the inner backend, and returns the
163    /// backend.
164    ///
165    /// An empty root is a new share: `build` writes the marker, unless the
166    /// inner backend is read-only. A root with a marker is an existing share:
167    /// the key has to verify, and the settings set on the builder have to
168    /// equal the marker's. Settings not set take the marker's.
169    ///
170    /// # Errors
171    ///
172    /// Fails with an [`EncryptionError`]:
173    ///
174    /// - [`EncryptionError::InvalidSetting`]: a setting is out of range or clashes with another.
175    /// - [`EncryptionError::SettingMismatch`]: a setting differs from the share's.
176    /// - [`EncryptionError::KeyMismatch`]: the key is not the share's.
177    /// - [`EncryptionError::MarkerMissing`]: the root has entries and no marker.
178    /// - [`EncryptionError::MarkerInvalid`]: the marker is not a file of the right size, does
179    ///   not start with the marker magic, or holds field values out of range.
180    /// - [`EncryptionError::UnsupportedFormat`]: the marker has another format version.
181    /// - [`EncryptionError::Backend`]: the inner backend failed.
182    /// - [`EncryptionError::Random`]: the random generator failed.
183    pub async fn build(self) -> Result<EncryptedBackend<B>, EncryptionError> {
184        let requested = self.requested()?;
185        let Self {
186            inner,
187            key,
188            case_insensitive,
189            name_cache_ttl,
190            restore_marker,
191            ..
192        } = self;
193        let keys = KeySchedule::new(key);
194        let marker = establish(&inner, &keys, &requested, restore_marker, fill_random).await?;
195        let settings = Settings {
196            encrypt_names: marker.encrypt_names,
197            case_insensitive: marker.encrypt_names && case_insensitive,
198            block_shift: marker.block_shift,
199            long_name_threshold: marker.long_name_threshold,
200            name_cache_ttl,
201        };
202        Ok(EncryptedBackend::new(inner, keys, settings))
203    }
204
205    /// The settings that were set, checked against their ranges.
206    fn requested(&self) -> Result<Requested, EncryptionError> {
207        let block_shift = match self.block_size {
208            None => None,
209            Some(bytes) => Some(shift_of(bytes).ok_or(EncryptionError::InvalidSetting {
210                setting: "block_size",
211            })?),
212        };
213        if let Some(threshold) = self.long_name_threshold
214            && (threshold < MIN_LONG_NAME_THRESHOLD || self.encrypt_names == Some(false))
215        {
216            return Err(EncryptionError::InvalidSetting {
217                setting: "long_name_threshold",
218            });
219        }
220        Ok(Requested {
221            encrypt_names: self.encrypt_names,
222            block_shift,
223            long_name_threshold: self.long_name_threshold,
224        })
225    }
226}
227
228/// The shift of a block of `bytes`, if that is a power of two the format
229/// allows.
230fn shift_of(bytes: u32) -> Option<BlockShift> {
231    if !bytes.is_power_of_two() {
232        return None;
233    }
234    u8::try_from(bytes.trailing_zeros())
235        .ok()
236        .and_then(BlockShift::new)
237}
238
239#[cfg(test)]
240mod tests {
241    use super::super::format::MARKER_NAME;
242    use super::super::testing::{assert_invalid, build, key};
243    use super::*;
244    use crate::tests::faulty::Faulty;
245    use crate::tests::memfs::MemFsBackend;
246
247    type FaultyBuilder = EncryptedBackendBuilder<Faulty<MemFsBackend>>;
248
249    /// The error of a build that fails on its settings, before it opens
250    /// anything in the inner backend.
251    async fn refused(setup: impl FnOnce(FaultyBuilder) -> FaultyBuilder) -> EncryptionError {
252        let files = MemFsBackend::new();
253        let faulty = Faulty::new(files.clone());
254        let error = setup(EncryptedBackend::builder(faulty.clone(), key()))
255            .build()
256            .await
257            .unwrap_err();
258        assert_eq!(faulty.opens(), 0, "the inner backend was not used");
259        assert_eq!(files.contents(MARKER_NAME), None);
260        error
261    }
262
263    #[tokio::test]
264    async fn settings_that_are_set_are_in_force() {
265        let files = MemFsBackend::new();
266        let backend = build(&files, |builder| {
267            builder
268                .block_size(16_384)
269                .long_name_threshold(100)
270                .case_insensitive(false)
271                .name_cache_ttl(Duration::from_secs(5))
272        })
273        .await
274        .unwrap();
275        let settings = backend.shared.settings;
276        assert!(settings.encrypt_names);
277        assert!(!settings.case_insensitive);
278        assert_eq!(settings.block_shift.get(), 14);
279        assert_eq!(settings.long_name_threshold, 100);
280        assert_eq!(settings.name_cache_ttl, Duration::from_secs(5));
281    }
282
283    #[tokio::test]
284    async fn case_insensitive_is_off_when_names_are_in_the_clear() {
285        let files = MemFsBackend::new();
286        let backend = build(&files, |builder| {
287            builder.encrypt_names(false).case_insensitive(true)
288        })
289        .await
290        .unwrap();
291        assert!(!backend.shared.settings.case_insensitive);
292    }
293
294    #[tokio::test]
295    async fn block_sizes_from_8192_to_1048576_in_powers_of_two_are_accepted() {
296        for shift in [13u8, 20] {
297            let files = MemFsBackend::new();
298            let backend = build(&files, |builder| builder.block_size(1 << shift))
299                .await
300                .unwrap();
301            assert_eq!(backend.shared.settings.block_shift.get(), shift);
302        }
303    }
304
305    #[tokio::test]
306    async fn other_block_sizes_are_invalid() {
307        for bytes in [0, 4096, 12_288, 2_097_152] {
308            let error = refused(|builder| builder.block_size(bytes)).await;
309            assert_invalid(&error, "block_size");
310        }
311    }
312
313    #[tokio::test]
314    async fn thresholds_from_62_to_255_are_accepted() {
315        for threshold in [62, 255] {
316            let files = MemFsBackend::new();
317            let backend = build(&files, |builder| {
318                builder.encrypt_names(true).long_name_threshold(threshold)
319            })
320            .await
321            .unwrap();
322            assert_eq!(backend.shared.settings.long_name_threshold, threshold);
323        }
324    }
325
326    #[tokio::test]
327    async fn a_threshold_below_62_is_invalid() {
328        let error = refused(|builder| builder.long_name_threshold(61)).await;
329        assert_invalid(&error, "long_name_threshold");
330    }
331
332    #[tokio::test]
333    async fn a_threshold_with_names_in_the_clear_is_invalid() {
334        let error = refused(|builder| builder.encrypt_names(false).long_name_threshold(100)).await;
335        assert_invalid(&error, "long_name_threshold");
336    }
337
338    #[test]
339    fn debug_shows_the_settings_and_redacts_the_key() {
340        let builder = EncryptedBackend::builder(MemFsBackend::new(), key());
341        assert_eq!(
342            format!("{builder:?}"),
343            "EncryptedBackendBuilder { key: <redacted>, encrypt_names: None, \
344             case_insensitive: true, block_size: None, long_name_threshold: None, \
345             name_cache_ttl: 30s, restore_marker: false, .. }"
346        );
347        assert!(format!("{:?}", builder.restore_marker()).contains("restore_marker: true"));
348    }
349}