Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

smb-server

SMB file-sharing server library for Rust.

  • Dialects: SMB 2.0.2, 2.1, 3.0, 3.0.2, 3.1.1 over TCP
  • Auth: NTLMv2, anonymous, guest
  • Signing and encryption (AES-CCM, AES-GCM)
  • Leases, durable handles, change notifications
  • Named streams, macOS metadata, extended attributes
  • Server-side copy and block cloning
  • Share listing, mDNS and WS-Discovery
  • Users and shares can be added, updated, and removed at runtime
  • Pluggable storage: implement ShareBackend, or use the built-in LocalFsBackend or S3Backend
  • Encrypted storage: EncryptedBackend wraps another backend to encrypt file contents and, by default, file names

Works with Windows Explorer, macOS Finder, Linux CIFS mounts, and smbclient.

API reference: docs.rs/smb-server.

Quick start

Install

cargo add smb-server
FeatureDefaultAdds
localfsonLocalFsBackend
discoveryoffmDNS and WS-Discovery announcements
s3offS3Backend
encryptionoffEncryptedBackend
[dependencies]
smb-server = { version = "0.12", features = ["discovery"] }

Serve a directory

use smb_server::{Access, LocalFsBackend, Share, SmbServer};

let server = SmbServer::builder()
    .listen("0.0.0.0:4445".parse()?)
    .user("alice", "password")
    .share(
        Share::new("home", LocalFsBackend::new("/srv/home")?)
            .user("alice", Access::ReadWrite),
    )
    .build()?;

server.bind().await?;
server.serve().await?;

Stop

Call server.shutdown(), or use server.shutdown_handle() from another task. Once triggered, serve():

  • stops accepting new connections
  • closes each active connection after its current request finishes
  • returns once every connection and disconnected durable handle has closed

Run the example

cargo run -p minimal-smb-example

The example listens on 127.0.0.1:4445 and serves directories under smb-example in the system temp directory.

ShareAccess
publicanonymous read-write
mediaanonymous read-only
homealice read-write, bob read-only
VariableEffect
SMB_LISTENListen address
SMB_ROOTRoot directory for the shares
SMB_PASSWORDPassword for alice and bob. If unset, a password is generated and logged at startup
SMB_DISCOVERY=1Announce the server on the network. Requires --features discovery and a non-loopback address
SMB_STREAMS=0Disable named streams
SMB_COPY=0Disable server-side copy
SMB_S3_BUCKETServe this S3 bucket as the only share (s3). Requires --features s3. See backends
SMB_ENCRYPTION_KEY64-hex-digit encryption key. Adds an encrypted vault share, or encrypts s3 when SMB_S3_BUCKET is also set. Requires --features encryption. See encrypted storage
SMB_DISCOVERY=1 SMB_LISTEN='[::]:4445' cargo run -p minimal-smb-example --features discovery

Shares and users

SmbServer::builder()
    .user("alice", "password")
    .share(Share::new("home", backend).user("alice", Access::ReadWrite))

Access

Call on ShareWho gets in
.user(name, Access::ReadWrite)That user, read-write
.user(name, Access::Read)That user, read-only
.public()Anonymous and guest, read-write
.public_read_only()Anonymous and guest, read-only
  • Without .public() or .public_read_only(), only listed users can connect.
  • A public share cannot also list .user() entries; build() fails with PublicMixedWithUsers.

Guest

  • Logging on as guest with an empty password grants anonymous access, unless a user named guest (any case) is configured. macOS Finder sends this for Connect As Guest.
  • Guest and anonymous sessions are neither signed nor encrypted. Clients that require signing cannot establish a guest session.

Per-share switches

All options are enabled by default.

Call on ShareDisables
.leases(false)Leases
.durable_handles(false)Durable handles
.change_notify(false)Change notifications
.named_streams(false)Named streams
.extended_attributes(false)Extended attributes
.server_side_copy(false)Server-side copy
.listed(false)Showing the share in share listings

Other calls on Share:

Call on ShareEffect
.encrypt_data()Require encryption on this share
.remark(text)Comment shown next to the share in listings

Runtime config

Get a ConfigHandle before serve() and use it from another task while the server runs:

let config = server.config_handle();
let home = Share::new("home", LocalFsBackend::new("/srv/home")?)
    .user("alice", Access::ReadWrite);

tokio::spawn(async move {
    config.add_user("alice", "password").await?;
    config.add_share(home).await?;
    Ok::<_, smb_server::ConfigError>(())
});

server.serve().await?;
CallEffect
add_user(name, password)Adds a user, or replaces the password and disconnects active sessions for an existing user
remove_user(name)Removes the user and disconnects their active sessions
add_share(share)Adds a share and makes it available to new tree connections
remove_share(name)Removes the share and closes its tree connections and open handles
grant_share_user(share, user, access)Grants or updates a user’s access on the share; lowering access disconnects their tree connections to that share
revoke_share_user(share, user)Revokes a user’s access and closes their tree connections and open handles on that share
set_share_mode(share, ShareMode)Changes the share’s access mode and closes its tree connections. Switching a share with listed users to a public mode fails
set_max_opens_per_connection(n)Updates the per-connection open-handle limit; already open handles stay open

Any call that disconnects a user also closes their disconnected durable handles.

Limits and timeouts

All limits and timeouts are configured on SmbServer::builder().

Limits

OptionDefaultPast the limit
max_connections1024Connection closed
max_sessions_per_connection64STATUS_INSUFFICIENT_RESOURCES
max_trees_per_session128STATUS_INSUFFICIENT_RESOURCES
max_opens_per_connection16384STATUS_INSUFFICIENT_RESOURCES
max_locks_per_open1024STATUS_INSUFFICIENT_RESOURCES
max_disconnected_opens4096See durable handles

max_read_size and max_write_size set the largest allowed READ and WRITE sizes. The default is 1 MiB, with a range of 64 KiB to 8 MiB.

ConfigHandle::set_max_opens_per_connection updates the open-handle limit at runtime.

Timeouts

OptionDefaultEffect
handshake_timeout30 sCloses a connection that has not established a session
idle_timeout15 minCloses a connection with no requests and no open files
io_timeout60 sCloses a connection that stalls while sending a request or reading a response
tcp_keepalive60 sIdle time before sending TCP keepalive probes. None disables keepalive
durable_handle_timeout2 minSee durable handles

Logon throttle

logon_throttle(max_failures, lockout) defaults to 10 failures and a 60 s lockout.

ScopeLocked out afterResult
Single usernamemax_failures failures, each within lockout of the previous oneSTATUS_ACCOUNT_LOCKED_OUT until lockout elapses
Single client address10 x max_failures failures across any usernamesSTATUS_ACCOUNT_LOCKED_OUT until lockout elapses
Single connectionmax_failures failuresConnection closed
  • Unknown usernames count the same as configured ones.
  • Setting max_failures to 0 disables the throttle.

Signing and encryption

Signing

DialectAlgorithm
SMB 2.0.2, 2.1HMAC-SHA-256
SMB 3.xAES-CMAC

require_signing(true) on the builder is off by default. When enabled:

  • every authenticated session must sign requests
  • NEGOTIATE advertises signing as required

When it is off, a client can still require signing for its own sessions. Anonymous and guest sessions are never signed.

Encryption

DialectCiphers
SMB 3.1.1AES-128 or AES-256, CCM or GCM
SMB 3.0, 3.0.2AES-128-CCM, for clients that advertise encryption

Clients that send encrypted requests receive encrypted replies.

Require encryption on a single share:

Share::new("secret", LocalFsBackend::new("/srv/secret")?)
    .user("alice", Access::ReadWrite)
    .encrypt_data()

Require encryption for every session with encrypt_data(true) on the builder.

When encryption is required, these clients are refused:

  • SMB 2.x clients
  • SMB 3.x clients with no cipher in common
  • Anonymous and guest sessions (they can establish a session, but tree connections are refused)

Setting reject_unencrypted_access(false) on the builder serves all of these unencrypted instead.

Storage encryption

encrypt_data encrypts SMB 3.x traffic in transit between client and server. EncryptedBackend encrypts file contents and, by default, file names at rest in its inner backend. A share can use both. See encrypted storage.

Logon throttle

See Limits and timeouts.

Backends

A share serves any type that implements ShareBackend. To write one, see ShareBackend in the API docs.

LocalFsBackend

Feature localfs, on by default. Serves a directory on the host.

LocalFsBackend::new("/srv/home")?

Paths and symlinks cannot reach outside the directory.

CallEffect
.read_only()Refuses writes
.watch_host_changes(false)Stops reporting host-side changes. Linux only, on by default. See change notifications
.stream_store(path)Keeps large named streams in path. Linux only. See named streams

sweep_streams() frees stored stream data no file uses. See named streams.

On Windows, the directory may be a UNC path or a mapped drive, and the server account needs traverse rights on the share’s directories. On volumes that reject POSIX deletes (such as an SMB share), deleted entries are moved to a hidden .smb-deleted directory in the share root until their last handle closes, freeing the original name immediately. Clients cannot list, open, or create .smb-deleted.

On Windows, a rename that fails with STATUS_ACCESS_DENIED (for example, renaming a directory while another program has an entry below it open) is retried for up to one second before failing.

When the directory lives on another machine, the Windows SMB client can store a new name in the casing another program (such as a virus scanner) uses to open it at the same moment, and can ignore a rename that changes only letter case. After each create or rename of a file, directory, or named stream, the backend reads back the stored name. If the casing differs, it renames the entry to a temporary name (~smb-<32 hex digits>) and then to the requested name.

While this two-step rename is in progress, the entry appears under the temporary name; if the server stops mid-rename, that temporary name stays in the directory. A case-only rename that cannot be corrected fails and leaves the name unchanged. If another program holds a newly created entry open without delete sharing, the create succeeds under the stored casing and logs a warning. If another client claims the requested name during the correction, the create fails with STATUS_SHARING_VIOLATION and deletes the entry.

S3Backend

Feature s3, off by default. Serves a bucket, or the keys under a prefix, as a share. Each file maps to an object and each directory maps to a key prefix. The object store must support ListObjectsV2, HeadObject, ranged GetObject, PutObject, CopyObject, multipart uploads with UploadPartCopy, and DeleteObjects, all signed with SigV4.

Changes land in a local cache directory and upload to the bucket in the background. Reads fetch byte ranges from the object. A file’s modification time comes from its mtime metadata, falling back to src_last_modified_millis, and then to the store’s object modification time.

smb-server = { version = "0.12", features = ["s3"] }
use smb_server::{Access, S3Backend, Share};

let s3 = S3Backend::builder("https://s3.example.com", "us-east-1", "example-bucket")
    .credentials("access-key", "secret-key")
    .cache_dir("/path/to/cache")
    .build()
    .await?;

let share = Share::new("s3", s3.clone()).user("alice", Access::ReadWrite);

builder(endpoint, region, bucket) takes an https:// or http:// endpoint URL with no path and the region used to sign requests. build() validates the settings, locks the cache directory, lists one key from the bucket, recovers any pending state from the cache directory, and starts background uploads. It fails if any setting or the cache directory is unusable, or if the store rejects or does not respond for the bucket. A prefix with an empty, ., or .. component, or one that leaves no room for a name under 1024 bytes, is rejected.

CallDefaultEffect
credentials(access_key, secret_key)RequiredSigns requests
session_token(token)NoneSession token for temporary credentials
prefix(prefix)Whole bucketServes only the keys under prefix. Leading and trailing / are stripped
cache_dir(dir)Required unless read-onlySee cache directory
read_only()OffSee read-only
path_style(bool)AutomaticPlaces the bucket in the URL path (true) or host name (false). Automatic uses the host name for amazonaws.com endpoints with a DNS-label bucket name, and the path otherwise
case_insensitive(bool)trueMatches names without regard to case. See names and listings
request_timeout(duration)30 sTime limit on store requests for a single client request, retries included
metadata_ttl(duration)30 sHow long the server trusts a listing or object metadata read from the store
listing_metadata_max(n)1000Maximum entries per listing whose stored times are fetched (one request each). 0 fetches none
upload_delay(duration)5 sDelay after the last change before uploading to the bucket
part_size(bytes)16 MiBMultipart upload part size, 5 MiB to 5 GiB. Files up to this size upload in one request. Files that would exceed 10,000 parts use larger parts
upload_concurrency(n)4Maximum concurrent uploads and in-flight parts per upload. Must be at least 1
read_chunk(bytes)8 MiBSize of ranged object reads, 64 KiB to 32 MiB
max_dir_rename_objects(n)10000Maximum objects a renamed directory may contain. See limitations

Cache directory

Stores every change that has not reached the bucket yet: file data, times, attributes, renames, and deletes. It must live on durable local storage; losing the directory loses those changes. On Windows, it must be on a local NTFS or ReFS volume; build() rejects paths on an SMB share or mapped network drive.

  • Created if missing. Only one backend can use a cache directory at a time. It stays locked until every clone of the backend is dropped, all handles opened through it are closed, and all in-flight requests and background saves of closed files have finished.
  • Bound to one endpoint, bucket, prefix, and case setting; build() rejects a directory created with different settings.
  • Written data is recorded when a client flushes the file or closes its last handle. For files kept open (such as under a lease or durable handle), it is recorded when the upload starts: upload_delay after the last write, or later while upload_concurrency uploads are running. Records for closed files are written in the background. The next build() deletes data files that were never recorded. Renames and deletes are recorded before the client receives a reply. See limitations for what a crash can lose.
  • Clients see the total size and free space of the cache disk as the share’s size and free space.
  • Building a backend on a cache directory with pending changes restores those files, times, renames, and deletes and uploads them without waiting for upload_delay. It also retries previously failed uploads and aborts leftover multipart uploads.
  • Data that cannot be read back is moved to the conflicts subdirectory inside the cache directory, with an error logged.

Uploads and shutdown

A file is uploaded upload_delay after its last modification, whether open or closed. Opening a file without overwriting it, or closing it, does not count as a modification.

sync() waits until every change made before the call reaches the bucket. It waits through transient errors and a full cache disk, but returns early with an error if a change fails permanently (other changes may still be in flight). failures() lists paths that failed permanently along with their errors. Listed paths are not retried until the next build() on the cache directory. Files moved to conflicts and deletes rejected by the store do not appear in failures(); they only cause sync() to fail.

Dropping the last clone of the backend stops background uploads. Call sync() after serve() returns, even if serve() failed:

let served = server.serve().await;
let synced = s3.sync().await;
for (path, error) in s3.failures() {
    eprintln!("{path}: {error}");
}
served?;
synced?;

Read-only

read_only() serves the bucket without a cache directory; build() fails if cache_dir is also set. All writes fail with STATUS_ACCESS_DENIED. The share reports the default volume size (4 PiB total, 2 PiB free), and sync() returns Ok immediately.

Lifecycle rules

  • Add a lifecycle rule to abort incomplete multipart uploads. A crash, or a retried request whose response was lost, can leave one in the bucket, and the store retains its parts until aborted.
  • Versioned buckets retain old versions of objects that the backend overwrites, deletes, renames, or updates metadata on. Add a lifecycle rule that keeps only the latest version.

Example

The example serves a bucket when SMB_S3_BUCKET is set, exposing one share (s3) with alice read-write and bob read-only. After the server stops, it calls sync() and logs the result and any failures(). A second Ctrl-C interrupts the wait; anything recorded in SMB_S3_CACHE uploads on the next run. See cache directory.

VariableEffect
SMB_S3_BUCKETBucket to serve
SMB_S3_ENDPOINTEndpoint URL
SMB_S3_REGIONSigning region
SMB_S3_ACCESS_KEY, SMB_S3_SECRET_KEYCredentials
SMB_S3_CACHECache directory
SMB_S3_PREFIXServe only the keys under this prefix (optional)

When SMB_S3_BUCKET is set, every variable except SMB_S3_PREFIX is required. Without --features s3, SMB_S3_BUCKET is ignored with a warning.

SMB_S3_BUCKET='<bucket>' SMB_S3_ENDPOINT=https://s3.example.com SMB_S3_REGION=us-east-1 \
SMB_S3_ACCESS_KEY='<access key>' SMB_S3_SECRET_KEY='<secret key>' SMB_S3_CACHE='<cache directory>' \
cargo run -p minimal-smb-example --features s3

Leases

By default, every share grants SMB2 leases with read, handle, and write caching. Clients can:

  • cache data they read
  • keep files open after applications close them
  • cache writes while every other open of the file holds the same lease or only reads attributes

Breaks

A lease breaks when another open that does not hold the lease opens, writes, locks, renames, or deletes the file in a way that conflicts with the cached state. This includes opens from the same client with a different lease key or no lease.

OperationWhile the break is pending
Open, renameWaits until the client writes back or closes, up to 35 s
LockRefused until the client writes back

Named streams

  • Each named stream of a file has its own leases.
  • Opening the base file or its other streams does not break those leases.
  • Overwriting the base file breaks handle caching on its streams.

Changes outside the server

Changes made directly on the host, or through another share backed by the same directory, do not break leases, so clients may keep serving cached copies. Disable leases on such a share:

Share::new("shared", backend).leases(false)

Durable handles

A file opened with a durable handle request (v1 or v2) and a handle-caching lease stays open after the connection drops or the client logs off. It retains its share mode, byte-range locks, and lease.

When the same user reconnects from the same client, the client reopens the file with the same handle, locks, and lease. Until then, the server keeps it as a disconnected durable handle.

How long

RequestKept for
v1, or v2 without a timeoutdurable_handle_timeout, 2 min by default
v2 with a timeoutThe requested timeout, up to 5 min or durable_handle_timeout, whichever is longer

durable_handle_timeout accepts values from 1 ms to 49 days.

How many

max_disconnected_opens defaults to 4096 across all clients. A single user can hold at most a quarter of that limit, rounded up. Files that would exceed either limit are closed on disconnect.

Closed early by

  • An open, write, lock, rename, or delete that conflicts with what the lease caches
  • ConfigHandle calls that:
    • remove the user or the share
    • revoke the user’s access or lower it to read-only
    • change the share’s mode
    • change the user’s password

Disable on a single share with .durable_handles(false).

Change notifications

Windows Explorer and macOS Finder watch each open folder. Watching clients receive notifications for changes made through any connection to the share, either directly in the folder or anywhere below it when watching a subtree.

ChangeReported
Create, delete, renameImmediately
Attributes or times setImmediately
Write, truncate, overwriteWhen the writing handle closes, as SIZE, LAST_WRITE, and ATTRIBUTES changes

Disable on a single share with .change_notify(false).

Changes outside the server

Changes made directly on the host, or through another share backed by the same directory, are reported only if the backend watches for them.

On Linux, LocalFsBackend watches via inotify:

  • Watches entries directly inside a watched folder only.
  • Uses at most 4096 kernel watches per backend.
  • If a folder exceeds that limit, or hits fs.inotify.max_user_watches or fs.inotify.max_user_instances, it only receives changes made through the server and a warning is logged once.
  • Call .watch_host_changes(false) on the backend to disable host watching.

On other platforms, only changes made through the server are reported.

Named streams and macOS

A share whose backend supports named streams serves them and reports FILE_NAMED_STREAMS. Calling .named_streams(false) on the Share disables them; a CREATE naming a stream then fails with STATUS_OBJECT_NAME_INVALID.

ClientUses streams for
WindowsAlternate data streams such as file.txt:name. dir /r and Get-Item -Stream * list them; copy and robocopy copy them
macOSFinder info, resource forks, tags, comments, and other xattrs on files and folders, avoiding ._ files

Where LocalFsBackend keeps them

HostStorageLimits
Linuxxattr user.DosStream.<name>:$DATA (Samba vfs_streams_xattr layout)Large streams use the stream store. Requires user xattrs; without them, macOS clients fall back to ._ files
macOSThe file’s own xattrs (AFP_AfpInfo maps to com.apple.FinderInfo, AFP_Resource maps to com.apple.ResourceFork, others keep their name)Resource fork: 16 MiB; other streams: 1 MiB. Exceeding either returns STATUS_DISK_FULL
WindowsNTFS alternate data streamsUnsupported on FAT and exFAT

On a macOS host, the host’s Finder displays the tags, labels, comments, and icons set by clients.

Stream store

Linux only. Stores streams that outgrow an xattr: larger than 65,535 bytes or beyond the filesystem’s xattr space for the file (on ext4, one block shared by all of a file’s xattrs). Each xattr stores the stream data plus a trailing NUL byte.

  • Stored in .smb-streams in the share root (mode 0700), created on the first request to a writable share. LocalFsBackend::stream_store(path) moves it outside the share.
  • Clients cannot list, open, or create .smb-streams.
  • Each file with streams in the store records its entry in the user.smb-server.streams xattr.
  • Streams follow renames and hard links, including those made on the host.
  • A copy made with xattrs shares the original’s stored streams until either file modifies a stream; that file then gets its own copy.
  • Back up and move shares with xattrs and the stream store intact (for example, rsync -aX). Copies made without xattrs lose their streams.
  • Samba serving the same directory sees only xattr-held streams and lists .smb-streams as a regular folder.

Cleanup: the store retains streams for deleted files and for files replaced on the host without their xattrs. LocalFsBackend::sweep_streams frees a stored stream once two consecutive calls find no file referencing it and no request touched it in between.

Apple AAPL context

macOS clients send Apple’s AAPL create context in the first CREATE on a share. The server:

  • replies with the model string smb-server, or the value set by apple_model
  • reports itself as a Unix server on Unix hosts
  • on shares with named streams, includes each entry’s Finder info, resource fork size, and Unix mode in Finder listings

Setting apple_extensions(false) on the builder ignores the AAPL context.

Existing ._ files

._ files written while a share had streams disabled remain and list as ordinary files. Run dot_clean -m on the mounted share from a Mac to move them into streams.

Extended attributes

A share whose backend supports extended attributes serves them and reports FILE_SUPPORTS_EXTENDED_ATTRIBUTES. Calling .extended_attributes(false) on the Share disables them.

Linux clients read and set them as user.* attributes on a CIFS mount.

Where LocalFsBackend keeps them

HostStorage
Linuxxattrs named user.<name> (Samba layout), when the filesystem supports user xattrs
WindowsNTFS extended attributes
macOSUnsupported; macOS xattrs are exposed as named streams instead

Limits on Linux

These namespaces are hidden from clients, and setting them fails with STATUS_ACCESS_DENIED:

  • user.DosStream.*
  • user.smb-server.*
  • user.DOSATTRIB
  • user.SAMBA_PAI
  • user.SAMBA_STREAMS
  • user.SmbReparse
  • user.org.netatalk.Metadata
OperationError
Exceeds the file’s available xattr spaceSTATUS_EA_TOO_LARGE
Set on a read-only fileSTATUS_ACCESS_DENIED, unless the server runs as a user that can write to any file (such as root)

Server-side copy

Windows Explorer, cp on a Linux CIFS mount, and macOS Finder ask the server to copy file data directly.

RequestBehavior
COPYCHUNK, COPYCHUNK_WRITECopies byte ranges within a share or between two shares in the same session
FSCTL_DUPLICATE_EXTENTS_TO_FILEClones a byte range on a backend that shares blocks between files
Apple whole-file copyCopies a file with its last write time, its creation time (except on Linux), and its named streams when both shares support them. Advertised on shares with named streams
CallDisables
.server_side_copy(false) on ShareAll server-side copy on that share; clients copy data themselves
apple_copyfile(false) on the builderApple whole-file copy only

LocalFsBackend

HostCopyCloning
Linuxcopy_file_range(2): shares blocks where the filesystem supports it, copies in the kernel otherwise, and falls back to reads and writes. Named streams always use reads and writesBtrfs and XFS with reflinks: supports FSCTL_DUPLICATE_EXTENTS_TO_FILE and reports FILE_SUPPORTS_BLOCK_REFCOUNTING
WindowsReads and writesVolumes that report block cloning, such as ReFS
macOSReads and writesNone

Block cloning is unavailable on a .read_only() backend, or when the server cannot create files in the share root.

Share listing

Windows Explorer, net view, macOS Finder, smbutil view, and smbclient -L can list a server’s shares. Each session sees the shares it is allowed to connect to, in the order they were added, plus IPC$. Sessions that cannot encrypt do not see shares that require encryption. Shares ending in $ are included in the list; clients hide them by convention.

Share::new("photos", LocalFsBackend::new("/srv/photos")?)
    .user("alice", Access::Read)
    .remark("Family photos")
CallEffect
.remark(text) on ShareComment shown next to the share
.listed(false) on ShareOmits the share from listings. Still reachable by name; this is not access control
share_listing(false) on the builderDisables share listing

Network discovery

Requires the discovery feature. The server is announced while serve() runs and withdrawn before it returns. The listen address must not be loopback.

SmbServer::builder()
    .listen("[::]:445".parse()?)
    .share(Share::new("public", LocalFsBackend::new("/srv/public")?).public())
    .discovery(Discovery::new())
    .build()?

mDNS and DNS-SD

Advertises _smb._tcp on the listen port. Appears in the macOS Finder sidebar, GNOME Files, and Dolphin.

HostRegisters with
LinuxAvahi, when running
macOSmDNSResponder
WindowsDNS Client service
OtherwiseBuilt-in mDNS responder

The advertised name is Discovery::name if set. Otherwise it defaults to the NetBIOS name, except on macOS with neither name nor model set, where it uses the computer name.

WS-Discovery (Windows Explorer)

Appears in the Windows Explorer Network view under the NetBIOS name and workgroup.

Requirements:

  • a host other than Windows
  • port 445
  • a NetBIOS name matching the host name (otherwise a warning is logged)
  • network discovery enabled for the client’s network profile

Additional setup:

  • Listen on [::]:445. Windows may resolve the host name to IPv6 and connect over IPv6 only.
  • On macOS, run as root, or the OS may block the announcements.

NetBIOS name

Defaults to the first label of the host name in uppercase, truncated to 15 characters. Override it with netbios_name on the builder.

Firewall

PortPurpose
UDP 5353mDNS
UDP 3702WS-Discovery
TCP 5357WS-Discovery. If already in use, a free port is chosen and a warning is logged

Options

Configure Discovery::new() with:

CallSets
.name(name)Name displayed by file managers
.model(code)Model code macOS Finder uses to choose the server icon
.ws_discovery(bool)false disables WS-Discovery; true requires it and fails build() if it cannot be announced. When unset, it is announced whenever the requirements above are met
.workgroup(name)Workgroup shown in Windows (WORKGROUP by default)
.manufacturer, .model_name, .firmware_versionFields shown in the server’s Windows properties

Encrypted storage

Feature encryption, off by default. EncryptedBackend wraps another backend and encrypts file contents and, by default, file names under a 32-byte key. The inner backend stores ciphertext while clients see plaintext.

smb-server = { version = "0.12", features = ["encryption"] }

Local directory

use smb_server::{Access, EncryptedBackend, LocalFsBackend, Share};

let key: [u8; 32] = load_key()?;
let vault = EncryptedBackend::builder(LocalFsBackend::new("/srv/vault")?, key)
    .build()
    .await?;

let share = Share::new("vault", vault).user("alice", Access::ReadWrite);

The key must be 32 raw bytes supplied by the caller; the backend does not derive it from a passphrase.

S3 bucket

smb-server = { version = "0.12", features = ["s3", "encryption"] }
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
use smb_server::{Access, EncryptedBackend, S3Backend, Share, SmbServer};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let key: [u8; 32] = std::fs::read("/etc/smb/vault.key")?
        .try_into()
        .map_err(|_| "the key file must hold 32 bytes")?;

    let s3 = S3Backend::builder("https://s3.example.com", "us-east-1", "vault-bucket")
        .credentials("access-key", "secret-key")
        .cache_dir("/var/cache/smb-vault")
        .case_insensitive(false)
        .build()
        .await?;
    let vault = EncryptedBackend::builder(s3.clone(), key).build().await?;

    let server = SmbServer::builder()
        .listen("0.0.0.0:4445".parse()?)
        .user("alice", "password")
        .share(Share::new("vault", vault).user("alice", Access::ReadWrite))
        .build()?;
    server.bind().await?;

    let served = server.serve().await;
    s3.sync().await?;
    served?;
    Ok(())
}

When encrypting names, configure the inner S3Backend with case_insensitive(false). With the default true, looking up a missing key also lists the directory. The cache directory records the case setting, so build() rejects a cache created with the opposite value. Call sync() after serve() returns so pending changes reach the bucket; see backends.

What is protected

File contents are encrypted in blocks with AES-256-GCM, using a separate key per file. Every non-empty file starts with a header carrying a random file ID from which that file’s key is derived. File names are encrypted with AES-SIV unless encrypt_names(false) is set.

Someone with access to the inner backend’s storage still learns:

  • the exact size of every file and where it has holes (blocks never written)
  • the number of files and directories, and the shape of the directory tree
  • timestamps, attributes, and POSIX modes
  • the length of every name, and which names are identical across different directories
  • the block size and whether names are encrypted
  • between two snapshots of the storage, which blocks were rewritten and which files were truncated to zero
  • every file name, if encrypt_names(false) is set

Modifying bytes inside a block, moving a block to another offset or to a file with a different file ID, altering a file header, or reading a file encrypted under another key all cause reads to fail. Forged or altered names are omitted from listings and cannot be opened. See limitations for changes that go undetected. Every user allowed to open the share can read every file in it.

Settings

CallDefaultEffect
encrypt_names(bool)trueEncrypts file and directory names. Fixed when the share is created
block_size(bytes)64 KiBPlaintext bytes per block, a power of two from 8 KiB to 1 MiB. Fixed when the share is created
long_name_threshold(chars)255Longest stored name, 62 to 255 characters. Longer encrypted names are stored as <hash>.l (34 characters) next to a <hash>.n object holding the encrypted name. Fixed when the share is created; not allowed with encrypt_names(false)
case_insensitive(bool)trueMatches encrypted names without regard to case. With plaintext names, the inner backend’s rule applies
name_cache_ttl(duration)30 sHow long decrypted directory names are trusted against changes made outside this backend. Duration::ZERO re-lists the directory on every lookup that needs it. Applies only to case-insensitive encrypted names
restore_marker()OffAllows build() to write a new marker

encrypt_names, block_size, and long_name_threshold are stored in the marker. Any setting not specified on the builder uses the marker’s value (or its default for a new share), and specifying a value that differs from the marker fails build() with SettingMismatch. Out-of-range values fail with InvalidSetting. case_insensitive and name_cache_ttl are not stored in the marker and take their defaults unless set.

Marker

The root of the inner backend stores a 60-byte .smb-encryption marker containing the format version, the settings fixed at creation, a random 16-byte share ID, and an HMAC-SHA-256 over those fields using a key derived from the share key. Clients cannot list or open this file.

build() writes the marker into an empty root (unless the inner backend is read-only) and reads it from any non-empty root. It fails in these cases:

Root stateError
Marker has the right size, magic, and version, but HMAC verification fails (wrong key or tampered bytes after the version)KeyMismatch
Marker has the wrong size, wrong magic, or is a directoryMarkerInvalid
Marker uses a format version this release does not supportUnsupportedFormat
Root has entries but no markerMarkerMissing

A crash during the first build can leave a truncated marker, causing MarkerInvalid. Delete it and build again.

restore_marker() writes a new marker into a non-empty root that is missing one. The marker records the settings configured on the builder (or defaults), so pass the same settings the share was created with. Before writing, build() verifies the key and block size:

  • With encrypted names, at least one entry in the root must decode under the key.
  • The first non-empty file, found breadth-first within the first 10,000 entries, must have a header matching the chosen block size and a first block that is either a hole or verifies under the key.

If verification fails, build() returns KeyMismatch (or SettingMismatch for the block size) and writes nothing. With plaintext names, any file counts: a stray file such as .DS_Store encountered first in the root causes KeyMismatch until removed. With plaintext names and no non-empty files, no check can reject a wrong key.

Keys

  • Give each share its own key. If two shares share a key and block size, a stored file copied from one share’s storage can be read through the other.
  • The key is not stored anywhere. Losing the key loses the data. Losing the marker loses no data, but restore_marker() does not verify encrypt_names or long_name_threshold, so keep a record of those settings.
  • build() wipes the builder’s copy of the key once derived keys are created, and derived keys and AES key schedules are wiped on drop. Any copy retained by the caller is the caller’s responsibility to wipe. Not wiped: internal state in the hmac and sha2 crates, and the GHASH subkey in aes-gcm (which lives in each cipher and in copies made during setup and per operation; aes-gcm wipes only one temporary copy).

Damaged blocks

Reading a block that fails authentication returns STATUS_UNEXPECTED_IO_ERROR and logs a warning with the path, stored path, and block number. Reads elsewhere in the file still work, and a write covering the entire block replaces it. Client behavior:

ClientResult
Windows Explorer“Interrupted Action” (0x8007045D) with Try Again, Skip, and Cancel
robocopyRetries every 30 seconds up to a million times by default. Pass /R and /W (for example, /R:2 /W:1)
macOS FinderError -8084. Leaves a full-size copy filled with zeros after the point of failure
cp on macOS and Linux“Input/output error”

A copy inside the share fails the same way; Finder shows error -36 and leaves no file.

Limits

  • Contents: with random nonces, NIST SP 800-38D allows up to 2^32 block encryptions per key. This limit applies per file key: 256 TiB written to one file at 64 KiB blocks, 32 TiB at 8 KiB, or 4 PiB at 1 MiB, counting every block rewrite. Truncating a file to zero or overwriting it on open starts a new key. The backend does not track write counts.
  • Names: RFC 5297 advises at most 2^48 distinct AES-SIV invocations per key. The share uses one invocation per distinct name.

aarch64

On aarch64, AES and GHASH run in software unless the crate is built with both flags:

RUSTFLAGS="--cfg aes_armv8 --cfg polyval_armv8" cargo build --release

On aarch64 targets other than Linux, Android, and Apple platforms, also enable the aes target feature (for example, -C target-feature=+aes in RUSTFLAGS). Linux and Android detect it at runtime, and Apple platforms assume it.

Example

With --features encryption and SMB_ENCRYPTION_KEY set to 64 hex digits, the example adds a vault share backed by the vault directory inside SMB_ROOT, with alice read-write and bob read-only. When SMB_S3_BUCKET is also set (requiring --features s3,encryption), it encrypts the s3 share instead. An invalid key length or setting SMB_ENCRYPTION_KEY without the encryption feature stops the example.

SMB_ENCRYPTION_KEY='<64 hex digits>' cargo run -p minimal-smb-example --features encryption
  • Any 64 hex digits work as a key, such as the output of openssl rand -hex 32.
  • Toggling SMB_ENCRYPTION_KEY on or off while reusing an existing SMB_S3_CACHE fails due to the cache directory’s recorded case setting.

Limitations

Not supported:

  • SMB1
  • Kerberos, NTLMv1
  • Oplocks, directory leases
  • Answering a replayed CREATE with its original open
  • Persistent and resilient handles
  • Change notifications for changes made outside the server, except with LocalFsBackend on Linux for entries directly in a watched folder
  • Named pipes other than srvsvc; RPC beyond listing shares and describing the server
  • DFS
  • Multichannel, compression
  • Transports other than direct TCP (NetBIOS sessions, QUIC, RDMA)
  • SMB extended attributes with LocalFsBackend on macOS (macOS xattrs are exposed as named streams instead)
  • Security descriptors, quotas
  • Reparse points
  • Previous Versions snapshots
  • Time Machine
  • Discovery over NetBIOS

S3 backend

See backends for how S3Backend works and for the settings referenced below.

Writers and storage

  • Run only one server per bucket prefix. Concurrent writers to the same keys are last-writer-wins. Only a file partially modified by the server whose object was concurrently changed or deleted is moved to the conflicts subdirectory of the cache directory; the bucket keeps the other version.
  • A crash, or stopping without sync(), can lose file data written since it was last recorded in the cache directory. An unrecorded new file is lost; an unrecorded modification reverts to what is in the bucket. See cache directory for when data is recorded.
  • The maximum file size is bounded by the free space on the cache disk. Writes that do not fit fail with STATUS_DISK_FULL.
  • Modifying part of a large file downloads the rest of the file and re-uploads the entire object.
  • Server-side copy reads and writes data through the server.
  • On Windows hosts, directory entries in the cache directory are not fsynced.
  • Timestamps and attributes of the share root are kept in memory only and reset on restart.

Renames and deletes

  • Renames and deletes take effect immediately for clients and sync to the bucket in the background: a renamed file is written to its new key, and the old key is deleted once the new key holds its content. Deleted objects are removed in batches once no deletes have occurred for upload_delay (at most one minute after the first delete became due).
  • A directory rename moves at most max_dir_rename_objects objects, including entries held locally by the server. Larger directories fail with STATUS_ACCESS_DENIED without making any changes.
  • A directory cannot replace a file: renaming a directory over a file with ReplaceIfExists set fails with STATUS_ACCESS_DENIED.
  • A directory rename also fails with STATUS_ACCESS_DENIED when:
    • a key below the directory has a name no client can open
    • two keys would map to the same name
    • the move is too large to record in the cache directory
    • the new name differs from the old in case only and a sibling directory with the new spelling already exists
  • While a directory rename or delete is in progress, these operations fail with STATUS_SHARING_VIOLATION:
    • renaming or deleting a directory above or below it
    • creating or renaming anything below it
    • while a rename is moving entries, opening an existing entry below it that the server does not hold in memory
  • A directory rename also fails with STATUS_SHARING_VIOLATION when:
    • a subdirectory below it is still being created
    • the keys below it keep changing while being listed
  • Renaming a directory tree adds a marker object for each directory in the tree.
  • Renames that form a cycle (such as swapping two names through a third) download and re-upload one file per cycle; that file must fit in the free space on the cache disk.
  • When a file takes the name of a directory (or vice versa), the new object is uploaded after the old name’s object is deleted. If that delete can only happen after the new object is written (for example, swapping a file and a directory, or moving a directory’s only file onto the directory’s name), the new object is written without waiting. Object stores that represent directories as real folders reject this, leaving the entry in failures() until the next backend is built.
  • Copying an object for a rename or timestamp update applies the bucket’s default ACL rather than preserving the original ACL.
  • Copy requests do not attach an ETag condition to the source; if another writer replaces the source concurrently, the copy uses the replacement.
  • If the store rejects copying an object onto itself, timestamp and attribute changes on files larger than part_size are not persisted, and the server logs a warning.

Names and listings

  • By default, names are matched case-insensitively: a lookup that does not match any key exactly opens the first key that differs only in case. Uploads and deletes of keys differing only in case wait on each other, and creating a directory waits for pending deletes of any colliding key (failing with STATUS_UNEXPECTED_IO_ERROR after request_timeout).
  • On stores that treat names differing only in case as the same object, renaming a file to change only its casing keeps the old spelling in the bucket.
  • case_insensitive(false) requires a case-sensitive store. On a case-insensitive store, changing Doc overwrites or deletes doc.
  • A directory whose full listing (across all pages) exceeds request_timeout fails with STATUS_UNEXPECTED_IO_ERROR. With case-insensitive names, looking up a non-exact match in that directory (either a new name or an existing one with different casing) fails the same way.
  • A listing fetches stored timestamps for up to listing_metadata_max entries whose metadata is not yet cached. Beyond that limit, or if fetching an entry fails or times out, files report the store’s object modification time and directories report the time the backend was built.
  • Keys no client can open, such as names containing : or empty path components (a//b), are omitted from listings. Paths whose key exceeds 1024 bytes fail with STATUS_OBJECT_NAME_INVALID.
  • If a file and a directory have the same name, only the directory is shown.
  • Named streams and extended attributes are not supported. macOS clients store Finder metadata in ._ files, which are stored as regular objects in the bucket.

Reads and the store

  • Store requests for a single client request stop at request_timeout; slow responses fail with STATUS_UNEXPECTED_IO_ERROR.
  • Changes made outside the server do not trigger change notifications and can take up to metadata_ttl to become visible.
  • If an object is replaced outside the server, an open handle keeps reading cached chunks of the old version (up to 4 chunks per version, 128 MiB total) until it requests an uncached chunk, which fetches the new version.
  • For versioned buckets, see lifecycle rules.

Encrypted storage

See encrypted storage for how EncryptedBackend works and for the settings referenced below.

Integrity and visibility

  • These changes go undetected: restoring an older block or file, truncating a file at a block boundary, zeroing a block, appending zero blocks, swapping files, moving or copying a stored file, deleting files, and changing timestamps or attributes.
  • File sizes, timestamps, attributes, directory structure, and name lengths remain visible in the inner backend. See what is protected.
  • The backend does not enforce the per-key block encryption limit. See limits.

Writers and crashes

  • Run only one backend instance per stored tree. Another writer (such as a second backend built over the same tree) can cause read errors and lost updates. Clones of one backend share state, so multiple shares can safely serve the same tree through clones.
  • With case-insensitive names, case-variant lookups and creates use a cached directory listing refreshed every name_cache_ttl. Names added by another writer can go unseen for that duration.
  • With encrypted names, foreign entries (such as files placed in the inner backend manually) are omitted from listings, and clients cannot delete a directory that contains one. With plaintext names, every entry listed by the inner backend (except the marker) is visible.
  • A crash or power loss can render blocks being written unreadable. Power loss can also drop or tear any write since the last FLUSH.
  • After a crash involving a partial last block, an append or a write past it can render the old last block unreadable.
  • After a crash, a write into a new file starting at block 0 can leave an empty file.
  • A write that leaves a gap of blocks after a partial last block first pads that block with zeros. A crash between padding and writing can leave the file extended by the padding alone.
  • A write that fails at or past the previous end of the stored file truncates the file back to that end (or to the end of the padded last block once written), keeping existing data blocks readable. If that truncation also fails, a trailing fragment remains. The next write or truncate strips fragments up to 28 bytes; longer fragments are read as a partial last block and fail authentication.
  • A write that fails while overwriting existing blocks can tear them (for example, on a full disk where overwriting requires allocating new space).
  • Reading a damaged block fails with STATUS_UNEXPECTED_IO_ERROR. See damaged blocks.

Names

  • An encrypted name is roughly 1.6 characters per UTF-8 byte of the original name, plus 26 characters. Host path limits apply to stored names: ext4 limits names to 255 bytes, NTFS limits names to 255 UTF-16 units, and S3 keys are limited to 1024 bytes (which deep trees reach sooner). Encrypted names are ASCII, so byte and UTF-16 lengths match. On S3, keys exceeding 1024 bytes fail with STATUS_OBJECT_NAME_INVALID. Lowering long_name_threshold caps each stored name at that many characters.
  • At the default threshold, names longer than 143 UTF-8 bytes are stored as two objects. Listing a directory reads the second object for each such name the backend has not seen yet.
  • Names are stored exactly as the client spells them, without Unicode normalization, so composed and decomposed forms of the same name are distinct.
  • Windows rejects certain names as path components, such as DOS device names (con, nul.txt). A tree written on another OS and served from a Windows host omits those entries from listings, and directories containing them cannot be deleted as empty.
  • With plaintext names, clients cannot create or open .smb-encryption in the share root.

Features

  • Named streams and extended attributes are not supported. macOS clients store Finder metadata in ._ files, which are encrypted like any other file.
  • Block cloning is not supported. Server-side copy runs as reads and writes through the backend.
  • On aarch64, AES and GHASH run in software unless built with the flags in aarch64.