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
- Variables
- func ListenQUIC(addr string, tlsConf *tls.Config, opts ...QUICOption) (net.Listener, error)
- func ParseClientCAs(pemBytes []byte) (*x509.CertPool, error)
- func RequireClientCertificate(conf *tls.Config, caPEM []byte) error
- type Accepted
- type Acceptor
- type ClientConn
- func (c *ClientConn) CipherName() string
- func (c *ClientConn) Close() error
- func (c *ClientConn) Dialect() uint16
- func (c *ClientConn) Encrypted() bool
- func (c *ClientConn) Logoff(ctx context.Context) error
- func (c *ClientConn) Mount(ctx context.Context, share string) (*ClientShare, error)
- func (c *ClientConn) Signing() string
- type ClientDirEntry
- type ClientFile
- type ClientFsInfo
- type ClientInfo
- type ClientOptions
- type ClientShare
- func (s *ClientShare) Close(ctx context.Context) error
- func (s *ClientShare) Open(ctx context.Context, p string) (*ClientFile, error)
- func (s *ClientShare) ReadDir(ctx context.Context, p string) ([]ClientDirEntry, error)
- func (s *ClientShare) Remove(ctx context.Context, p string) error
- func (s *ClientShare) Stat(ctx context.Context, p string) (ClientInfo, error)
- func (s *ClientShare) Statfs(ctx context.Context) (ClientFsInfo, error)
- func (s *ClientShare) StatfsAt(ctx context.Context, p string) (ClientFsInfo, error)
- func (s *ClientShare) WriteFile(ctx context.Context, p string, data []byte) error
- type GSSError
- type GSSInitiator
- type QUICOption
- type Server
- func (s *Server) AddUser(user, password string)
- func (s *Server) AddUserHash(user string, ntHash []byte) error
- func (s *Server) Close() error
- func (s *Server) ListenAndServe(addr string) error
- func (s *Server) RemoveUser(user string)
- func (s *Server) Serve(ln net.Listener) error
- func (s *Server) SetName(name string)
- func (s *Server) Share(name string, fsys filesystem.Filesystem, opts ...ShareOption) error
- type ShareOption
- func Access(decide func(user string) (connect, write bool)) ShareOption
- func AllowUsers(users ...string) ShareOption
- func ReadOnly() ShareOption
- func RequireEncryption() ShareOption
- func UnstorableTimes(p TimePolicy) ShareOption
- func WithCapacity(total, avail uint64) ShareOption
- func WithCapacityFunc(f func() (total, avail uint64)) ShareOption
- func WriteUsers(users ...string) ShareOption
- type StatusError
- type TimePolicy
Constants ¶
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.
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.
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).
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.
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 ¶
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.
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.
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
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
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
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
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
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) 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.
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
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.
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.
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) AddUserHash ¶ added in v0.2.0
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) ListenAndServe ¶
ListenAndServe listens on addr and serves until Close.
func (*Server) RemoveUser ¶ added in v0.3.0
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) SetName ¶
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
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 )
Source Files
¶
- accept_errno.go
- access.go
- async.go
- attrs.go
- casefold.go
- ccm.go
- cl_conn.go
- cl_gss.go
- cl_ntlm.go
- cl_ops.go
- cl_wire.go
- clientcert.go
- cmac.go
- copychunk.go
- credit.go
- dir.go
- diskfull_errno.go
- doc.go
- encrypt.go
- fdlimit_unix.go
- file.go
- frame.go
- header.go
- inflight.go
- info.go
- ioctl.go
- kerberos.go
- limits.go
- lock.go
- md4.go
- negctx.go
- negotiate.go
- notify.go
- ntlm.go
- path.go
- pipe.go
- preauth.go
- seq.go
- server.go
- session.go
- settimes.go
- sign.go
- spnego.go
- srvsvc.go
- status.go
- transport_quic.go
- tree.go
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
|
