smb

package module
v0.22.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 29, 2026 License: BSD-3-Clause Imports: 40 Imported by: 5 modules, 4 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-filesystems/smb

smb

A pure-Go SMB2 server that exports any go-filesystems Filesystem, so a disk image can be mounted by the file manager of Windows, macOS or Linux with nothing installed on the client side.

Sibling of nfs, webdav and sftp, and the one those three cannot replace: SMB is what Windows speaks natively, and what macOS's Finder speaks best.

Why not "cifs"

mount -t cifs is what a Linux user types, and this is the server it connects to — but CIFS names SMB 1, which Windows removes by default and which this server will not speak. The one SMB1 frame it answers is the legacy greeting, and the answer is "let us speak SMB2".

Measured on macOS 26's client: it opens with an SMB1 NEGOTIATE offering NT LM 0.12, SMB 2.002 and SMB 2.???, and once told to use SMB2 it offers dialects 0x0202, 0x0210, 0x0300, 0x0302 and 0x0311 — no CIFS in sight.

Status

A share mounts, and you can work in it.

Verified with the macOS kernel client on macOS 26 — mount_smbfs, then ls, cat, a write, and a 512 KiB copy whose sha256 matches — over a FAT32 image served by go-filesystems/fat32. smbutil statshares reported SMB_3.0.2 and SIGNING_SUPPORTED TRUE (before 3.1.1 was added; the same client now settles on 3.1.1, see below).

And with the Linux kernel client in CI, which mounts it with no dialect named:

//127.0.0.1/disk on /mnt type cifs (rw,vers=default,username=alice,…)

And with Windows — the client this was written for. Windows 11 ARM64 25H2, New-SmbMapping, then dir, type, a subdirectory, a write, a rename, a delete, and a 512 KiB copy whose sha256 matches the host's. The client reports what it negotiated:

ServerName ShareName Dialect Signed Encrypted
---------- --------- ------- ------ ---------
10.0.2.100 IPC$      3.0.2     True     False
10.0.2.100 shared    3.0.2     True     False

Large reads and writes. The server claims multi-credit operations (SMB2_GLOBAL_CAP_LARGE_MTU, since v0.6.0) for 2.1 and 3.x, so a client reads and writes up to MaxReadSize/MaxWriteSize (1 MiB) per request. Without the claim, the foreign client this was first measured with (go-smb2) and the Linux kernel client both hold every request to 64 KiB. A request whose CreditCharge does not pay for what it sends or asks for is refused with STATUS_INVALID_PARAMETER (MS-SMB2 3.3.5.2.5). What counts is the payload of 3.1.5.2, the data within the variable-length field, not the fixed part of the request: a WRITE of exactly 64 KiB pays one credit (fixed in v0.17.1, issue #70). Measured through go-fileshare/fileshare: about ×2.2.

Server-side copy. FSCTL_SRV_REQUEST_RESUME_KEY and FSCTL_SRV_COPYCHUNK/_WRITE are answered (since v0.7.0), so a copy within a share -- Explorer's, or the Linux client's copy_file_range(2) -- is made on the server through hostcopy: a megabyte at a time, or copy_file_range(2) in the kernel between two files of the host, which shares blocks on btrfs and XFS. The bytes never cross the network. A request is held to Windows' limits (256 chunks, 1 MiB each, 16 MiB in all), a resume key names an open of the same session only, and byte-range locks hold as they do for READ and WRITE.

Signed True is why signing is implemented: Windows requires it. The per-user lists hold there too — a reader's write comes back as "The media is write protected", and a share allow does not name them as "Access is denied". See docs/verifying-with-windows.md for the recipe and the two traps that make this hard to do at all.

dialect negotiation including the 1996 greeting a modern client still opens with
NTLMv2 over SPNEGO the password never leaves the server
Kerberos over SPNEGO MS-KRB5 and Kerberos V5, through an Acceptor you provide (see below); the session key is the first 16 bytes of the context key, the whole key for AES-256 encryption on 3.1.1; a session ends with its ticket; Server.DisableNTLM makes the server Kerberos-only
opening, reading, writing positional through Opener/WritableFile, whole-file where a driver has neither
timestamps a driver with filesystem.TimesReader reports its own creation, access, write and change times, in FileBasicInformation, FileNetworkOpenInformation, the directory classes and CREATE; a time the format does not keep (FAT has no change time) is 0, "not specified" in MS-FSCC, never NOW. A driver without the capability still answers NOW for all four. Setting times (touch -d, cp -p, robocopy /COPY:T): SET_INFO FileBasicInformation maps LastAccessTime and LastWriteTime to MetadataSetter.Chtimes (the other one is read back through TimesReader so it is not clobbered); 0 keeps; -1 freezes the time on that handle (writes, resizes and the close put it back) and -2 resumes (MS-FSCC 2.4.7); below -2 is STATUS_INVALID_PARAMETER. A time that cannot be stored (a CreationTime, which the interface has no setter for; a ChangeTime on its own, since it is the server's clock and Chtimes refreshes it to now; an access or write time on a driver without Chtimes) follows the share's smb.UnstorableTimes(policy) option: smb.TimesIgnore (the zero value and default) answers success and drops it, as Samba does, so Explorer and robocopy /COPY:T copies keep working; smb.TimesRefuse answers STATUS_NOT_SUPPORTED and applies nothing in the request; smb.TimesLog ignores and writes one structured slog line (share, path, fields; path quoted and escaped) to Server.Logger (default slog.Default()). A value equal to what the driver reports is nothing to store. -1 on a driver with Chtimes but no TimesReader is always STATUS_NOT_SUPPORTED: that is a capability gap. FileAttributes are still accepted and dropped
listing, renaming, truncating, deleting including the chained requests macOS sends on every open, and the ones Windows sends whose FIRST operation is meant to fail
signing HMAC-SHA256 for 2.x, AES-CMAC for 3.x, and AES-GMAC on 3.1.1 when the client offers it (SMB2_SIGNING_CAPABILITIES), all implemented here
dialects 2.1, 3.0, 3.0.2 and 3.1.1 — Linux mounts with no vers= at all, and macOS mount_smbfs settles on 3.1.1
3.1.1 negotiate contexts (PREAUTH_INTEGRITY_CAPABILITIES with SHA-512, SIGNING_CAPABILITIES), the pre-authentication integrity hash over NEGOTIATE and SESSION_SETUP, and the signing key derived from it (SMBSigningKey), as MS-SMB2 3.3.5.4 and 3.3.5.5.3 describe. A 3.1.1 connection that sends FSCTL_VALIDATE_NEGOTIATE_INFO is terminated (3.3.5.15.12); on 3.0 and 3.0.2 the validation compares the dialect list, the GUID, the security mode and the capabilities, and a mismatch terminates the connection too
logins in progress each authentication in progress is keyed by the session id the server allocated at its first leg (3.3.5.5.1), so a connection can have several and an injected SESSION_SETUP with SessionId 0 starts an exchange of its own and cannot overwrite another's; at most 16 are held per connection, the oldest dropped first; a refused login ends its exchange
session ids the server chooses the id of a new session; a SESSION_SETUP naming an id it never gave out is STATUS_USER_SESSION_DELETED; one naming a live session is that session authenticating again, must be signed (or encrypted), must authenticate the same user, and leaves the session (keys, trees, handles) as it was (3.3.5.5, 3.3.5.5.2)
sessions every command but NEGOTIATE, SESSION_SETUP, ECHO and CANCEL must name an authenticated session (STATUS_USER_SESSION_DELETED otherwise, 3.3.5.2.9); a tree belongs to the session that connected it and LOGOFF drops it, with its handles and pending operations; an answer sent later is signed (or encrypted) with the key of the session that asked and is dropped when that session is gone. Session and signing keys are wiped at LOGOFF and at disconnect
per-source limits Server.MaxConnectionsPerSource (default 32) and Server.MaxPreAuthPerSource (default 16) bound what one remote address (an IPv6 address by its /64) may hold, in all and with no authenticated session, so one source flooding cannot lock out another. Over a cap the connection is closed at accept, logged once per burst, like the global caps; a negative value switches one off. Behind a NAT or proxy, where many clients share an address, raise them; loopback is not exempt
connection limits, continued Server.IdleTimeout (default 15 minutes, Windows' own autodisconnect): an authenticated connection with no open handle and no operation pending that has made no request for that long is closed. A connection whose last session logs off counts as unauthenticated again (a place in the cap, the clock started over), so valid credentials cannot hold every slot. The accept loop retries a temporary failure (EMFILE, ENFILE, ECONNABORTED, ECONNRESET) with a wait of 5 ms doubling to 1 s instead of ending, and only a closed listener ends it. Every connection is a descriptor: where the soft RLIMIT_NOFILE is below 1024 the default MaxConnections is three quarters of it (192 on macOS, whose limit is 256) so EMFILE is not what is reached first
connection limits Server.MaxConnections (default 1024, less where the descriptor limit is lower), Server.MaxPreAuthConnections (default 256: connections with no authenticated session) and Server.PreAuthTimeout (default one minute: a connection that has not authenticated by then is closed). A connection over a cap is closed as it is accepted, before a goroutine or buffer is spent, and the refusal is logged once per burst. A negative value switches a bound off. A flood of idle connections fills the unauthenticated cap and nothing more, and a client that logs in still gets in below it
replay the command sequence window (3.3.1.1, 3.3.5.2.3): { 0 } at the start, extended by the credits each reply carries, every MessageId (and the CreditCharge ids after it) usable once, CANCEL consuming none, the SMB1 greeting using up id 0. The credits a client holds unused are bounded (64 before anybody has authenticated on the connection, 2048 after; an answer sent later grants none, its credits went out in the interim reply). An id outside the window ends the connection, so a captured signed or encrypted frame sent again is refused. Measured with macOS mount_smbfs, go-smb2 and the Linux kernel client
signing required Server.RequireSigning makes the server the one that insists (SMB2_NEGOTIATE_SIGNING_REQUIRED in the NEGOTIATE response, every session held to it, whether or not the client asked; verified with go-smb2 that does not ask, macOS mount_smbfs and the Linux kernel client). Replies of a compounded chain are signed over their padding and NextCommand, as 3.1.4.1 says (they were not, which macOS found the moment the server required signing). A client that sets SMB2_NEGOTIATE_SIGNING_REQUIRED gets a session whose every request must be signed (or encrypted): an unsigned one is refused STATUS_ACCESS_DENIED (3.3.5.2.4), CANCEL excepted as 3.3.5.16 says. On 3.1.1 a TREE_CONNECT that is neither signed nor encrypted ends the connection (3.3.5.7; the specification's "not signed or not encrypted" is read as "neither", since the literal reading would refuse every signed-only request)
encryption AES-128-CCM on 3.0 and 3.0.2; on 3.1.1 AES-128-GCM, AES-128-CCM, AES-256-GCM, AES-256-CCM negotiated by the ENCRYPTION_CAPABILITIES context. TRANSFORM_HEADER, a key per direction, a nonce counter per session; a frame that fails to decrypt ends the connection. Offered by default (Server.DisableEncryption turns it off); required per share with smb.RequireEncryption() (SMB2_SHAREFLAG_ENCRYPT_DATA; unencrypted requests get STATUS_ACCESS_DENIED, a client that cannot encrypt is refused at TREE_CONNECT) or for every session with Server.EncryptData (SMB2_SESSION_FLAG_ENCRYPT_DATA; refused at SESSION_SETUP). Not done: SMB compression, and encrypted READs run one at a time rather than beside others
byte-range locks taken, released and enforced on reads and writes, including waiting for one
change notification on changes that go through this server — one made in the image by something else is invisible, because nothing underneath tells us
asynchronous replies STATUS_PENDING with an AsyncId, and CANCEL
per-user access who may connect (allow) and who may write (writers), per share — a reader is told so in the access mask rather than one refusal at a time
share enumeration NetrShareEnum over DCE/RPC on \srvsvc, listing what this user may connect to — verified against Samba's own client
streams, oplocks and leases not yet, and each answers by name rather than by silence

Enumeration is verified with Samba's smbclient -L, which is the reference implementation of the client side. macOS cannot judge it: smbutil view binds with ncacn_np:HOST[\pipe\srvsvc], and a named-pipe binding has no port field, so it dials 445 whatever the URL said — against a server on a high port it logs RPC to srvsrvc gave error 0x16c9a034, falls back to the SMB1 \PIPE\LANMAN call, and prints "unable to list resources: Broken pipe". A proxy between the two shows the tree connect to IPC$ and then nothing: the pipe is never opened. Serving on 445 needs privilege, so that check is a person's to run.

Windows found one defect nothing else could, and it is the reason to test against an operating system rather than a library: a chained request whose predecessor failed was carried out anyway. Windows checks that a rename's target name is free with a compounded CREATE + CLOSE in one message, and the CREATE is supposed to fail. The CLOSE that follows carries an all-ones file id — "the file the previous operation opened" — and with no such file it resolved to whatever the connection opened last: the source file, still held by the client. The next SET_INFO came back FILE_CLOSED and the rename failed with "The handle is invalid", about a handle the server had shut behind the client's back. macOS and Linux never send a chain whose first operation fails, and the Go client never chains at all.

What is still unchecked: this ran through a QEMU guest-forward rather than on port 445 itself; and the Windows run above predates 3.1.1 and encryption (it negotiated 3.0.2, Encrypted False) and has not been repeated.

3.1.1, read from the server's side. A session logs what it negotiated at Debug level on Server.Logger: dialect=3.1.1 signing=AES-128-GMAC cipher=AES-128-GCM, and a line saying the first request of the session really arrived encrypted. macOS 26's mount_smbfs negotiates exactly that (go test -tags macmount -run TestMacMount -v); the Linux kernel client in CI mounts with no vers= and the lane asserts the session says dialect=3.1.1; the in-house client, which checks the signature of the last SESSION_SETUP response, negotiates 3.1.1 and AES-GMAC in the unit tests, and reads and writes 560 kB through a share that requires encryption (AES-128 and AES-256; the 3.0 and 3.0.2 dialects were exercised end to end by go-smb2 until v0.22.0 and are now covered server-side only). A second Linux lane mounts a RequireEncryption share with no seal option and asserts that requests arrived encrypted.

Sizes a client names are bounded before they are allocated. Where a driver has neither positional writes nor Truncate, a WRITE or an end-of-file SET_INFO rewrites the whole file at its new size, so the client chooses the allocation. ⛔ Measured before the bound: one SET_INFO with end-of-file 2⁶³ panicked the server (slice bounds out of range), one with 2⁶² panicked it (makeslice: len out of range), and a WRITE at offset 2³⁸ was an allocation that would take it down. That path now grows a file by at most 8 MiB past its end and to at most 1 GiB, as go-filesystems/nfs does, and answers STATUS_DISK_FULL beyond; a negative offset or size is STATUS_INVALID_PARAMETER. A driver with WritableFile or Truncate is not limited by this: its own storage decides.

Concurrent requests (v0.8.0). A connection answers up to 32 requests at once (Server.MaxInFlight; -1 is the one-at-a-time server of v0.7) with a server-wide ceiling of 128 (Server.MaxInFlightTotal), both taken before a frame is read, so an idle connection holds nothing and a client that does not read its replies keeps its requests counted. Replies leave as they are ready, each carrying its own MessageId (MS-SMB2 3.3.1.1: the server accepts requests in any order and the client matches by MessageId). What runs beside others is a frame holding one READ of a plain file, under the share lock readers already shared; everything else is a barrier that waits for the requests before it and runs alone, which keeps the connection's tables single-writer. That includes a compound chain, answered whole and in order as MS-SMB2 3.3.5.2.7 requires ("The server MUST handle each individual operation that is described in the chain in order"), and the requests that go asynchronous (lock waits, CHANGE_NOTIFY), whose interim reply is sent by the barrier. WRITE is a barrier because it holds the share exclusively anyway. The credits granted are the protocol's own window and are unchanged. The mechanism is go-filesystems/inflight, shared with the NFS and SFTP servers. A client that sends half a frame and stops holds its slot and token for at most Server.RecordTimeout (30 s), and then loses the connection.

smbc, the client

The module also holds an SMB2/3 client: the package github.com/go-filesystems/smb/client and the command smbc.

go install github.com/go-filesystems/smb/cmd/smbc@latest

smbc ls    --credentials-file ~/.smbcred //nas/data/photos
smbc df    --credentials-file ~/.smbcred --human-readable //nas/data
smbc du    --credentials-file ~/.smbcred --summarize --human-readable //nas/data/photos
smbc check --credentials-file ~/.smbcred //nas/data
  • df asks FileFsFullSizeInformation (MS-FSCC 2.5.4); du is the apparent size, summed over concurrent directory listings (--jobs), symlinks never followed.
  • check connects, authenticates, tree-connects, lists the directory, then creates a temporary file, reads it back and deletes it. It prints one line per step and a verdict, and the exit status names the class: 10 connect, 11 auth, 12 tree connect, 13 read probe, 14 write probe, 2 usage.
  • Credentials come from two places only: --credentials-file PATH (mount.cifs format: username=, password=, domain=; refused unless the file is yours and mode 0600 or stricter) or --credential NAME, which reads $CREDENTIALS_DIRECTORY/NAME (systemd LoadCredentialEncrypted=). There is no flag and no environment variable that carries a password. Not on Windows yet: the mode and owner check has no Windows ACL equivalent, so the client refuses every credentials file there rather than read one unchecked.
  • NTLMv2, signing required, SMB 3.1.1 offered first, encryption required: every request is sent encrypted whether or not the server asks, and a server that cannot encrypt is refused (smbc exits 10, the error wraps ErrEncryptionRequired). --allow-unencrypted (Options.AllowUnencrypted) opts out, stays signed, and prints a warning. Checked against Samba 4.22 with server smb encrypt = required and desired (SMB_SAMBA_INTEROP=1 go test -run TestSambaEncryption, needs docker). Authentication is an interface (client.Authenticator); Kerberos plugs in there (client/krb).
  • Everything a server names is bounded: directory entries, walk size and depth, volume sizes (overflow refused), names with separators or .. dropped.

The protocol engine is our own since v0.21.0. The library (client.Dial) and smbc run on the in-house engine by default; the client package adds the safe name and credential handling, the bounds and the probe on top of it. The go-smb2 engine was removed in v0.22.0 and the module no longer depends on it. To migrate:

  • library: delete Options.Engine = client.EngineGoSMB2 (the in-house engine is the default and the only one; Options.Notify is deprecated and unused);
  • command line: drop --engine=go-smb2 (it now exits non-zero with an error; --engine=own is the default);
  • client.Initiator is now an alias of smb.GSSInitiator;
  • NTLM.Initiator returns an error: NTLM is driven by the engine from its Credentials, it has no GSS initiator.

Encryption stays required and --allow-unencrypted still warns. The in-house engine supports NTLMv2 and, since v0.21.1, Kerberos (below); any other custom client.Authenticator works on it too, through its Initiator. The tables below compare the engine with go-smb2 v0.1.1 and are historical.

Kerberos on the in-house engine (v0.21.1)

The SPNEGO exchange is driven by any client.Initiator, over several legs, with the mechListMIC checked and the session key taken from the initiator. Package client/krb is the Kerberos Authenticator (a separate package, so the core module has no Kerberos dependency): krb.FromCCache(path, krb5conf), krb.FromKeytab(keytab, user, realm, krb5conf) or krb.New(gokrb5Client); the SPN is cifs/<host>.

a, _ := krb.FromCCache("", "") // KRB5CCNAME
ses, err := client.Dial(ctx, target, client.Options{Auth: a})

Tested against the in-repo server, against a go-authn/kdc v0.13.0, and against Samba 4.22.11 with an MIT krb5 KDC 1.21.3 (signed and encrypted; a wrong server key is refused with STATUS_LOGON_FAILURE): SMB_INTEROP=1 go test . in interop/ (needs docker). Heimdal is not tested.

Session setup time. One setup (TCP connect, negotiate, Kerberos SESSION_SETUP, tree connect, close) over loopback to the in-repo server, with a warm ticket cache (both engines hold the same gokrb5 client and its service ticket, so no KDC is asked): SMB_BENCH=<rounds> go test -run TestKerberosSetupTiming .. (Historical: the benchmark went with go-smb2 in v0.22.0.) Measured 2026-11-29 19:54-19:56 CET on a bare-metal Linux host (32 cores), Go 1.27.4 cross-compiled binary pinned with taskset -c 13 and GOMAXPROCS=1, 1-min load 1.2-1.9. 10 rounds, the three sessions rotating so that each goes first, middle and last (A, B, A' / B, A', A ...); A' is a second own-engine session, its gap to A is the noise floor. Median (min-max):

Case go-smb2 own engine own engine (A/A) own vs go-smb2
signed 403 us (387-414) 353 us (320-361) 350 us (336-360) 1.14x faster
encrypted 411 us (406-418) 350 us (344-352) 351 us (345-357) 1.17x faster

Allocations per setup (go-smb2 / own): signed 2,165 / 2,086 (133 / 146 kB), encrypted 2,155 / 2,048 (132 / 133 kB). The own engine is faster and makes fewer mallocs; signed setup allocates 10 % more bytes, which the time does not show.

The in-house engine

ClientConn (cl_*.go) is an engine of our own: SMB 3.1.1 only, negotiate with preauth integrity, encryption and signing contexts, NTLMv2 with the SPNEGO mechListMIC, tree connect, create, query-info, query-directory, read, close. Encryption is required unless ClientOptions.AllowUnencrypted is set. It was measured against go-smb2 with a throwaway harness (not in this repository: it is a measuring tool, with no guard tests) against Samba 4.22 in a container, smb encrypt = required: dialect 0x311, AES-128-GCM, AES-128-GMAC signing interoperate.

Measured 2026-11-29 07:18-07:23 CET at commit f175693 (go-smb2 v0.1.1, smb v0.20.1), SMB 3.1.1, AES-128-GCM, signing AES-128-GMAC, encryption required. Method: bare-metal host (Ryzen 9 7950X, Zen 4, Linux 6.8), Samba 4.19.5 run as an unprivileged user on loopback (the host has no LXD or Docker we may use, so this is not the 4.22 of the earlier runs), server pinned to cores 2-3, client pinned with taskset -c 13 and GOMAXPROCS=1, Go 1.27.4 cross-compiled binary. Per round the three sessions run in the order A, B, A' and then reversed (A' is a second go-smb2 session: its gap to A is the noise floor). 6 kept rounds of 7 (one discarded: host load above the limit at its end); 1-min load at round start 1.7-4.0 (our own server and client account for about 1.5 of it), limit 4. The cases are: read and write of a 256 MiB file, du over 100,000 files in 1,000 directories, create 5,000 files of 4 KiB, read them back. Median of 6 (min-max); allocations are runtime.MemStats deltas of the median round.

Case (median, min-max) go-smb2 go-smb2 (A/A) own engine own vs go-smb2
read 256 MiB 208 ms (193-229) 198 ms (173-224) 149 ms (125-185) 1.4x faster
write 256 MiB 226 ms (213-236) 201 ms (194-212) 271 ms (240-273) 1.2-1.35x slower
du, 100k files 1.67 s (1.58-1.74) 1.65 s (1.61-1.75) 1.24 s (1.21-1.29) 1.35x faster
create 5,000 small files 7.44 s (7.34-7.49) 7.43 s (7.36-7.48) 6.93 s (6.86-7.01) 7% faster
read 5,000 small files 1.42 s (1.36-1.51) 1.41 s (1.38-1.56) 3.18 s (2.86-3.30) 2.2x slower
Allocations (median round) go-smb2 mallocs / bytes own engine mallocs / bytes
read 256 MiB 1,059 / 3.3 MB 756 / 269.5 MB
write 256 MiB 1,558 / 0.13 MB 232 / 806.1 MB
du, 100k files 256,057 / 39.4 MB 139,045 / 43.9 MB
create 5,000 small files 134,751 / 9.8 MB 74,762 / 28.3 MB
read 5,000 small files 159,751 / 59.1 MB 424,751 / 97.7 MB

That table is the engine at f175693 (v0.20.1): slower on a large write (one round trip at a time, three payload-sized allocations per chunk), 2.2 times slower on small reads (a READ per 512-byte io.ReadAll read) and allocating the file's size on a large read. v0.20.2 fixes the three (frames recycled, the request built in place, four 1 MiB writes in flight, read-ahead). Measured the same way on 2026-11-29 11:30 CET (7 rounds, none discarded, load 1.9-2.4):

Case (median, min-max) go-smb2 go-smb2 (A/A) own engine v0.20.2 own vs go-smb2
read 256 MiB 189 ms (177-212) 180 ms (172-192) 152 ms (143-164) 1.25x faster
write 256 MiB 209 ms (194-231) 199 ms (194-224) 106 ms (98-128) 2.0x faster
du, 100k files 1.61 s (1.59-1.71) 1.61 s (1.52-1.63) 1.22 s (1.17-1.23) 1.3x faster
create 5,000 small files 7.38 s (7.28-7.46) 7.47 s (7.22-7.59) 6.85 s (6.76-6.88) 7% faster
read 5,000 small files 1.38 s (1.33-1.41) 1.39 s (1.35-1.44) 1.04 s (0.99-1.08) 1.33x faster
Allocations (median round) go-smb2 mallocs / bytes own engine mallocs / bytes
read 256 MiB 1,054 / 2.2-3.3 MB 640 / 0.04 MB (was 756 / 269.5 MB)
write 256 MiB 1,561 / 0.13-2.2 MB 555 / 2.1 MB (was 232 / 806.1 MB)
du, 100k files 256,057 / 39.4 MB 135,041 / 33.8 MB
create 5,000 small files 134,763 / 9.8 MB 59,762 / 1.1 MB (was 74,762 / 28.3 MB)
read 5,000 small files 159,753 / 59.1 MB 104,752 / 53.5 MB (was 424,751 / 97.7 MB)

The engine is faster than go-smb2 on all five cases and makes fewer mallocs on all five. Allocation-count tests (cl_alloc_test.go) hold the client's heap per bulk read or write under 1/8 of the payload and a 4 KiB file under 25 allocations.

Reads are pipelined: io.Copy reaches WriteTo, which keeps four READs of up to MaxReadSize in flight on the granted credits, and frames, plain messages and pending slots are pooled (the earlier sequential version made one synchronous round trip per 8 KiB io.Discard read, 360 k mallocs). client runs on it. The server's final SESSION_SETUP response must carry its mechListMIC (RFC 4178 section 5): a stripped one is refused. Frames are bounded by the negotiated size, credits, interim responses, directory entries and idle batches; go-smb2 allocates up to 16 MiB from the frame's own length field.

Serving one from the command line

The command lives in its own product now: go-fileshare/fileshare, which serves the same images over SMB, NFS and WebDAV from one configuration — the same users, the same per-share access, in one place.

go install -tags nonfs,nowebdav github.com/go-fileshare/fileshare@latest   # SMB only

fileshare --image disk.img --user alice --password-file pw   # one image, now
fileshare --config /etc/fileshare.d                          # several, with users
fileshare check /etc/fileshare.d                             # before restarting it

cmd/smb-server used to live here and has been removed. Two reasons, and the second is the one that matters:

  • It could never be installed. Its go.mod carried replace github.com/go-filesystems/smb => ../.. so that it always built against this library's HEAD — and go install pkg@latest refuses a module with a replace directive outright. The line in this README telling people to run it was wrong for its whole life.
  • A person wants to share an image, not to run the SMB one. Which protocol carries it is a property of the client at the other end. One command that serves an image over SMB, NFS and WebDAV — with one set of users and one set of access rules — is the thing that was actually wanted, and a per-protocol command is that thing minus two protocols.

Building only SMB into it is a build tag, so the binary is not carrying what you did not ask for.

Serving one from Go

fs, err := fat32.Open("disk.img", -1)
if err != nil {
	return err
}
defer fs.Close()

srv := smb.New()
srv.AddUser("alice", "hunter2")
if err := srv.Share("disk", fs); err != nil {
	return err
}
return srv.ListenAndServe("127.0.0.1:4445")

Port 445 is the one a client dials without being told, and it needs privilege on every operating system — so the examples use a high port, and the mount command names it.

Kerberos, with no password

A client that holds a Kerberos ticket (a Windows machine that is not in a domain but has a ticket from your realm, a Linux box with sec=krb5) can log in without a password if the server accepts Kerberos in SPNEGO. Set Server.Kerberos to an smb.Acceptor, which this module leaves to you so that it keeps its one dependency:

type Acceptor interface {
	Accept(token []byte) (*smb.Accepted, []byte, error)
}

Accept gets the RFC 4121 token that carries the AP-REQ (always framed with the standard Kerberos OID: Windows frames it with the Microsoft one, 1.2.840.48018.1.2.2, and the server converts), and returns who the client is (Accepted.User, the name your allow and writers lists see; mapping a principal to it is your decision, and an unknown principal is an error, never a default), the AP-REP to send back, the context key, and when the ticket ends. The replay cache is the acceptor's. With a keytab and go-authn/krb5 or gokrb5 it is about forty lines; kerberos_test.go has one over gokrb5.

The NEGOTIATE response then lists MS-KRB5, Kerberos V5, and NTLMSSP, in that order, so a Windows client picks Kerberos. The first 16 bytes of the context key are Session.SessionKey ([MS-SMB2] 3.3.5.5.3 step 6; [MS-KILE] 3.1.1.2), from which the signing key and the 128-bit ciphers' keys derive. On 3.1.1 with AES-256-CCM or AES-256-GCM the encryption keys derive from the whole context key, Session.FullSessionKey (32 bytes for AES256 Kerberos; step 11), which NTLM does not have, so the two differ there. A key shorter than 16 bytes, or one for a ticket that has already expired, refuses the client. The key must be the AP-REP's subkey when mutual authentication is requested ([MS-KILE] 3.1.1.2; see Accepted.Key). A session ends when its ticket does: every command but LOGOFF, CLOSE and LOCK then answers STATUS_NETWORK_SESSION_EXPIRED (3.3.5.2.9) until the client authenticates again, which a Kerberos client does by itself.

Server.DisableNTLM = true makes the server Kerberos-only: NTLMSSP is not offered and is refused if sent, and Serve returns smb.ErrNeedKerberos when there is no acceptor, so the mistake shows at start-up rather than as every client's logon failure. Users added with AddUser are then of no use: a password is only ever checked by NTLM.

The mechListMIC of RFC 4178 section 5 is neither checked nor sent. It is optional only when the mechanism is the client's first choice (section 3.2 (c) II and section 5), so a Kerberos token behind a mechanism list that does not start with MS-KRB5 or Kerberos V5 (NTLMSSP first, say) is refused with STATUS_LOGON_FAILURE, without the acceptor seeing it; a Windows client lists MS-KRB5 first. NTLMSSP does not check the MIC either; that is a separate defect (go-filesystems/smb#67), not something this section fixes. IAKerb and PKU2U are not offered.

The size a client is told

The filesystem interface has no statfs, so a share reports a placeholder size (4 GiB, 2 GiB free) unless the caller says otherwise. smb.WithCapacity(total, avail) sets fixed numbers. smb.WithCapacityFunc(f) asks f at every size query (FileFsSizeInformation, FileFsFullSizeInformation), for a share whose free space or quota changes while it is served. f must be safe for concurrent use and must not block.

var total, avail atomic.Uint64 // kept up to date elsewhere
srv.Share("data", fs, smb.WithCapacityFunc(func() (uint64, uint64) {
	return total.Load(), avail.Load()
}))
SMB over QUIC

smb.ListenQUIC(addr, tlsConf) returns a net.Listener for SMB 3.1.1 over QUIC (UDP, TLS 1.3, ALPN smb, one bidirectional stream per connection); give it to Serve as any other. The certificate needs a DNS name in its SAN, which Windows 11 and Server 2025 clients check. No 0-RTT. Bounds: WithQUICMaxConnections (default 1024; over it a connection is closed with application error 1), WithQUICRetryRate (Initial packets per second before source-address validation by Retry, default 64), WithQUICWindows. A connection that never opens its stream is closed after 10 s.

Per [MS-SMB2] 3.3.5.4 a QUIC connection gets no multi-credit requests and no LARGE_MTU: every read and write is at most 64 KiB, so a 1 MiB read is sixteen round trips (go test -bench Transport -cpu 1 . against TCP). The SMB2_TRANSPORT_CAPABILITIES context is parsed, and with Server.DisableEncryptionOverSecureTransport the SMB-level encryption is left to TLS when the client says it accepts that.

smb.RequireClientCertificate(conf, caPEM) makes the handshake demand a client certificate chaining to the given CAs (ParseClientCAs refuses an empty, oversized, or non-certificate bundle). Kerberos is still what names the person. -tags noquic builds without it; ListenQUIC then returns ErrNoQUIC.

Security notes

  • A file handle belongs to the session and the tree that opened it. READ, WRITE, CLOSE, FLUSH, LOCK, IOCTL, QUERY_DIRECTORY, CHANGE_NOTIFY, QUERY_INFO and SET_INFO answer STATUS_FILE_CLOSED to a request of any other session or tree, even one that names the right FileId (MS-SMB2 3.3.5.9 to 3.3.5.13). Before v0.17.2 the lookup used the FileId alone, so a second session on the same connection could read, write and close another session's open file.
  • The all-ones FileId means "the file the previous operation of this compound opened" (MS-SMB2 3.3.5.2.7.2). It resolves only in a related operation, only within the same chain, and only to an open of the same session and tree.

Licence

BSD-3-Clause.

Documentation

Overview

Package smb implements an SMB2 server that exports any github.com/go-filesystems/interface.Filesystem, in pure Go with CGO_ENABLED=0 and no dependency outside the standard library. The client (package github.com/go-filesystems/smb/client and the smbc command) lives in its own sub-package and keeps this one free of its dependencies.

It is the sibling of go-filesystems/nfs, /webdav and /sftp, and the one they cannot replace: SMB is what Windows speaks natively — its NFS client is an optional feature and its WebDAV redirector is fragile — and it is what the macOS Finder speaks best.

Why the package is not called cifs

`mount -t cifs` is what a Linux user types, and this is the server it connects to. But CIFS names SMB 1, which Windows removes by default and which this server will not speak. Exactly one SMB1 frame is answered here: the legacy greeting, whose answer is "let us speak SMB2".

That is not a reading of the specification, it is what the client on the desk did. macOS 26 opens with an SMB1 NEGOTIATE offering "NT LM 0.12", "SMB 2.002" and "SMB 2.???"; told to use SMB2, it offers 0x0202, 0x0210, 0x0300, 0x0302 and 0x0311, and nothing older.

What is implemented

Dialects 2.1, 3.0, 3.0.2 and 3.1.1; NTLMv2 authentication over SPNEGO or raw, as the client prefers, or Kerberos over SPNEGO through the Acceptor in Server.Kerberos (with Server.DisableNTLM for a Kerberos-only server); signing, with HMAC-SHA256, AES-CMAC or (on 3.1.1, when the client offers it) AES-GMAC as the dialect requires; and the file operations a file manager performs: opening, reading, writing, listing, renaming, truncating and deleting.

3.1.1 is the whole of what [MS-SMB2] 3.3.5.4 and 3.3.5.5.3 ask of a server that is not encrypting: the negotiate contexts it reads (preauthentication integrity with SHA-512, signing capabilities; contexts of any other type are ignored), the pre-authentication integrity hash chained over NEGOTIATE and SESSION_SETUP, and the signing key derived from that hash with the SP800-108 counter-mode KDF (label "SMBSigningKey"). FSCTL_VALIDATE_NEGOTIATE_INFO on a 3.1.1 connection ends it, as 3.3.5.15.12 says.

That is enough for `mount -t cifs` on Linux -- with no vers= at all -- and for mount_smbfs on macOS, which settles on 3.1.1 signed with AES-GMAC; the Windows redirector was last measured, before 3.1.1, at 3.0.2 with Signed True. A session reports what it negotiated at Debug level on Server.Logger.

Several requests can arrive in ONE message, and the ones after the first may say they are RELATED: they carry no session or tree of their own, and an all-ones file id means "the file the previous operation opened". A related request whose predecessor FAILED is refused with the predecessor's status rather than carried out -- there is no such file, and doing it anyway acts on whatever the connection opened last. Windows checks a rename's target with a compounded CREATE + CLOSE whose CREATE is meant to fail; carrying out that CLOSE shut the client's source handle and the rename came back "The handle is invalid".

Encryption is here, for 3.0, 3.0.2 and 3.1.1 ([MS-SMB2] 2.2.41, 3.1.4.3, 3.3.4.1.4, 3.3.5.2.1.1, 3.3.5.2.9, 3.3.5.2.11, 3.3.5.5.3). 3.0 and 3.0.2 use AES-128-CCM, announced by the encryption capability bit; 3.1.1 negotiates one of AES-128-GCM, AES-128-CCM, AES-256-GCM and AES-256-CCM in an ENCRYPTION context, preferring them in that order. Each session derives a key per direction from its session key, a frame that begins with a TRANSFORM_HEADER is decrypted before it is read, and the reply is encrypted as one unit when the request was or when the session or the share requires it. A frame that cannot be decrypted, or that names another session than the one it was encrypted for, ends the connection. Compression, which can nest inside an encrypted message, is not negotiated, so a decrypted message that is not a plain SMB2 message ends the connection too.

A signature or an authentication tag proves who made a message, not that it is new, so the server also keeps the command sequence window of [MS-SMB2] 3.3.1.1 and 3.3.5.2.3: the MessageIds it will accept, { 0 } at the start and extended by the credits its replies carry. Each id is accepted once; a request outside the window -- a replayed one, or one nobody was granted -- ends the connection. The id is taken before the signature is verified, which is the order the specification gives (3.3.5.2.3 before 3.3.5.2.4): a forged request can use up an id, so it can end a connection, and cannot do more than a peer that closes the socket. The credits a client may hold unused are capped, fewer before anybody has authenticated.

Offering encryption changes nothing for a client that does not ask for it. Requiring it is two options: RequireEncryption on one share (TREE_CONNECT answers SMB2_SHAREFLAG_ENCRYPT_DATA, a request on the share that arrives in the clear is refused with STATUS_ACCESS_DENIED, and a client that cannot encrypt is refused at TREE_CONNECT), and Server.EncryptData for every session (SMB2_SESSION_FLAG_ENCRYPT_DATA; a client that cannot encrypt is refused at SESSION_SETUP). Server.DisableEncryption stops the server offering it.

A session logs what it negotiated at Debug level on Server.Logger: the dialect, the signing algorithm and the cipher; and, once per session, that a request really did arrive encrypted.

Not implemented: the rule that a 3.1.1 TREE_CONNECT neither signed nor encrypted ends the connection (3.3.5.7), and encrypted reads run one at a time rather than beside others, because only a plaintext frame is classified for that (see inflight.go).

Byte-range locks are here, and enforced: a read crosses a shared lock and stops at an exclusive one, a write stops at either, and a handle never conflicts with itself. A client that asks to WAIT for one is promised an answer and gets it when the holder lets go, or STATUS_CANCELLED if it gives up first.

Change notification is here too, on the same machinery, with one limit stated where it will be met: the changes reported are the ones that go THROUGH THIS SERVER. A file written into the image by something else is invisible, because nothing underneath tells us.

Both work because a reply may now be sent later: an interim STATUS_PENDING with an AsyncId, the loop carrying on reading, and the real answer whenever it is ready. CANCEL ends one, and so does closing the handle it was taken on.

A client can also ask what shares there ARE, rather than being told a name: TREE_CONNECT to IPC$, open \srvsvc, and call NetrShareEnum over DCE/RPC. The list is the shares this user may connect to -- see access.go -- and srvsvc.go is the three formats that carry it.

Not here: alternate data streams, security descriptors, oplocks and leases (so a client caches nothing), and the other pipes a client may ask for (\wkssvc, \lsarpc). Each of those answers by name rather than by silence.

Serving one

fs, err := fat32.Open("disk.img", -1)
if err != nil {
	return err
}
defer fs.Close()

srv := smb.New()
srv.AddUser("alice", "hunter2")
if err := srv.Share("disk", fs); err != nil {
	return err
}
return srv.ListenAndServe("127.0.0.1:4445")

Port 445 is the one a client dials without being told, and it needs privilege on every operating system -- so the examples use a high port, and the mount command names it:

mount_smbfs //alice@127.0.0.1:4445/disk /Volumes/disk          # macOS
mount -t cifs //127.0.0.1/disk /mnt -o port=4445,vers=2.1,...   # Linux

Where a password comes from

Server.AddUser takes the password. Server.AddUserHash takes its MD4 -- the "NT hash" -- which is what a directory keeps when it holds enough for SMB without holding the password: Samba's sambaNTPassword attribute, or a column beside it in a database.

It exists because NTLMv2 is a challenge-response. The client never sends the password, so a server must compute MD4(UTF16LE(password)) itself -- which means an LDAP BIND cannot authenticate an SMB session, and neither can a bcrypt. Worth being plain about: the hash IS the credential, and anybody holding it can authenticate as that person exactly as if they held the password.

Who gets what

A share with no lists on it is every authenticated user's, read-write. AllowUsers and WriteUsers narrow that, and compose:

srv.Share("photos", photos, smb.AllowUsers("alice", "bob"), smb.WriteUsers("alice"))

Bob may connect and read; Carol is refused at TREE_CONNECT with ACCESS_DENIED, which a client shows as a permission rather than a missing share. ReadOnly outranks both.

A reader is told so in the access mask of the reply that grants the share, not one refusal at a time: a client that was granted the write bits offers the actions and fails on each, which looks like a broken share.

When the disk is full

A driver error that is, or wraps, ENOSPC, EDQUOT or EFBIG answers STATUS_DISK_FULL (0xC000007F), as Samba's map_nt_error_from_unix does. EDQUOT deliberately does not answer STATUS_QUOTA_EXCEEDED: Samba notes that Windows applications need DISK_FULL there.

Index

Constants

View Source
const (
	// DefaultMaxInFlight is how many requests one connection has in progress
	// at once. macOS and Windows keep a few dozen reads outstanding.
	DefaultMaxInFlight = 32
	// DefaultMaxInFlightTotal bounds the requests in progress across every
	// connection: each READ holds up to maxReadSize (1 MiB) of reply, so memory
	// for them is at most about 128 MiB.
	DefaultMaxInFlightTotal = 128
)

Defaults for Server.MaxInFlight and Server.MaxInFlightTotal.

View Source
const (
	// DefaultMaxConnections is how many connections the server holds at once.
	DefaultMaxConnections = 1024
	// DefaultMaxPreAuthConnections is how many of them may have no authenticated
	// session. A client that is logging in holds a slot for a second or two; a
	// macOS mount uses two connections; a few hundred at once is a very large site
	// all mounting in the same instant.
	DefaultMaxPreAuthConnections = 256
	// DefaultPreAuthTimeout is how long a connection may take to authenticate
	// before it is closed. NTLM is two round trips, so a minute is generous.
	DefaultPreAuthTimeout = time.Minute
)

Limits on connections, and on what a connection may hold before it has proved who it is.

A connection costs a goroutine, buffers, a credit window and a place in the server's tables, and until somebody has authenticated on it, nothing has been earned. [MS-SMB2] leaves the policy to the server (3.3.5.1 on accepting a transport connection); a server that leaves loopback needs one, or a peer that opens connections and says nothing holds them for as long as it likes.

Three bounds, each with a default and each switched off by a negative value: the connections open, the ones among them that have no authenticated session, and how long one of those may stay silent of authentication.

View Source
const (
	DefaultMaxConnectionsPerSource = 32
	DefaultMaxPreAuthPerSource     = 16
)

Per-source bounds: one address (an IPv6 /64) cannot take every slot. Defaults are well under the global ones; a NAT or proxy in front of many clients raises them (or a negative value switches them off).

View Source
const DefaultIdleTimeout = 15 * time.Minute

DefaultIdleTimeout is how long an authenticated connection with no open handle and no operation pending may go without a request before it is closed. It is Windows' own "autodisconnect" (15 minutes), and a client whose mount is merely idle reconnects transparently; what it stops is valid credentials holding a slot forever.

View Source
const DefaultRecordTimeout = 30 * time.Second

DefaultRecordTimeout is how long the rest of a frame may take to arrive once its first byte has: 30 s, as in go-filesystems/nfs.

Variables

View Source
var ErrEncryptionRequired = errors.New("smb: encryption is required and the server does not offer it")

ErrEncryptionRequired is returned when encryption is required (the default) and the server cannot provide it.

View Source
var ErrNeedKerberos = errors.New("smb: DisableNTLM needs a Kerberos acceptor, or nobody can log in")

ErrNeedKerberos is what Server.Serve returns when NTLM is disabled and no Kerberos acceptor is set: a server that accepts neither would refuse every client, and the mistake belongs at start-up rather than in the first client's logon failure.

View Source
var ErrNoClientCA = errors.New("smb: the client CA file holds no certificate")

ErrNoClientCA is returned for a CA file with no certificate in it.

Functions

func ListenQUIC added in v0.18.0

func ListenQUIC(addr string, tlsConf *tls.Config, opts ...QUICOption) (net.Listener, error)

ListenQUIC listens on UDP addr and returns a net.Listener whose Accept yields one net.Conn per QUIC connection: its first bidirectional stream, with RemoteAddr the client's UDP address. Pass it to Server.Serve.

tlsConf must carry the server certificate. The listener forces TLS 1.3 and the ALPN "smb", never accepts 0-RTT, lets a peer open one bidirectional stream and no unidirectional one, and sends Retry when Initials arrive faster than WithQUICRetryRate. Set ClientAuth and ClientCAs on tlsConf to require a client certificate (see RequireClientCertificate).

func ParseClientCAs added in v0.18.0

func ParseClientCAs(pemBytes []byte) (*x509.CertPool, error)

ParseClientCAs reads a PEM bundle of CA certificates. It refuses a file with no certificate, one over 1 MiB, more than 64 certificates, a PEM block that is not a CERTIFICATE, and a certificate that does not parse, so a half-valid bundle never silently trusts less (or more) than the operator wrote.

func RequireClientCertificate added in v0.18.0

func RequireClientCertificate(conf *tls.Config, caPEM []byte) error

RequireClientCertificate makes conf demand a client certificate that chains to one of the CAs in caPEM (tls.RequireAndVerifyClientCert; Go checks the EKU Client Authentication). A client with none, or one from another CA, is refused in the handshake, before a byte of SMB is read.

Types

type Accepted added in v0.17.0

type Accepted struct {
	// User is the name the server's access rules see: the one a share's allow and
	// writers lists name, and the one [Server.Access] receives. Mapping a principal
	// to it is the EMBEDDER's decision (alice@EXAMPLE.ORG and alice@PARTNER.ORG are
	// different people), and an unknown principal is refused by returning an error
	// from Accept, never by returning an empty or default User.
	User string
	// Principal is who the client proved to be, in full ("alice@EXAMPLE.ORG"), for
	// the log.
	Principal string
	// Key is the GSS-API context key, at least 16 bytes (a shorter one refuses the
	// client). WHICH key matters, because the client derives its signing key from
	// the same one and a different key signs fine here and fails every request there:
	//
	//   - mutual authentication requested (Windows always does): the acceptor's
	//     subkey, the one the AP-REP carries. [MS-KILE] 3.1.1.2: "The subkey in the
	//     EncAPRepPart of the KRB_AP_REP message ... is used as the session key
	//     when MutualAuthentication is requested", and with AES "the subkeys are
	//     different and the subkey in the KRB_AP_REP message is used" (not the
	//     AP-REQ's). So an acceptor must put a subkey in its AP-REP and return it.
	//   - otherwise: the initiator's authenticator subkey, else the ticket's
	//     session key (RFC 4121 section 2).
	//
	// The server uses the first 16 bytes as Session.SessionKey and, on 3.1.1 with
	// an AES-256 cipher, the whole key as Session.FullSessionKey ([MS-SMB2]
	// 3.3.5.5.3 steps 6 and 11). It is a secret. The server copies it and wipes
	// its copy; the slice stays yours, and wiping it is yours too.
	Key []byte
	// Expires is when the ticket stops being valid, or the zero time for never. The
	// session then expires ([MS-SMB2] 3.3.5.5.3 step 15) and the client has to
	// authenticate again.
	Expires time.Time
}

Accepted is what a successful Acceptor.Accept establishes.

type Acceptor added in v0.17.0

type Acceptor interface {
	Accept(token []byte) (*Accepted, []byte, error)
}

Acceptor verifies a Kerberos AP-REQ for the server. The embedder provides it, which keeps this module free of a Kerberos library: a keytab-backed one is about forty lines over go-authn/krb5 or gokrb5.

Accept is handed the GSS-API token of RFC 4121 section 4.1 -- the InitialContextToken that carries the AP-REQ -- always framed with the Kerberos V5 OID (1.2.840.113554.1.2.2): the server has already rewritten the Microsoft OID a Windows client sends, so an implementation never sees it. It returns who the client is, the token to send back (the AP-REP when the client asked for mutual authentication, which Windows always does; framed with the same OID), and an error that refuses the client. Accept may be called by several connections at once. Replay detection (RFC 4120 section 3.2.3) belongs to it, since it holds the replay cache.

type ClientConn added in v0.20.1

type ClientConn struct {
	// contains filtered or unexported fields
}

ClientConn is one authenticated SMB 3.1.1 connection. It is safe for concurrent use: requests are multiplexed by MessageId.

func ClientDial added in v0.20.1

func ClientDial(ctx context.Context, nc net.Conn, o ClientOptions) (*ClientConn, error)

ClientDial negotiates, authenticates and returns a connection that signs (and, unless allowed otherwise, encrypts) everything after the authentication. It owns nc from here on.

func (*ClientConn) CipherName added in v0.20.1

func (c *ClientConn) CipherName() string

func (*ClientConn) Close added in v0.20.1

func (c *ClientConn) Close() error

Close drops the connection; pending requests fail.

func (*ClientConn) Dialect added in v0.20.1

func (c *ClientConn) Dialect() uint16

Dialect, CipherName and Encrypted report what was negotiated.

func (*ClientConn) Encrypted added in v0.20.1

func (c *ClientConn) Encrypted() bool

func (*ClientConn) Logoff added in v0.20.1

func (c *ClientConn) Logoff(ctx context.Context) error

Logoff ends the session and drops the connection.

func (*ClientConn) Mount added in v0.20.1

func (c *ClientConn) Mount(ctx context.Context, share string) (*ClientShare, error)

Mount tree-connects share. A share that requires encryption switches the connection to it; one that the server cannot encrypt for is refused.

func (*ClientConn) Signing added in v0.20.1

func (c *ClientConn) Signing() string

type ClientDirEntry added in v0.20.1

type ClientDirEntry struct {
	Name    string
	Size    int64
	Attrs   uint32
	ModTime time.Time
}

ClientDirEntry is one entry of a directory listing.

func (ClientDirEntry) IsDir added in v0.20.1

func (e ClientDirEntry) IsDir() bool

IsDir and IsReparse read the FILE_ATTRIBUTE bits.

func (ClientDirEntry) IsReparse added in v0.20.1

func (e ClientDirEntry) IsReparse() bool

type ClientFile added in v0.20.1

type ClientFile struct {
	// contains filtered or unexported fields
}

ClientFile is an open file, read-only.

func (*ClientFile) Close added in v0.20.1

func (f *ClientFile) Close() error

Close releases the handle.

func (*ClientFile) Read added in v0.20.1

func (f *ClientFile) Read(p []byte) (int, error)

func (*ClientFile) ReadAt added in v0.20.1

func (f *ClientFile) ReadAt(p []byte, off int64) (int, error)

ReadAt fills p from offset off, with the pieces of a large p read concurrently. It returns io.EOF when the file ends before p is full.

func (*ClientFile) Size added in v0.20.1

func (f *ClientFile) Size() int64

Size is the length the server reported at open.

func (*ClientFile) WriteTo added in v0.20.1

func (f *ClientFile) WriteTo(w io.Writer) (int64, error)

WriteTo copies the rest of the file to w with clReadWindow READs in flight, which is what io.Copy uses instead of a round trip per buffer. Each piece is written from the response it arrived in.

type ClientFsInfo added in v0.20.1

type ClientFsInfo struct {
	Unit, Total, Free, Avail uint64 // bytes per allocation unit, then units
}

ClientFsInfo is the share's capacity.

type ClientInfo added in v0.20.1

type ClientInfo struct {
	Name    string
	Size    int64
	Attrs   uint32
	ModTime time.Time
}

ClientInfo is what Stat knows.

func (ClientInfo) IsDir added in v0.20.1

func (i ClientInfo) IsDir() bool

type ClientOptions added in v0.20.1

type ClientOptions struct {
	User, Password, Domain string
	// GSS, when set, authenticates through this GSS-API initiator (Kerberos,
	// for one) over SPNEGO instead of NTLMv2 with User and Password.
	GSS GSSInitiator
	// Host is the server's name, for the SPN cifs/<Host> an NTLM exchange binds to.
	Host string
	// AllowUnencrypted turns OFF the requirement that every message after the
	// authentication is encrypted. Signing stays required either way.
	AllowUnencrypted bool
	// contains filtered or unexported fields
}

ClientOptions configure ClientDial.

type ClientShare added in v0.20.1

type ClientShare struct {
	// contains filtered or unexported fields
}

ClientShare is a tree connect.

func (*ClientShare) Close added in v0.20.1

func (s *ClientShare) Close(ctx context.Context) error

Close disconnects the tree.

func (*ClientShare) Open added in v0.20.1

func (s *ClientShare) Open(ctx context.Context, p string) (*ClientFile, error)

Open opens p for reading. ctx bounds every read made through the file.

func (*ClientShare) ReadDir added in v0.20.1

func (s *ClientShare) ReadDir(ctx context.Context, p string) ([]ClientDirEntry, error)

ReadDir lists a directory: QUERY_DIRECTORY until STATUS_NO_MORE_FILES, "." and ".." left out.

func (*ClientShare) Remove added in v0.20.1

func (s *ClientShare) Remove(ctx context.Context, p string) error

Remove deletes a file or an empty directory: it opens with DELETE and delete-on-close, and the close does the deletion.

func (*ClientShare) Stat added in v0.20.1

func (s *ClientShare) Stat(ctx context.Context, p string) (ClientInfo, error)

Stat opens p for its attributes only (a reparse point is not followed) and closes it.

func (*ClientShare) Statfs added in v0.20.1

func (s *ClientShare) Statfs(ctx context.Context) (ClientFsInfo, error)

Statfs reads FileFsFullSizeInformation through the share's root.

func (*ClientShare) StatfsAt added in v0.21.0

func (s *ClientShare) StatfsAt(ctx context.Context, p string) (ClientFsInfo, error)

StatfsAt reads the volume size through the directory p; a path that does not exist is an error, as for Stat.

func (*ClientShare) WriteFile added in v0.20.1

func (s *ClientShare) WriteFile(ctx context.Context, p string, data []byte) error

WriteFile creates or truncates p and writes data to it.

type GSSError added in v0.21.1

type GSSError struct{ Err error }

GSSError is a failure of the GSS initiator itself (no ticket, a bad AP-REP), as opposed to the server's refusal, which is a *StatusError.

func (*GSSError) Error added in v0.21.1

func (e *GSSError) Error() string

func (*GSSError) Unwrap added in v0.21.1

func (e *GSSError) Unwrap() error

type GSSInitiator added in v0.21.1

type GSSInitiator interface {
	// OID is the mechanism offered in the NegTokenInit.
	OID() asn1.ObjectIdentifier
	// InitSecContext returns the first token.
	InitSecContext() ([]byte, error)
	// AcceptSecContext consumes the server's token and returns the next one to
	// send, possibly empty.
	AcceptSecContext(sc []byte) ([]byte, error)
	// Sum is GSS_GetMIC: the mechListMIC over the list this client offered.
	Sum(bs []byte) []byte
	// SessionKey is the context's key, whole: the engine takes the first 16
	// bytes as Session.SessionKey and, for AES-256 ciphers, all of it as
	// Session.FullSessionKey ([MS-SMB2] 3.2.5.3.1).
	SessionKey() []byte
}

GSSInitiator is the client side of a GSS-API security context. It has the method set of the Initiator interface of the Go SMB clients on purpose (go-smb2's, until v0.22.0): whatever implements that implements this.

The engine calls InitSecContext once, then AcceptSecContext with each token the server sends back, then SessionKey when the server says the session is established. An initiator may also implement

Complete() bool                 reports that the context is established
VerifyMIC(msg, mic []byte) error  checks the server's mechListMIC

Without Complete the context counts as established after the first AcceptSecContext, or when the server finishes without sending a token (Kerberos without mutual authentication). Without VerifyMIC a mechListMIC the server sends is not checked (the offered list has one mechanism, so there is nothing to be walked down to).

type QUICOption added in v0.18.0

type QUICOption func(*quicOptions)

A QUICOption adjusts ListenQUIC.

func WithQUICMaxConnections added in v0.18.0

func WithQUICMaxConnections(n int) QUICOption

WithQUICMaxConnections bounds the QUIC connections the listener holds, both the ones waiting for their first stream and the ones accepted and not yet closed. Above it a new connection is closed with an application error.

func WithQUICRetryRate added in v0.18.0

func WithQUICRetryRate(perSecond int) QUICOption

WithQUICRetryRate sets how many Initial packets per second from addresses not yet validated the listener tolerates before it answers with a Retry (RFC 9000 8.1.2), which costs the client one round trip and the server no state. Under that rate no round trip is added.

func WithQUICWindows added in v0.18.0

func WithQUICWindows(stream, conn uint64) QUICOption

WithQUICWindows sets the largest flow-control windows, per stream and per connection, which bound what one peer that never reads can make the server buffer. Zero keeps the default (16 MiB each).

type Server

type Server struct {

	// MaxInFlight is how many requests one connection may have in progress at
	// once. Zero means [DefaultMaxInFlight]; a negative value means 1, the
	// one-request-at-a-time server of v0.7 and before. Set it before the first
	// connection.
	MaxInFlight int
	// Kerberos, when set, makes the server accept Kerberos in SPNEGO: it offers
	// MS-KRB5 and Kerberos V5 ahead of NTLMSSP, and hands the AP-REQ to the
	// acceptor. See [Acceptor]. Set it before the first connection.
	Kerberos Acceptor
	// DisableNTLM refuses NTLMSSP: the NEGOTIATE response does not offer it and a
	// client that sends it anyway is answered STATUS_LOGON_FAILURE. It needs
	// [Server.Kerberos], and [Server.Serve] returns [ErrNeedKerberos] without it.
	// The users added with [Server.AddUser] have no use then, since a password is
	// only ever checked by NTLM. Set it before the first connection.
	DisableNTLM bool
	// Logger receives the [TimesLog] lines. Nil means slog.Default(). (The
	// server had no logger before; this is its first.) Set it before the first
	// connection.
	Logger *slog.Logger
	// MaxInFlightTotal caps the requests in progress across every connection.
	// Zero or less means [DefaultMaxInFlightTotal]. A request takes its share
	// before its frame is read and gives it back when its reply is written, so
	// a client that does not read its replies keeps its requests counted.
	// Set it before the first connection.
	MaxInFlightTotal int
	// RecordTimeout bounds how long the rest of a frame may take once its
	// first byte has arrived: the request holds a slot and a token of the
	// budget meanwhile. Zero means [DefaultRecordTimeout]; a negative value
	// disables it. A frame that does not complete in time closes the
	// connection. Set it before the first connection.
	RecordTimeout time.Duration

	// EncryptData requires encryption of every session: a client that cannot
	// encrypt (SMB 2.1, or 3.x with no cipher in common) is refused at
	// SESSION_SETUP with STATUS_ACCESS_DENIED, and one that can is told to
	// (SMB2_SESSION_FLAG_ENCRYPT_DATA) and has any unencrypted request refused.
	// To require it of one share only, use [RequireEncryption]. Set it before
	// the first connection.
	EncryptData bool
	// RequireSigning makes the server require message signing of every client
	// ([MS-SMB2] 3.3.5.4: SMB2_NEGOTIATE_SIGNING_REQUIRED in the NEGOTIATE
	// response): every session is held to it, so a request that arrives neither
	// signed nor encrypted is refused with STATUS_ACCESS_DENIED whether or not
	// the client asked for signing. Windows clients require it already; this is
	// what makes the server the one that insists. Set it before the first
	// connection.
	RequireSigning bool
	// DisableEncryption stops the server offering encryption at all: no
	// ENCRYPTION context is answered on 3.1.1 and the capability is not claimed
	// on 3.0 and 3.0.2. It outranks [Server.EncryptData] and [RequireEncryption],
	// whose shares then refuse every connection. Set it before the first
	// connection.
	DisableEncryption bool
	// DisableEncryptionOverSecureTransport is [MS-SMB2] 3.3.1.4's
	// DisableEncryptionOverSecureTransport: on a QUIC connection, a client that
	// sets SMB2_ACCEPT_TRANSPORT_LEVEL_SECURITY in its SMB2_TRANSPORT_CAPABILITIES
	// context is told the server accepts it, and SMB 3.1.1 encryption is not
	// negotiated on that connection (TLS 1.3 already encrypts it). The default,
	// false, keeps SMB encryption and signing on top of TLS.
	DisableEncryptionOverSecureTransport bool
	// MaxConnections is how many connections the server holds at once; zero means
	// [DefaultMaxConnections] and a negative value no limit. A connection over the
	// limit is closed as it is accepted. Set it before the first connection.
	//
	// Every connection is a file descriptor, and so is every file a driver opens:
	// where the process's soft descriptor limit (RLIMIT_NOFILE) is below the
	// default, the default is three quarters of it (192 on macOS, whose limit is
	// 256) so that EMFILE is not what reaches first; raise the limit and set this
	// to use more.
	MaxConnections int
	// MaxPreAuthConnections is how many connections may have no authenticated
	// session; zero means [DefaultMaxPreAuthConnections], a negative value no
	// limit. A flood of connections that never log in fills this and nothing more,
	// and a client that does log in frees its place. Set it before the first
	// connection.
	MaxPreAuthConnections int
	// PreAuthTimeout is how long a connection may go without authenticating before
	// it is closed; zero means [DefaultPreAuthTimeout], a negative value never.
	// Set it before the first connection.
	PreAuthTimeout time.Duration
	// MaxConnectionsPerSource and MaxPreAuthPerSource bound what one remote
	// address (an IPv6 address by its /64) may hold, in all and with no
	// authenticated session; zero means [DefaultMaxConnectionsPerSource] (32) and
	// [DefaultMaxPreAuthPerSource] (16), a negative value no limit. One source
	// flooding cannot lock out another. Raise them behind a NAT or a proxy, where
	// many clients share an address. Loopback is not exempt. Set before the first
	// connection.
	MaxConnectionsPerSource int
	MaxPreAuthPerSource     int

	// IdleTimeout is how long an authenticated connection with no open handle and
	// no operation pending may go without a request before it is closed; zero
	// means [DefaultIdleTimeout], a negative value never. A connection whose last
	// session logs off counts as unauthenticated again. Set it before the first
	// connection.
	IdleTimeout time.Duration
	// contains filtered or unexported fields
}

A Server exports one or more shares over SMB2.

fs, err := fat32.Open("disk.img", -1)
…
srv := smb.New()
srv.AddUser("alice", "secret")
if err := srv.Share("disk", fs); err != nil {
	return err
}
return srv.ListenAndServe("127.0.0.1:4445")

Port 445 is the one clients dial without being told; it needs privilege on every OS, so the examples use a high port and the mount command names it.

func New

func New() *Server

New returns a server with no shares and no users. A server with no users authenticates nobody: SMB has no anonymous mode worth offering, and a client asked to mount without credentials is told so rather than let in.

func (*Server) AddUser

func (s *Server) AddUser(user, password string)

AddUser adds a set of credentials the server will accept.

func (*Server) AddUserHash added in v0.2.0

func (s *Server) AddUserHash(user string, ntHash []byte) error

AddUserHash adds a user whose password this server does not have, only its MD4 -- the "NT hash", which is what a directory keeps: Samba's sambaNTPassword attribute, or a column beside it in a database.

It exists because NTLMv2 is a challenge-response. The client never sends the password, so the server must compute MD4(UTF16LE(password)) itself; a site whose people live in LDAP cannot answer that with a bind and cannot answer it with a bcrypt. The hash IS the credential here, which is worth being plain about: anybody holding it can authenticate as that person, exactly as if they held the password. It is not a password hash in the sense a login form means, and storing it does not make a leak less bad.

The hash is 16 bytes. A shorter or longer one is refused rather than padded: a mangled hash would fail every login with "wrong password", which is the least useful thing a server could say.

func (*Server) Close

func (s *Server) Close() error

Close stops the listeners and drops every connection.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(addr string) error

ListenAndServe listens on addr and serves until Close.

func (*Server) RemoveUser added in v0.3.0

func (s *Server) RemoveUser(user string)

RemoveUser forgets a user: their next authentication fails. A session already established is not cut, as removing an account from a directory does not unmount what somebody already has open.

func (*Server) Serve

func (s *Server) Serve(ln net.Listener) error

Serve accepts connections until the listener is closed.

func (*Server) SetName

func (s *Server) SetName(name string)

SetName sets the NetBIOS-style name the server calls itself in the NTLM challenge. It is cosmetic -- clients show it -- but it must be stable across the two halves of an authentication, which is why it is a field and not a per-message decision.

func (*Server) Share

func (s *Server) Share(name string, fsys filesystem.Filesystem, opts ...ShareOption) error

Share exports a filesystem under a name. The name is what appears after the host in \\host\name, and SMB compares it without case.

type ShareOption

type ShareOption func(*share)

ShareOption changes how one share is exported.

func Access added in v0.3.0

func Access(decide func(user string) (connect, write bool)) ShareOption

Access hands the decision to the caller: decide is asked, when somebody connects, whether that user may connect and whether they may write. It replaces AllowUsers and WriteUsers for this share, and ReadOnly still wins over it.

It exists for a caller whose people change while the server runs -- a directory re-read every few minutes, people whose access follows groups an identity provider asserts -- and for whom a list given once, at Share, is a list that goes stale. The answer is asked at every TREE CONNECT and every share listing, so a change reaches the next connection; one already open keeps what it was given, as a mount does.

func AllowUsers

func AllowUsers(users ...string) ShareOption

AllowUsers names the only users who may connect to this share. Called more than once, the names accumulate.

func ReadOnly

func ReadOnly() ShareOption

ReadOnly refuses every write on this share, whatever the driver underneath would have allowed.

func RequireEncryption added in v0.13.0

func RequireEncryption() ShareOption

RequireEncryption makes this share refuse everything that is not encrypted ([MS-SMB2] 3.3.5.2.11, with Share.EncryptData and RejectUnencryptedAccess both TRUE). TREE_CONNECT answers SMB2_SHAREFLAG_ENCRYPT_DATA, so a client encrypts from then on; a request on the share that arrives unencrypted is answered STATUS_ACCESS_DENIED, and everything the server sends on it is encrypted. A client that cannot encrypt -- SMB 2.1, or 3.x with no cipher in common -- is refused at TREE_CONNECT with STATUS_ACCESS_DENIED.

func UnstorableTimes added in v0.10.0

func UnstorableTimes(p TimePolicy) ShareOption

UnstorableTimes sets the share's TimePolicy.

func WithCapacity added in v0.5.0

func WithCapacity(total, avail uint64) ShareOption

WithCapacity sets the total and available byte counts this share reports as its size and free space (FileFsSizeInformation and FileFsFullSizeInformation: what Explorer, Finder and `df` show).

A share given neither this nor WithCapacityFunc reports a placeholder -- 4 GiB with 2 GiB free -- because the Filesystem contract has no statfs, and zero free would make a client refuse every write before trying. A caller that knows the size (it opened the image) or the free space (it serves a directory, a quota) says so here. A zero total means "unknown" and keeps the placeholder.

func WithCapacityFunc added in v0.5.0

func WithCapacityFunc(f func() (total, avail uint64)) ShareOption

WithCapacityFunc is WithCapacity asked at every query instead of once: for a share whose free space goes down with every write, or whose quota is resized while it is served.

f runs on the connection's goroutine at every size query: it must be safe for concurrent use and must not block, because the client waits for it. A caller whose numbers are slow to obtain keeps the last ones it has and refreshes them elsewhere. Of the two options, the one given last wins; a nil f is the same as never giving either.

func WriteUsers

func WriteUsers(users ...string) ShareOption

WriteUsers names the only users who may write to this share. Everyone else who may connect gets it read-only.

type StatusError added in v0.20.1

type StatusError struct {
	Command string
	Status  uint32
}

StatusError is a non-success NTSTATUS a server answered a command with.

func (*StatusError) Error added in v0.20.1

func (e *StatusError) Error() string

func (*StatusError) Is added in v0.20.1

func (e *StatusError) Is(target error) bool

Is maps the statuses a caller tests for onto the os errors, so errors.Is(err, os.ErrNotExist) works as for a local file.

type TimePolicy added in v0.10.0

type TimePolicy uint8

TimePolicy says what a share does with a time a client sets and the server cannot store: a CreationTime (the filesystem interface has no setter for it), a ChangeTime on its own (it is the server's own clock; see setBasicTimes), and a LastAccessTime or LastWriteTime on a driver without filesystem.MetadataSetter. The zero value is TimesIgnore.

It does not cover -1 on a driver that has Chtimes but no filesystem.TimesReader: that is a capability gap (the value to freeze cannot be read), not a stored field being dropped, and it is always STATUS_NOT_SUPPORTED. Nor does it change how malformed values are answered.

const (
	// TimesIgnore answers success and drops the unstorable fields silently, as
	// Samba's smb_set_file_time does, so a copy that preserves times (Windows
	// Explorer, robocopy /COPY:T) keeps working. It is the default.
	TimesIgnore TimePolicy = iota
	// TimesRefuse answers STATUS_NOT_SUPPORTED (MS-SMB2 3.3.5.21.1) and applies
	// nothing in that request, so a backup tool never believes an unstored time
	// was kept.
	TimesRefuse
	// TimesLog is TimesIgnore plus one structured slog line per request, naming
	// the share, the path and each dropped field. The path is client-supplied and
	// is written quoted and ASCII-escaped, so it cannot forge a log line.
	TimesLog
)

Directories

Path Synopsis
Package client is an SMB2/3 client for the shares this module serves and for any other SMB server: connect, authenticate (pluggable), mount a share, list, size, walk and probe it.
Package client is an SMB2/3 client for the shares this module serves and for any other SMB server: connect, authenticate (pluggable), mount a share, list, size, walk and probe it.
krb
Package krb is the Kerberos Authenticator of the SMB client: a GSS-API initiator ([RFC 4121]) that the in-house engine drives through SPNEGO ([RFC 4178]).
Package krb is the Kerberos Authenticator of the SMB client: a GSS-API initiator ([RFC 4121]) that the in-house engine drives through SPNEGO ([RFC 4178]).
smbc
Package smbc is the smbc command: ls, df, du and check against an SMB share.
Package smbc is the smbc command: ls, df, du and check against an SMB share.
cmd
smbc command
Command smbc is an SMB2/3 client: ls, df, du, check.
Command smbc is an SMB2/3 client: ls, df, du, check.
smb-server module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址