Skip to main content

smb_server/encrypted/
backend.rs

1//! The backend type and its `ShareBackend` implementation.
2
3use std::fmt;
4use std::sync::Arc;
5use std::time::Duration;
6
7use async_trait::async_trait;
8
9use super::cache::{LongNames, MAX_CACHED_NAMES, MAX_LONG_NAMES, NameCache};
10use super::format::BlockShift;
11use super::keys::KeySchedule;
12use super::locks::Locks;
13use super::node::{NameMatch, NodeTable};
14use crate::backend::{
15    BackendCapabilities, Handle, OpenAction, OpenOptions, ShareBackend, VolumeInfo,
16};
17use crate::error::SmbResult;
18use crate::path::SmbPath;
19
20/// Longest name a client can give, in characters.
21const MAX_CLIENT_NAME_LEN: u32 = 255;
22
23/// Serves the files of another backend with their contents encrypted, and by
24/// default their names too, under a 32-byte key. The inner backend stores
25/// ciphertext; clients see plaintext.
26///
27/// The root of the inner backend holds one object that is not a file of the
28/// share, the marker `.smb-encryption`. It records the settings the share was
29/// made with and a check value of the key.
30/// [`build`](crate::EncryptedBackendBuilder::build) writes it into an empty
31/// root and reads it from any other, so a wrong key, or settings that differ
32/// from the share's, fail the build. A root with entries and no marker fails
33/// it too, unless
34/// [`restore_marker`](crate::EncryptedBackendBuilder::restore_marker) is set.
35///
36/// The block size, whether names are encrypted and the long-name threshold
37/// are fixed when the share is made. The key is not stored anywhere, and the
38/// data cannot be read without it. Give each share a key of its own. With
39/// one key, a stored file copied into another share's storage reads back
40/// through that share when both use the same block size.
41///
42/// File sizes, times and attributes, the shape of the tree and the length of
43/// every name stay visible in the inner backend.
44///
45/// A read of a block that fails authentication returns
46/// [`SmbError::Io`](crate::SmbError::Io), which clients see as
47/// STATUS_UNEXPECTED_IO_ERROR. A crash can leave the block being written
48/// unreadable.
49///
50/// With encrypted names over an `S3Backend`, build that backend with
51/// `case_insensitive(false)`.
52///
53/// The backend reports no named streams and no extended attributes, and
54/// answers [`copy_range`](ShareBackend::copy_range) and
55/// [`clone_range`](ShareBackend::clone_range) with
56/// [`NotSupported`](crate::SmbError::NotSupported).
57///
58/// Clones share all state, so several shares can serve one encrypted tree
59/// through clones of one backend. Two backends built separately over one
60/// tree are not supported.
61///
62/// ```no_run
63/// use smb_server::{Access, EncryptedBackend, Share, ShareBackend, SmbServer};
64/// # async fn run<B: ShareBackend>(inner: B, key: [u8; 32]) -> Result<(), Box<dyn std::error::Error>> {
65/// let vault = EncryptedBackend::builder(inner, key).build().await?;
66/// SmbServer::builder()
67///     .listen("0.0.0.0:4445".parse()?)
68///     .user("alice", "password")
69///     .share(Share::new("vault", vault).user("alice", Access::ReadWrite))
70///     .build()?
71///     .serve()
72///     .await?;
73/// # Ok(()) }
74/// ```
75pub struct EncryptedBackend<B> {
76    pub(super) shared: Arc<Shared<B>>,
77}
78
79/// What the clones of a backend share.
80pub(super) struct Shared<B> {
81    pub(super) inner: B,
82    pub(super) keys: KeySchedule,
83    pub(super) settings: Settings,
84    /// The files and directories that handles have open.
85    pub(super) nodes: Arc<NodeTable>,
86    pub(super) locks: Locks,
87    /// The decoded names of directories, when names are encrypted.
88    pub(super) names: NameCache,
89    pub(super) long_names: LongNames,
90}
91
92impl<B: ShareBackend> Shared<B> {
93    /// How stored paths compare: as they are when names are encrypted, else
94    /// the way the inner backend compares names.
95    pub(super) fn name_match(&self) -> NameMatch {
96        if self.settings.encrypt_names || self.inner.capabilities().case_sensitive {
97            NameMatch::Exact
98        } else {
99            NameMatch::Folded
100        }
101    }
102}
103
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
105pub(super) struct Settings {
106    pub(super) encrypt_names: bool,
107    /// Encrypted names match without regard to case; false when names are
108    /// not encrypted.
109    pub(super) case_insensitive: bool,
110    pub(super) block_shift: BlockShift,
111    /// Longest stored name; 0 when names are not encrypted.
112    pub(super) long_name_threshold: u8,
113    pub(super) name_cache_ttl: Duration,
114}
115
116impl<B> EncryptedBackend<B> {
117    pub(super) fn new(inner: B, keys: KeySchedule, settings: Settings) -> Self {
118        Self {
119            shared: Arc::new(Shared {
120                inner,
121                keys,
122                settings,
123                nodes: NodeTable::new(),
124                locks: Locks::new(),
125                names: NameCache::new(settings.name_cache_ttl, MAX_CACHED_NAMES),
126                long_names: LongNames::new(MAX_LONG_NAMES),
127            }),
128        }
129    }
130
131    #[cfg(test)]
132    pub(super) fn node_count(&self) -> usize {
133        self.shared.nodes.len()
134    }
135}
136
137impl<B> Clone for EncryptedBackend<B> {
138    fn clone(&self) -> Self {
139        Self {
140            shared: Arc::clone(&self.shared),
141        }
142    }
143}
144
145impl<B> fmt::Debug for EncryptedBackend<B> {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        let settings = &self.shared.settings;
148        f.debug_struct("EncryptedBackend")
149            .field("encrypt_names", &settings.encrypt_names)
150            .field("case_insensitive", &settings.case_insensitive)
151            .field("block_size", &settings.block_shift.block_size())
152            .field("long_name_threshold", &settings.long_name_threshold)
153            .field("name_cache_ttl", &settings.name_cache_ttl)
154            .finish_non_exhaustive()
155    }
156}
157
158#[async_trait]
159impl<B: ShareBackend> ShareBackend for EncryptedBackend<B> {
160    async fn open(
161        &self,
162        path: &SmbPath,
163        opts: OpenOptions,
164    ) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
165        let (handle, action) = self.open_handle(path, opts).await?;
166        Ok((Box::new(handle), action))
167    }
168
169    async fn unlink(&self, path: &SmbPath) -> SmbResult<()> {
170        self.unlink_path(path).await
171    }
172
173    async fn rename(&self, from: &SmbPath, to: &SmbPath, replace_if_exists: bool) -> SmbResult<()> {
174        self.rename_path(from, to, replace_if_exists).await
175    }
176
177    fn capabilities(&self) -> BackendCapabilities {
178        let inner = self.shared.inner.capabilities();
179        let settings = &self.shared.settings;
180        BackendCapabilities {
181            case_sensitive: if settings.encrypt_names {
182                !settings.case_insensitive
183            } else {
184                inner.case_sensitive
185            },
186            named_streams: false,
187            extended_attributes: false,
188            block_cloning: false,
189            ..inner
190        }
191    }
192
193    async fn volume_info(&self) -> SmbResult<VolumeInfo> {
194        let mut volume = self.shared.inner.volume_info().await?;
195        if self.shared.settings.encrypt_names {
196            volume.max_name_length = MAX_CLIENT_NAME_LEN;
197        }
198        Ok(volume)
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::super::testing::{
205        Reporting, build, key, key_schedule, many_names, names_settings, read_only,
206    };
207    use super::*;
208    use crate::backend::OpenIntent;
209    use crate::error::SmbError;
210    use crate::tests::memfs::MemFsBackend;
211    use crate::tests::util::{dir_opts, opts, path};
212
213    async fn built(files: &MemFsBackend) -> EncryptedBackend<MemFsBackend> {
214        build(files, |builder| builder).await.unwrap()
215    }
216
217    #[test]
218    fn clones_share_one_state_whether_or_not_the_inner_backend_clones() {
219        struct NotClone;
220        fn assert_send_sync<T: Send + Sync + 'static>() {}
221        assert_send_sync::<EncryptedBackend<NotClone>>();
222        let backend = EncryptedBackend::new(NotClone, key_schedule(), names_settings());
223        let clone = backend.clone();
224        assert!(Arc::ptr_eq(&backend.shared, &clone.shared));
225    }
226
227    #[tokio::test]
228    async fn the_name_caches_are_bounded() {
229        let backend = built(&MemFsBackend::new()).await;
230        let long = &backend.shared.long_names;
231        for n in 0..10_001 {
232            long.insert(format!("h{n}.l"), "name");
233        }
234        assert_eq!(long.len(), 10_000);
235        assert_eq!(long.get("h0.l"), None);
236
237        let names = &backend.shared.names;
238        for key in ["a", "b"] {
239            names.install_if(key.to_string(), many_names(60_000), || true);
240        }
241        assert_eq!(names.keys(), ["b"]);
242        names.install_if("big".to_string(), many_names(100_001), || true);
243        assert_eq!(names.keys(), ["big"]);
244    }
245
246    #[tokio::test]
247    async fn debug_shows_the_settings_in_force_and_no_key() {
248        let backend = built(&MemFsBackend::new()).await;
249        assert_eq!(
250            format!("{backend:?}"),
251            "EncryptedBackend { encrypt_names: true, case_insensitive: true, \
252             block_size: 65536, long_name_threshold: 255, name_cache_ttl: 30s, .. }"
253        );
254        let clear = build(&MemFsBackend::new(), |builder| {
255            builder
256                .encrypt_names(false)
257                .case_insensitive(true)
258                .block_size(8192)
259                .name_cache_ttl(Duration::ZERO)
260        })
261        .await
262        .unwrap();
263        assert_eq!(
264            format!("{clear:?}"),
265            "EncryptedBackend { encrypt_names: false, case_insensitive: false, \
266             block_size: 8192, long_name_threshold: 0, name_cache_ttl: 0ns, .. }"
267        );
268    }
269
270    #[tokio::test]
271    async fn capabilities_follow_the_settings_and_the_inner_backend() {
272        let files = MemFsBackend::new();
273        let inner = files.capabilities();
274        assert!(!inner.case_sensitive && inner.named_streams && inner.extended_attributes);
275
276        let backend = built(&files).await;
277        let caps = backend.capabilities();
278        assert!(!caps.is_read_only);
279        assert!(!caps.case_sensitive, "case-insensitive names");
280        assert!(!caps.named_streams);
281        assert!(!caps.extended_attributes);
282        assert!(!caps.block_cloning);
283
284        let exact = build(&files, |builder| builder.case_insensitive(false))
285            .await
286            .unwrap();
287        assert!(exact.capabilities().case_sensitive, "exact names");
288    }
289
290    #[tokio::test]
291    async fn capabilities_with_names_in_the_clear_are_the_inner_backends() {
292        for inner_case_sensitive in [false, true] {
293            let files = MemFsBackend::new();
294            let reported = BackendCapabilities {
295                case_sensitive: inner_case_sensitive,
296                block_cloning: true,
297                ..files.capabilities()
298            };
299            let backend = EncryptedBackend::builder(Reporting::new(files, reported), key())
300                .encrypt_names(false)
301                .case_insensitive(inner_case_sensitive)
302                .build()
303                .await
304                .unwrap();
305            let caps = backend.capabilities();
306            assert_eq!(
307                caps.case_sensitive, inner_case_sensitive,
308                "the inner backend decides"
309            );
310            assert!(!caps.named_streams && !caps.extended_attributes && !caps.block_cloning);
311        }
312    }
313
314    #[tokio::test]
315    async fn a_read_only_inner_backend_makes_a_read_only_backend() {
316        let backend = EncryptedBackend::builder(read_only(&MemFsBackend::new()), key())
317            .build()
318            .await
319            .unwrap();
320        assert!(backend.capabilities().is_read_only);
321    }
322
323    #[tokio::test]
324    async fn volume_info_is_the_inner_backends_with_names_of_any_client_length() {
325        let volume = VolumeInfo {
326            label: Some("disk".to_string()),
327            serial_number: 7,
328            max_name_length: 143,
329            ..VolumeInfo::default()
330        };
331        let reported = || {
332            Reporting::new(MemFsBackend::new(), BackendCapabilities::default())
333                .with_volume(volume.clone())
334        };
335
336        let encrypted = EncryptedBackend::builder(reported(), key())
337            .build()
338            .await
339            .unwrap();
340        let got = encrypted.volume_info().await.unwrap();
341        assert_eq!(got.max_name_length, 255);
342        assert_eq!(got.label.as_deref(), Some("disk"));
343        assert_eq!(got.serial_number, 7);
344
345        let clear = EncryptedBackend::builder(reported(), key())
346            .encrypt_names(false)
347            .build()
348            .await
349            .unwrap();
350        assert_eq!(clear.volume_info().await.unwrap().max_name_length, 143);
351    }
352
353    #[tokio::test]
354    async fn a_stored_name_that_is_not_the_shares_cannot_be_opened_unlinked_or_renamed() {
355        let files = MemFsBackend::new();
356        let backend = built(&files).await;
357        files.clone().with_file("f", b"abc");
358        for intent in [OpenIntent::Open, OpenIntent::Truncate] {
359            assert!(
360                matches!(
361                    backend.open(&path("f"), opts(intent)).await,
362                    Err(SmbError::NotFound)
363                ),
364                "{intent:?}: `f` is no name of the share"
365            );
366        }
367        assert!(matches!(
368            backend.unlink(&path("f")).await,
369            Err(SmbError::NotFound)
370        ));
371        assert!(matches!(
372            backend.rename(&path("f"), &path("g"), false).await,
373            Err(SmbError::NotFound)
374        ));
375        assert_eq!(files.contents("f").unwrap(), b"abc");
376    }
377
378    #[tokio::test]
379    async fn the_root_lists_only_the_names_of_the_share_and_cannot_be_unlinked_or_renamed() {
380        let files = MemFsBackend::new();
381        let backend = built(&files).await;
382        files.clone().with_file("f", b"abc");
383        let (handle, action) = backend
384            .open(&path("new"), opts(OpenIntent::Create))
385            .await
386            .unwrap();
387        assert_eq!(action, OpenAction::Created);
388        handle.close().await.unwrap();
389        assert!(matches!(
390            backend.unlink(&SmbPath::root()).await,
391            Err(SmbError::AccessDenied)
392        ));
393        assert!(matches!(
394            backend.rename(&SmbPath::root(), &path("g"), false).await,
395            Err(SmbError::AccessDenied)
396        ));
397        assert!(matches!(
398            backend.rename(&path("f"), &SmbPath::root(), false).await,
399            Err(SmbError::AccessDenied)
400        ));
401        assert_eq!(files.contents("f").unwrap(), b"abc");
402
403        let (root, action) = backend
404            .open(&SmbPath::root(), dir_opts(OpenIntent::Open))
405            .await
406            .unwrap();
407        assert_eq!(action, OpenAction::Opened);
408        assert!(root.stat().await.unwrap().is_directory);
409        for listed in [
410            root.list_dir(None).await.unwrap(),
411            root.list_dir_sized(None, true).await.unwrap(),
412        ] {
413            let names: Vec<_> = listed.iter().map(|entry| &entry.info.name).collect();
414            assert_eq!(names, ["new"]);
415        }
416        assert!(!root.dir_is_empty().await.unwrap());
417        root.close().await.unwrap();
418        assert_eq!(files.open_handles(), 0);
419    }
420
421    #[tokio::test]
422    async fn streams_and_copies_are_never_forwarded() {
423        let files = MemFsBackend::new();
424        let backend = built(&files).await;
425        files.clone().with_file("f", b"abc");
426        let stream = "s".parse().unwrap();
427        let (src, _) = files
428            .open(&path("f"), opts(OpenIntent::Open))
429            .await
430            .unwrap();
431        let (dst, _) = files
432            .open(&path(""), dir_opts(OpenIntent::Open))
433            .await
434            .unwrap();
435        assert!(matches!(
436            backend.copy_range(&*src, 0, &*dst, 0, 3).await,
437            Err(SmbError::NotSupported)
438        ));
439        assert!(matches!(
440            backend.clone_range(&*src, 0, &*dst, 0, 3).await,
441            Err(SmbError::NotSupported)
442        ));
443        dst.close().await.unwrap();
444        assert!(matches!(
445            backend
446                .open_stream(src, &path("f"), &stream, opts(OpenIntent::Create))
447                .await,
448            Err(SmbError::NotSupported)
449        ));
450        assert!(matches!(
451            backend.remove_stream(&path("f"), 0, &stream).await,
452            Err(SmbError::NotSupported)
453        ));
454        assert!(matches!(
455            backend
456                .rename_stream(&path("f"), 0, Some(&stream), None, false)
457                .await,
458            Err(SmbError::NotSupported)
459        ));
460        assert_eq!(files.contents("f").unwrap(), b"abc");
461        assert!(files.stream_names("f").is_empty());
462    }
463}