feat: add experimental standalone SMB service for Finder
This commit is contained in:
55 files changed
+7961
-10
No files matched your search
@@ -0,0 +1,202 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Embedded SMB implementation
|
||||
|
||||
Imported from [softwarity/smbserver v0.1.1](https://github.com/softwarity/smbserver/tree/v0.1.1), commit `88586e668400859c882428b308408c26086bb1d5` (2026-10-04). Go module checksum: `h1:TV8VpKrzyiaZGUl9A6+ES4rdOEY4NMRp+xo9LYojXxY=`. Apache-2.0 license retained in `LICENSE`. All upstream top-level Go source, unit, socket and fuzz tests were imported; its command, CI and native-client integration scripts were not imported. Package name remains `smbserver`.
|
||||
|
||||
This is a maintained local adaptation, not an unmodified dependency. RouterShelf changes:
|
||||
|
||||
- Four connections, two sessions/connection, two trees/session, 64 open handles/server, eight compound commands, 128 credits and 64 KiB I/O. Directory scans fail explicitly above 1,024 entries; byte-range locks are bounded to 128/file. Five-minute authenticated read deadline.
|
||||
- `DiskMetadata` rejects named streams and removes their capability advertisement; permits `.DS_Store` and disk AppleDouble sidecars. RouterShelf always enables it. Upstream's bounded ephemeral streams remain for upstream regression tests, inaccessible through the shipped command.
|
||||
- Filesystem case sensitivity is explicitly configurable for exFAT. Failed filesystem size queries return an error rather than synthetic capacity.
|
||||
- Bidirectional share access checks before opening/truncating, byte-range lock enforcement on data I/O and truncation, write-through and close synchronization, close/delete error reporting, and access checks on attribute changes. Nonblocking file opens verify the actual regular-file identity before truncating to avoid blocking on a replaced FIFO. Unsupported ACL and per-file protection-mode changes return an error in the RouterShelf profile.
|
||||
- Protocol trace via environment disabled, preventing accidental filenames in logs. Optional explicit diagnostics report numeric commands/status/credits and peer events without filenames or authentication tokens. Upstream authentication test isolated into subtests for the smaller connection bound.
|
||||
- Added RouterShelf policy, metadata, sharing, transfer integrity and reconnect regression tests. Startup can require an expected root identity and signals ready only after confinement is initialized.
|
||||
|
||||
Review upstream changes and security issues before updating. Reapply/review each adaptation and run `make test`, race checks, fuzz checks and both builds. Require native Finder and target validation before promoting support claims. This young implementation has not received a RouterShelf independent security audit; it is for private trusted clients, never Internet exposure. Its internal API is not a supported public RouterShelf library.
|
||||
|
||||
The initial 16-credit adaptation stalled the native macOS client before mkdir; 128 credits passed the local native smoke check. Credits bound the request window, while the synchronous parser and frame/I/O limits independently bound allocations. Preserve this native-client regression check when tuning credits.
|
||||
@@ -0,0 +1,434 @@
|
||||
// Modified by RouterShelf. See UPSTREAM.md for adaptation details and Apache-2.0 provenance.
|
||||
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"runtime/debug"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// conn is one TCP connection. Its requests are handled one at a time, in
|
||||
// order, by the goroutine that reads them.
|
||||
type conn struct {
|
||||
srv *server
|
||||
nc net.Conn
|
||||
// wmu serialises the writes: besides the responses, a connection
|
||||
// carries the oplock breaks caused by other clients.
|
||||
wmu sync.Mutex
|
||||
|
||||
negotiated bool
|
||||
smb1Seen bool
|
||||
dialect uint16
|
||||
maxIO uint32
|
||||
// What the client said in NEGOTIATE, for its later validation.
|
||||
clientGUID [16]byte
|
||||
clientCaps uint32
|
||||
clientSecMode uint16
|
||||
|
||||
// credits is the number of credits the client currently holds.
|
||||
credits int
|
||||
authenticated bool
|
||||
|
||||
// mu guards sessions, which another connection reaches when a client
|
||||
// that reconnected retires its previous session.
|
||||
mu sync.Mutex
|
||||
sessions map[uint64]*session
|
||||
}
|
||||
|
||||
// request is one command of a message, with what the connection resolved
|
||||
// about it before calling the handler.
|
||||
type request struct {
|
||||
hdr header
|
||||
// msg is the command, header included, so that the offsets of the
|
||||
// protocol index it directly.
|
||||
msg []byte
|
||||
sess *session
|
||||
tree *tree
|
||||
chain *chain
|
||||
// sign tells that the response must be signed: the request was, or
|
||||
// this is the response that concludes a session setup.
|
||||
sign bool
|
||||
// fatal makes the connection close once the response is sent.
|
||||
fatal bool
|
||||
// silent suppresses the response (CANCEL has none).
|
||||
silent bool
|
||||
// note is what a handler wants the trace to say about the request.
|
||||
note string
|
||||
}
|
||||
|
||||
// chain is the state shared by the commands of a compound request: a related
|
||||
// command inherits the session, tree and file of its predecessor.
|
||||
type chain struct {
|
||||
sessionID uint64
|
||||
treeID uint32
|
||||
fileID uint64
|
||||
hasFile bool
|
||||
// status is why there is no file, when a CREATE of the chain failed.
|
||||
status ntStatus
|
||||
}
|
||||
|
||||
var errProtocol = errors.New("protocol violation")
|
||||
|
||||
// trace logs every command and its status through Config.Logf. It exists to
|
||||
// diagnose a client from the outside, in CI for instance.
|
||||
var trace = false
|
||||
|
||||
func (c *conn) serve() {
|
||||
defer c.close()
|
||||
defer func() {
|
||||
// Last line of defence: a bug in a decoder must cost the
|
||||
// offending connection, never the process embedding the server.
|
||||
if p := recover(); p != nil {
|
||||
c.srv.logf("panic serving %v: %v\n%s", c.nc.RemoteAddr(), p, debug.Stack())
|
||||
}
|
||||
}()
|
||||
for {
|
||||
timeout := 5 * time.Minute
|
||||
if !c.authenticated {
|
||||
timeout = preAuthTimeout
|
||||
}
|
||||
c.nc.SetReadDeadline(time.Now().Add(timeout))
|
||||
msg, err := c.readFrame()
|
||||
if err == nil {
|
||||
err = c.handleFrame(msg)
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, errProtocol) {
|
||||
c.srv.logf("closing %v: %v", c.nc.RemoteAddr(), err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *conn) readFrame() ([]byte, error) {
|
||||
var h [4]byte
|
||||
if _, err := io.ReadFull(c.nc, h[:]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n := int(h[1])<<16 | int(h[2])<<8 | int(h[3])
|
||||
limit := preAuthFrame
|
||||
if c.authenticated {
|
||||
limit = maxIO + 0x10000
|
||||
}
|
||||
// The first byte is the NetBIOS session message type, zero on the
|
||||
// direct TCP transport, which is the only one served.
|
||||
if h[0] != 0 || n < 4 || n > limit {
|
||||
return nil, fmt.Errorf("%w: frame type %d of %d bytes", errProtocol, h[0], n)
|
||||
}
|
||||
msg := make([]byte, n)
|
||||
if _, err := io.ReadFull(c.nc, msg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return msg, nil
|
||||
}
|
||||
|
||||
func (c *conn) handleFrame(msg []byte) error {
|
||||
if msg[0] == 0xFF && msg[1] == 'S' && msg[2] == 'M' && msg[3] == 'B' {
|
||||
return c.smb1Negotiate(msg)
|
||||
}
|
||||
return c.handleMessage(msg)
|
||||
}
|
||||
|
||||
// handleMessage processes a message, which is one command or a compound
|
||||
// chain of them, and sends the responses as one message.
|
||||
func (c *conn) handleMessage(msg []byte) error {
|
||||
var (
|
||||
payload []byte
|
||||
ch chain
|
||||
fatal bool
|
||||
)
|
||||
for off, n := 0, 0; ; n++ {
|
||||
hdr, ok := parseHeader(msg[off:])
|
||||
if !ok || n >= maxCompound {
|
||||
return errProtocol
|
||||
}
|
||||
end := len(msg)
|
||||
if hdr.next != 0 {
|
||||
if hdr.next < headerSize || hdr.next%8 != 0 || int(hdr.next) > len(msg)-off-headerSize {
|
||||
return errProtocol
|
||||
}
|
||||
end = off + int(hdr.next)
|
||||
}
|
||||
r := &request{hdr: hdr, msg: msg[off:end], chain: &ch}
|
||||
out, err := c.process(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fatal = fatal || r.fatal
|
||||
if out != nil {
|
||||
// Each response of a compound is padded to eight bytes,
|
||||
// linked to the next one, and signed on its own.
|
||||
if hdr.next != 0 {
|
||||
out = pad8(out)
|
||||
le.PutUint32(out[20:], uint32(len(out)))
|
||||
}
|
||||
if r.sign && r.sess != nil && r.sess.signingKey != nil {
|
||||
signWith(r.sess.mac, out)
|
||||
}
|
||||
if payload == nil {
|
||||
payload = out
|
||||
} else {
|
||||
payload = append(payload, out...)
|
||||
}
|
||||
}
|
||||
if hdr.next == 0 {
|
||||
break
|
||||
}
|
||||
off = end
|
||||
}
|
||||
if payload != nil {
|
||||
if err := c.send(payload); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if fatal {
|
||||
return errProtocol
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// process runs one command and returns its response, header included, or nil
|
||||
// when the command has none.
|
||||
func (c *conn) process(r *request) ([]byte, error) {
|
||||
h := &r.hdr
|
||||
if h.flags&flagResponse != 0 {
|
||||
return nil, errProtocol
|
||||
}
|
||||
// CANCEL is the one command that consumes no credit.
|
||||
if h.command != cmdCancel {
|
||||
charge := max(int(h.creditCharge), 1)
|
||||
if charge > c.credits {
|
||||
return nil, fmt.Errorf("%w: credit charge %d exceeds the %d granted", errProtocol, charge, c.credits)
|
||||
}
|
||||
c.credits -= charge
|
||||
}
|
||||
|
||||
st, out := c.route(r)
|
||||
if trace {
|
||||
c.srv.logf("%v: command %d message %d flags %#x %s: status %#x", c.nc.RemoteAddr(), h.command, h.messageID, h.flags, r.note, uint32(st))
|
||||
}
|
||||
if r.silent {
|
||||
return nil, nil
|
||||
}
|
||||
// A response carries its body only on success and on the warnings
|
||||
// that return data; everything else gets the error body.
|
||||
if out == nil {
|
||||
out = errorBody(nil)
|
||||
}
|
||||
|
||||
rh := header{
|
||||
creditCharge: h.creditCharge,
|
||||
status: st,
|
||||
command: h.command,
|
||||
flags: flagResponse | h.flags&flagRelated,
|
||||
messageID: h.messageID,
|
||||
sessionID: h.sessionID,
|
||||
treeID: h.treeID,
|
||||
}
|
||||
if r.sess != nil {
|
||||
rh.sessionID = r.sess.id
|
||||
}
|
||||
if r.tree != nil {
|
||||
rh.treeID = r.tree.id
|
||||
}
|
||||
// Grant what the client asks, within the window, and never leave it
|
||||
// without a credit to send its next request.
|
||||
grant := min(max(int(h.credits), 1), maxCredits-c.credits)
|
||||
c.credits += grant
|
||||
rh.credits = uint16(grant)
|
||||
if c.srv.cfg.Logf != nil {
|
||||
c.srv.logf("command=%d status=%#x charge=%d grant=%d available=%d", h.command, uint32(st), h.creditCharge, grant, c.credits)
|
||||
}
|
||||
rh.put(out)
|
||||
|
||||
r.chain.sessionID = rh.sessionID
|
||||
r.chain.treeID = rh.treeID
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// route authenticates the command and dispatches it. Nothing below the
|
||||
// session lookup runs for a peer that has not logged in.
|
||||
func (c *conn) route(r *request) (ntStatus, []byte) {
|
||||
h := &r.hdr
|
||||
if !c.negotiated {
|
||||
if h.command != cmdNegotiate {
|
||||
r.fatal = true
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
return c.negotiate(r)
|
||||
}
|
||||
switch h.command {
|
||||
case cmdNegotiate:
|
||||
// A second NEGOTIATE on a connection is a protocol violation.
|
||||
r.fatal = true
|
||||
return statusInvalidParameter, nil
|
||||
case cmdSessionSetup:
|
||||
return c.sessionSetup(r)
|
||||
case cmdEcho:
|
||||
// Clients send keepalive echoes outside of any session.
|
||||
if h.sessionID == 0 {
|
||||
return statusSuccess, emptyBody()
|
||||
}
|
||||
}
|
||||
|
||||
sid, tid := h.sessionID, h.treeID
|
||||
if h.flags&flagRelated != 0 {
|
||||
sid, tid = r.chain.sessionID, r.chain.treeID
|
||||
}
|
||||
sess := c.session(sid)
|
||||
if sess == nil || !sess.authenticated {
|
||||
return statusUserSessionDeleted, nil
|
||||
}
|
||||
// Signing is required: an unsigned or badly signed request is refused
|
||||
// whatever the client negotiated.
|
||||
if h.flags&flagSigned == 0 || !verifyWith(sess.mac, r.msg) {
|
||||
return statusAccessDenied, nil
|
||||
}
|
||||
r.sess = sess
|
||||
r.sign = true
|
||||
|
||||
switch h.command {
|
||||
case cmdLogoff:
|
||||
sess.close()
|
||||
return statusSuccess, emptyBody()
|
||||
case cmdTreeConnect:
|
||||
return c.treeConnect(r)
|
||||
case cmdEcho:
|
||||
return statusSuccess, emptyBody()
|
||||
case cmdCancel:
|
||||
// No request ever stays pending, so there is nothing to cancel.
|
||||
r.silent = true
|
||||
return statusSuccess, nil
|
||||
}
|
||||
|
||||
tree := sess.tree(tid)
|
||||
if tree == nil {
|
||||
return statusNetworkNameDeleted, nil
|
||||
}
|
||||
r.tree = tree
|
||||
|
||||
switch h.command {
|
||||
case cmdTreeDisconnect:
|
||||
sess.removeTree(tree)
|
||||
return statusSuccess, emptyBody()
|
||||
case cmdCreate:
|
||||
st, out := c.create(r)
|
||||
if st != statusSuccess {
|
||||
r.chain.hasFile = false
|
||||
r.chain.status = st
|
||||
}
|
||||
return st, out
|
||||
case cmdClose:
|
||||
return c.closeFile(r)
|
||||
case cmdFlush:
|
||||
return c.flush(r)
|
||||
case cmdRead:
|
||||
return c.read(r)
|
||||
case cmdWrite:
|
||||
return c.write(r)
|
||||
case cmdLock:
|
||||
return c.lock(r)
|
||||
case cmdIoctl:
|
||||
return c.ioctl(r)
|
||||
case cmdQueryDirectory:
|
||||
return c.queryDirectory(r)
|
||||
case cmdQueryInfo:
|
||||
return c.queryInfo(r)
|
||||
case cmdSetInfo:
|
||||
return c.setInfo(r)
|
||||
case cmdOplockBreak:
|
||||
return c.oplockBreak(r)
|
||||
}
|
||||
// CHANGE_NOTIFY lands here: directories are not watched.
|
||||
return statusNotSupported, nil
|
||||
}
|
||||
|
||||
// errorBody is the SMB2 ERROR response body, with optional error data.
|
||||
func errorBody(data []byte) []byte {
|
||||
out := newMsg(8 + max(len(data), 1))
|
||||
le.PutUint16(out[headerSize:], 9)
|
||||
le.PutUint32(out[headerSize+4:], uint32(len(data)))
|
||||
copy(out[headerSize+8:], data)
|
||||
return out
|
||||
}
|
||||
|
||||
// emptyBody is the four-byte body shared by the responses that carry no
|
||||
// data (ECHO, LOGOFF, TREE_DISCONNECT, FLUSH, LOCK).
|
||||
func emptyBody() []byte {
|
||||
out := newMsg(4)
|
||||
le.PutUint16(out[headerSize:], 4)
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *conn) send(payload []byte) error {
|
||||
var h [4]byte
|
||||
h[1], h[2], h[3] = byte(len(payload)>>16), byte(len(payload)>>8), byte(len(payload))
|
||||
c.wmu.Lock()
|
||||
defer c.wmu.Unlock()
|
||||
c.nc.SetWriteDeadline(time.Now().Add(writeTimeout))
|
||||
bufs := net.Buffers{h[:], payload}
|
||||
_, err := bufs.WriteTo(c.nc)
|
||||
return err
|
||||
}
|
||||
|
||||
// mac is the SMB 2 signature: the first 16 bytes of the HMAC-SHA256 of the
|
||||
// message, computed with its signature field zeroed.
|
||||
func mac(key, msg []byte) []byte {
|
||||
h := hmac.New(sha256.New, key)
|
||||
h.Write(msg)
|
||||
return h.Sum(nil)[:16]
|
||||
}
|
||||
|
||||
// signWith sets the signed flag of a response and fills its signature.
|
||||
func signWith(mac func([]byte) []byte, msg []byte) {
|
||||
le.PutUint32(msg[16:], le.Uint32(msg[16:])|flagSigned)
|
||||
clear(msg[48:64])
|
||||
copy(msg[48:64], mac(msg))
|
||||
}
|
||||
|
||||
// verifyWith checks the signature of a request. It zeroes the signature
|
||||
// field of msg, which nothing reads afterwards.
|
||||
func verifyWith(mac func([]byte) []byte, msg []byte) bool {
|
||||
var got [16]byte
|
||||
copy(got[:], msg[48:64])
|
||||
clear(msg[48:64])
|
||||
return hmac.Equal(got[:], mac(msg))
|
||||
}
|
||||
|
||||
func sign(key, msg []byte) {
|
||||
signWith(func(b []byte) []byte { return mac(key, b) }, msg)
|
||||
}
|
||||
|
||||
func verify(key, msg []byte) bool {
|
||||
return verifyWith(func(b []byte) []byte { return mac(key, b) }, msg)
|
||||
}
|
||||
|
||||
func (c *conn) session(id uint64) *session {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.sessions[id]
|
||||
}
|
||||
|
||||
func (c *conn) close() {
|
||||
c.nc.Close()
|
||||
c.mu.Lock()
|
||||
sessions := make([]*session, 0, len(c.sessions))
|
||||
for _, s := range c.sessions {
|
||||
sessions = append(sessions, s)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
for _, s := range sessions {
|
||||
s.close()
|
||||
}
|
||||
c.srv.mu.Lock()
|
||||
delete(c.srv.conns, c)
|
||||
c.srv.mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
)
|
||||
|
||||
// SMB 3.0 signs with AES-CMAC under a key derived from the session key. It
|
||||
// is here for the clients that are configured to speak SMB 3.0 and nothing
|
||||
// else; see the dialects in negotiate.go.
|
||||
|
||||
// kdf is the SP800-108 counter-mode derivation of [MS-SMB2] 3.1.4.2, fixed to
|
||||
// HMAC-SHA256 and a 128-bit output. label and context include their
|
||||
// terminating NUL where the specification says so.
|
||||
func kdf(key, label, context []byte) []byte {
|
||||
h := hmac.New(sha256.New, key)
|
||||
h.Write([]byte{0, 0, 0, 1})
|
||||
h.Write(label)
|
||||
h.Write([]byte{0})
|
||||
h.Write(context)
|
||||
h.Write([]byte{0, 0, 0, 128})
|
||||
return h.Sum(nil)[:16]
|
||||
}
|
||||
|
||||
// aesCMAC implements RFC 4493, the signing algorithm of SMB 3.x.
|
||||
func aesCMAC(key, msg []byte) (mac [16]byte) {
|
||||
blk, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return mac
|
||||
}
|
||||
var k1, k2 [16]byte
|
||||
blk.Encrypt(k1[:], k1[:])
|
||||
cmacDouble(&k1)
|
||||
k2 = k1
|
||||
cmacDouble(&k2)
|
||||
|
||||
// All blocks but the last go through plain CBC with a zero IV, which
|
||||
// the standard library runs much faster than block-at-a-time calls.
|
||||
if n := (len(msg) - 1) / 16 * 16; n > 0 {
|
||||
cbc := cipher.NewCBCEncrypter(blk, mac[:])
|
||||
var scratch [4096]byte
|
||||
for rest := msg[:n]; len(rest) > 0; {
|
||||
m := min(len(rest), len(scratch))
|
||||
cbc.CryptBlocks(scratch[:m], rest[:m])
|
||||
copy(mac[:], scratch[m-16:m])
|
||||
rest = rest[m:]
|
||||
}
|
||||
msg = msg[n:]
|
||||
}
|
||||
var last [16]byte
|
||||
copy(last[:], msg)
|
||||
if len(msg) == 16 {
|
||||
subtle.XORBytes(last[:], last[:], k1[:])
|
||||
} else {
|
||||
last[len(msg)] = 0x80
|
||||
subtle.XORBytes(last[:], last[:], k2[:])
|
||||
}
|
||||
subtle.XORBytes(mac[:], mac[:], last[:])
|
||||
blk.Encrypt(mac[:], mac[:])
|
||||
return mac
|
||||
}
|
||||
|
||||
// cmacDouble multiplies k by x in GF(2^128).
|
||||
func cmacDouble(k *[16]byte) {
|
||||
carry := k[0] >> 7
|
||||
for i := 0; i < 15; i++ {
|
||||
k[i] = k[i]<<1 | k[i+1]>>7
|
||||
}
|
||||
k[15] <<= 1
|
||||
if carry != 0 {
|
||||
k[15] ^= 0x87
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
// Modified by RouterShelf. See UPSTREAM.md for adaptation details and Apache-2.0 provenance.
|
||||
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// File information classes of QUERY_DIRECTORY ([MS-FSCC] 2.4).
|
||||
const (
|
||||
classDirectory = 1
|
||||
classFullDirectory = 2
|
||||
classBothDirectory = 3
|
||||
classNames = 12
|
||||
classIDBoth = 37
|
||||
classIDFull = 38
|
||||
)
|
||||
|
||||
// dirScan is the state of an enumeration: the names are read once, when the
|
||||
// scan starts, and handed out across as many requests as the client needs.
|
||||
type dirScan struct {
|
||||
names []string
|
||||
pos int
|
||||
pattern string
|
||||
// served tells the first request, which answers "no such file" when
|
||||
// nothing matches, from the following ones, which answer "no more".
|
||||
served bool
|
||||
}
|
||||
|
||||
func (c *conn) queryDirectory(r *request) (ntStatus, []byte) {
|
||||
p := r.msg[headerSize:]
|
||||
if len(p) < 32 || le.Uint16(p) != 33 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
class, flags := p[2], p[3]
|
||||
limit := le.Uint32(p[28:])
|
||||
raw, ok := sub(r.msg, uint32(le.Uint16(p[24:])), uint32(le.Uint16(p[26:])))
|
||||
if !ok || !c.charged(r, limit) {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
if trace {
|
||||
r.note = fmt.Sprintf("class %d flags %#x pattern %q", class, flags, decodeUTF16(raw))
|
||||
}
|
||||
o, st := c.lookup(r, p[8:24])
|
||||
if st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
if !o.isDir {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
if entrySize(class, "") == 0 {
|
||||
return statusInvalidInfoClass, nil
|
||||
}
|
||||
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
if o.closed {
|
||||
return statusFileClosed, nil
|
||||
}
|
||||
const restart, single, reopen = 0x01, 0x02, 0x10
|
||||
if o.dir == nil || flags&(restart|reopen) != 0 {
|
||||
d, err := c.srv.root.Open(o.path)
|
||||
if err != nil {
|
||||
return errStatus(err), nil
|
||||
}
|
||||
names, err := d.Readdirnames(maxDirectoryEntries + 1)
|
||||
d.Close()
|
||||
if err != nil && err != io.EOF && len(names) == 0 {
|
||||
return errStatus(err), nil
|
||||
}
|
||||
if len(names) > maxDirectoryEntries {
|
||||
return statusInsufficientResources, nil
|
||||
}
|
||||
sort.Strings(names)
|
||||
o.dir = &dirScan{
|
||||
names: append([]string{".", ".."}, names...),
|
||||
pattern: nameFromWire(decodeUTF16(raw)),
|
||||
}
|
||||
}
|
||||
scan := o.dir
|
||||
wild := strings.ContainsAny(scan.pattern, `*?<>"`)
|
||||
|
||||
out := newMsg(8)
|
||||
last := -1
|
||||
for scan.pos < len(scan.names) {
|
||||
name := scan.names[scan.pos]
|
||||
if scan.pattern != "" && scan.pattern != "*" {
|
||||
if wild && !matchPattern(scan.pattern, name) || !wild && scan.pattern != name {
|
||||
scan.pos++
|
||||
continue
|
||||
}
|
||||
}
|
||||
wire := nameToWire(name)
|
||||
start := (len(out) + 7) &^ 7
|
||||
if uint32(start-headerSize-8+entrySize(class, wire)) > limit {
|
||||
if last < 0 {
|
||||
// Not even one entry fits.
|
||||
return statusInfoLengthMismatch, nil
|
||||
}
|
||||
break
|
||||
}
|
||||
// "." and ".." both describe the directory itself: the parent of
|
||||
// the share root is not something to report on.
|
||||
target := o.path
|
||||
if name != "." && name != ".." {
|
||||
target = path.Join(o.path, name)
|
||||
}
|
||||
fi, err := c.srv.root.Stat(target)
|
||||
if err != nil {
|
||||
// A dangling or escaping symbolic link is listed as the link
|
||||
// it is; a name that vanished since the scan is skipped.
|
||||
if fi, err = c.srv.root.Lstat(target); err != nil {
|
||||
scan.pos++
|
||||
continue
|
||||
}
|
||||
}
|
||||
info := c.srv.info(fi, target)
|
||||
if last >= 0 {
|
||||
out = pad8(out)
|
||||
le.PutUint32(out[last:], uint32(len(out)-last))
|
||||
}
|
||||
last = len(out)
|
||||
out = appendEntry(out, class, wire, &info, uint32(scan.pos))
|
||||
scan.pos++
|
||||
if flags&single != 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
if last < 0 {
|
||||
if !scan.served {
|
||||
scan.served = true
|
||||
return statusNoSuchFile, nil
|
||||
}
|
||||
return statusNoMoreFiles, nil
|
||||
}
|
||||
scan.served = true
|
||||
le.PutUint16(out[headerSize:], 9)
|
||||
le.PutUint16(out[headerSize+2:], headerSize+8)
|
||||
le.PutUint32(out[headerSize+4:], uint32(len(out)-headerSize-8))
|
||||
return statusSuccess, out
|
||||
}
|
||||
|
||||
// entrySize returns the encoded size of a directory entry, or zero for a
|
||||
// class the server does not know.
|
||||
func entrySize(class byte, wire string) int {
|
||||
n := 2 * len([]rune(wire))
|
||||
for _, r := range wire {
|
||||
if r > 0xFFFF {
|
||||
n += 2
|
||||
}
|
||||
}
|
||||
switch class {
|
||||
case classDirectory:
|
||||
return 64 + n
|
||||
case classFullDirectory:
|
||||
return 68 + n
|
||||
case classBothDirectory:
|
||||
return 94 + n
|
||||
case classIDFull:
|
||||
return 80 + n
|
||||
case classIDBoth:
|
||||
return 104 + n
|
||||
case classNames:
|
||||
return 12 + n
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func appendEntry(out []byte, class byte, wire string, in *fileInfo, index uint32) []byte {
|
||||
name := encodeUTF16(wire)
|
||||
base := len(out)
|
||||
out = append(out, make([]byte, entrySize(class, wire)-len(name))...)
|
||||
b := out[base:]
|
||||
le.PutUint32(b[4:], index)
|
||||
if class == classNames {
|
||||
le.PutUint32(b[8:], uint32(len(name)))
|
||||
return append(out, name...)
|
||||
}
|
||||
in.putTimes(b[8:])
|
||||
le.PutUint64(b[40:], in.size)
|
||||
le.PutUint64(b[48:], in.alloc)
|
||||
le.PutUint32(b[56:], in.attrs)
|
||||
le.PutUint32(b[60:], uint32(len(name)))
|
||||
// Offsets 64 and up hold, depending on the class, the EA size, an
|
||||
// empty 8.3 name and the file id; only the last is ever non-zero.
|
||||
switch class {
|
||||
case classIDFull:
|
||||
le.PutUint64(b[72:], in.ino)
|
||||
case classIDBoth:
|
||||
le.PutUint64(b[96:], in.ino)
|
||||
}
|
||||
return append(out, name...)
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The fuzz targets feed the decoders what a hostile client could send. The
|
||||
// property is the same everywhere: no panic, and for the paths, no way out
|
||||
// of the root.
|
||||
|
||||
// sink is the network side of a connection under fuzzing: it accepts and
|
||||
// forgets whatever the server writes.
|
||||
type sink struct{}
|
||||
|
||||
func (sink) Read([]byte) (int, error) { return 0, net.ErrClosed }
|
||||
func (sink) Write(b []byte) (int, error) { return len(b), nil }
|
||||
func (sink) Close() error { return nil }
|
||||
func (sink) LocalAddr() net.Addr { return &net.TCPAddr{} }
|
||||
func (sink) RemoteAddr() net.Addr { return &net.TCPAddr{} }
|
||||
func (sink) SetDeadline(time.Time) error { return nil }
|
||||
func (sink) SetReadDeadline(time.Time) error { return nil }
|
||||
func (sink) SetWriteDeadline(time.Time) error { return nil }
|
||||
|
||||
func fuzzServer(f *testing.F) *server {
|
||||
root := f.TempDir()
|
||||
os.WriteFile(filepath.Join(root, "file"), []byte("some content"), 0o644)
|
||||
os.MkdirAll(filepath.Join(root, "dir", "sub"), 0o755)
|
||||
os.WriteFile(filepath.Join(root, "dir", "inner"), []byte("inner"), 0o644)
|
||||
s, err := newServer(Config{Root: root, Share: testShare, User: testUser, NTHash: NTHash(testPassword)})
|
||||
if err != nil {
|
||||
f.Fatal(err)
|
||||
}
|
||||
f.Cleanup(func() { s.root.Close() })
|
||||
return s
|
||||
}
|
||||
|
||||
// FuzzPreAuth sends arbitrary frames to a connection that has not logged in.
|
||||
func FuzzPreAuth(f *testing.F) {
|
||||
s := fuzzServer(f)
|
||||
c := &testClient{t: f}
|
||||
body := make([]byte, 36)
|
||||
le.PutUint16(body, 36)
|
||||
le.PutUint16(body[2:], 2)
|
||||
body = le.AppendUint16(le.AppendUint16(body, dialect202), dialect210)
|
||||
f.Add(c.request(cmdNegotiate, body))
|
||||
f.Add(smb1Negotiate("NT LM 0.12", "SMB 2.002", "SMB 2.???"))
|
||||
f.Add(c.request(cmdSessionSetup, sessionSetupBody(negTokenInit())))
|
||||
f.Add(c.request(cmdSessionSetup, sessionSetupBody(append([]byte(ntlmSignature), 1, 0, 0, 0, 0, 0, 0, 0))))
|
||||
f.Add(c.request(cmdEcho, []byte{4, 0, 0, 0}))
|
||||
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
// Each input is a sequence of frames on one connection, split
|
||||
// the way the transport would: negotiate first, then the rest.
|
||||
c := s.newConn(sink{})
|
||||
defer c.close()
|
||||
for _, msg := range [][]byte{f0(data), data} {
|
||||
if len(msg) < 4 {
|
||||
return
|
||||
}
|
||||
if c.handleFrame(msg) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// f0 is a valid NEGOTIATE, so that half of the fuzzing effort goes to the
|
||||
// state that follows it.
|
||||
func f0(data []byte) []byte {
|
||||
if len(data) == 0 || data[0]&1 == 0 {
|
||||
return data
|
||||
}
|
||||
body := make([]byte, 36)
|
||||
le.PutUint16(body, 36)
|
||||
le.PutUint16(body[2:], 1)
|
||||
return (&testClient{}).request(cmdNegotiate, le.AppendUint16(body, dialect210))
|
||||
}
|
||||
|
||||
// FuzzMessage sends arbitrary messages on an authenticated session. The
|
||||
// harness signs them, since the point is to reach the command decoders and
|
||||
// not to forge a signature.
|
||||
func FuzzMessage(f *testing.F) {
|
||||
s := fuzzServer(f)
|
||||
key := bytes.Repeat([]byte{7}, 16)
|
||||
c := &testClient{t: f, key: key, sessionID: 1, treeID: 1}
|
||||
related := bytes.Repeat([]byte{0xFF}, 16)
|
||||
|
||||
// One seed per command, each as a related chain behind a CREATE so
|
||||
// that it operates on a real handle.
|
||||
file := createBody("file", accessRW, dispOpenIf, 0)
|
||||
openDir := createBody("dir", accessRead, dispOpen, optDirectory)
|
||||
lock := make([]byte, 24)
|
||||
le.PutUint16(lock, 48)
|
||||
le.PutUint16(lock[2:], 1)
|
||||
copy(lock[8:], related)
|
||||
lock = append(lock, make([]byte, 24)...)
|
||||
lock[24+8], lock[24+16] = 10, lockExclusive
|
||||
ioctl := make([]byte, 57)
|
||||
le.PutUint16(ioctl, 57)
|
||||
le.PutUint32(ioctl[4:], fsctlDFSGetReferrals)
|
||||
notify := make([]byte, 32)
|
||||
le.PutUint16(notify, 32)
|
||||
copy(notify[8:], related)
|
||||
flush := closeBody(related)
|
||||
seeds := []struct {
|
||||
cmds []uint16
|
||||
bodies [][]byte
|
||||
}{
|
||||
{[]uint16{cmdCreate, cmdRead, cmdClose}, [][]byte{file, readBody(related, 0, 100), closeBody(related)}},
|
||||
{[]uint16{cmdCreate, cmdWrite, cmdFlush}, [][]byte{file, writeBody(related, 3, []byte("data")), flush}},
|
||||
{[]uint16{cmdCreate, cmdQueryDirectory}, [][]byte{openDir, queryDirectoryBody(related, classIDBoth, "*", 65536)}},
|
||||
{[]uint16{cmdCreate, cmdQueryDirectory}, [][]byte{openDir, queryDirectoryBody(related, classNames, "in*", 200)}},
|
||||
{[]uint16{cmdCreate, cmdQueryInfo}, [][]byte{file, queryInfoBody(related, infoFile, fileAll, 4096)}},
|
||||
{[]uint16{cmdCreate, cmdQueryInfo}, [][]byte{file, queryInfoBody(related, infoFilesystem, fsAttribute, 4096)}},
|
||||
{[]uint16{cmdCreate, cmdQueryInfo}, [][]byte{file, queryInfoBody(related, infoSecurity, 0, 4096)}},
|
||||
{[]uint16{cmdCreate, cmdSetInfo}, [][]byte{file, setInfoBody(related, fileRename, renameData(`dir\moved`, true))}},
|
||||
{[]uint16{cmdCreate, cmdSetInfo}, [][]byte{file, setInfoBody(related, fileEndOfFile, make([]byte, 8))}},
|
||||
{[]uint16{cmdCreate, cmdSetInfo}, [][]byte{file, setInfoBody(related, fileBasic, make([]byte, 40))}},
|
||||
{[]uint16{cmdCreate, cmdSetInfo}, [][]byte{file, setInfoBody(related, fileDisposition, []byte{1})}},
|
||||
{[]uint16{cmdCreate, cmdLock}, [][]byte{file, lock}},
|
||||
{[]uint16{cmdCreate, cmdWrite, cmdRead}, [][]byte{createBody("file:meta:$DATA", accessRW, dispOpenIf, 0), writeBody(related, 2, []byte("stream")), readBody(related, 0, 100)}},
|
||||
{[]uint16{cmdCreate, cmdQueryInfo}, [][]byte{file, queryInfoBody(related, infoFile, fileStream, 4096)}},
|
||||
{[]uint16{cmdCreate, cmdChangeNotify}, [][]byte{openDir, notify}},
|
||||
{[]uint16{cmdIoctl}, [][]byte{ioctl}},
|
||||
{[]uint16{cmdEcho, cmdTreeDisconnect, cmdLogoff}, [][]byte{{4, 0, 0, 0}, {4, 0, 0, 0}, {4, 0, 0, 0}}},
|
||||
{[]uint16{cmdTreeConnect}, [][]byte{append([]byte{9, 0, 0, 0, 72, 0, 10, 0}, encodeUTF16(`\\s\vol`)...)}},
|
||||
}
|
||||
for _, seed := range seeds {
|
||||
f.Add(c.compound(seed.cmds, seed.bodies))
|
||||
}
|
||||
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
c := s.newConn(sink{})
|
||||
defer c.close()
|
||||
c.setDialect(dialect210)
|
||||
c.authenticated = true
|
||||
c.credits = maxCredits
|
||||
sess := &session{id: 1, conn: c, authenticated: true, signingKey: key,
|
||||
trees: map[uint32]*tree{1: {id: 1}, 2: {id: 2, ipc: true}}, opens: map[uint64]*open{}}
|
||||
c.sessions[1] = sess
|
||||
|
||||
// Sign every command of the chain, following the same links the
|
||||
// server follows.
|
||||
msg := bytes.Clone(data)
|
||||
for off := 0; len(msg)-off >= headerSize; {
|
||||
next := int(le.Uint32(msg[off+20:]))
|
||||
end := len(msg)
|
||||
if next >= headerSize && next <= len(msg)-off-headerSize {
|
||||
end = off + next
|
||||
}
|
||||
le.PutUint64(msg[off+40:], 1)
|
||||
sign(key, msg[off:end])
|
||||
if end == len(msg) {
|
||||
break
|
||||
}
|
||||
off = end
|
||||
}
|
||||
if len(msg) < 4 {
|
||||
return
|
||||
}
|
||||
c.handleFrame(msg)
|
||||
|
||||
// Whatever the message did, it did it inside the root.
|
||||
if entries, err := os.ReadDir(filepath.Dir(s.rootPath)); err == nil && len(entries) != 1 {
|
||||
t.Fatalf("something appeared next to the root: %v", entries)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzSPNEGO(f *testing.F) {
|
||||
f.Add(negTokenInit())
|
||||
f.Add(negTokenResp(negAcceptIncomplete, true, []byte(ntlmSignature), []byte("mic")))
|
||||
f.Add([]byte(ntlmSignature))
|
||||
f.Fuzz(func(t *testing.T, data []byte) {
|
||||
parseSPNEGO(data)
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzNTLM(f *testing.F) {
|
||||
hash := NTHash(testPassword)
|
||||
f.Add(append([]byte(ntlmSignature), 1, 0, 0, 0, 1, 2, 3, 4), authenticateMessage(testUser, "D", make([]byte, 60), make([]byte, 16)))
|
||||
f.Fuzz(func(t *testing.T, negotiate, authenticate []byte) {
|
||||
var a ntlmAuth
|
||||
a.start(negotiate, time.Unix(0, 0))
|
||||
if a.authenticate(authenticate, testUser, hash) {
|
||||
// Guessing a valid response is not something a fuzzer
|
||||
// does; if it happens the check is broken.
|
||||
t.Fatal("random data authenticated")
|
||||
}
|
||||
avFlags(authenticate)
|
||||
})
|
||||
}
|
||||
|
||||
func FuzzParsePath(f *testing.F) {
|
||||
for _, s := range []string{"", "a", `a\b`, `..\x`, "a", "", `a\..\..\b`, "x:y", `\\server\share`} {
|
||||
f.Add(s)
|
||||
}
|
||||
f.Fuzz(func(t *testing.T, name string) {
|
||||
p, st := parsePath(name)
|
||||
if st != statusSuccess {
|
||||
return
|
||||
}
|
||||
// An accepted path is local: relative, and without any element
|
||||
// that could climb out.
|
||||
if p != "." && !filepath.IsLocal(filepath.FromSlash(p)) {
|
||||
t.Fatalf("parsePath(%q) = %q, which is not local", name, p)
|
||||
}
|
||||
for _, part := range strings.Split(p, "/") {
|
||||
if part == ".." || part == "" {
|
||||
t.Fatalf("parsePath(%q) = %q", name, p)
|
||||
}
|
||||
}
|
||||
matchPattern(name, p)
|
||||
nameToWire(p)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,555 @@
|
||||
// Modified by RouterShelf. See UPSTREAM.md for adaptation details and Apache-2.0 provenance.
|
||||
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"math"
|
||||
)
|
||||
|
||||
const (
|
||||
infoFile = 1
|
||||
infoFilesystem = 2
|
||||
infoSecurity = 3
|
||||
)
|
||||
|
||||
// File information classes ([MS-FSCC] 2.4).
|
||||
const (
|
||||
fileBasic = 4
|
||||
fileStandard = 5
|
||||
fileInternal = 6
|
||||
fileEA = 7
|
||||
fileAccess = 8
|
||||
fileRename = 10
|
||||
fileDisposition = 13
|
||||
filePosition = 14
|
||||
fileFullEA = 15
|
||||
fileMode = 16
|
||||
fileAlignment = 17
|
||||
fileAll = 18
|
||||
fileAllocation = 19
|
||||
fileEndOfFile = 20
|
||||
fileAlternateName = 21
|
||||
fileStream = 22
|
||||
fileNetworkOpen = 34
|
||||
fileAttributeTag = 35
|
||||
fileID = 59
|
||||
fileDispositionEx = 64
|
||||
fileRenameEx = 65
|
||||
fsVolume = 1
|
||||
fsSize = 3
|
||||
fsDevice = 4
|
||||
fsAttribute = 5
|
||||
fsFullSize = 7
|
||||
fsSectorSize = 11
|
||||
fsCaseSensitive = 0x00000001
|
||||
fsCasePreserved = 0x00000002
|
||||
fsUnicodeOnDisk = 0x00000004
|
||||
fsNamedStreams = 0x00040000
|
||||
)
|
||||
|
||||
func (c *conn) queryInfo(r *request) (ntStatus, []byte) {
|
||||
p := r.msg[headerSize:]
|
||||
if len(p) < 40 || le.Uint16(p) != 41 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
kind, class := p[2], p[3]
|
||||
limit := le.Uint32(p[4:])
|
||||
additional := le.Uint32(p[16:])
|
||||
if !c.charged(r, limit) {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
if trace {
|
||||
r.note = fmt.Sprintf("type %d class %d", kind, class)
|
||||
}
|
||||
o, st := c.lookup(r, p[24:40])
|
||||
if st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
|
||||
var data []byte
|
||||
switch {
|
||||
case kind == infoFile:
|
||||
data, st = c.fileInfo(o, class)
|
||||
case kind == infoFilesystem:
|
||||
data, st = c.filesystemInfo(class)
|
||||
case kind == infoSecurity:
|
||||
data = c.securityDescriptor(additional)
|
||||
if uint32(len(data)) > limit {
|
||||
// The one case where the error says how much room is needed.
|
||||
return statusBufferTooSmall, errorBody(le.AppendUint32(nil, uint32(len(data))))
|
||||
}
|
||||
default:
|
||||
st = statusNotSupported
|
||||
}
|
||||
if st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
if uint32(len(data)) > limit {
|
||||
data = data[:limit]
|
||||
st = statusBufferOverflow
|
||||
}
|
||||
out := newMsg(8)
|
||||
le.PutUint16(out[headerSize:], 9)
|
||||
le.PutUint16(out[headerSize+2:], headerSize+8)
|
||||
le.PutUint32(out[headerSize+4:], uint32(len(data)))
|
||||
out = append(out, data...)
|
||||
if len(data) == 0 {
|
||||
out = append(out, 0)
|
||||
}
|
||||
return st, out
|
||||
}
|
||||
|
||||
func (c *conn) fileInfo(o *open, class byte) ([]byte, ntStatus) {
|
||||
in, st := c.srv.stat(o)
|
||||
if st != statusSuccess {
|
||||
return nil, st
|
||||
}
|
||||
basic := func() []byte {
|
||||
b := make([]byte, 40)
|
||||
in.putTimes(b)
|
||||
le.PutUint32(b[32:], in.attrs)
|
||||
return b
|
||||
}
|
||||
standard := func() []byte {
|
||||
b := make([]byte, 24)
|
||||
le.PutUint64(b, in.alloc)
|
||||
le.PutUint64(b[8:], in.size)
|
||||
le.PutUint32(b[16:], in.nlink)
|
||||
c.srv.mu.Lock()
|
||||
if o.shared != nil && o.shared.deletePending || o.stream != nil && o.deleteOnClose {
|
||||
b[20] = 1
|
||||
}
|
||||
c.srv.mu.Unlock()
|
||||
if in.isDir {
|
||||
b[21] = 1
|
||||
}
|
||||
return b
|
||||
}
|
||||
name := func() []byte {
|
||||
p, _ := o.location()
|
||||
n := encodeUTF16(wirePath(p))
|
||||
return append(le.AppendUint32(nil, uint32(len(n))), n...)
|
||||
}
|
||||
switch class {
|
||||
case fileBasic:
|
||||
return basic(), statusSuccess
|
||||
case fileStandard:
|
||||
return standard(), statusSuccess
|
||||
case fileInternal:
|
||||
return le.AppendUint64(nil, in.ino), statusSuccess
|
||||
case fileEA, fileMode, fileAlignment:
|
||||
return make([]byte, 4), statusSuccess
|
||||
case fileAccess:
|
||||
return le.AppendUint32(nil, o.access), statusSuccess
|
||||
case filePosition:
|
||||
return make([]byte, 8), statusSuccess
|
||||
case fileAll:
|
||||
b := append(basic(), standard()...)
|
||||
b = le.AppendUint64(b, in.ino)
|
||||
b = le.AppendUint32(b, 0) // EA size
|
||||
b = le.AppendUint32(b, o.access) // access
|
||||
b = le.AppendUint64(b, 0) // position
|
||||
b = le.AppendUint32(b, 0) // mode
|
||||
b = le.AppendUint32(b, 0) // alignment
|
||||
return append(b, name()...), statusSuccess
|
||||
case fileStream:
|
||||
key := o.streamKey
|
||||
if o.stream == nil {
|
||||
key = o.shared.key
|
||||
}
|
||||
return c.srv.streamInfo(&in, key), statusSuccess
|
||||
case fileNetworkOpen:
|
||||
b := make([]byte, 56)
|
||||
in.putTimes(b)
|
||||
le.PutUint64(b[32:], in.alloc)
|
||||
le.PutUint64(b[40:], in.size)
|
||||
le.PutUint32(b[48:], in.attrs)
|
||||
return b, statusSuccess
|
||||
case fileAttributeTag:
|
||||
b := make([]byte, 8)
|
||||
le.PutUint32(b, in.attrs)
|
||||
return b, statusSuccess
|
||||
case fileID:
|
||||
b := make([]byte, 24)
|
||||
le.PutUint64(b, in.dev)
|
||||
le.PutUint64(b[8:], in.ino)
|
||||
return b, statusSuccess
|
||||
case fileFullEA:
|
||||
return nil, statusNoEasOnFile
|
||||
case fileAlternateName:
|
||||
// No 8.3 names.
|
||||
return nil, statusObjectNameNotFound
|
||||
}
|
||||
return nil, statusInvalidInfoClass
|
||||
}
|
||||
|
||||
func (c *conn) filesystemInfo(class byte) ([]byte, ntStatus) {
|
||||
s := c.srv
|
||||
switch class {
|
||||
case fsVolume:
|
||||
label := encodeUTF16(s.cfg.Share)
|
||||
b := make([]byte, 18, 18+len(label))
|
||||
le.PutUint64(b, filetime(s.start))
|
||||
le.PutUint32(b[8:], le.Uint32(s.guid[:]))
|
||||
le.PutUint32(b[12:], uint32(len(label)))
|
||||
return append(b, label...), statusSuccess
|
||||
case fsSize, fsFullSize:
|
||||
total, free, avail, unit, err := diskSpace(s.rootPath)
|
||||
if err != nil || unit == 0 {
|
||||
return nil, statusAccessDenied
|
||||
}
|
||||
// Clients multiply units by sectors by bytes: a 512-byte sector
|
||||
// lets any block size that is a multiple of it come out exact.
|
||||
sectors := max(unit/512, 1)
|
||||
if class == fsSize {
|
||||
b := make([]byte, 24)
|
||||
le.PutUint64(b, total)
|
||||
le.PutUint64(b[8:], avail)
|
||||
le.PutUint32(b[16:], sectors)
|
||||
le.PutUint32(b[20:], 512)
|
||||
return b, statusSuccess
|
||||
}
|
||||
b := make([]byte, 32)
|
||||
le.PutUint64(b, total)
|
||||
le.PutUint64(b[8:], avail)
|
||||
le.PutUint64(b[16:], free)
|
||||
le.PutUint32(b[24:], sectors)
|
||||
le.PutUint32(b[28:], 512)
|
||||
return b, statusSuccess
|
||||
case fsDevice:
|
||||
b := make([]byte, 8)
|
||||
le.PutUint32(b, 7) // FILE_DEVICE_DISK
|
||||
le.PutUint32(b[4:], 0x20) // FILE_DEVICE_IS_MOUNTED
|
||||
return b, statusSuccess
|
||||
case fsAttribute:
|
||||
// Names are stored as the client spells them, on a filesystem
|
||||
// that tells cases apart: saying so keeps a case-sensitive client
|
||||
// from being lied to. ACLs are not advertised because they are
|
||||
// not there.
|
||||
name := encodeUTF16("NTFS")
|
||||
b := make([]byte, 12, 12+len(name))
|
||||
attrs := uint32(fsCasePreserved | fsUnicodeOnDisk)
|
||||
if !s.cfg.CaseInsensitive {
|
||||
attrs |= fsCaseSensitive
|
||||
}
|
||||
if !s.cfg.DiskMetadata {
|
||||
attrs |= fsNamedStreams
|
||||
}
|
||||
le.PutUint32(b, attrs)
|
||||
le.PutUint32(b[4:], 255)
|
||||
le.PutUint32(b[8:], uint32(len(name)))
|
||||
return append(b, name...), statusSuccess
|
||||
case fsSectorSize:
|
||||
b := make([]byte, 28)
|
||||
for i := 0; i < 16; i += 4 {
|
||||
le.PutUint32(b[i:], 512)
|
||||
}
|
||||
le.PutUint32(b[16:], 3) // aligned device, partition aligned on device
|
||||
return b, statusSuccess
|
||||
}
|
||||
return nil, statusInvalidInfoClass
|
||||
}
|
||||
|
||||
// securityDescriptor is the minimal descriptor clients insist on reading:
|
||||
// one owner, one group, and a DACL granting everyone full control. Access is
|
||||
// really decided by the single account of the server and by the permissions
|
||||
// of the files for the uid of the process.
|
||||
func (c *conn) securityDescriptor(want uint32) []byte {
|
||||
// A machine-local SID derived from the server GUID, so that it is
|
||||
// stable for the life of the server and unique across servers.
|
||||
sid := func(rid uint32) []byte {
|
||||
b := []byte{1, 5, 0, 0, 0, 0, 0, 5}
|
||||
b = le.AppendUint32(b, 21)
|
||||
b = append(b, c.srv.guid[:12]...)
|
||||
return le.AppendUint32(b, rid)
|
||||
}
|
||||
everyone := []byte{1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0}
|
||||
|
||||
const selfRelative, daclPresent = 0x8000, 0x0004
|
||||
b := make([]byte, 20)
|
||||
b[0] = 1
|
||||
control := uint16(selfRelative)
|
||||
if want&1 != 0 {
|
||||
le.PutUint32(b[4:], uint32(len(b)))
|
||||
b = append(b, sid(1000)...)
|
||||
}
|
||||
if want&2 != 0 {
|
||||
le.PutUint32(b[8:], uint32(len(b)))
|
||||
b = append(b, sid(513)...)
|
||||
}
|
||||
if want&4 != 0 {
|
||||
control |= daclPresent
|
||||
le.PutUint32(b[16:], uint32(len(b)))
|
||||
ace := []byte{0, 0, 0, 0}
|
||||
le.PutUint16(ace[2:], uint16(8+len(everyone)))
|
||||
ace = le.AppendUint32(ace, accessAll)
|
||||
ace = append(ace, everyone...)
|
||||
acl := []byte{2, 0, 0, 0, 1, 0, 0, 0}
|
||||
le.PutUint16(acl[2:], uint16(8+len(ace)))
|
||||
b = append(append(b, acl...), ace...)
|
||||
}
|
||||
le.PutUint16(b[2:], control)
|
||||
return b
|
||||
}
|
||||
|
||||
func (c *conn) setInfo(r *request) (ntStatus, []byte) {
|
||||
p := r.msg[headerSize:]
|
||||
if len(p) < 32 || le.Uint16(p) != 33 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
kind, class := p[2], p[3]
|
||||
data, ok := sub(r.msg, uint32(le.Uint16(p[8:])), le.Uint32(p[4:]))
|
||||
if !ok {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
o, st := c.lookup(r, p[16:32])
|
||||
if st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
if c.srv.cfg.ReadOnly {
|
||||
return statusAccessDenied, nil
|
||||
}
|
||||
switch kind {
|
||||
case infoFile:
|
||||
st = c.setFileInfo(o, class, data)
|
||||
case infoSecurity:
|
||||
// No persistent ACL support: never acknowledge a permission change.
|
||||
st = statusNotSupported
|
||||
default:
|
||||
st = statusNotSupported
|
||||
}
|
||||
if st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
out := newMsg(2)
|
||||
le.PutUint16(out[headerSize:], 2)
|
||||
return statusSuccess, out
|
||||
}
|
||||
|
||||
func (c *conn) setFileInfo(o *open, class byte, data []byte) ntStatus {
|
||||
s := c.srv
|
||||
p, f := o.location()
|
||||
if o.stream != nil {
|
||||
return c.setStreamInfo(o, class, data)
|
||||
}
|
||||
switch class {
|
||||
case fileBasic:
|
||||
if o.access&0x100 == 0 {
|
||||
return statusAccessDenied
|
||||
}
|
||||
if len(data) < 36 {
|
||||
return statusInfoLengthMismatch
|
||||
}
|
||||
return s.setBasic(p, data)
|
||||
case fileEndOfFile, fileAllocation:
|
||||
if len(data) < 8 {
|
||||
return statusInfoLengthMismatch
|
||||
}
|
||||
size := le.Uint64(data)
|
||||
if f == nil || o.access&(fileWriteData|fileAppendData) == 0 {
|
||||
return statusAccessDenied
|
||||
}
|
||||
if size > math.MaxInt64 {
|
||||
return statusInvalidParameter
|
||||
}
|
||||
s.breakOplocks(c, o.shared)
|
||||
if class == fileAllocation {
|
||||
// Allocation is advisory, except that shrinking it below the
|
||||
// end of the file truncates.
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
return errStatus(err)
|
||||
}
|
||||
if int64(size) >= fi.Size() {
|
||||
return statusSuccess
|
||||
}
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if !ioAllowed(o, 0, math.MaxUint64, true) {
|
||||
return statusFileLockConflict
|
||||
}
|
||||
return errStatus(f.Truncate(int64(size)))
|
||||
case fileDisposition, fileDispositionEx:
|
||||
if len(data) < 1 {
|
||||
return statusInfoLengthMismatch
|
||||
}
|
||||
if o.access&accessDelete == 0 {
|
||||
return statusAccessDenied
|
||||
}
|
||||
pending := data[0]&1 != 0
|
||||
if pending && o.isDir {
|
||||
if st := s.emptyDir(p); st != statusSuccess {
|
||||
return st
|
||||
}
|
||||
}
|
||||
s.mu.Lock()
|
||||
o.shared.deletePending = pending
|
||||
s.mu.Unlock()
|
||||
if !pending {
|
||||
o.mu.Lock()
|
||||
o.deleteOnClose = false
|
||||
o.mu.Unlock()
|
||||
}
|
||||
return statusSuccess
|
||||
case fileRename, fileRenameEx:
|
||||
if len(data) < 20 {
|
||||
return statusInfoLengthMismatch
|
||||
}
|
||||
raw, ok := sub(data, 20, le.Uint32(data[16:]))
|
||||
if !ok {
|
||||
return statusInvalidParameter
|
||||
}
|
||||
// A non-zero root directory handle would make the name relative
|
||||
// to it; no client uses that over SMB2.
|
||||
if le.Uint64(data[8:]) != 0 {
|
||||
return statusInvalidParameter
|
||||
}
|
||||
target, st := parsePath(decodeUTF16(raw))
|
||||
if st != statusSuccess {
|
||||
return st
|
||||
}
|
||||
if target == "." {
|
||||
return statusObjectNameInvalid
|
||||
}
|
||||
replace := data[0]&1 != 0
|
||||
if o.access&accessDelete == 0 {
|
||||
return statusAccessDenied
|
||||
}
|
||||
return s.rename(p, target, replace)
|
||||
case filePosition, fileMode:
|
||||
return statusSuccess
|
||||
case fileFullEA:
|
||||
return statusEasNotSupported
|
||||
}
|
||||
return statusInvalidInfoClass
|
||||
}
|
||||
|
||||
// setStreamInfo is setFileInfo for a handle on a named stream: it has a
|
||||
// length and can be deleted, the rest belongs to its file.
|
||||
func (c *conn) setStreamInfo(o *open, class byte, data []byte) ntStatus {
|
||||
switch class {
|
||||
case fileEndOfFile, fileAllocation:
|
||||
if len(data) < 8 {
|
||||
return statusInfoLengthMismatch
|
||||
}
|
||||
if o.access&(fileWriteData|fileAppendData) == 0 {
|
||||
return statusAccessDenied
|
||||
}
|
||||
size := le.Uint64(data)
|
||||
if class == fileAllocation && size >= c.srv.streamSize(o.stream) {
|
||||
return statusSuccess
|
||||
}
|
||||
return c.srv.truncateStream(o.stream, size)
|
||||
case fileDisposition, fileDispositionEx:
|
||||
if len(data) < 1 {
|
||||
return statusInfoLengthMismatch
|
||||
}
|
||||
if o.access&accessDelete == 0 {
|
||||
return statusAccessDenied
|
||||
}
|
||||
c.srv.mu.Lock()
|
||||
o.deleteOnClose = data[0]&1 != 0
|
||||
c.srv.mu.Unlock()
|
||||
return statusSuccess
|
||||
case fileBasic, filePosition, fileMode:
|
||||
return statusSuccess
|
||||
}
|
||||
return statusNotSupported
|
||||
}
|
||||
|
||||
// setBasic applies FileBasicInformation: the timestamps POSIX can set, and
|
||||
// the read-only attribute, expressed as the write permission bits.
|
||||
func (s *server) setBasic(p string, data []byte) ntStatus {
|
||||
atime, mtime := fromFiletime(le.Uint64(data[8:])), fromFiletime(le.Uint64(data[16:]))
|
||||
if !atime.IsZero() || !mtime.IsZero() {
|
||||
if err := s.root.Chtimes(p, atime, mtime); err != nil {
|
||||
return errStatus(err)
|
||||
}
|
||||
}
|
||||
// Zero attributes mean "leave them alone".
|
||||
if attrs := le.Uint32(data[32:]); attrs != 0 {
|
||||
fi, err := s.root.Stat(p)
|
||||
if err != nil {
|
||||
return errStatus(err)
|
||||
}
|
||||
if !fi.IsDir() {
|
||||
mode := fi.Mode().Perm()
|
||||
readOnly := mode&0o222 == 0
|
||||
// RouterShelf enforces share policy, not exFAT mode bits. Never
|
||||
// acknowledge a per-file protection change the mount may ignore.
|
||||
if s.cfg.DiskMetadata && (attrs&attrReadOnly != 0) != readOnly {
|
||||
return statusNotSupported
|
||||
}
|
||||
switch {
|
||||
case attrs&attrReadOnly != 0 && !readOnly:
|
||||
err = s.root.Chmod(p, mode&^0o222)
|
||||
case attrs&attrReadOnly == 0 && readOnly:
|
||||
err = s.root.Chmod(p, mode|0o200)
|
||||
}
|
||||
if err != nil {
|
||||
return errStatus(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return statusSuccess
|
||||
}
|
||||
|
||||
func (s *server) emptyDir(p string) ntStatus {
|
||||
d, err := s.root.Open(p)
|
||||
if err != nil {
|
||||
return errStatus(err)
|
||||
}
|
||||
defer d.Close()
|
||||
if names, _ := d.Readdirnames(1); len(names) > 0 {
|
||||
return statusDirectoryNotEmpty
|
||||
}
|
||||
return statusSuccess
|
||||
}
|
||||
|
||||
// occupied reports whether the target of a rename or link is taken. The check
|
||||
// and the operation that follows are not atomic with respect to processes
|
||||
// outside the server, which POSIX gives no portable way to achieve.
|
||||
func (s *server) occupied(target string, replace bool) ntStatus {
|
||||
fi, err := s.root.Lstat(target)
|
||||
switch {
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
return statusSuccess
|
||||
case err != nil:
|
||||
return errStatus(err)
|
||||
case !replace:
|
||||
return statusObjectNameCollision
|
||||
case fi.IsDir():
|
||||
return statusAccessDenied
|
||||
}
|
||||
return statusSuccess
|
||||
}
|
||||
|
||||
func (s *server) rename(from, to string, replace bool) ntStatus {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for _, sf := range s.files {
|
||||
for _, o := range sf.opens {
|
||||
if (o.path == from || o.path == to) && o.shareAccess&4 == 0 {
|
||||
return statusSharingViolation
|
||||
}
|
||||
}
|
||||
}
|
||||
if from == to {
|
||||
return statusSuccess
|
||||
}
|
||||
if st := s.occupied(to, replace); st != statusSuccess {
|
||||
return st
|
||||
}
|
||||
if err := s.root.Rename(from, to); err != nil {
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return s.missing(to)
|
||||
}
|
||||
return errStatus(err)
|
||||
}
|
||||
s.renamed(from, to)
|
||||
return statusSuccess
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
// Modified by RouterShelf. See UPSTREAM.md for adaptation details and Apache-2.0 provenance.
|
||||
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"io"
|
||||
"math"
|
||||
)
|
||||
|
||||
// charged reports whether the credit charge of a request covers a payload of
|
||||
// n bytes: one credit per 64 KiB, on the dialects that have multi-credit
|
||||
// requests ([MS-SMB2] 3.3.5.2.5).
|
||||
func (c *conn) charged(r *request, n uint32) bool {
|
||||
if n > c.maxIO {
|
||||
return false
|
||||
}
|
||||
if c.dialect == dialect202 || n <= 0x10000 {
|
||||
return true
|
||||
}
|
||||
return uint32(r.hdr.creditCharge) >= (n-1)/0x10000+1
|
||||
}
|
||||
|
||||
func (c *conn) read(r *request) (ntStatus, []byte) {
|
||||
p := r.msg[headerSize:]
|
||||
if len(p) < 48 || le.Uint16(p) != 49 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
length := le.Uint32(p[4:])
|
||||
offset := le.Uint64(p[8:])
|
||||
minimum := le.Uint32(p[32:])
|
||||
if !c.charged(r, length) || offset > math.MaxInt64 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
o, st := c.lookup(r, p[16:32])
|
||||
if st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
// The file is read straight into the response, after the header and
|
||||
// the 16 bytes of fixed fields.
|
||||
const dataOff = headerSize + 16
|
||||
out := newMsg(16 + max(int(length), 1))
|
||||
_, f := o.location()
|
||||
var n int
|
||||
switch {
|
||||
case o.isDir:
|
||||
return statusInvalidDeviceRequest, nil
|
||||
case o.stream != nil:
|
||||
n = c.srv.readStream(o.stream, out[dataOff:], offset)
|
||||
case f == nil || o.access&(fileReadData|fileExecute) == 0:
|
||||
return statusAccessDenied, nil
|
||||
default:
|
||||
c.srv.mu.Lock()
|
||||
defer c.srv.mu.Unlock()
|
||||
if !ioAllowed(o, offset, uint64(length), false) {
|
||||
return statusFileLockConflict, nil
|
||||
}
|
||||
var err error
|
||||
n, err = f.ReadAt(out[dataOff:], int64(offset))
|
||||
if err != nil && err != io.EOF {
|
||||
return errStatus(err), nil
|
||||
}
|
||||
}
|
||||
if length > 0 && (n == 0 || uint32(n) < minimum) {
|
||||
return statusEndOfFile, nil
|
||||
}
|
||||
q := out[headerSize:]
|
||||
le.PutUint16(q, 17)
|
||||
q[2] = dataOff
|
||||
le.PutUint32(q[4:], uint32(n))
|
||||
return statusSuccess, out[:max(dataOff+n, dataOff+1)]
|
||||
}
|
||||
|
||||
func (c *conn) write(r *request) (ntStatus, []byte) {
|
||||
p := r.msg[headerSize:]
|
||||
if len(p) < 48 || le.Uint16(p) != 49 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
length := le.Uint32(p[4:])
|
||||
offset := le.Uint64(p[8:])
|
||||
data, ok := sub(r.msg, uint32(le.Uint16(p[2:])), length)
|
||||
if !ok || !c.charged(r, length) {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
o, st := c.lookup(r, p[16:32])
|
||||
if st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
_, f := o.location()
|
||||
switch {
|
||||
case o.isDir:
|
||||
return statusInvalidDeviceRequest, nil
|
||||
case o.access&(fileWriteData|fileAppendData) == 0 || c.srv.cfg.ReadOnly:
|
||||
return statusAccessDenied, nil
|
||||
case o.stream != nil:
|
||||
if offset == math.MaxUint64 {
|
||||
offset = c.srv.streamSize(o.stream)
|
||||
}
|
||||
if st := c.srv.writeStream(o.stream, data, offset); st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
return statusSuccess, writeResponse(length)
|
||||
case f == nil:
|
||||
return statusAccessDenied, nil
|
||||
}
|
||||
c.srv.breakOplocks(c, o.shared)
|
||||
c.srv.mu.Lock()
|
||||
defer c.srv.mu.Unlock()
|
||||
// An offset of all ones means "at the end of the file".
|
||||
if offset == math.MaxUint64 {
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
return errStatus(err), nil
|
||||
}
|
||||
offset = uint64(fi.Size())
|
||||
}
|
||||
if offset > math.MaxInt64-uint64(length) {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
if !ioAllowed(o, offset, uint64(length), true) {
|
||||
return statusFileLockConflict, nil
|
||||
}
|
||||
if _, err := f.WriteAt(data, int64(offset)); err != nil {
|
||||
return errStatus(err), nil
|
||||
}
|
||||
if le.Uint32(p[44:])&1 != 0 {
|
||||
if err := f.Sync(); err != nil {
|
||||
return errStatus(err), nil
|
||||
}
|
||||
}
|
||||
return statusSuccess, writeResponse(length)
|
||||
}
|
||||
|
||||
func writeResponse(count uint32) []byte {
|
||||
out := newMsg(17)
|
||||
le.PutUint16(out[headerSize:], 17)
|
||||
le.PutUint32(out[headerSize+4:], count)
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *conn) flush(r *request) (ntStatus, []byte) {
|
||||
p := r.msg[headerSize:]
|
||||
if len(p) < 24 || le.Uint16(p) != 24 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
o, st := c.lookup(r, p[8:24])
|
||||
if st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
// A handle without write access has nothing of its own to flush.
|
||||
if _, f := o.location(); f != nil && o.access&(fileWriteData|fileAppendData) != 0 {
|
||||
if err := f.Sync(); err != nil {
|
||||
return errStatus(err), nil
|
||||
}
|
||||
}
|
||||
return statusSuccess, emptyBody()
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package smbserver
|
||||
|
||||
import "fmt"
|
||||
|
||||
const (
|
||||
fsctlDFSGetReferrals uint32 = 0x00060194
|
||||
fsctlValidateNegotiateInfo uint32 = 0x00140204
|
||||
)
|
||||
|
||||
// ioctl refuses nearly every control code. None is needed to serve files;
|
||||
// the ones clients send on their own initiative (DFS referrals, network
|
||||
// interface queries, resume keys for server-side copy) all have a documented
|
||||
// fallback when the server declines.
|
||||
func (c *conn) ioctl(r *request) (ntStatus, []byte) {
|
||||
p := r.msg[headerSize:]
|
||||
if len(p) < 56 || le.Uint16(p) != 57 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
code := le.Uint32(p[4:])
|
||||
if trace {
|
||||
r.note = fmt.Sprintf("code %#x", code)
|
||||
}
|
||||
switch {
|
||||
case code == fsctlDFSGetReferrals:
|
||||
// What a server without a DFS namespace answers; clients then
|
||||
// carry on with a plain tree connect.
|
||||
return statusNotFound, nil
|
||||
case code == fsctlValidateNegotiateInfo && c.dialect == dialect300:
|
||||
// SMB 3.0 clients require it; on SMB 2 they do without.
|
||||
input, ok := sub(r.msg, le.Uint32(p[24:]), le.Uint32(p[28:]))
|
||||
if !ok {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
data, st := c.validateNegotiate(r, input)
|
||||
if st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
if uint32(len(data)) > le.Uint32(p[44:]) {
|
||||
return statusBufferTooSmall, nil
|
||||
}
|
||||
out := newMsg(48)
|
||||
q := out[headerSize:]
|
||||
le.PutUint16(q, 49)
|
||||
le.PutUint32(q[4:], code)
|
||||
copy(q[8:24], p[8:24])
|
||||
le.PutUint32(q[24:], headerSize+48)
|
||||
le.PutUint32(q[32:], headerSize+48)
|
||||
le.PutUint32(q[36:], uint32(len(data)))
|
||||
return statusSuccess, append(out, data...)
|
||||
}
|
||||
return statusNotSupported, nil
|
||||
}
|
||||
|
||||
// validateNegotiate answers FSCTL_VALIDATE_NEGOTIATE_INFO: the client
|
||||
// repeats, under the protection of its signature, what it sent in the
|
||||
// unprotected NEGOTIATE. A mismatch means someone tampered with the
|
||||
// negotiation, and the connection is dropped.
|
||||
func (c *conn) validateNegotiate(r *request, in []byte) ([]byte, ntStatus) {
|
||||
if len(in) < 24 {
|
||||
return nil, statusInvalidParameter
|
||||
}
|
||||
count := int(le.Uint16(in[22:]))
|
||||
if len(in) < 24+2*count {
|
||||
return nil, statusInvalidParameter
|
||||
}
|
||||
offered := make([]uint16, count)
|
||||
for i := range offered {
|
||||
offered[i] = le.Uint16(in[24+2*i:])
|
||||
}
|
||||
if le.Uint32(in) != c.clientCaps || string(in[4:20]) != string(c.clientGUID[:]) ||
|
||||
le.Uint16(in[20:]) != c.clientSecMode || pickDialect(offered) != c.dialect {
|
||||
r.fatal = true
|
||||
return nil, statusAccessDenied
|
||||
}
|
||||
out := make([]byte, 24)
|
||||
le.PutUint32(out, capLargeMTU)
|
||||
copy(out[4:], c.srv.guid[:])
|
||||
le.PutUint16(out[20:], secModeSigningEnabled|secModeSigningRequired)
|
||||
le.PutUint16(out[22:], c.dialect)
|
||||
return out, statusSuccess
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// Modified by RouterShelf. See UPSTREAM.md for adaptation details and Apache-2.0 provenance.
|
||||
|
||||
package smbserver
|
||||
|
||||
// Byte-range locks are kept in the server and arbitrate between its clients
|
||||
// only: they are not pushed down to the filesystem, so a process working on
|
||||
// the volume directly does not see them. A lock that cannot be taken is
|
||||
// refused at once; the server never makes a request wait.
|
||||
|
||||
const (
|
||||
lockShared = 0x01
|
||||
lockExclusive = 0x02
|
||||
lockUnlock = 0x04
|
||||
)
|
||||
|
||||
type rangeLock struct {
|
||||
owner *open
|
||||
off, n uint64
|
||||
exclusive bool
|
||||
}
|
||||
|
||||
func (l *rangeLock) overlaps(off, n uint64) bool {
|
||||
// Empty ranges never conflict. The subtractions avoid overflowing on
|
||||
// ranges that reach the top of the 64-bit space, which Windows
|
||||
// applications use as advisory lock areas.
|
||||
if l.n == 0 || n == 0 {
|
||||
return false
|
||||
}
|
||||
return off-l.off < l.n || l.off-off < n
|
||||
}
|
||||
|
||||
func (c *conn) lock(r *request) (ntStatus, []byte) {
|
||||
p := r.msg[headerSize:]
|
||||
if len(p) < 24 || le.Uint16(p) != 48 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
count := int(le.Uint16(p[2:]))
|
||||
if count == 0 || count > 64 || len(p) < 24+24*count {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
o, st := c.lookup(r, p[8:24])
|
||||
if st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
if o.isDir || o.stream != nil {
|
||||
return statusInvalidDeviceRequest, nil
|
||||
}
|
||||
|
||||
s := c.srv
|
||||
// A byte-range lock is something a cached read would not see.
|
||||
s.breakOplocks(c, o.shared)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
sf := o.shared
|
||||
if len(sf.locks)+count > 128 {
|
||||
return statusInsufficientResources, nil
|
||||
}
|
||||
taken := len(sf.locks)
|
||||
for i := 0; i < count; i++ {
|
||||
e := p[24+24*i:]
|
||||
off, n, flags := le.Uint64(e), le.Uint64(e[8:]), le.Uint32(e[16:])
|
||||
if flags&lockUnlock != 0 {
|
||||
found := false
|
||||
for j, l := range sf.locks {
|
||||
if l.owner == o && l.off == off && l.n == n {
|
||||
sf.locks = append(sf.locks[:j], sf.locks[j+1:]...)
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return statusRangeNotLocked, nil
|
||||
}
|
||||
taken = len(sf.locks)
|
||||
continue
|
||||
}
|
||||
exclusive := flags&lockExclusive != 0
|
||||
if !exclusive && flags&lockShared == 0 {
|
||||
sf.locks = sf.locks[:taken]
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
for _, l := range sf.locks {
|
||||
if (exclusive || l.exclusive) && l.overlaps(off, n) {
|
||||
// A request takes all its ranges or none.
|
||||
sf.locks = sf.locks[:taken]
|
||||
return statusLockNotGranted, nil
|
||||
}
|
||||
}
|
||||
sf.locks = append(sf.locks, rangeLock{o, off, n, exclusive})
|
||||
}
|
||||
return statusSuccess, emptyBody()
|
||||
}
|
||||
|
||||
// dropLocks removes every lock a handle holds. Called with s.mu held.
|
||||
func (s *server) dropLocks(sf *sharedFile, o *open) {
|
||||
kept := sf.locks[:0]
|
||||
for _, l := range sf.locks {
|
||||
if l.owner != o {
|
||||
kept = append(kept, l)
|
||||
}
|
||||
}
|
||||
sf.locks = kept
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Windows forbids in file names a handful of characters that POSIX allows.
|
||||
// SMB clients on Linux and macOS carry those through the protocol by mapping
|
||||
// them to the Unicode private range, a convention inherited from Services
|
||||
// for Macintosh. The server undoes the mapping so that a file named "a:b" in
|
||||
// the volume is "a:b" on the mounted side as well.
|
||||
var sfmToPosix = map[rune]rune{
|
||||
0xF020: '"', 0xF021: '*', 0xF022: ':', 0xF023: '<', 0xF024: '>',
|
||||
0xF025: '?', 0xF026: '\\', 0xF027: '|', 0xF028: ' ', 0xF029: '.',
|
||||
}
|
||||
|
||||
var posixToSFM = map[rune]rune{
|
||||
'"': 0xF020, '*': 0xF021, ':': 0xF022, '<': 0xF023, '>': 0xF024,
|
||||
'?': 0xF025, '\\': 0xF026, '|': 0xF027,
|
||||
}
|
||||
|
||||
func nameFromWire(s string) string {
|
||||
return strings.Map(func(r rune) rune {
|
||||
if p, ok := sfmToPosix[r]; ok {
|
||||
return p
|
||||
}
|
||||
if r >= 0xF001 && r <= 0xF01F {
|
||||
return r - 0xF000
|
||||
}
|
||||
return r
|
||||
}, s)
|
||||
}
|
||||
|
||||
func nameToWire(s string) string {
|
||||
if s == "" || s == "." || s == ".." {
|
||||
return s
|
||||
}
|
||||
r := []rune(s)
|
||||
for i, c := range r {
|
||||
if m, ok := posixToSFM[c]; ok {
|
||||
r[i] = m
|
||||
} else if c >= 0x01 && c <= 0x1F {
|
||||
r[i] = c + 0xF000
|
||||
}
|
||||
}
|
||||
// A trailing space or period cannot be expressed in a Windows name.
|
||||
switch last := len(r) - 1; r[last] {
|
||||
case ' ':
|
||||
r[last] = 0xF028
|
||||
case '.':
|
||||
r[last] = 0xF029
|
||||
}
|
||||
return string(r)
|
||||
}
|
||||
|
||||
// parsePath turns the name of a CREATE or rename target into a slash
|
||||
// separated path relative to the share root, "." being the root itself.
|
||||
//
|
||||
// It is the first of two barriers against path traversal: every component
|
||||
// must be a plain name, so "..", absolute paths and embedded separators are
|
||||
// refused here. The second barrier is os.Root, which resolves the path
|
||||
// without ever leaving the root directory, symbolic links included.
|
||||
func parsePath(name string) (string, ntStatus) {
|
||||
if name == "" {
|
||||
return ".", statusSuccess
|
||||
}
|
||||
parts := strings.Split(name, `\`)
|
||||
for i, p := range parts {
|
||||
// A colon introduces a named stream, which parseName has split
|
||||
// off already. A literal colon in a file name arrives mapped.
|
||||
if strings.ContainsRune(p, ':') {
|
||||
return "", statusObjectNameInvalid
|
||||
}
|
||||
p = nameFromWire(p)
|
||||
if p == "" || p == "." || p == ".." || len(p) > 255 || strings.ContainsAny(p, "/\x00") {
|
||||
return "", statusObjectNameInvalid
|
||||
}
|
||||
if os.PathSeparator != '/' && strings.ContainsRune(p, os.PathSeparator) {
|
||||
return "", statusObjectNameInvalid
|
||||
}
|
||||
parts[i] = p
|
||||
}
|
||||
return strings.Join(parts, "/"), statusSuccess
|
||||
}
|
||||
|
||||
// wirePath is the reverse of parsePath, for the classes of information that
|
||||
// return the full name of an open file.
|
||||
func wirePath(p string) string {
|
||||
if p == "." {
|
||||
return `\`
|
||||
}
|
||||
parts := strings.Split(p, "/")
|
||||
for i, s := range parts {
|
||||
parts[i] = nameToWire(s)
|
||||
}
|
||||
return `\` + strings.Join(parts, `\`)
|
||||
}
|
||||
|
||||
// matchPattern implements the wildcard search of QUERY_DIRECTORY. Besides *
|
||||
// and ?, the DOS wildcards <, > and " of [MS-FSCC] 2.1.4.4 are accepted and
|
||||
// treated as their plain counterparts, which is how they behave for the
|
||||
// names without 8.3 constraints that this server holds.
|
||||
func matchPattern(pattern, name string) bool {
|
||||
p := []rune(strings.ToLower(pattern))
|
||||
for i, c := range p {
|
||||
switch c {
|
||||
case '<':
|
||||
p[i] = '*'
|
||||
case '>':
|
||||
p[i] = '?'
|
||||
case '"':
|
||||
p[i] = '.'
|
||||
}
|
||||
}
|
||||
n := []rune(strings.ToLower(name))
|
||||
// Iterative glob match with single backtrack point.
|
||||
pi, ni, star, mark := 0, 0, -1, 0
|
||||
for ni < len(n) {
|
||||
switch {
|
||||
case pi < len(p) && (p[pi] == '?' || p[pi] == n[ni]):
|
||||
pi++
|
||||
ni++
|
||||
case pi < len(p) && p[pi] == '*':
|
||||
star, mark = pi, ni
|
||||
pi++
|
||||
case star >= 0:
|
||||
pi = star + 1
|
||||
mark++
|
||||
ni = mark
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
for pi < len(p) && p[pi] == '*' {
|
||||
pi++
|
||||
}
|
||||
return pi == len(p)
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
secModeSigningEnabled uint16 = 1
|
||||
secModeSigningRequired uint16 = 2
|
||||
|
||||
capLargeMTU uint32 = 0x00000004
|
||||
)
|
||||
|
||||
// dialects lists what the server speaks, preferred first. SMB 2.1 is what
|
||||
// every native client is served: it leaves out the whole of SMB 3
|
||||
// (encryption, negotiate contexts, pre-authentication integrity) that a
|
||||
// single share behind a tunnel has no use for. SMB 3.0 comes last, so it is
|
||||
// only chosen for a client that offers nothing lower, which is one mounted
|
||||
// with an explicit "vers=3.0"; it is then served without encryption nor
|
||||
// multichannel, the difference being the signing algorithm.
|
||||
var dialects = []uint16{dialect210, dialect202, dialect300}
|
||||
|
||||
func pickDialect(offered []uint16) uint16 {
|
||||
for _, d := range dialects {
|
||||
if slices.Contains(offered, d) {
|
||||
return d
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// smb1Negotiate answers the SMB1 NEGOTIATE that older clients open with.
|
||||
// SMB1 itself is never spoken: the only acceptable outcome is the client
|
||||
// offering an SMB2 dialect, in which case the reply is an SMB2 NEGOTIATE
|
||||
// response telling it to carry on in SMB2. Anything else closes the
|
||||
// connection.
|
||||
func (c *conn) smb1Negotiate(msg []byte) error {
|
||||
if c.negotiated || c.smb1Seen || len(msg) < 35 || msg[4] != 0x72 {
|
||||
return errProtocol
|
||||
}
|
||||
c.smb1Seen = true
|
||||
// After the 32-byte header: word count (zero), byte count, then the
|
||||
// dialect strings, each introduced by 0x02 and NUL terminated.
|
||||
var wildcard, smb202 bool
|
||||
for _, d := range bytes.Split(msg[35:], []byte{0}) {
|
||||
switch string(bytes.TrimPrefix(d, []byte{2})) {
|
||||
case "SMB 2.???":
|
||||
wildcard = true
|
||||
case "SMB 2.002":
|
||||
smb202 = true
|
||||
}
|
||||
}
|
||||
dialect := dialectAny
|
||||
switch {
|
||||
case wildcard:
|
||||
case smb202:
|
||||
dialect = dialect202
|
||||
c.setDialect(dialect202)
|
||||
default:
|
||||
return fmt.Errorf("%w: SMB1 only client", errProtocol)
|
||||
}
|
||||
out := c.negotiateResponse(dialect)
|
||||
rh := header{command: cmdNegotiate, flags: flagResponse, credits: 1}
|
||||
rh.put(out)
|
||||
return c.send(out)
|
||||
}
|
||||
|
||||
func (c *conn) setDialect(d uint16) {
|
||||
c.negotiated = true
|
||||
c.dialect = d
|
||||
c.maxIO = maxIO
|
||||
if d == dialect202 {
|
||||
// SMB 2.0.2 has no multi-credit requests: 64 KiB is its ceiling.
|
||||
c.maxIO = 0x10000
|
||||
}
|
||||
}
|
||||
|
||||
func (c *conn) negotiate(r *request) (ntStatus, []byte) {
|
||||
p := r.msg[headerSize:]
|
||||
if len(p) < 36 || le.Uint16(p) != 36 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
count := int(le.Uint16(p[2:]))
|
||||
if count == 0 || count > 64 || len(p) < 36+2*count {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
offered := make([]uint16, count)
|
||||
for i := range offered {
|
||||
offered[i] = le.Uint16(p[36+2*i:])
|
||||
}
|
||||
dialect := pickDialect(offered)
|
||||
if dialect == 0 {
|
||||
return statusNotSupported, nil
|
||||
}
|
||||
// Kept for the validation an SMB 3.0 client asks for once signed.
|
||||
c.clientSecMode = le.Uint16(p[4:])
|
||||
c.clientCaps = le.Uint32(p[8:])
|
||||
copy(c.clientGUID[:], p[12:28])
|
||||
c.setDialect(dialect)
|
||||
return statusSuccess, c.negotiateResponse(dialect)
|
||||
}
|
||||
|
||||
func (c *conn) negotiateResponse(dialect uint16) []byte {
|
||||
token := negTokenInit()
|
||||
out := newMsg(64)
|
||||
p := out[headerSize:]
|
||||
le.PutUint16(p, 65)
|
||||
le.PutUint16(p[2:], secModeSigningEnabled|secModeSigningRequired)
|
||||
le.PutUint16(p[4:], dialect)
|
||||
copy(p[8:], c.srv.guid[:])
|
||||
size := uint32(0x10000)
|
||||
if dialect != dialect202 {
|
||||
le.PutUint32(p[24:], capLargeMTU)
|
||||
size = maxIO
|
||||
}
|
||||
le.PutUint32(p[28:], size)
|
||||
le.PutUint32(p[32:], size)
|
||||
le.PutUint32(p[36:], size)
|
||||
le.PutUint64(p[40:], filetime(time.Now()))
|
||||
le.PutUint64(p[48:], filetime(c.srv.start))
|
||||
le.PutUint16(p[56:], headerSize+64)
|
||||
le.PutUint16(p[58:], uint16(len(token)))
|
||||
return append(out, token...)
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"crypto/rc4"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/md4"
|
||||
)
|
||||
|
||||
// NTLMv2 server side, from [MS-NLMP]. Only version 2 responses are accepted:
|
||||
// LM and NTLMv1 are refused outright.
|
||||
|
||||
const (
|
||||
ntlmSignature = "NTLMSSP\x00"
|
||||
|
||||
ntlmUnicode uint32 = 0x00000001
|
||||
ntlmRequestTarget uint32 = 0x00000004
|
||||
ntlmSign uint32 = 0x00000010
|
||||
ntlmSeal uint32 = 0x00000020
|
||||
ntlmNTLM uint32 = 0x00000200
|
||||
ntlmAlwaysSign uint32 = 0x00008000
|
||||
ntlmTargetServer uint32 = 0x00020000
|
||||
ntlmExtendedSession uint32 = 0x00080000
|
||||
ntlmTargetInfo uint32 = 0x00800000
|
||||
ntlmVersion uint32 = 0x02000000
|
||||
ntlm128 uint32 = 0x20000000
|
||||
ntlmKeyExch uint32 = 0x40000000
|
||||
ntlm56 uint32 = 0x80000000
|
||||
)
|
||||
|
||||
// serverName is what the server calls itself in the NTLM challenge. It is a
|
||||
// constant so that nothing about the host (a pod name, for instance) reaches
|
||||
// an unauthenticated peer.
|
||||
const serverName = "SMBSERVER"
|
||||
|
||||
// NTHash returns the NT hash of a password: MD4 over its UTF-16LE encoding.
|
||||
// It is the secret Config.NTHash expects.
|
||||
func NTHash(password string) [16]byte {
|
||||
h := md4.New()
|
||||
h.Write(encodeUTF16(password))
|
||||
var out [16]byte
|
||||
copy(out[:], h.Sum(nil))
|
||||
return out
|
||||
}
|
||||
|
||||
func hmacMD5(key []byte, parts ...[]byte) []byte {
|
||||
h := hmac.New(md5.New, key)
|
||||
for _, p := range parts {
|
||||
h.Write(p)
|
||||
}
|
||||
return h.Sum(nil)
|
||||
}
|
||||
|
||||
// ntlmAuth carries one NTLM exchange from NEGOTIATE to AUTHENTICATE.
|
||||
type ntlmAuth struct {
|
||||
negotiate []byte
|
||||
challenge []byte
|
||||
nonce [8]byte
|
||||
flags uint32
|
||||
|
||||
// Set by authenticate on success.
|
||||
sessionKey []byte
|
||||
authFlags uint32
|
||||
}
|
||||
|
||||
func isNTLM(b []byte, msgType uint32) bool {
|
||||
return len(b) >= 12 && string(b[:8]) == ntlmSignature && le.Uint32(b[8:]) == msgType
|
||||
}
|
||||
|
||||
// start answers a NEGOTIATE message with a CHALLENGE.
|
||||
func (a *ntlmAuth) start(negotiate []byte, now time.Time) ([]byte, bool) {
|
||||
if !isNTLM(negotiate, 1) || len(negotiate) < 16 {
|
||||
return nil, false
|
||||
}
|
||||
a.negotiate = append([]byte(nil), negotiate...)
|
||||
client := le.Uint32(negotiate[12:])
|
||||
a.flags = ntlmUnicode | ntlmRequestTarget | ntlmNTLM | ntlmAlwaysSign | ntlmTargetServer |
|
||||
ntlmExtendedSession | ntlmTargetInfo | ntlmVersion |
|
||||
client&(ntlmSign|ntlmSeal|ntlmKeyExch|ntlm128|ntlm56)
|
||||
rand.Read(a.nonce[:])
|
||||
|
||||
name := encodeUTF16(serverName)
|
||||
var info []byte
|
||||
av := func(id uint16, v []byte) {
|
||||
info = le.AppendUint16(info, id)
|
||||
info = le.AppendUint16(info, uint16(len(v)))
|
||||
info = append(info, v...)
|
||||
}
|
||||
av(2, name) // MsvAvNbDomainName
|
||||
av(1, name) // MsvAvNbComputerName
|
||||
av(4, name) // MsvAvDnsDomainName
|
||||
av(3, name) // MsvAvDnsComputerName
|
||||
// The timestamp is what makes clients include a MIC in AUTHENTICATE.
|
||||
av(7, le.AppendUint64(nil, filetime(now)))
|
||||
av(0, nil)
|
||||
|
||||
msg := make([]byte, 56, 56+len(name)+len(info))
|
||||
copy(msg, ntlmSignature)
|
||||
le.PutUint32(msg[8:], 2)
|
||||
le.PutUint16(msg[12:], uint16(len(name)))
|
||||
le.PutUint16(msg[14:], uint16(len(name)))
|
||||
le.PutUint32(msg[16:], 56)
|
||||
le.PutUint32(msg[20:], a.flags)
|
||||
copy(msg[24:], a.nonce[:])
|
||||
le.PutUint16(msg[40:], uint16(len(info)))
|
||||
le.PutUint16(msg[42:], uint16(len(info)))
|
||||
le.PutUint32(msg[44:], uint32(56+len(name)))
|
||||
// Version: 6.1 build 7600, NTLM revision 15.
|
||||
copy(msg[48:], []byte{6, 1, 0xb0, 0x1d, 0, 0, 0, 15})
|
||||
msg = append(msg, name...)
|
||||
msg = append(msg, info...)
|
||||
a.challenge = msg
|
||||
return msg, true
|
||||
}
|
||||
|
||||
// authenticate checks an AUTHENTICATE message against the single account of
|
||||
// the server. On success a.sessionKey holds the exported session key.
|
||||
func (a *ntlmAuth) authenticate(msg []byte, user string, ntHash [16]byte) bool {
|
||||
if a.challenge == nil || !isNTLM(msg, 3) || len(msg) < 64 {
|
||||
return false
|
||||
}
|
||||
field := func(off int) []byte {
|
||||
b, _ := sub(msg, le.Uint32(msg[off+4:]), uint32(le.Uint16(msg[off:])))
|
||||
return b
|
||||
}
|
||||
nt, domain, name, encKey := field(20), field(28), field(36), field(52)
|
||||
flags := le.Uint32(msg[60:])
|
||||
|
||||
// An NTLMv2 response is the 16-byte proof followed by a blob of at
|
||||
// least 32 bytes. The 24-byte NTLMv1 response fails this test.
|
||||
if len(nt) < 48 || nt[16] != 1 || nt[17] != 1 {
|
||||
return false
|
||||
}
|
||||
text := func(b []byte) string {
|
||||
if flags&ntlmUnicode != 0 {
|
||||
return decodeUTF16(b)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
userName := text(name)
|
||||
if !strings.EqualFold(userName, user) {
|
||||
return false
|
||||
}
|
||||
proof, blob := nt[:16], nt[16:]
|
||||
|
||||
// Clients disagree on the domain they fold into the hash (their own
|
||||
// workgroup, the server name from the challenge, or nothing), so the
|
||||
// one they sent is used, as [MS-NLMP] 3.3.2 specifies.
|
||||
owf := hmacMD5(ntHash[:], encodeUTF16(strings.ToUpper(userName)+text(domain)))
|
||||
if !hmac.Equal(hmacMD5(owf, a.nonce[:], blob), proof) {
|
||||
return false
|
||||
}
|
||||
key := hmacMD5(owf, proof)
|
||||
if flags&ntlmKeyExch != 0 {
|
||||
if len(encKey) != 16 {
|
||||
return false
|
||||
}
|
||||
c, _ := rc4.NewCipher(key)
|
||||
key = make([]byte, 16)
|
||||
c.XORKeyStream(key, encKey)
|
||||
}
|
||||
|
||||
// When the blob says a MIC is present, it protects the three messages
|
||||
// of the exchange against tampering and must verify.
|
||||
if avFlags(blob[28:])&2 != 0 {
|
||||
if len(msg) < 88 {
|
||||
return false
|
||||
}
|
||||
clean := append([]byte(nil), msg...)
|
||||
clear(clean[72:88])
|
||||
if !hmac.Equal(hmacMD5(key, a.negotiate, a.challenge, clean), msg[72:88]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
a.sessionKey = key
|
||||
a.authFlags = flags
|
||||
return true
|
||||
}
|
||||
|
||||
// avFlags returns the MsvAvFlags value of an AV pair list, or zero.
|
||||
func avFlags(av []byte) uint32 {
|
||||
for len(av) >= 4 {
|
||||
id, n := le.Uint16(av), int(le.Uint16(av[2:]))
|
||||
av = av[4:]
|
||||
if id == 0 || len(av) < n {
|
||||
return 0
|
||||
}
|
||||
if id == 6 && n >= 4 {
|
||||
return le.Uint32(av)
|
||||
}
|
||||
av = av[n:]
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// mechListMIC signs the SPNEGO mechanism list with the server-to-client NTLM
|
||||
// signing key ([MS-NLMP] 3.4.4.2, sequence number zero). Windows expects it
|
||||
// back whenever it sent its own.
|
||||
func (a *ntlmAuth) mechListMIC(mechTypes []byte) []byte {
|
||||
if a.authFlags&ntlmExtendedSession == 0 {
|
||||
return nil
|
||||
}
|
||||
const signMagic = "session key to server-to-client signing key magic constant\x00"
|
||||
const sealMagic = "session key to server-to-client sealing key magic constant\x00"
|
||||
signKey := md5.Sum(append(append([]byte(nil), a.sessionKey...), signMagic...))
|
||||
sum := hmacMD5(signKey[:], []byte{0, 0, 0, 0}, mechTypes)[:8]
|
||||
if a.authFlags&ntlmKeyExch != 0 {
|
||||
k := a.sessionKey
|
||||
switch {
|
||||
case a.authFlags&ntlm128 != 0:
|
||||
case a.authFlags&ntlm56 != 0:
|
||||
k = k[:7]
|
||||
default:
|
||||
k = k[:5]
|
||||
}
|
||||
sealKey := md5.Sum(append(append([]byte(nil), k...), sealMagic...))
|
||||
c, _ := rc4.NewCipher(sealKey[:])
|
||||
c.XORKeyStream(sum, sum)
|
||||
}
|
||||
out := []byte{1, 0, 0, 0}
|
||||
out = append(out, sum...)
|
||||
return append(out, 0, 0, 0, 0)
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
// Modified by RouterShelf. See UPSTREAM.md for adaptation details and Apache-2.0 provenance.
|
||||
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Access mask bits ([MS-SMB2] 2.2.13.1).
|
||||
const (
|
||||
fileReadData uint32 = 0x00000001
|
||||
fileWriteData uint32 = 0x00000002
|
||||
fileAppendData uint32 = 0x00000004
|
||||
fileExecute uint32 = 0x00000020
|
||||
accessDelete uint32 = 0x00010000
|
||||
accessMaximum uint32 = 0x02000000
|
||||
accessGenericAll uint32 = 0x10000000
|
||||
accessGenericExec uint32 = 0x20000000
|
||||
accessGenericWrite uint32 = 0x40000000
|
||||
accessGenericRead uint32 = 0x80000000
|
||||
accessAll uint32 = 0x001F01FF
|
||||
accessReadOnly uint32 = 0x001200A9
|
||||
accessModifying uint32 = 0x000D0156 // write data, append, EAs, attributes, delete, DAC, owner
|
||||
optDirectory uint32 = 0x00000001
|
||||
optNonDirectory uint32 = 0x00000040
|
||||
optDeleteOnClose uint32 = 0x00001000
|
||||
dispSupersede uint32 = 0
|
||||
dispOpen uint32 = 1
|
||||
dispCreate uint32 = 2
|
||||
dispOpenIf uint32 = 3
|
||||
dispOverwrite uint32 = 4
|
||||
dispOverwriteIf uint32 = 5
|
||||
actionSuperseded uint32 = 0
|
||||
actionOpened uint32 = 1
|
||||
actionCreated uint32 = 2
|
||||
actionOverwritten uint32 = 3
|
||||
attrReadOnly uint32 = 0x00000001
|
||||
attrHidden uint32 = 0x00000002
|
||||
attrDirectory uint32 = 0x00000010
|
||||
attrArchive uint32 = 0x00000020
|
||||
attrNormal uint32 = 0x00000080
|
||||
maxDirectoryEntries = 1024
|
||||
)
|
||||
|
||||
// open is a file handle held by a client.
|
||||
type open struct {
|
||||
id uint64
|
||||
sess *session
|
||||
tree *tree
|
||||
isDir bool
|
||||
access uint32
|
||||
shareAccess uint32
|
||||
// shared is nil for a handle on a named stream, which has stream
|
||||
// and streamKey, the identity of its file, instead.
|
||||
shared *sharedFile
|
||||
stream *memStream
|
||||
streamKey fileKey
|
||||
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
// path is relative to the share root. It follows renames, including
|
||||
// those made through another handle.
|
||||
path string
|
||||
// f is nil when the handle was opened for attributes only, and for
|
||||
// directories, which are read by path.
|
||||
f *os.File
|
||||
deleteOnClose bool
|
||||
dir *dirScan
|
||||
// oplock tells that the handle holds a level II oplock. Guarded by
|
||||
// the server lock.
|
||||
oplock bool
|
||||
}
|
||||
|
||||
// sharedFile is what the handles open on one file have in common: the
|
||||
// pending deletion and the byte-range locks.
|
||||
type sharedFile struct {
|
||||
key fileKey
|
||||
opens []*open
|
||||
deletePending bool
|
||||
locks []rangeLock
|
||||
// holders counts the handles under oplock; size and mtime are what
|
||||
// the file looked like when the first of them was granted.
|
||||
holders atomic.Int32
|
||||
size int64
|
||||
mtime time.Time
|
||||
}
|
||||
|
||||
func (o *open) location() (string, *os.File) {
|
||||
o.mu.Lock()
|
||||
defer o.mu.Unlock()
|
||||
return o.path, o.f
|
||||
}
|
||||
|
||||
// stat describes the file behind a handle.
|
||||
func (s *server) stat(o *open) (fileInfo, ntStatus) {
|
||||
p, f := o.location()
|
||||
var fi os.FileInfo
|
||||
var err error
|
||||
if f != nil {
|
||||
fi, err = f.Stat()
|
||||
} else {
|
||||
fi, err = s.root.Stat(p)
|
||||
}
|
||||
if err != nil {
|
||||
return fileInfo{}, errStatus(err)
|
||||
}
|
||||
in := s.info(fi, p)
|
||||
if o.stream != nil {
|
||||
// A stream borrows the timestamps of its file and has a size
|
||||
// of its own.
|
||||
in.size = s.streamSize(o.stream)
|
||||
in.alloc = (in.size + 4095) &^ 4095
|
||||
in.isDir, in.attrs = false, attrNormal
|
||||
}
|
||||
return in, statusSuccess
|
||||
}
|
||||
|
||||
// normalizeAccess expands the generic rights of a desired access into the
|
||||
// specific ones.
|
||||
func normalizeAccess(a uint32) uint32 {
|
||||
if a&(accessGenericAll|accessMaximum) != 0 {
|
||||
a |= accessAll
|
||||
}
|
||||
if a&accessGenericRead != 0 {
|
||||
a |= 0x00120089
|
||||
}
|
||||
if a&accessGenericWrite != 0 {
|
||||
a |= 0x00120116
|
||||
}
|
||||
if a&accessGenericExec != 0 {
|
||||
a |= 0x001200A0
|
||||
}
|
||||
return a & accessAll
|
||||
}
|
||||
|
||||
// openFile implements CREATE for the disk share. The whole decision runs
|
||||
// under the server lock so that a pending deletion is seen atomically with
|
||||
// respect to other clients.
|
||||
func (s *server) openFile(r *request, p string, desired, disp, opts uint32, wantOplock bool, shareAccess ...uint32) (*open, uint32, ntStatus) {
|
||||
if disp > dispOverwriteIf {
|
||||
return nil, 0, statusInvalidParameter
|
||||
}
|
||||
access := normalizeAccess(desired)
|
||||
if opts&optDeleteOnClose != 0 && access&accessDelete == 0 {
|
||||
return nil, 0, statusAccessDenied
|
||||
}
|
||||
if (disp == dispSupersede || disp == dispOverwrite || disp == dispOverwriteIf) && access&(fileWriteData|fileAppendData) == 0 {
|
||||
return nil, 0, statusAccessDenied
|
||||
}
|
||||
if s.cfg.ReadOnly {
|
||||
// "Whatever I may have" is answered with read access; an
|
||||
// explicit request to modify is refused.
|
||||
if desired&accessMaximum != 0 && desired&(accessGenericAll|accessGenericWrite) == 0 {
|
||||
access = normalizeAccess(desired&^accessMaximum) | accessReadOnly
|
||||
}
|
||||
if access&accessModifying != 0 || opts&optDeleteOnClose != 0 || (disp != dispOpen && disp != dispOpenIf) {
|
||||
return nil, 0, statusAccessDenied
|
||||
}
|
||||
}
|
||||
|
||||
// The oplock holders to notify, once the server lock is released.
|
||||
var broken []*open
|
||||
defer func() { s.notifyBreak(r.sess.conn, broken) }()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.nOpens >= maxOpens {
|
||||
return nil, 0, statusTooManyOpenedFiles
|
||||
}
|
||||
|
||||
fi, err := s.root.Stat(p)
|
||||
exists := err == nil
|
||||
if err != nil && !errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, 0, errStatus(err)
|
||||
}
|
||||
var (
|
||||
f *os.File
|
||||
action = actionOpened
|
||||
)
|
||||
switch {
|
||||
case !exists:
|
||||
if disp == dispOpen || disp == dispOverwrite || s.cfg.ReadOnly {
|
||||
return nil, 0, s.missing(p)
|
||||
}
|
||||
// The Finder drops a .DS_Store in every folder it shows. The
|
||||
// volume is not a desktop: the file is refused, which the
|
||||
// Finder takes as it does on any read-only volume.
|
||||
if !s.cfg.DiskMetadata && path.Base(p) == ".DS_Store" {
|
||||
return nil, 0, statusAccessDenied
|
||||
}
|
||||
if opts&optDirectory != 0 {
|
||||
err = s.root.Mkdir(p, 0o777)
|
||||
} else {
|
||||
// The mode is left to the umask of the process, like any
|
||||
// file the workload itself would create.
|
||||
f, err = s.root.OpenFile(p, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0o666)
|
||||
}
|
||||
if err != nil {
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
return nil, 0, s.missing(p)
|
||||
}
|
||||
return nil, 0, errStatus(err)
|
||||
}
|
||||
action = actionCreated
|
||||
case disp == dispCreate:
|
||||
return nil, 0, statusObjectNameCollision
|
||||
case fi.IsDir():
|
||||
if opts&optNonDirectory != 0 {
|
||||
return nil, 0, statusFileIsADirectory
|
||||
}
|
||||
if disp != dispOpen && disp != dispOpenIf {
|
||||
return nil, 0, statusAccessDenied
|
||||
}
|
||||
default:
|
||||
if opts&optDirectory != 0 {
|
||||
return nil, 0, statusNotADirectory
|
||||
}
|
||||
}
|
||||
if f != nil {
|
||||
fi, err = f.Stat()
|
||||
} else if !exists {
|
||||
fi, err = s.root.Stat(p)
|
||||
}
|
||||
if err != nil {
|
||||
if f != nil {
|
||||
f.Close()
|
||||
}
|
||||
return nil, 0, errStatus(err)
|
||||
}
|
||||
|
||||
key := keyOf(fi, p)
|
||||
sf := s.files[key]
|
||||
if sf == nil {
|
||||
sf = &sharedFile{key: key}
|
||||
}
|
||||
fail := func(st ntStatus) (*open, uint32, ntStatus) {
|
||||
if f != nil {
|
||||
f.Close()
|
||||
}
|
||||
return nil, 0, st
|
||||
}
|
||||
sharing := uint32(7)
|
||||
if len(shareAccess) > 0 {
|
||||
sharing = shareAccess[0] & 7
|
||||
}
|
||||
for _, other := range sf.opens {
|
||||
if !compatibleShare(access, sharing, other.access, other.shareAccess) {
|
||||
return fail(statusSharingViolation)
|
||||
}
|
||||
}
|
||||
if sf.deletePending {
|
||||
return fail(statusDeletePending)
|
||||
}
|
||||
|
||||
if exists && !fi.IsDir() {
|
||||
truncate := disp == dispSupersede || disp == dispOverwrite || disp == dispOverwriteIf
|
||||
if truncate {
|
||||
action = actionOverwritten
|
||||
if disp == dispSupersede {
|
||||
action = actionSuperseded
|
||||
}
|
||||
}
|
||||
write := truncate || access&(fileWriteData|fileAppendData) != 0
|
||||
read := access&(fileReadData|fileExecute) != 0
|
||||
// Opening a FIFO or a device could block or have side effects;
|
||||
// such files are visible but their content is not served.
|
||||
if (read || write) && !fi.Mode().IsRegular() {
|
||||
return fail(statusAccessDenied)
|
||||
}
|
||||
if read || write {
|
||||
flag := os.O_RDONLY
|
||||
if write {
|
||||
flag = os.O_RDWR
|
||||
}
|
||||
if truncate {
|
||||
for _, l := range sf.locks {
|
||||
if l.n != 0 {
|
||||
return fail(statusFileLockConflict)
|
||||
}
|
||||
}
|
||||
}
|
||||
f, err = s.root.OpenFile(p, flag|syscall.O_NONBLOCK, 0)
|
||||
if err != nil && write && errors.Is(err, fs.ErrPermission) {
|
||||
switch {
|
||||
case desired&accessMaximum != 0 && !truncate:
|
||||
// The client asked for whatever it can get:
|
||||
// settle for what the file permits.
|
||||
access &^= fileWriteData | fileAppendData
|
||||
if f, err = s.root.OpenFile(p, os.O_RDONLY, 0); err != nil {
|
||||
access &^= fileReadData | fileExecute
|
||||
f, err = nil, nil
|
||||
}
|
||||
case !read:
|
||||
f, err = s.root.OpenFile(p, flag&^os.O_RDWR|os.O_WRONLY|syscall.O_NONBLOCK, 0)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, 0, errStatus(err)
|
||||
}
|
||||
if f != nil {
|
||||
actual, err := f.Stat()
|
||||
if err != nil {
|
||||
return fail(errStatus(err))
|
||||
}
|
||||
if !os.SameFile(fi, actual) {
|
||||
return fail(statusSharingViolation)
|
||||
}
|
||||
if !actual.Mode().IsRegular() {
|
||||
return fail(statusAccessDenied)
|
||||
}
|
||||
}
|
||||
if truncate {
|
||||
if err := f.Truncate(0); err != nil {
|
||||
return fail(errStatus(err))
|
||||
}
|
||||
broken = s.takeHolders(sf)
|
||||
if fi, err = f.Stat(); err != nil {
|
||||
return fail(errStatus(err))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
o := &open{
|
||||
id: s.newID(),
|
||||
sess: r.sess,
|
||||
tree: r.tree,
|
||||
isDir: fi.IsDir(),
|
||||
access: access,
|
||||
shareAccess: sharing,
|
||||
shared: sf,
|
||||
path: p,
|
||||
f: f,
|
||||
deleteOnClose: opts&optDeleteOnClose != 0,
|
||||
}
|
||||
sf.opens = append(sf.opens, o)
|
||||
s.files[key] = sf
|
||||
s.nOpens++
|
||||
// Readers only: a handle that can write would break its own oplock
|
||||
// with its first write.
|
||||
if wantOplock && fi.Mode().IsRegular() && access&(fileWriteData|fileAppendData) == 0 {
|
||||
s.grantOplock(o, fi.Size(), fi.ModTime())
|
||||
}
|
||||
return o, action, statusSuccess
|
||||
}
|
||||
|
||||
// missing tells a missing file from a missing parent directory, a
|
||||
// distinction clients rely on when they create a path recursively.
|
||||
func (s *server) missing(p string) ntStatus {
|
||||
if dir := path.Dir(p); dir != "." {
|
||||
if fi, err := s.root.Stat(dir); err != nil || !fi.IsDir() {
|
||||
return statusObjectPathNotFound
|
||||
}
|
||||
}
|
||||
return statusObjectNameNotFound
|
||||
}
|
||||
|
||||
// release closes a handle that has already been removed from its session.
|
||||
func (s *server) release(o *open) ntStatus {
|
||||
o.mu.Lock()
|
||||
if o.closed {
|
||||
o.mu.Unlock()
|
||||
return statusSuccess
|
||||
}
|
||||
o.closed = true
|
||||
f := o.f
|
||||
o.f = nil
|
||||
o.dir = nil
|
||||
o.mu.Unlock()
|
||||
|
||||
var closeErr error
|
||||
if f != nil {
|
||||
closeErr = f.Close()
|
||||
}
|
||||
if o.stream != nil {
|
||||
s.releaseStream(o)
|
||||
return statusSuccess
|
||||
}
|
||||
sf := o.shared
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.nOpens--
|
||||
for i, other := range sf.opens {
|
||||
if other == o {
|
||||
sf.opens = append(sf.opens[:i], sf.opens[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
s.dropLocks(sf, o)
|
||||
s.dropOplock(o)
|
||||
if o.deleteOnClose {
|
||||
sf.deletePending = true
|
||||
}
|
||||
if len(sf.opens) == 0 {
|
||||
// The deletion requested through any handle takes effect when
|
||||
// the last one goes. Failure (a directory that filled up in
|
||||
// the meantime) has nobody left to be reported to.
|
||||
if sf.deletePending {
|
||||
if err := s.root.Remove(o.path); err != nil {
|
||||
closeErr = err
|
||||
} else {
|
||||
s.dropStreams(sf.key)
|
||||
}
|
||||
}
|
||||
delete(s.files, sf.key)
|
||||
}
|
||||
return errStatus(closeErr)
|
||||
}
|
||||
|
||||
// renamed updates the path of every handle at or below a renamed file.
|
||||
// Called with s.mu held.
|
||||
func (s *server) renamed(from, to string) {
|
||||
for _, sf := range s.files {
|
||||
for _, o := range sf.opens {
|
||||
o.mu.Lock()
|
||||
if o.path == from {
|
||||
o.path = to
|
||||
} else if strings.HasPrefix(o.path, from+"/") {
|
||||
o.path = to + o.path[len(from):]
|
||||
}
|
||||
o.mu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// lookup resolves the FileId of a request to a handle of its session and
|
||||
// tree. In a related compound request the all-ones id stands for the file
|
||||
// of the previous command.
|
||||
func (c *conn) lookup(r *request, id []byte) (*open, ntStatus) {
|
||||
persistent, volatile := le.Uint64(id), le.Uint64(id[8:])
|
||||
if r.hdr.flags&flagRelated != 0 && persistent == ^uint64(0) && volatile == ^uint64(0) {
|
||||
if !r.chain.hasFile {
|
||||
if r.chain.status != statusSuccess {
|
||||
return nil, r.chain.status
|
||||
}
|
||||
return nil, statusFileClosed
|
||||
}
|
||||
volatile = r.chain.fileID
|
||||
}
|
||||
o := r.sess.open(volatile)
|
||||
if o == nil || o.tree != r.tree {
|
||||
return nil, statusFileClosed
|
||||
}
|
||||
r.chain.fileID, r.chain.hasFile = volatile, true
|
||||
return o, statusSuccess
|
||||
}
|
||||
|
||||
func (c *conn) create(r *request) (ntStatus, []byte) {
|
||||
p := r.msg[headerSize:]
|
||||
if len(p) < 56 || le.Uint16(p) != 57 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
desired := le.Uint32(p[24:])
|
||||
disp := le.Uint32(p[36:])
|
||||
opts := le.Uint32(p[40:])
|
||||
var raw []byte
|
||||
if n := uint32(le.Uint16(p[46:])); n > 0 {
|
||||
var ok bool
|
||||
if raw, ok = sub(r.msg, uint32(le.Uint16(p[44:])), n); !ok {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
}
|
||||
contexts, ok := parseCreateContexts(r.msg, le.Uint32(p[48:]), le.Uint32(p[52:]))
|
||||
if !ok {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
name := decodeUTF16(raw)
|
||||
if trace {
|
||||
r.note = fmt.Sprintf("%q access %#x disposition %d options %#x contexts %d", name, desired, disp, opts, len(contexts))
|
||||
}
|
||||
|
||||
var (
|
||||
o *open
|
||||
action uint32
|
||||
)
|
||||
// IPC$ is connectable because clients probe it, but it holds no pipe.
|
||||
if r.tree.ipc {
|
||||
return statusObjectNameNotFound, nil
|
||||
}
|
||||
rel, stream, st := parseName(name)
|
||||
switch {
|
||||
case st != statusSuccess:
|
||||
case stream != "":
|
||||
o, action, st = c.srv.openStream(r, rel, stream, desired, disp, opts)
|
||||
default:
|
||||
o, action, st = c.srv.openFile(r, rel, desired, disp, opts, p[3] != oplockNone && p[3] != 0xFF, le.Uint32(p[32:]))
|
||||
}
|
||||
if st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
s := r.sess
|
||||
s.mu.Lock()
|
||||
closed := s.closed
|
||||
if !closed {
|
||||
s.opens[o.id] = o
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if closed {
|
||||
c.srv.release(o)
|
||||
return statusUserSessionDeleted, nil
|
||||
}
|
||||
r.chain.fileID, r.chain.hasFile = o.id, true
|
||||
|
||||
info, st := c.srv.stat(o)
|
||||
if st != statusSuccess {
|
||||
s.mu.Lock()
|
||||
delete(s.opens, o.id)
|
||||
s.mu.Unlock()
|
||||
c.srv.release(o)
|
||||
return st, nil
|
||||
}
|
||||
|
||||
out := newMsg(88)
|
||||
p = out[headerSize:]
|
||||
le.PutUint16(p, 89)
|
||||
c.srv.mu.Lock()
|
||||
if o.oplock {
|
||||
p[2] = oplockLevelII
|
||||
}
|
||||
c.srv.mu.Unlock()
|
||||
le.PutUint32(p[4:], action)
|
||||
info.putTimes(p[8:])
|
||||
le.PutUint64(p[40:], info.alloc)
|
||||
le.PutUint64(p[48:], info.size)
|
||||
le.PutUint32(p[56:], info.attrs)
|
||||
le.PutUint64(p[64:], o.id)
|
||||
le.PutUint64(p[72:], o.id)
|
||||
|
||||
var reply [][]byte
|
||||
if _, ok := contexts["MxAc"]; ok {
|
||||
// What the user may do with the file, not what this handle was
|
||||
// opened for: the Finder decides from it whether a folder can be
|
||||
// read, and takes one answered with the access of a handle
|
||||
// opened for attributes as a write-only drop box.
|
||||
maximal := accessAll
|
||||
if c.srv.cfg.ReadOnly {
|
||||
maximal = accessReadOnly
|
||||
}
|
||||
d := make([]byte, 8)
|
||||
le.PutUint32(d[4:], maximal)
|
||||
reply = append(reply, createContext("MxAc", d))
|
||||
}
|
||||
if _, ok := contexts["QFid"]; ok {
|
||||
d := make([]byte, 32)
|
||||
le.PutUint64(d, info.ino)
|
||||
le.PutUint64(d[8:], info.dev)
|
||||
reply = append(reply, createContext("QFid", d))
|
||||
}
|
||||
if len(reply) == 0 {
|
||||
return statusSuccess, append(out, 0)
|
||||
}
|
||||
le.PutUint32(out[headerSize+80:], uint32(len(out)))
|
||||
start := len(out)
|
||||
for i, ctx := range reply {
|
||||
if i < len(reply)-1 {
|
||||
ctx = pad8(ctx)
|
||||
le.PutUint32(ctx, uint32(len(ctx)))
|
||||
}
|
||||
out = append(out, ctx...)
|
||||
}
|
||||
le.PutUint32(out[headerSize+84:], uint32(len(out)-start))
|
||||
return statusSuccess, out
|
||||
}
|
||||
|
||||
// parseCreateContexts indexes the create contexts of a request by name.
|
||||
func parseCreateContexts(msg []byte, off, n uint32) (map[string][]byte, bool) {
|
||||
if n == 0 {
|
||||
return nil, true
|
||||
}
|
||||
b, ok := sub(msg, off, n)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
out := make(map[string][]byte)
|
||||
for len(out) < 64 {
|
||||
if len(b) < 16 {
|
||||
return nil, false
|
||||
}
|
||||
next := le.Uint32(b)
|
||||
name, ok1 := sub(b, uint32(le.Uint16(b[4:])), uint32(le.Uint16(b[6:])))
|
||||
data, ok2 := sub(b, uint32(le.Uint16(b[10:])), le.Uint32(b[12:]))
|
||||
if !ok1 || !ok2 {
|
||||
return nil, false
|
||||
}
|
||||
out[string(name)] = data
|
||||
if next == 0 {
|
||||
return out, true
|
||||
}
|
||||
if next < 16 || uint64(next) > uint64(len(b)) {
|
||||
return nil, false
|
||||
}
|
||||
b = b[next:]
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func createContext(name string, data []byte) []byte {
|
||||
b := make([]byte, 24, 24+len(data))
|
||||
le.PutUint16(b[4:], 16)
|
||||
le.PutUint16(b[6:], 4)
|
||||
le.PutUint16(b[10:], 24)
|
||||
le.PutUint32(b[12:], uint32(len(data)))
|
||||
copy(b[16:], name)
|
||||
return append(b, data...)
|
||||
}
|
||||
|
||||
func (c *conn) closeFile(r *request) (ntStatus, []byte) {
|
||||
p := r.msg[headerSize:]
|
||||
if len(p) < 24 || le.Uint16(p) != 24 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
o, st := c.lookup(r, p[8:24])
|
||||
if st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
out := newMsg(60)
|
||||
q := out[headerSize:]
|
||||
le.PutUint16(q, 60)
|
||||
// Flag 1 asks for the attributes of the file as it is being closed.
|
||||
if le.Uint16(p[2:])&1 != 0 {
|
||||
if info, st := c.srv.stat(o); st == statusSuccess {
|
||||
le.PutUint16(q[2:], 1)
|
||||
info.putTimes(q[8:])
|
||||
le.PutUint64(q[40:], info.alloc)
|
||||
le.PutUint64(q[48:], info.size)
|
||||
le.PutUint32(q[56:], info.attrs)
|
||||
}
|
||||
}
|
||||
if _, f := o.location(); f != nil && o.access&(fileWriteData|fileAppendData) != 0 {
|
||||
if err := f.Sync(); err != nil {
|
||||
r.sess.mu.Lock()
|
||||
delete(r.sess.opens, o.id)
|
||||
r.sess.mu.Unlock()
|
||||
c.srv.release(o)
|
||||
return errStatus(err), nil
|
||||
}
|
||||
}
|
||||
s := r.sess
|
||||
s.mu.Lock()
|
||||
delete(s.opens, o.id)
|
||||
s.mu.Unlock()
|
||||
st = c.srv.release(o)
|
||||
r.chain.hasFile = false
|
||||
if st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
return statusSuccess, out
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Level II oplocks, and only those.
|
||||
//
|
||||
// Without any oplock a client may cache nothing: reading a small file costs
|
||||
// it an extra round trip to find the end of the file, which measured at up
|
||||
// to four times the time Samba takes on a tree of small files. A level II
|
||||
// oplock lets every holder cache what it reads, and costs the server one
|
||||
// thing: telling the holders when the file changes. That notification needs
|
||||
// no acknowledgement, unlike the break of an exclusive oplock or of a lease,
|
||||
// which is why the server stops at this level.
|
||||
//
|
||||
// The file can also change behind the server, written by the workload that
|
||||
// owns the volume. A client holding an oplock would never look again, so the
|
||||
// server watches the files under oplock and breaks when one moves.
|
||||
|
||||
const (
|
||||
oplockNone = 0x00
|
||||
oplockLevelII = 0x01
|
||||
|
||||
// watchInterval is how often files under oplock are checked for a
|
||||
// change made outside the server, hence how stale a cached read of
|
||||
// a file the workload is writing can be.
|
||||
watchInterval = time.Second
|
||||
)
|
||||
|
||||
// grantOplock records o as a level II holder. Called with s.mu held.
|
||||
func (s *server) grantOplock(o *open, size int64, mtime time.Time) {
|
||||
sf := o.shared
|
||||
if sf.holders.Load() == 0 {
|
||||
sf.size, sf.mtime = size, mtime
|
||||
}
|
||||
o.oplock = true
|
||||
sf.holders.Add(1)
|
||||
s.oplocks.Add(1)
|
||||
}
|
||||
|
||||
// takeHolders ends every oplock on a file and returns the handles to
|
||||
// notify. Called with s.mu held.
|
||||
func (s *server) takeHolders(sf *sharedFile) []*open {
|
||||
var out []*open
|
||||
for _, o := range sf.opens {
|
||||
if o.oplock {
|
||||
s.dropOplock(o)
|
||||
out = append(out, o)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// dropOplock forgets the oplock of a handle. Called with s.mu held.
|
||||
func (s *server) dropOplock(o *open) {
|
||||
if o.oplock {
|
||||
o.oplock = false
|
||||
o.shared.holders.Add(-1)
|
||||
s.oplocks.Add(-1)
|
||||
}
|
||||
}
|
||||
|
||||
// breakOplocks tells the holders of a file that it is about to change. from
|
||||
// is the connection whose request causes the change, or nil.
|
||||
func (s *server) breakOplocks(from *conn, sf *sharedFile) {
|
||||
// Writes come by the thousand and oplocked files are few: the common
|
||||
// case must not take the server lock.
|
||||
if sf.holders.Load() == 0 {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
holders := s.takeHolders(sf)
|
||||
s.mu.Unlock()
|
||||
s.notifyBreak(from, holders)
|
||||
}
|
||||
|
||||
// notifyBreak sends the oplock break notifications. It must be called
|
||||
// without s.mu, since it writes to the network.
|
||||
func (s *server) notifyBreak(from *conn, holders []*open) {
|
||||
for _, o := range holders {
|
||||
msg := newMsg(24)
|
||||
h := header{command: cmdOplockBreak, flags: flagResponse, messageID: ^uint64(0)}
|
||||
h.put(msg)
|
||||
le.PutUint16(msg[headerSize:], 24)
|
||||
msg[headerSize+2] = oplockNone
|
||||
le.PutUint64(msg[headerSize+8:], o.id)
|
||||
le.PutUint64(msg[headerSize+16:], o.id)
|
||||
c := o.sess.conn
|
||||
if c == from {
|
||||
// Ahead of the response to the request that broke it.
|
||||
c.send(msg)
|
||||
} else {
|
||||
// Another client, which may be slow to read: it must
|
||||
// not hold up this one.
|
||||
go c.send(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// watch breaks the oplocks of the files that changed without the server
|
||||
// being involved.
|
||||
func (s *server) watch(ctx context.Context) {
|
||||
type probe struct {
|
||||
sf *sharedFile
|
||||
path string
|
||||
size int64
|
||||
mtime time.Time
|
||||
}
|
||||
tick := time.NewTicker(watchInterval)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
if s.oplocks.Load() == 0 {
|
||||
continue
|
||||
}
|
||||
var probes []probe
|
||||
s.mu.Lock()
|
||||
for _, sf := range s.files {
|
||||
if sf.holders.Load() > 0 && len(sf.opens) > 0 {
|
||||
probes = append(probes, probe{sf, sf.opens[0].path, sf.size, sf.mtime})
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, p := range probes {
|
||||
fi, err := s.root.Stat(p.path)
|
||||
if err == nil && fi.Size() == p.size && fi.ModTime().Equal(p.mtime) {
|
||||
continue
|
||||
}
|
||||
s.breakOplocks(nil, p.sf)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// oplockBreak answers the acknowledgement some clients send to a break,
|
||||
// though a break to "none" does not call for one.
|
||||
func (c *conn) oplockBreak(r *request) (ntStatus, []byte) {
|
||||
p := r.msg[headerSize:]
|
||||
if len(p) < 24 || le.Uint16(p) != 24 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
if _, st := c.lookup(r, p[8:24]); st != statusSuccess {
|
||||
return st, nil
|
||||
}
|
||||
out := newMsg(24)
|
||||
le.PutUint16(out[headerSize:], 24)
|
||||
copy(out[headerSize+8:], p[8:24])
|
||||
return statusSuccess, out
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package smbserver
|
||||
|
||||
// compatibleShare applies both handles' SMB share access masks before opening
|
||||
// or truncating an existing file. This is independent of authentication.
|
||||
func compatibleShare(a, share, b, other uint32) bool {
|
||||
needs := func(access uint32) uint32 {
|
||||
var n uint32
|
||||
if access&(fileReadData|fileExecute) != 0 {
|
||||
n |= 1
|
||||
}
|
||||
if access&(fileWriteData|fileAppendData) != 0 {
|
||||
n |= 2
|
||||
}
|
||||
if access&accessDelete != 0 {
|
||||
n |= 4
|
||||
}
|
||||
return n
|
||||
}
|
||||
return needs(a)&^other == 0 && needs(b)&^share == 0
|
||||
}
|
||||
|
||||
// ioAllowed must be called with the server mutex held, including during the
|
||||
// subsequent I/O. Locks protect data, not just competing LOCK requests.
|
||||
func ioAllowed(o *open, off, n uint64, write bool) bool {
|
||||
for _, l := range o.shared.locks {
|
||||
if l.owner != o && (write || l.exclusive) && l.overlaps(off, n) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func takeLock(c *testClient, id []byte, flags uint32) ntStatus {
|
||||
body := make([]byte, 24)
|
||||
le.PutUint16(body, 48)
|
||||
le.PutUint16(body[2:], 1)
|
||||
copy(body[8:], id)
|
||||
body = le.AppendUint64(body, 0)
|
||||
body = le.AppendUint64(body, 100)
|
||||
body = le.AppendUint32(body, flags)
|
||||
body = le.AppendUint32(body, 0)
|
||||
st, _ := c.do(cmdLock, body)
|
||||
return st
|
||||
}
|
||||
func TestRouterShelfLocksProtectData(t *testing.T) {
|
||||
addr := startServer(t, Config{DiskMetadata: true})
|
||||
a, b := connect(t, addr), connect(t, addr)
|
||||
ia, st := a.create("file", accessRW, dispCreate, 0)
|
||||
if st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
ib, st := b.create("file", accessRW, dispOpen, 0)
|
||||
if st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
if st := a.write(ia, 0, []byte("original")); st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
if st := takeLock(a, ia, lockExclusive); st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
if st := b.write(ib, 0, []byte("corrupt!")); st != statusFileLockConflict {
|
||||
t.Fatalf("locked write: %x", st)
|
||||
}
|
||||
if _, st := b.read(ib, 0, 8); st != statusFileLockConflict {
|
||||
t.Fatalf("locked read: %x", st)
|
||||
}
|
||||
if st, _ := b.do(cmdSetInfo, setInfoBody(ib, fileEndOfFile, le.AppendUint64(nil, 0))); st != statusFileLockConflict {
|
||||
t.Fatalf("locked truncate: %x", st)
|
||||
}
|
||||
if _, st := b.create("file", accessRW, dispOverwrite, 0); st != statusFileLockConflict {
|
||||
t.Fatalf("locked overwrite: %x", st)
|
||||
}
|
||||
if st := takeLock(a, ia, lockUnlock); st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
if data, st := b.read(ib, 0, 8); st != statusSuccess || string(data) != "original" {
|
||||
t.Fatalf("data damaged: %q %x", data, st)
|
||||
}
|
||||
}
|
||||
func TestRouterShelfShareModes(t *testing.T) {
|
||||
addr := startServer(t, Config{})
|
||||
a, b := connect(t, addr), connect(t, addr)
|
||||
body := createBody("file", accessRW, dispCreate, 0)
|
||||
le.PutUint32(body[32:], 1) // only share read
|
||||
st, resp := a.do(cmdCreate, body)
|
||||
if st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
id := bytes.Clone(resp[headerSize+64 : headerSize+80])
|
||||
if _, st := b.create("file", accessRW, dispOverwrite, 0); st != statusSharingViolation {
|
||||
t.Fatalf("conflicting writer: %x", st)
|
||||
}
|
||||
if _, st := b.create("file", accessRead, dispOpen, 0); st != statusSuccess {
|
||||
t.Fatalf("compatible reader: %x", st)
|
||||
}
|
||||
if st := a.close(id); st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
}
|
||||
func TestRouterShelfDiskMetadata(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
addr := startServer(t, Config{Root: root, DiskMetadata: true})
|
||||
c := connect(t, addr)
|
||||
id, st := c.create("data", accessRW, dispCreate, 0)
|
||||
if st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
basic := make([]byte, 40)
|
||||
le.PutUint32(basic[32:], attrReadOnly)
|
||||
if st, _ := c.do(cmdSetInfo, setInfoBody(id, fileBasic, basic)); st != statusNotSupported {
|
||||
t.Fatalf("per-file protection falsely acknowledged: %x", st)
|
||||
}
|
||||
c.close(id)
|
||||
if _, st := c.create("data:AFP_Resource", accessRW, dispOpenIf, 0); st != statusNotSupported {
|
||||
t.Fatalf("volatile metadata accepted: %x", st)
|
||||
}
|
||||
for _, name := range []string{"._data", ".DS_Store"} {
|
||||
id, st := c.create(name, accessRW, dispCreate, 0)
|
||||
if st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
if st := c.write(id, 0, []byte("persistent metadata")); st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
c.close(id)
|
||||
}
|
||||
// A new independent server sees the disk files, with no in-memory metadata.
|
||||
d := connect(t, startServer(t, Config{Root: root, DiskMetadata: true}))
|
||||
for _, name := range []string{"._data", ".DS_Store"} {
|
||||
id, st := d.create(name, accessRead, dispOpen, 0)
|
||||
if st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
data, st := d.read(id, 0, 100)
|
||||
if st != statusSuccess || string(data) != "persistent metadata" {
|
||||
t.Fatalf("lost metadata: %q %x", data, st)
|
||||
}
|
||||
d.close(id)
|
||||
}
|
||||
}
|
||||
func TestRouterShelfTransferAndReconnect(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
addr := startServer(t, Config{Root: root, DiskMetadata: true})
|
||||
c := connect(t, addr)
|
||||
id, st := c.create("transfer.partial", accessRW, dispCreate, 0)
|
||||
if st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
block := bytes.Repeat([]byte("0123456789abcdef"), 4096)
|
||||
want := sha256.New()
|
||||
const chunks = 192 // 12 MiB; only one 64 KiB payload is held at a time.
|
||||
for i := 0; i < chunks; i++ {
|
||||
if i == chunks/2 {
|
||||
c.nc.Close() // interrupt an open transfer; reconnect and explicitly reopen
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
c = connect(t, addr)
|
||||
id, st = c.create("transfer.partial", accessRW, dispOpen, 0)
|
||||
if st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
}
|
||||
if st := c.write(id, uint64(i*len(block)), block); st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
want.Write(block)
|
||||
}
|
||||
if st := c.close(id); st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
f, err := os.Open(filepath.Join(root, "transfer.partial"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
got := sha256.New()
|
||||
if _, err := io.Copy(got, f); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(want.Sum(nil), got.Sum(nil)) {
|
||||
t.Fatal("transfer checksum mismatch")
|
||||
}
|
||||
}
|
||||
func TestRouterShelfDirectoryBoundIsExplicit(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
for i := 0; i <= maxDirectoryEntries; i++ {
|
||||
if err := os.WriteFile(filepath.Join(root, fmt.Sprint(i)), nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
c := connect(t, startServer(t, Config{Root: root, DiskMetadata: true}))
|
||||
id, st := c.create("", accessRead, dispOpen, optDirectory)
|
||||
if st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
st, _ = c.do(cmdQueryDirectory, queryDirectoryBody(id, classNames, "*", maxIO))
|
||||
if st != statusInsufficientResources {
|
||||
t.Fatalf("oversized listing should fail explicitly: %x", st)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouterShelfCloseReportsDeleteFailure(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
c := connect(t, startServer(t, Config{Root: root, DiskMetadata: true}))
|
||||
id, st := c.create("folder", accessRW, dispCreate, optDirectory)
|
||||
if st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
if st, _ := c.do(cmdSetInfo, setInfoBody(id, fileDisposition, []byte{1})); st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "folder", "external-change"), []byte("external writer"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if st := c.close(id); st != statusDirectoryNotEmpty {
|
||||
t.Fatalf("delete failure acknowledged as success: %x", st)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouterShelfConcurrentWritesThroughRename(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
addr := startServer(t, Config{Root: root, DiskMetadata: true})
|
||||
a, b := connect(t, addr), connect(t, addr)
|
||||
ia, st := a.create("shared", accessRW, dispCreate, 0)
|
||||
if st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
ib, st := b.create("shared", accessRW, dispOpen, 0)
|
||||
if st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
const count = 32
|
||||
one, two := bytes.Repeat([]byte{1}, maxIO), bytes.Repeat([]byte{2}, maxIO)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for i := 0; i < count; i++ {
|
||||
if st := a.write(ia, uint64(2*i*maxIO), one); st != statusSuccess {
|
||||
t.Errorf("writer a: %x", st)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
for i := 0; i < count; i++ {
|
||||
if st := b.write(ib, uint64((2*i+1)*maxIO), two); st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
}
|
||||
<-done
|
||||
if st, _ := b.do(cmdSetInfo, setInfoBody(ib, fileRename, renameData("renamed", false))); st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
a.close(ia)
|
||||
b.close(ib)
|
||||
f, err := os.Open(filepath.Join(root, "renamed"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
block := make([]byte, maxIO)
|
||||
for i := 0; i < count*2; i++ {
|
||||
if _, err := io.ReadFull(f, block); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := one
|
||||
if i%2 == 1 {
|
||||
want = two
|
||||
}
|
||||
if !bytes.Equal(block, want) {
|
||||
t.Fatalf("concurrent data damaged at chunk %d", i)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouterShelfRefusesNonregularData(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := syscall.Mkfifo(filepath.Join(root, "pipe"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := connect(t, startServer(t, Config{Root: root, DiskMetadata: true}))
|
||||
if _, st := c.create("pipe", accessRead, dispOpen, 0); st != statusAccessDenied {
|
||||
t.Fatalf("FIFO read should be denied: %x", st)
|
||||
}
|
||||
if _, st := c.create("pipe", accessRW, dispOverwrite, 0); st != statusAccessDenied {
|
||||
t.Fatalf("FIFO overwrite should be denied: %x", st)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,311 @@
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// session is an authenticated logon on one connection.
|
||||
type session struct {
|
||||
id uint64
|
||||
conn *conn
|
||||
|
||||
// auth is the exchange in progress; nil once it has concluded.
|
||||
auth *authState
|
||||
authenticated bool
|
||||
|
||||
// signingKey is the NTLM session key on SMB 2, and a key derived from
|
||||
// it on SMB 3.0, which also changes the algorithm.
|
||||
signingKey []byte
|
||||
cmac bool
|
||||
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
trees map[uint32]*tree
|
||||
opens map[uint64]*open
|
||||
nextTree uint32
|
||||
}
|
||||
|
||||
// tree is a connection to the share or to IPC$.
|
||||
type tree struct {
|
||||
id uint32
|
||||
ipc bool
|
||||
}
|
||||
|
||||
type authState struct {
|
||||
ntlm ntlmAuth
|
||||
rounds int
|
||||
raw bool
|
||||
mechTypes []byte
|
||||
wantMIC bool
|
||||
}
|
||||
|
||||
func (c *conn) sessionSetup(r *request) (ntStatus, []byte) {
|
||||
p := r.msg[headerSize:]
|
||||
if len(p) < 24 || le.Uint16(p) != 25 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
// Binding an existing session to a new connection is multichannel,
|
||||
// which is not offered.
|
||||
if p[2]&1 != 0 {
|
||||
return statusRequestNotAccepted, nil
|
||||
}
|
||||
token, ok := sub(r.msg, uint32(le.Uint16(p[12:])), uint32(le.Uint16(p[14:])))
|
||||
if !ok {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
previous := le.Uint64(p[16:])
|
||||
|
||||
var sess *session
|
||||
if r.hdr.sessionID == 0 {
|
||||
sess = &session{
|
||||
id: c.srv.newID(),
|
||||
conn: c,
|
||||
auth: &authState{},
|
||||
trees: make(map[uint32]*tree),
|
||||
opens: make(map[uint64]*open),
|
||||
}
|
||||
c.mu.Lock()
|
||||
full := len(c.sessions) >= maxSessionsPerConn
|
||||
if !full {
|
||||
c.sessions[sess.id] = sess
|
||||
}
|
||||
c.mu.Unlock()
|
||||
if full {
|
||||
return statusInsufficientResources, nil
|
||||
}
|
||||
} else if sess = c.session(r.hdr.sessionID); sess == nil {
|
||||
return statusUserSessionDeleted, nil
|
||||
}
|
||||
r.sess = sess
|
||||
if sess.authenticated {
|
||||
// Re-authentication of a live session: the credentials are
|
||||
// checked again and the keys are kept.
|
||||
if sess.auth == nil {
|
||||
sess.auth = &authState{}
|
||||
}
|
||||
}
|
||||
|
||||
st, blob := sess.step(token)
|
||||
switch st {
|
||||
case statusMoreProcessingRequired:
|
||||
case statusSuccess:
|
||||
key := sess.auth.ntlm.sessionKey
|
||||
sess.auth = nil
|
||||
if !sess.authenticated {
|
||||
sess.signingKey = key
|
||||
if c.dialect == dialect300 {
|
||||
sess.signingKey = kdf(key, []byte("SMB2AESCMAC\x00"), []byte("SmbSign\x00"))
|
||||
sess.cmac = true
|
||||
}
|
||||
sess.authenticated = true
|
||||
c.authenticated = true
|
||||
c.nc.SetReadDeadline(time.Time{})
|
||||
c.srv.register(sess, previous)
|
||||
c.srv.logf("session opened from %v", c.nc.RemoteAddr())
|
||||
}
|
||||
r.sign = true
|
||||
default:
|
||||
c.srv.logf("authentication failed from %v", c.nc.RemoteAddr())
|
||||
if sess.authenticated {
|
||||
sess.auth = nil
|
||||
} else {
|
||||
sess.close()
|
||||
}
|
||||
r.sess = nil
|
||||
return st, nil
|
||||
}
|
||||
|
||||
out := newMsg(8)
|
||||
le.PutUint16(out[headerSize:], 9)
|
||||
le.PutUint16(out[headerSize+4:], headerSize+8)
|
||||
le.PutUint16(out[headerSize+6:], uint16(len(blob)))
|
||||
return st, append(out, blob...)
|
||||
}
|
||||
|
||||
// step advances the SPNEGO and NTLM exchange by one client token.
|
||||
func (s *session) step(token []byte) (ntStatus, []byte) {
|
||||
a := s.auth
|
||||
// A legitimate exchange takes two or three legs.
|
||||
if a.rounds++; a.rounds > 4 {
|
||||
return statusLogonFailure, nil
|
||||
}
|
||||
tok, ok := parseSPNEGO(token)
|
||||
if !ok {
|
||||
return statusLogonFailure, nil
|
||||
}
|
||||
if tok.raw {
|
||||
a.raw = true
|
||||
}
|
||||
if tok.init {
|
||||
a.mechTypes = tok.mechTypes
|
||||
// RFC 4178 makes the MIC mandatory when the mechanism that ends
|
||||
// up used was not the first choice of the client.
|
||||
a.wantMIC = !tok.ntlmFirst
|
||||
}
|
||||
wrap := func(state byte, withMech bool, t, mic []byte) []byte {
|
||||
if a.raw {
|
||||
return t
|
||||
}
|
||||
return negTokenResp(state, withMech, t, mic)
|
||||
}
|
||||
switch {
|
||||
case isNTLM(tok.mechToken, 1):
|
||||
challenge, ok := a.ntlm.start(tok.mechToken, time.Now())
|
||||
if !ok {
|
||||
return statusLogonFailure, nil
|
||||
}
|
||||
return statusMoreProcessingRequired, wrap(negAcceptIncomplete, true, challenge, nil)
|
||||
case isNTLM(tok.mechToken, 3):
|
||||
cfg := &s.conn.srv.cfg
|
||||
if !a.ntlm.authenticate(tok.mechToken, cfg.User, cfg.NTHash) {
|
||||
return statusLogonFailure, nil
|
||||
}
|
||||
var mic []byte
|
||||
if a.mechTypes != nil && (tok.mic != nil || a.wantMIC) {
|
||||
// The MIC of the client is not verified: with a single
|
||||
// mechanism on offer there is no negotiation it could
|
||||
// have been protecting.
|
||||
mic = a.ntlm.mechListMIC(a.mechTypes)
|
||||
}
|
||||
return statusSuccess, wrap(negAcceptCompleted, false, nil, mic)
|
||||
case tok.init && !tok.raw:
|
||||
// The client led with a token for a mechanism the server does
|
||||
// not have (Kerberos, NEGOEX). Point it at NTLMSSP.
|
||||
return statusMoreProcessingRequired, negTokenResp(negAcceptIncomplete, true, nil, nil)
|
||||
}
|
||||
return statusLogonFailure, nil
|
||||
}
|
||||
|
||||
func (s *session) mac(msg []byte) []byte {
|
||||
if s.cmac {
|
||||
m := aesCMAC(s.signingKey, msg)
|
||||
return m[:]
|
||||
}
|
||||
return mac(s.signingKey, msg)
|
||||
}
|
||||
|
||||
func (s *session) tree(id uint32) *tree {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.trees[id]
|
||||
}
|
||||
|
||||
func (s *session) open(id uint64) *open {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.opens[id]
|
||||
}
|
||||
|
||||
func (s *session) removeTree(t *tree) {
|
||||
s.mu.Lock()
|
||||
delete(s.trees, t.id)
|
||||
var opens []*open
|
||||
for id, o := range s.opens {
|
||||
if o.tree == t {
|
||||
opens = append(opens, o)
|
||||
delete(s.opens, id)
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, o := range opens {
|
||||
s.conn.srv.release(o)
|
||||
}
|
||||
}
|
||||
|
||||
// close ends the session and releases every file it holds. The keys stay,
|
||||
// so that the response to a LOGOFF can still be signed.
|
||||
func (s *session) close() {
|
||||
s.mu.Lock()
|
||||
if s.closed {
|
||||
s.mu.Unlock()
|
||||
return
|
||||
}
|
||||
s.closed = true
|
||||
s.authenticated = false
|
||||
opens := s.opens
|
||||
s.opens = map[uint64]*open{}
|
||||
s.trees = map[uint32]*tree{}
|
||||
s.mu.Unlock()
|
||||
for _, o := range opens {
|
||||
s.conn.srv.release(o)
|
||||
}
|
||||
c := s.conn
|
||||
c.mu.Lock()
|
||||
delete(c.sessions, s.id)
|
||||
c.mu.Unlock()
|
||||
c.srv.mu.Lock()
|
||||
delete(c.srv.sessions, s.id)
|
||||
c.srv.mu.Unlock()
|
||||
}
|
||||
|
||||
// register records a freshly authenticated session and retires the one it
|
||||
// replaces. A client that reconnects after a network cut names its previous
|
||||
// session; closing it releases the handles and locks the dead connection
|
||||
// would otherwise hold until TCP notices.
|
||||
func (srv *server) register(s *session, previous uint64) {
|
||||
srv.mu.Lock()
|
||||
srv.sessions[s.id] = s
|
||||
old := srv.sessions[previous]
|
||||
srv.mu.Unlock()
|
||||
if old != nil && old != s {
|
||||
old.close()
|
||||
if old.conn != s.conn {
|
||||
old.conn.nc.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *conn) treeConnect(r *request) (ntStatus, []byte) {
|
||||
p := r.msg[headerSize:]
|
||||
if len(p) < 8 || le.Uint16(p) != 9 {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
raw, ok := sub(r.msg, uint32(le.Uint16(p[4:])), uint32(le.Uint16(p[6:])))
|
||||
if !ok {
|
||||
return statusInvalidParameter, nil
|
||||
}
|
||||
// The path is \\server\share; the server part is whatever name the
|
||||
// client reached us by and is not checked.
|
||||
name := decodeUTF16(raw)
|
||||
name = name[strings.LastIndexByte(name, '\\')+1:]
|
||||
t := &tree{}
|
||||
switch {
|
||||
case strings.EqualFold(name, "IPC$"):
|
||||
t.ipc = true
|
||||
case strings.EqualFold(name, c.srv.cfg.Share):
|
||||
default:
|
||||
return statusBadNetworkName, nil
|
||||
}
|
||||
s := r.sess
|
||||
s.mu.Lock()
|
||||
full := len(s.trees) >= maxTreesPerSession || s.closed
|
||||
if !full {
|
||||
s.nextTree++
|
||||
t.id = s.nextTree
|
||||
s.trees[t.id] = t
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if full {
|
||||
return statusInsufficientResources, nil
|
||||
}
|
||||
r.tree = t
|
||||
|
||||
out := newMsg(16)
|
||||
p = out[headerSize:]
|
||||
le.PutUint16(p, 16)
|
||||
access := uint32(0x001F01FF)
|
||||
switch {
|
||||
case t.ipc:
|
||||
p[2] = 2 // pipe
|
||||
access = accessReadOnly
|
||||
default:
|
||||
p[2] = 1 // disk
|
||||
if c.srv.cfg.ReadOnly {
|
||||
access = accessReadOnly
|
||||
}
|
||||
}
|
||||
le.PutUint32(p[12:], access)
|
||||
return statusSuccess, out
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
// Modified by RouterShelf. See UPSTREAM.md for adaptation details and Apache-2.0 provenance.
|
||||
|
||||
// Package smbserver is an SMB 2 and 3 file server in pure Go.
|
||||
//
|
||||
// It serves one directory as one share to one user, on a listener the caller
|
||||
// provides. It needs no privilege, no account database and no file on disk
|
||||
// besides the directory it serves: the files it creates belong to the uid of
|
||||
// the process, whatever that uid is.
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config describes the share to serve.
|
||||
type Config struct {
|
||||
// Root is the directory to serve. Nothing outside of it is reachable,
|
||||
// including through symbolic links.
|
||||
Root string
|
||||
// ExpectedRoot prevents serving a replacement between validation and open.
|
||||
ExpectedRoot os.FileInfo
|
||||
// Ready runs after confinement and cancellation are initialized.
|
||||
Ready func()
|
||||
// Share is the name clients connect to, as in //host/Share.
|
||||
Share string
|
||||
// User is the only account that may log in.
|
||||
User string
|
||||
// NTHash is the NT hash of the password of User. See NTHash.
|
||||
NTHash [16]byte
|
||||
// Allow restricts the source addresses accepted. Empty means any.
|
||||
Allow []netip.Prefix
|
||||
// ReadOnly refuses every operation that would modify the share.
|
||||
ReadOnly bool
|
||||
// DiskMetadata disables ephemeral streams; clients can use AppleDouble files.
|
||||
DiskMetadata bool
|
||||
// CaseInsensitive describes exFAT-style name lookup.
|
||||
CaseInsensitive bool
|
||||
// Logf, when set, receives one line per notable event.
|
||||
Logf func(format string, args ...any)
|
||||
}
|
||||
|
||||
// Limits on what a client may ask of the server. They bound the memory and
|
||||
// the descriptors a peer can pin, before and after authentication.
|
||||
const (
|
||||
maxConns = 4
|
||||
maxSessionsPerConn = 2
|
||||
maxTreesPerSession = 2
|
||||
maxOpens = 64
|
||||
maxCompound = 8
|
||||
maxCredits = 128
|
||||
// maxIO is the largest read, write or transact payload.
|
||||
maxIO = 64 << 10
|
||||
// preAuthFrame bounds a message from a peer that has not logged in.
|
||||
preAuthFrame = 128 << 10
|
||||
// preAuthTimeout is how long a peer may stay connected without
|
||||
// completing authentication.
|
||||
preAuthTimeout = 30 * time.Second
|
||||
writeTimeout = 2 * time.Minute
|
||||
)
|
||||
|
||||
type server struct {
|
||||
cfg Config
|
||||
root *os.Root
|
||||
rootPath string
|
||||
guid [16]byte
|
||||
start time.Time
|
||||
|
||||
nextID atomic.Uint64
|
||||
// oplocks counts the handles under oplock, all files together.
|
||||
oplocks atomic.Int64
|
||||
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
conns map[*conn]struct{}
|
||||
sessions map[uint64]*session
|
||||
files map[fileKey]*sharedFile
|
||||
nOpens int
|
||||
// streams holds the named streams, by file; streamBytes is their
|
||||
// total size.
|
||||
streams map[fileKey]map[string]*memStream
|
||||
streamBytes int64
|
||||
}
|
||||
|
||||
// Serve accepts SMB connections on ln until ctx is cancelled, then closes
|
||||
// the listener and every connection and returns nil. It returns an error if
|
||||
// the configuration is invalid or the listener fails.
|
||||
func Serve(ctx context.Context, ln net.Listener, cfg Config) error {
|
||||
s, err := newServer(cfg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer s.root.Close()
|
||||
|
||||
stop := context.AfterFunc(ctx, func() {
|
||||
ln.Close()
|
||||
s.shutdown()
|
||||
})
|
||||
defer stop()
|
||||
|
||||
var wg sync.WaitGroup
|
||||
defer wg.Wait()
|
||||
defer s.shutdown()
|
||||
watching, stopWatch := context.WithCancel(ctx)
|
||||
defer stopWatch()
|
||||
wg.Go(func() { s.watch(watching) })
|
||||
if cfg.Ready != nil {
|
||||
cfg.Ready()
|
||||
}
|
||||
for {
|
||||
nc, err := ln.Accept()
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
return fmt.Errorf("smbserver: %w", err)
|
||||
}
|
||||
// Running out of descriptors is transient: back off and
|
||||
// keep serving the connections already established.
|
||||
s.logf("accept: %v", err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !s.allowed(nc.RemoteAddr()) {
|
||||
s.logf("refused connection from %v: source not allowed", nc.RemoteAddr())
|
||||
nc.Close()
|
||||
continue
|
||||
}
|
||||
c := s.newConn(nc)
|
||||
if c == nil {
|
||||
nc.Close()
|
||||
continue
|
||||
}
|
||||
wg.Go(c.serve)
|
||||
}
|
||||
}
|
||||
|
||||
func newServer(cfg Config) (*server, error) {
|
||||
if cfg.Share == "" || strings.EqualFold(cfg.Share, "IPC$") || strings.ContainsAny(cfg.Share, `\/`) {
|
||||
return nil, fmt.Errorf("smbserver: invalid share name %q", cfg.Share)
|
||||
}
|
||||
if cfg.User == "" {
|
||||
return nil, errors.New("smbserver: empty user name")
|
||||
}
|
||||
abs, err := filepath.Abs(cfg.Root)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("smbserver: %w", err)
|
||||
}
|
||||
root, err := os.OpenRoot(abs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("smbserver: %w", err)
|
||||
}
|
||||
if cfg.ExpectedRoot != nil {
|
||||
fi, err := root.Stat(".")
|
||||
if err != nil || !os.SameFile(cfg.ExpectedRoot, fi) {
|
||||
root.Close()
|
||||
return nil, errors.New("smbserver: storage identity changed before startup")
|
||||
}
|
||||
}
|
||||
s := &server{
|
||||
cfg: cfg,
|
||||
root: root,
|
||||
rootPath: abs,
|
||||
start: time.Now(),
|
||||
conns: make(map[*conn]struct{}),
|
||||
sessions: make(map[uint64]*session),
|
||||
files: make(map[fileKey]*sharedFile),
|
||||
streams: make(map[fileKey]map[string]*memStream),
|
||||
}
|
||||
rand.Read(s.guid[:])
|
||||
var seed [8]byte
|
||||
rand.Read(seed[:])
|
||||
// Identifiers start at a random point so that they are not guessable
|
||||
// across restarts; the top bit is cleared to leave room to count.
|
||||
s.nextID.Store(le.Uint64(seed[:]) >> 1)
|
||||
return s, nil
|
||||
}
|
||||
|
||||
func (s *server) logf(format string, args ...any) {
|
||||
if s.cfg.Logf != nil {
|
||||
s.cfg.Logf(format, args...)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *server) allowed(addr net.Addr) bool {
|
||||
if len(s.cfg.Allow) == 0 {
|
||||
return true
|
||||
}
|
||||
ap, err := netip.ParseAddrPort(addr.String())
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
ip := ap.Addr().Unmap()
|
||||
for _, p := range s.cfg.Allow {
|
||||
if p.Contains(ip) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *server) newConn(nc net.Conn) *conn {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.closed || len(s.conns) >= maxConns {
|
||||
return nil
|
||||
}
|
||||
if tc, ok := nc.(*net.TCPConn); ok {
|
||||
// A tunnel that drops without closing leaves the server side
|
||||
// half open; keepalives reclaim the handles and locks it holds.
|
||||
tc.SetKeepAliveConfig(net.KeepAliveConfig{Enable: true, Idle: 30 * time.Second, Interval: 10 * time.Second, Count: 3})
|
||||
}
|
||||
c := &conn{
|
||||
srv: s,
|
||||
nc: nc,
|
||||
credits: 1,
|
||||
sessions: make(map[uint64]*session),
|
||||
}
|
||||
s.conns[c] = struct{}{}
|
||||
return c
|
||||
}
|
||||
|
||||
func (s *server) shutdown() {
|
||||
s.mu.Lock()
|
||||
s.closed = true
|
||||
conns := make([]*conn, 0, len(s.conns))
|
||||
for c := range s.conns {
|
||||
conns = append(conns, c)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, c := range conns {
|
||||
c.nc.Close()
|
||||
}
|
||||
}
|
||||
|
||||
// newID returns a non-zero identifier unique for the life of the server. It
|
||||
// names sessions and open files alike.
|
||||
func (s *server) newID() uint64 {
|
||||
for {
|
||||
if id := s.nextID.Add(1); id != 0 && id != ^uint64(0) {
|
||||
return id
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package smbserver
|
||||
|
||||
import "bytes"
|
||||
|
||||
// This file holds the small subset of DER and SPNEGO ([MS-SPNG], RFC 4178)
|
||||
// that wraps NTLMSSP during session setup. It is hand-written rather than
|
||||
// built on encoding/asn1 because the structures are few, and a decoder that
|
||||
// only slices is easy to fuzz.
|
||||
|
||||
var (
|
||||
oidSPNEGO = []byte{0x2b, 0x06, 0x01, 0x05, 0x05, 0x02}
|
||||
oidNTLM = []byte{0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x02, 0x0a}
|
||||
)
|
||||
|
||||
func derTLV(tag byte, parts ...[]byte) []byte {
|
||||
n := 0
|
||||
for _, p := range parts {
|
||||
n += len(p)
|
||||
}
|
||||
out := []byte{tag}
|
||||
switch {
|
||||
case n < 0x80:
|
||||
out = append(out, byte(n))
|
||||
case n < 0x100:
|
||||
out = append(out, 0x81, byte(n))
|
||||
default:
|
||||
out = append(out, 0x82, byte(n>>8), byte(n))
|
||||
}
|
||||
for _, p := range parts {
|
||||
out = append(out, p...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// derRead splits the first TLV off b. raw is the whole element, header
|
||||
// included.
|
||||
func derRead(b []byte) (tag byte, content, raw, rest []byte, ok bool) {
|
||||
if len(b) < 2 {
|
||||
return
|
||||
}
|
||||
tag = b[0]
|
||||
n := int(b[1])
|
||||
hdr := 2
|
||||
if n >= 0x80 {
|
||||
k := n & 0x7f
|
||||
if k == 0 || k > 3 || len(b) < 2+k {
|
||||
return
|
||||
}
|
||||
n = 0
|
||||
for _, v := range b[2 : 2+k] {
|
||||
n = n<<8 | int(v)
|
||||
}
|
||||
hdr += k
|
||||
}
|
||||
if len(b)-hdr < n {
|
||||
return
|
||||
}
|
||||
return tag, b[hdr : hdr+n], b[:hdr+n], b[hdr+n:], true
|
||||
}
|
||||
|
||||
// spnegoToken is what the server needs out of a client security blob.
|
||||
type spnegoToken struct {
|
||||
// raw is set when the client sent bare NTLMSSP without SPNEGO.
|
||||
raw bool
|
||||
// init is set for a NegTokenInit, the first token of an exchange.
|
||||
init bool
|
||||
// mechTypes is the DER encoding of the client's mechanism list, which
|
||||
// the mechListMIC covers.
|
||||
mechTypes []byte
|
||||
// ntlmFirst reports whether NTLMSSP is the client's preferred
|
||||
// mechanism.
|
||||
ntlmFirst bool
|
||||
mechToken []byte
|
||||
mic []byte
|
||||
}
|
||||
|
||||
func parseSPNEGO(b []byte) (t spnegoToken, ok bool) {
|
||||
if bytes.HasPrefix(b, []byte(ntlmSignature)) {
|
||||
return spnegoToken{raw: true, mechToken: b}, true
|
||||
}
|
||||
tag, content, _, _, ok := derRead(b)
|
||||
if !ok {
|
||||
return t, false
|
||||
}
|
||||
switch tag {
|
||||
case 0x60: // GSS-API InitialContextToken
|
||||
otag, oid, _, rest, ok := derRead(content)
|
||||
if !ok || otag != 0x06 || !bytes.Equal(oid, oidSPNEGO) {
|
||||
return t, false
|
||||
}
|
||||
tag, content, _, _, ok = derRead(rest)
|
||||
if !ok || tag != 0xA0 {
|
||||
return t, false
|
||||
}
|
||||
t.init = true
|
||||
case 0xA0:
|
||||
t.init = true
|
||||
case 0xA1:
|
||||
default:
|
||||
return t, false
|
||||
}
|
||||
stag, seq, _, _, ok := derRead(content)
|
||||
if !ok || stag != 0x30 {
|
||||
return t, false
|
||||
}
|
||||
for len(seq) > 0 {
|
||||
var field []byte
|
||||
tag, field, _, seq, ok = derRead(seq)
|
||||
if !ok {
|
||||
return t, false
|
||||
}
|
||||
itag, inner, raw, _, ok := derRead(field)
|
||||
if !ok {
|
||||
return t, false
|
||||
}
|
||||
switch {
|
||||
case t.init && tag == 0xA0 && itag == 0x30:
|
||||
t.mechTypes = raw
|
||||
if ftag, first, _, _, ok := derRead(inner); ok && ftag == 0x06 {
|
||||
t.ntlmFirst = bytes.Equal(first, oidNTLM)
|
||||
}
|
||||
case tag == 0xA2 && itag == 0x04:
|
||||
t.mechToken = inner
|
||||
case tag == 0xA3 && itag == 0x04:
|
||||
t.mic = inner
|
||||
}
|
||||
}
|
||||
return t, true
|
||||
}
|
||||
|
||||
// negTokenInit is the security blob of the NEGOTIATE response: the server
|
||||
// announces NTLMSSP as its only mechanism.
|
||||
func negTokenInit() []byte {
|
||||
mechs := derTLV(0xA0, derTLV(0x30, derTLV(0x06, oidNTLM)))
|
||||
return derTLV(0x60, derTLV(0x06, oidSPNEGO), derTLV(0xA0, derTLV(0x30, mechs)))
|
||||
}
|
||||
|
||||
const (
|
||||
negAcceptCompleted = 0
|
||||
negAcceptIncomplete = 1
|
||||
)
|
||||
|
||||
func negTokenResp(state byte, withMech bool, token, mic []byte) []byte {
|
||||
seq := derTLV(0xA0, derTLV(0x0A, []byte{state}))
|
||||
if withMech {
|
||||
seq = append(seq, derTLV(0xA1, derTLV(0x06, oidNTLM))...)
|
||||
}
|
||||
if token != nil {
|
||||
seq = append(seq, derTLV(0xA2, derTLV(0x04, token))...)
|
||||
}
|
||||
if mic != nil {
|
||||
seq = append(seq, derTLV(0xA3, derTLV(0x04, mic))...)
|
||||
}
|
||||
return derTLV(0xA1, derTLV(0x30, seq))
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"hash/fnv"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// fileKey identifies a file independently of its name, so that two handles
|
||||
// opened under different paths (a rename, a hard link) share their state.
|
||||
// Where the platform exposes no inode, the path stands in.
|
||||
type fileKey struct {
|
||||
dev, ino uint64
|
||||
path string
|
||||
}
|
||||
|
||||
// sysInfo is what the platform knows about a file beyond os.FileInfo.
|
||||
type sysInfo struct {
|
||||
dev, ino uint64
|
||||
nlink uint32
|
||||
alloc uint64
|
||||
atime time.Time
|
||||
ctime time.Time
|
||||
btime time.Time
|
||||
}
|
||||
|
||||
// fileInfo is a file as the protocol describes it.
|
||||
type fileInfo struct {
|
||||
size, alloc uint64
|
||||
btime, atime time.Time
|
||||
mtime, ctime time.Time
|
||||
attrs uint32
|
||||
dev, ino uint64
|
||||
nlink uint32
|
||||
isDir bool
|
||||
}
|
||||
|
||||
func keyOf(fi os.FileInfo, p string) fileKey {
|
||||
if st, ok := sysStat(fi); ok {
|
||||
return fileKey{dev: st.dev, ino: st.ino}
|
||||
}
|
||||
return fileKey{path: p}
|
||||
}
|
||||
|
||||
func hash64(s string) uint64 {
|
||||
h := fnv.New64a()
|
||||
h.Write([]byte(s))
|
||||
return h.Sum64()
|
||||
}
|
||||
|
||||
// info converts a stat result. p is the path of the file relative to the
|
||||
// share root; its last element decides the hidden attribute.
|
||||
func (s *server) info(fi os.FileInfo, p string) fileInfo {
|
||||
in := fileInfo{
|
||||
mtime: fi.ModTime(),
|
||||
isDir: fi.IsDir(),
|
||||
nlink: 1,
|
||||
}
|
||||
if st, ok := sysStat(fi); ok {
|
||||
in.dev, in.ino, in.nlink = st.dev, st.ino, st.nlink
|
||||
in.atime, in.ctime, in.btime = st.atime, st.ctime, st.btime
|
||||
in.alloc = st.alloc
|
||||
} else {
|
||||
in.ino = hash64(p)
|
||||
in.alloc = (uint64(fi.Size()) + 4095) &^ 4095
|
||||
}
|
||||
if in.atime.IsZero() {
|
||||
in.atime = in.mtime
|
||||
}
|
||||
if in.ctime.IsZero() {
|
||||
in.ctime = in.mtime
|
||||
}
|
||||
// Linux does not report a creation time through stat. The modification
|
||||
// time is the closest honest answer, and it is never in the future of
|
||||
// the other timestamps, which some clients check.
|
||||
if in.btime.IsZero() || in.btime.After(in.mtime) {
|
||||
in.btime = in.mtime
|
||||
}
|
||||
if in.isDir {
|
||||
in.attrs = attrDirectory
|
||||
in.alloc = 0
|
||||
} else {
|
||||
in.attrs = attrArchive
|
||||
in.size = uint64(fi.Size())
|
||||
}
|
||||
// A file nobody may write is read-only to a Windows client, which then
|
||||
// offers to clear the attribute before deleting; see setBasic.
|
||||
if !in.isDir && fi.Mode().Perm()&0o222 == 0 {
|
||||
in.attrs |= attrReadOnly
|
||||
}
|
||||
if base := path.Base(p); strings.HasPrefix(base, ".") && base != "." && base != ".." {
|
||||
in.attrs |= attrHidden
|
||||
}
|
||||
return in
|
||||
}
|
||||
|
||||
// putTimes writes the four timestamps every information class starts with.
|
||||
func (in *fileInfo) putTimes(b []byte) {
|
||||
le.PutUint64(b, filetime(in.btime))
|
||||
le.PutUint64(b[8:], filetime(in.atime))
|
||||
le.PutUint64(b[16:], filetime(in.mtime))
|
||||
le.PutUint64(b[24:], filetime(in.ctime))
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func sysStat(fi os.FileInfo) (sysInfo, bool) {
|
||||
st, ok := fi.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return sysInfo{}, false
|
||||
}
|
||||
return sysInfo{
|
||||
dev: uint64(st.Dev),
|
||||
ino: st.Ino,
|
||||
nlink: uint32(st.Nlink),
|
||||
alloc: uint64(st.Blocks) * 512,
|
||||
atime: time.Unix(st.Atimespec.Sec, st.Atimespec.Nsec),
|
||||
ctime: time.Unix(st.Ctimespec.Sec, st.Ctimespec.Nsec),
|
||||
btime: time.Unix(st.Birthtimespec.Sec, st.Birthtimespec.Nsec),
|
||||
}, true
|
||||
}
|
||||
|
||||
// diskSpace reports the capacity of the filesystem holding dir, in units of
|
||||
// unit bytes: total, free, and free to an unprivileged user.
|
||||
func diskSpace(dir string) (total, free, avail uint64, unit uint32, err error) {
|
||||
var st syscall.Statfs_t
|
||||
if err = syscall.Statfs(dir, &st); err != nil {
|
||||
return
|
||||
}
|
||||
return st.Blocks, st.Bfree, st.Bavail, st.Bsize, nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func sysStat(fi os.FileInfo) (sysInfo, bool) {
|
||||
st, ok := fi.Sys().(*syscall.Stat_t)
|
||||
if !ok {
|
||||
return sysInfo{}, false
|
||||
}
|
||||
return sysInfo{
|
||||
dev: uint64(st.Dev),
|
||||
ino: uint64(st.Ino),
|
||||
nlink: uint32(st.Nlink),
|
||||
alloc: uint64(st.Blocks) * 512,
|
||||
atime: time.Unix(int64(st.Atim.Sec), int64(st.Atim.Nsec)),
|
||||
ctime: time.Unix(int64(st.Ctim.Sec), int64(st.Ctim.Nsec)),
|
||||
}, true
|
||||
}
|
||||
|
||||
// diskSpace reports the capacity of the filesystem holding dir, in units of
|
||||
// unit bytes: total, free, and free to an unprivileged user.
|
||||
func diskSpace(dir string) (total, free, avail uint64, unit uint32, err error) {
|
||||
var st syscall.Statfs_t
|
||||
if err = syscall.Statfs(dir, &st); err != nil {
|
||||
return
|
||||
}
|
||||
return uint64(st.Blocks), uint64(st.Bfree), uint64(st.Bavail), uint32(st.Bsize), nil
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//go:build !linux && !darwin
|
||||
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
)
|
||||
|
||||
// On platforms without a portable inode the server falls back on paths for
|
||||
// file identity and on a fixed figure for the capacity. The package is meant
|
||||
// to run on Linux; these exist so that it builds and its tests run elsewhere.
|
||||
|
||||
func sysStat(os.FileInfo) (sysInfo, bool) { return sysInfo{}, false }
|
||||
|
||||
func diskSpace(string) (total, free, avail uint64, unit uint32, err error) {
|
||||
return 0, 0, 0, 0, errors.ErrUnsupported
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
// Modified by RouterShelf. See UPSTREAM.md for adaptation details and Apache-2.0 provenance.
|
||||
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// ntStatus is an NTSTATUS value as defined in [MS-ERREF].
|
||||
type ntStatus uint32
|
||||
|
||||
const (
|
||||
statusFileLockConflict ntStatus = 0xC0000054
|
||||
statusSuccess ntStatus = 0x00000000
|
||||
statusPending ntStatus = 0x00000103
|
||||
statusNotifyCleanup ntStatus = 0x0000010B
|
||||
statusBufferOverflow ntStatus = 0x80000005
|
||||
statusNoMoreFiles ntStatus = 0x80000006
|
||||
statusInvalidInfoClass ntStatus = 0xC0000003
|
||||
statusInfoLengthMismatch ntStatus = 0xC0000004
|
||||
statusInvalidParameter ntStatus = 0xC000000D
|
||||
statusNoSuchFile ntStatus = 0xC000000F
|
||||
statusInvalidDeviceRequest ntStatus = 0xC0000010
|
||||
statusEndOfFile ntStatus = 0xC0000011
|
||||
statusMoreProcessingRequired ntStatus = 0xC0000016
|
||||
statusAccessDenied ntStatus = 0xC0000022
|
||||
statusBufferTooSmall ntStatus = 0xC0000023
|
||||
statusObjectNameInvalid ntStatus = 0xC0000033
|
||||
statusObjectNameNotFound ntStatus = 0xC0000034
|
||||
statusObjectNameCollision ntStatus = 0xC0000035
|
||||
statusObjectPathNotFound ntStatus = 0xC000003A
|
||||
statusSharingViolation ntStatus = 0xC0000043
|
||||
statusEasNotSupported ntStatus = 0xC000004F
|
||||
statusNoEasOnFile ntStatus = 0xC0000052
|
||||
statusLockNotGranted ntStatus = 0xC0000055
|
||||
statusDeletePending ntStatus = 0xC0000056
|
||||
statusLogonFailure ntStatus = 0xC000006D
|
||||
statusRangeNotLocked ntStatus = 0xC000007E
|
||||
statusDiskFull ntStatus = 0xC000007F
|
||||
statusInsufficientResources ntStatus = 0xC000009A
|
||||
statusMediaWriteProtected ntStatus = 0xC00000A2
|
||||
statusFileIsADirectory ntStatus = 0xC00000BA
|
||||
statusNotSupported ntStatus = 0xC00000BB
|
||||
statusNetworkNameDeleted ntStatus = 0xC00000C9
|
||||
statusBadNetworkName ntStatus = 0xC00000CC
|
||||
statusRequestNotAccepted ntStatus = 0xC00000D0
|
||||
statusNotSameDevice ntStatus = 0xC00000D4
|
||||
statusDirectoryNotEmpty ntStatus = 0xC0000101
|
||||
statusNotADirectory ntStatus = 0xC0000103
|
||||
statusTooManyOpenedFiles ntStatus = 0xC000011F
|
||||
statusCancelled ntStatus = 0xC0000120
|
||||
statusFileClosed ntStatus = 0xC0000128
|
||||
statusUserSessionDeleted ntStatus = 0xC0000203
|
||||
statusNotFound ntStatus = 0xC0000225
|
||||
statusNotAReparsePoint ntStatus = 0xC0000275
|
||||
)
|
||||
|
||||
// errStatus maps a filesystem error to the status a Windows server would
|
||||
// return for the same situation. Anything unrecognised, including the error
|
||||
// os.Root reports when a path escapes the share, becomes ACCESS_DENIED so
|
||||
// that no detail about the host leaks to the client.
|
||||
func errStatus(err error) ntStatus {
|
||||
switch {
|
||||
case err == nil:
|
||||
return statusSuccess
|
||||
// ENOTEMPTY must be tested before fs.ErrExist, which also matches it.
|
||||
case errors.Is(err, syscall.ENOTEMPTY):
|
||||
return statusDirectoryNotEmpty
|
||||
case errors.Is(err, fs.ErrNotExist):
|
||||
return statusObjectNameNotFound
|
||||
case errors.Is(err, fs.ErrExist):
|
||||
return statusObjectNameCollision
|
||||
case errors.Is(err, fs.ErrPermission):
|
||||
return statusAccessDenied
|
||||
case errors.Is(err, fs.ErrClosed):
|
||||
return statusFileClosed
|
||||
case errors.Is(err, syscall.ENOSPC), errors.Is(err, syscall.EDQUOT):
|
||||
return statusDiskFull
|
||||
case errors.Is(err, syscall.EISDIR):
|
||||
return statusFileIsADirectory
|
||||
case errors.Is(err, syscall.ENOTDIR):
|
||||
return statusObjectPathNotFound
|
||||
case errors.Is(err, syscall.EROFS):
|
||||
return statusMediaWriteProtected
|
||||
case errors.Is(err, syscall.EXDEV):
|
||||
return statusNotSameDevice
|
||||
case errors.Is(err, syscall.EMFILE), errors.Is(err, syscall.ENFILE):
|
||||
return statusTooManyOpenedFiles
|
||||
case errors.Is(err, syscall.ENAMETOOLONG):
|
||||
return statusObjectNameInvalid
|
||||
case errors.Is(err, syscall.EINVAL):
|
||||
return statusInvalidParameter
|
||||
}
|
||||
return statusAccessDenied
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
// Modified by RouterShelf. See UPSTREAM.md for adaptation details and Apache-2.0 provenance.
|
||||
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Named streams, kept in memory.
|
||||
//
|
||||
// A macOS client attaches metadata to the files it copies: Finder
|
||||
// information, a quarantine flag, any extended attribute. On a server
|
||||
// without named streams it stores them in "._name" AppleDouble files next to
|
||||
// the originals, which litters a volume that belongs to a workload and not
|
||||
// to the developer's desktop. So the server offers named streams, and keeps
|
||||
// what is written to them in memory: nothing reaches the volume, whatever
|
||||
// its filesystem supports, and the metadata lives as long as the server
|
||||
// does, which is as long as anyone could want desktop metadata on a cluster
|
||||
// volume.
|
||||
|
||||
const (
|
||||
maxStreamSize = 64 << 10
|
||||
maxStreamsTotal = 256 << 10
|
||||
maxStreamsPerFile = 64
|
||||
)
|
||||
|
||||
// memStream is the content of one named stream. The server lock guards it.
|
||||
type memStream struct {
|
||||
name string
|
||||
data []byte
|
||||
}
|
||||
|
||||
// parseName splits the name of a CREATE into the path of the file and the
|
||||
// name of the stream, empty for the file itself. The syntax is
|
||||
// "path:stream:$DATA", the type being optional.
|
||||
func parseName(name string) (string, string, ntStatus) {
|
||||
file := name
|
||||
stream := ""
|
||||
if i := strings.IndexByte(name[strings.LastIndexByte(name, '\\')+1:], ':'); i >= 0 {
|
||||
i += strings.LastIndexByte(name, '\\') + 1
|
||||
file = name[:i]
|
||||
var kind string
|
||||
stream, kind, _ = strings.Cut(name[i+1:], ":")
|
||||
if kind != "" && !strings.EqualFold(kind, "$DATA") || len(stream) > 255 || strings.ContainsAny(stream, "\\/:\x00") {
|
||||
return "", "", statusObjectNameInvalid
|
||||
}
|
||||
}
|
||||
p, st := parsePath(file)
|
||||
return p, stream, st
|
||||
}
|
||||
|
||||
// openStream implements CREATE for a named stream of an existing file.
|
||||
func (s *server) openStream(r *request, p, name string, desired, disp uint32, opts uint32) (*open, uint32, ntStatus) {
|
||||
if s.cfg.DiskMetadata {
|
||||
return nil, 0, statusNotSupported
|
||||
}
|
||||
if disp > dispOverwriteIf {
|
||||
return nil, 0, statusInvalidParameter
|
||||
}
|
||||
access := normalizeAccess(desired)
|
||||
if s.cfg.ReadOnly {
|
||||
// Streams are not part of the volume, but a share announced as
|
||||
// read-only is read-only for them too.
|
||||
if desired&accessMaximum != 0 && desired&(accessGenericAll|accessGenericWrite) == 0 {
|
||||
access = normalizeAccess(desired&^accessMaximum) | accessReadOnly
|
||||
}
|
||||
if access&accessModifying != 0 || opts&optDeleteOnClose != 0 || disp != dispOpen {
|
||||
return nil, 0, statusAccessDenied
|
||||
}
|
||||
}
|
||||
if opts&optDirectory != 0 {
|
||||
return nil, 0, statusNotADirectory
|
||||
}
|
||||
fi, err := s.root.Stat(p)
|
||||
if err != nil {
|
||||
return nil, 0, errStatus(err)
|
||||
}
|
||||
key := keyOf(fi, p)
|
||||
id := strings.ToLower(name)
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.nOpens >= maxOpens {
|
||||
return nil, 0, statusTooManyOpenedFiles
|
||||
}
|
||||
ms := s.streams[key][id]
|
||||
action := actionOpened
|
||||
switch {
|
||||
case ms == nil:
|
||||
if disp == dispOpen || disp == dispOverwrite {
|
||||
return nil, 0, statusObjectNameNotFound
|
||||
}
|
||||
if len(s.streams[key]) >= maxStreamsPerFile {
|
||||
return nil, 0, statusInsufficientResources
|
||||
}
|
||||
if s.streams[key] == nil {
|
||||
s.streams[key] = make(map[string]*memStream)
|
||||
}
|
||||
ms = &memStream{name: name}
|
||||
s.streams[key][id] = ms
|
||||
action = actionCreated
|
||||
case disp == dispCreate:
|
||||
return nil, 0, statusObjectNameCollision
|
||||
case disp == dispSupersede || disp == dispOverwrite || disp == dispOverwriteIf:
|
||||
s.streamBytes -= int64(len(ms.data))
|
||||
ms.data = nil
|
||||
action = actionOverwritten
|
||||
}
|
||||
s.nOpens++
|
||||
return &open{
|
||||
id: s.newID(),
|
||||
sess: r.sess,
|
||||
tree: r.tree,
|
||||
access: access,
|
||||
path: p,
|
||||
stream: ms,
|
||||
streamKey: key,
|
||||
deleteOnClose: opts&optDeleteOnClose != 0,
|
||||
}, action, statusSuccess
|
||||
}
|
||||
|
||||
// releaseStream closes a handle on a stream.
|
||||
func (s *server) releaseStream(o *open) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.nOpens--
|
||||
if !o.deleteOnClose {
|
||||
return
|
||||
}
|
||||
id := strings.ToLower(o.stream.name)
|
||||
if s.streams[o.streamKey][id] == o.stream {
|
||||
s.streamBytes -= int64(len(o.stream.data))
|
||||
delete(s.streams[o.streamKey], id)
|
||||
if len(s.streams[o.streamKey]) == 0 {
|
||||
delete(s.streams, o.streamKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// dropStreams forgets the streams of a file that is gone. Called with s.mu
|
||||
// held.
|
||||
func (s *server) dropStreams(key fileKey) {
|
||||
for _, ms := range s.streams[key] {
|
||||
s.streamBytes -= int64(len(ms.data))
|
||||
}
|
||||
delete(s.streams, key)
|
||||
}
|
||||
|
||||
func (s *server) streamSize(ms *memStream) uint64 {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return uint64(len(ms.data))
|
||||
}
|
||||
|
||||
func (s *server) readStream(ms *memStream, b []byte, off uint64) int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if off >= uint64(len(ms.data)) {
|
||||
return 0
|
||||
}
|
||||
return copy(b, ms.data[off:])
|
||||
}
|
||||
|
||||
// resizeStream sets the length of a stream, within the memory the server
|
||||
// grants to streams. Called with s.mu held.
|
||||
func (s *server) resizeStream(ms *memStream, size uint64) ntStatus {
|
||||
if size > maxStreamSize || s.streamBytes+int64(size)-int64(len(ms.data)) > maxStreamsTotal {
|
||||
return statusDiskFull
|
||||
}
|
||||
s.streamBytes += int64(size) - int64(len(ms.data))
|
||||
if size <= uint64(len(ms.data)) {
|
||||
ms.data = ms.data[:size]
|
||||
} else {
|
||||
ms.data = append(ms.data, make([]byte, size-uint64(len(ms.data)))...)
|
||||
}
|
||||
return statusSuccess
|
||||
}
|
||||
|
||||
func (s *server) writeStream(ms *memStream, b []byte, off uint64) ntStatus {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if off > maxStreamSize {
|
||||
return statusDiskFull
|
||||
}
|
||||
if end := off + uint64(len(b)); end > uint64(len(ms.data)) {
|
||||
if st := s.resizeStream(ms, end); st != statusSuccess {
|
||||
return st
|
||||
}
|
||||
}
|
||||
copy(ms.data[off:], b)
|
||||
return statusSuccess
|
||||
}
|
||||
|
||||
func (s *server) truncateStream(ms *memStream, size uint64) ntStatus {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.resizeStream(ms, size)
|
||||
}
|
||||
|
||||
// streamInfo builds FileStreamInformation: the data stream of a file, then
|
||||
// its named streams.
|
||||
func (s *server) streamInfo(in *fileInfo, key fileKey) []byte {
|
||||
type entry struct {
|
||||
name string
|
||||
size, alloc uint64
|
||||
}
|
||||
var entries []entry
|
||||
if !in.isDir {
|
||||
entries = append(entries, entry{"::$DATA", in.size, in.alloc})
|
||||
}
|
||||
s.mu.Lock()
|
||||
for _, ms := range s.streams[key] {
|
||||
n := uint64(len(ms.data))
|
||||
entries = append(entries, entry{":" + ms.name + ":$DATA", n, (n + 4095) &^ 4095})
|
||||
}
|
||||
s.mu.Unlock()
|
||||
var out []byte
|
||||
last := 0
|
||||
for i, e := range entries {
|
||||
if i > 0 {
|
||||
out = pad8(out)
|
||||
le.PutUint32(out[last:], uint32(len(out)-last))
|
||||
}
|
||||
last = len(out)
|
||||
name := encodeUTF16(e.name)
|
||||
out = append(out, make([]byte, 24)...)
|
||||
le.PutUint32(out[last+4:], uint32(len(name)))
|
||||
le.PutUint64(out[last+8:], e.size)
|
||||
le.PutUint64(out[last+16:], e.alloc)
|
||||
out = append(out, name...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"encoding/hex"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func unhex(t testing.TB, s string) []byte {
|
||||
t.Helper()
|
||||
b, err := hex.DecodeString(s)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
// The values of this test are the worked example of [MS-NLMP] 4.2.4: user
|
||||
// "User", domain "Domain", password "Password".
|
||||
func TestNTLMv2Vectors(t *testing.T) {
|
||||
hash := NTHash("Password")
|
||||
if got := hex.EncodeToString(hash[:]); got != "a4f49c406510bdcab6824ee7c30fd852" {
|
||||
t.Fatalf("NT hash = %s", got)
|
||||
}
|
||||
owf := hmacMD5(hash[:], encodeUTF16("USER"+"Domain"))
|
||||
if got := hex.EncodeToString(owf); got != "0c868a403bfd7a93a3001ef22ef02e3f" {
|
||||
t.Fatalf("NTOWFv2 = %s", got)
|
||||
}
|
||||
|
||||
// The "temp" blob of the example: time zero, client challenge aa...,
|
||||
// and the two AV pairs of the server.
|
||||
var av []byte
|
||||
for _, p := range []struct {
|
||||
id uint16
|
||||
v string
|
||||
}{{2, "Domain"}, {1, "Server"}} {
|
||||
v := encodeUTF16(p.v)
|
||||
av = le.AppendUint16(av, p.id)
|
||||
av = le.AppendUint16(av, uint16(len(v)))
|
||||
av = append(av, v...)
|
||||
}
|
||||
av = append(av, 0, 0, 0, 0)
|
||||
blob := append([]byte{1, 1, 0, 0, 0, 0, 0, 0}, make([]byte, 8)...)
|
||||
blob = append(blob, bytes.Repeat([]byte{0xaa}, 8)...)
|
||||
blob = append(blob, 0, 0, 0, 0)
|
||||
blob = append(blob, av...)
|
||||
blob = append(blob, 0, 0, 0, 0)
|
||||
|
||||
nonce := unhex(t, "0123456789abcdef")
|
||||
proof := hmacMD5(owf, nonce, blob)
|
||||
if got := hex.EncodeToString(proof); got != "68cd0ab851e51c96aabc927bebef6a1c" {
|
||||
t.Fatalf("NTProofStr = %s", got)
|
||||
}
|
||||
if got := hex.EncodeToString(hmacMD5(owf, proof)); got != "8de40ccadbc14a82f15cb0ad0de95ca3" {
|
||||
t.Fatalf("SessionBaseKey = %s", got)
|
||||
}
|
||||
|
||||
// The same exchange through the server code, with key exchange: the
|
||||
// client sends the session key 55...55 encrypted under the base key.
|
||||
a := &ntlmAuth{challenge: []byte{0}}
|
||||
copy(a.nonce[:], nonce)
|
||||
msg := authenticateMessage("User", "Domain", append(proof, blob...), unhex(t, "c5dad2544fc9799094ce1ce90bc9d03e"))
|
||||
if !a.authenticate(msg, "user", hash) {
|
||||
t.Fatal("the example exchange was refused")
|
||||
}
|
||||
if !bytes.Equal(a.sessionKey, bytes.Repeat([]byte{0x55}, 16)) {
|
||||
t.Fatalf("exported session key = %x", a.sessionKey)
|
||||
}
|
||||
|
||||
bad := NTHash("password")
|
||||
if (&ntlmAuth{challenge: []byte{0}, nonce: a.nonce}).authenticate(msg, "user", bad) {
|
||||
t.Fatal("a wrong password was accepted")
|
||||
}
|
||||
if (&ntlmAuth{challenge: []byte{0}, nonce: a.nonce}).authenticate(msg, "other", hash) {
|
||||
t.Fatal("a wrong user was accepted")
|
||||
}
|
||||
// An NTLMv1 response is 24 bytes and must never be considered.
|
||||
v1 := authenticateMessage("User", "Domain", make([]byte, 24), nil)
|
||||
if (&ntlmAuth{challenge: []byte{0}, nonce: a.nonce}).authenticate(v1, "user", hash) {
|
||||
t.Fatal("an NTLMv1 response was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// authenticateMessage builds an NTLM AUTHENTICATE message. A non-nil key
|
||||
// turns key exchange on.
|
||||
func authenticateMessage(user, domain string, ntResponse, encKey []byte) []byte {
|
||||
flags := ntlmUnicode | ntlmNTLM | ntlmExtendedSession
|
||||
if encKey != nil {
|
||||
flags |= ntlmKeyExch
|
||||
}
|
||||
msg := make([]byte, 88)
|
||||
copy(msg, ntlmSignature)
|
||||
le.PutUint32(msg[8:], 3)
|
||||
le.PutUint32(msg[60:], flags)
|
||||
field := func(off int, v []byte) {
|
||||
le.PutUint16(msg[off:], uint16(len(v)))
|
||||
le.PutUint16(msg[off+2:], uint16(len(v)))
|
||||
le.PutUint32(msg[off+4:], uint32(len(msg)))
|
||||
msg = append(msg, v...)
|
||||
}
|
||||
field(20, ntResponse)
|
||||
field(28, encodeUTF16(domain))
|
||||
field(36, encodeUTF16(user))
|
||||
field(52, encKey)
|
||||
return msg
|
||||
}
|
||||
|
||||
// RFC 4231, test case 1, truncated to the 16 bytes SMB keeps.
|
||||
func TestSignature(t *testing.T) {
|
||||
key := bytes.Repeat([]byte{0x0b}, 20)
|
||||
if got := hex.EncodeToString(mac(key, []byte("Hi There"))); got != "b0344c61d8db38535ca8afceaf0bf12b" {
|
||||
t.Fatalf("mac = %s", got)
|
||||
}
|
||||
msg := make([]byte, headerSize+4)
|
||||
(&header{command: cmdEcho, messageID: 7}).put(msg)
|
||||
sign(key, msg)
|
||||
if le.Uint32(msg[16:])&flagSigned == 0 {
|
||||
t.Fatal("the signed flag is not set")
|
||||
}
|
||||
if !verify(key, bytes.Clone(msg)) {
|
||||
t.Fatal("a signed message does not verify")
|
||||
}
|
||||
msg[headerSize]++
|
||||
if verify(key, msg) {
|
||||
t.Fatal("a modified message verifies")
|
||||
}
|
||||
}
|
||||
|
||||
// RFC 4493, section 4.
|
||||
func TestAESCMAC(t *testing.T) {
|
||||
key := unhex(t, "2b7e151628aed2a6abf7158809cf4f3c")
|
||||
msg := unhex(t, "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
|
||||
for n, want := range map[int]string{
|
||||
0: "bb1d6929e95937287fa37d129b756746",
|
||||
16: "070a16b46b4d4144f79bdd9dd04a287c",
|
||||
40: "dfa66747de9ae63030ca32611497c827",
|
||||
64: "51f0bebf7e3b9d92fc49741779363cfe",
|
||||
} {
|
||||
if got := aesCMAC(key, msg[:n]); hex.EncodeToString(got[:]) != want {
|
||||
t.Errorf("CMAC of %d bytes = %x, want %s", n, got, want)
|
||||
}
|
||||
}
|
||||
// Longer than the internal chunk, against the definition applied one
|
||||
// block at a time.
|
||||
for _, n := range []int{4096, 4097, 8192 + 16, 12800} {
|
||||
long := bytes.Repeat(msg, 200)[:n]
|
||||
if got, want := aesCMAC(key, long), cmacReference(key, long); got != want {
|
||||
t.Errorf("CMAC of %d bytes = %x, want %x", n, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cmacReference(key, msg []byte) (x [16]byte) {
|
||||
blk, _ := aes.NewCipher(key)
|
||||
var k1 [16]byte
|
||||
blk.Encrypt(k1[:], k1[:])
|
||||
cmacDouble(&k1)
|
||||
k2 := k1
|
||||
cmacDouble(&k2)
|
||||
for len(msg) > 16 {
|
||||
for i := range x {
|
||||
x[i] ^= msg[i]
|
||||
}
|
||||
blk.Encrypt(x[:], x[:])
|
||||
msg = msg[16:]
|
||||
}
|
||||
var last [16]byte
|
||||
copy(last[:], msg)
|
||||
pad := k1
|
||||
if len(msg) < 16 {
|
||||
last[len(msg)] = 0x80
|
||||
pad = k2
|
||||
}
|
||||
for i := range x {
|
||||
x[i] ^= last[i] ^ pad[i]
|
||||
}
|
||||
blk.Encrypt(x[:], x[:])
|
||||
return x
|
||||
}
|
||||
|
||||
func TestHeaderRoundTrip(t *testing.T) {
|
||||
in := header{creditCharge: 3, status: statusAccessDenied, command: cmdRead, credits: 31, flags: flagResponse | flagSigned,
|
||||
next: 128, messageID: 1 << 40, treeID: 9, sessionID: 1<<63 + 5}
|
||||
b := make([]byte, headerSize)
|
||||
in.put(b)
|
||||
out, ok := parseHeader(b)
|
||||
if !ok || out != in {
|
||||
t.Fatalf("got %+v, want %+v", out, in)
|
||||
}
|
||||
async := header{flags: flagAsync, asyncID: 77}
|
||||
async.put(b)
|
||||
if out, _ := parseHeader(b); out.asyncID != 77 || out.treeID != 0 {
|
||||
t.Fatalf("async header: %+v", out)
|
||||
}
|
||||
for _, bad := range [][]byte{nil, b[:63], append([]byte{0xFF}, b[1:]...)} {
|
||||
if _, ok := parseHeader(bad); ok {
|
||||
t.Fatalf("parseHeader accepted %x", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSub(t *testing.T) {
|
||||
b := make([]byte, 10)
|
||||
for _, c := range []struct {
|
||||
off, n uint32
|
||||
ok bool
|
||||
}{{0, 10, true}, {10, 0, true}, {4, 6, true}, {4, 7, false}, {11, 0, false}, {1, 0xFFFFFFFF, false}, {0xFFFFFFFF, 2, false}} {
|
||||
if _, ok := sub(b, c.off, c.n); ok != c.ok {
|
||||
t.Errorf("sub(%d, %d) = %v", c.off, c.n, ok)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFiletime(t *testing.T) {
|
||||
when := time.Date(2024, 2, 29, 12, 34, 56, 789000000, time.UTC)
|
||||
if got := fromFiletime(filetime(when)); !got.Equal(when) {
|
||||
t.Fatalf("round trip: %v", got)
|
||||
}
|
||||
if filetime(time.Unix(0, 0)) != filetimeEpoch {
|
||||
t.Fatal("the Unix epoch is not at the documented offset")
|
||||
}
|
||||
for _, v := range []uint64{0, ^uint64(0), ^uint64(0) - 1} {
|
||||
if !fromFiletime(v).IsZero() {
|
||||
t.Errorf("fromFiletime(%#x) is not the zero time", v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUTF16(t *testing.T) {
|
||||
for _, s := range []string{"", "plain", "accentué", "日本語", "😀 astral"} {
|
||||
if got := decodeUTF16(encodeUTF16(s)); got != s {
|
||||
t.Errorf("round trip of %q gave %q", s, got)
|
||||
}
|
||||
}
|
||||
if got := decodeUTF16([]byte{'a', 0, 'b'}); got != "a" {
|
||||
t.Errorf("odd length input gave %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParsePath(t *testing.T) {
|
||||
good := map[string]string{
|
||||
"": ".",
|
||||
"a": "a",
|
||||
`a\b\c.txt`: "a/b/c.txt",
|
||||
"a\uF022b": "a:b",
|
||||
"what\uF025": "what?",
|
||||
"dot\uF029": "dot.",
|
||||
"..hidden": "..hidden",
|
||||
"...": "...",
|
||||
`dir\` + "trail\uF028": "dir/trail ",
|
||||
"back\uF026slash": `back\slash`,
|
||||
"ctrl\uF001": "ctrl\x01",
|
||||
"emoji😀": "emoji😀",
|
||||
}
|
||||
for in, want := range good {
|
||||
if in == "back\uF026slash" && nameFromWire("x\uF026") != `x\` {
|
||||
t.Fatal("backslash mapping")
|
||||
}
|
||||
got, st := parsePath(in)
|
||||
// A backslash inside a name is a separator on Windows hosts,
|
||||
// where the name is refused instead.
|
||||
if in == "back\uF026slash" && st != statusSuccess {
|
||||
continue
|
||||
}
|
||||
if st != statusSuccess || got != want {
|
||||
t.Errorf("parsePath(%q) = %q, %#x; want %q", in, got, uint32(st), want)
|
||||
}
|
||||
}
|
||||
bad := []string{
|
||||
"..", `..\x`, `a\..`, `a\..\b`, ".", `a\.\b`, `\a`, `a\`, `a\\b`, "a/b", "/etc/passwd",
|
||||
"a\x00b", "file:stream", "file:stream:$DATA", `C:\x`,
|
||||
// The mapped forms of dot must not smuggle a parent reference.
|
||||
".\uF029", "\uF029\uF029", `a\` + "\uF029\uF029" + `\b`, "\uF029",
|
||||
}
|
||||
for _, in := range bad {
|
||||
if got, st := parsePath(in); st == statusSuccess {
|
||||
t.Errorf("parsePath(%q) = %q, want a refusal", in, got)
|
||||
}
|
||||
}
|
||||
long := make([]byte, 256)
|
||||
for i := range long {
|
||||
long[i] = 'a'
|
||||
}
|
||||
if _, st := parsePath(string(long)); st == statusSuccess {
|
||||
t.Error("a 256-byte component was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseName(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
in, path, stream string
|
||||
ok bool
|
||||
}{
|
||||
{"file", "file", "", true},
|
||||
{"file::$DATA", "file", "", true},
|
||||
{"file:meta", "file", "meta", true},
|
||||
{"file:meta:$DATA", "file", "meta", true},
|
||||
{`dir\file:AFP_AfpInfo:$DATA`, "dir/file", "AFP_AfpInfo", true},
|
||||
{":onroot", ".", "onroot", true},
|
||||
{"file:meta:$INDEX_ALLOCATION", "", "", false},
|
||||
{"file:a:b:c", "", "", false},
|
||||
{`dir:stream\file`, "", "", false},
|
||||
{`..\file:meta`, "", "", false},
|
||||
{"file:" + string(make([]byte, 300)), "", "", false},
|
||||
} {
|
||||
p, stream, st := parseName(c.in)
|
||||
if (st == statusSuccess) != c.ok || c.ok && (p != c.path || stream != c.stream) {
|
||||
t.Errorf("parseName(%q) = %q, %q, %#x", c.in, p, stream, uint32(st))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNameMappingRoundTrip(t *testing.T) {
|
||||
for _, name := range []string{"a", "a:b", `q?*<>|"`, "trailing.", "trailing ", "mid.dle", ".", "..", ".git", "tab\there"} {
|
||||
wire := nameToWire(name)
|
||||
if name != "." && name != ".." {
|
||||
for _, r := range wire {
|
||||
if r < 0x20 || r == ':' || r == '?' || r == '*' {
|
||||
t.Errorf("nameToWire(%q) = %q still holds %q", name, wire, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
if got := nameFromWire(wire); got != name {
|
||||
t.Errorf("round trip of %q gave %q", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchPattern(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
pattern, name string
|
||||
want bool
|
||||
}{
|
||||
{"*", "anything", true},
|
||||
{"*.txt", "a.txt", true},
|
||||
{"*.TXT", "a.txt", true},
|
||||
{"*.txt", "a.txt.bak", false},
|
||||
{"a?c", "abc", true},
|
||||
{"a?c", "ac", false},
|
||||
{"a*b*c", "aXXbYYc", true},
|
||||
{"a*b*c", "aXXbYY", false},
|
||||
{"<.txt", "a.txt", true},
|
||||
{"", "", true},
|
||||
{"*", "", true},
|
||||
{"?", "", false},
|
||||
} {
|
||||
if got := matchPattern(c.pattern, c.name); got != c.want {
|
||||
t.Errorf("matchPattern(%q, %q) = %v", c.pattern, c.name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSPNEGO(t *testing.T) {
|
||||
ntlm := append([]byte(ntlmSignature), 1, 0, 0, 0, 0, 0, 0, 0)
|
||||
|
||||
tok, ok := parseSPNEGO(ntlm)
|
||||
if !ok || !tok.raw || !bytes.Equal(tok.mechToken, ntlm) {
|
||||
t.Fatalf("raw NTLMSSP: %+v %v", tok, ok)
|
||||
}
|
||||
|
||||
mechs := derTLV(0x30, derTLV(0x06, oidNTLM))
|
||||
init := derTLV(0x60, derTLV(0x06, oidSPNEGO), derTLV(0xA0, derTLV(0x30,
|
||||
derTLV(0xA0, mechs), derTLV(0xA2, derTLV(0x04, ntlm)))))
|
||||
tok, ok = parseSPNEGO(init)
|
||||
if !ok || !tok.init || !tok.ntlmFirst || !bytes.Equal(tok.mechToken, ntlm) || !bytes.Equal(tok.mechTypes, mechs) {
|
||||
t.Fatalf("NegTokenInit: %+v %v", tok, ok)
|
||||
}
|
||||
|
||||
// Another mechanism first: NTLM is then not the preferred one.
|
||||
other := derTLV(0x30, derTLV(0x06, []byte{0x2a, 0x86, 0x48}), derTLV(0x06, oidNTLM))
|
||||
tok, ok = parseSPNEGO(derTLV(0x60, derTLV(0x06, oidSPNEGO), derTLV(0xA0, derTLV(0x30, derTLV(0xA0, other)))))
|
||||
if !ok || tok.ntlmFirst || tok.mechToken != nil {
|
||||
t.Fatalf("NegTokenInit with a foreign mechanism: %+v %v", tok, ok)
|
||||
}
|
||||
|
||||
tok, ok = parseSPNEGO(negTokenResp(negAcceptIncomplete, true, ntlm, []byte("mic")))
|
||||
if !ok || tok.init || !bytes.Equal(tok.mechToken, ntlm) || string(tok.mic) != "mic" {
|
||||
t.Fatalf("NegTokenResp: %+v %v", tok, ok)
|
||||
}
|
||||
|
||||
// What the server itself announces must parse as an initial token
|
||||
// that prefers NTLM.
|
||||
tok, ok = parseSPNEGO(negTokenInit())
|
||||
if !ok || !tok.init || !tok.ntlmFirst {
|
||||
t.Fatalf("own NegTokenInit: %+v %v", tok, ok)
|
||||
}
|
||||
|
||||
// A long token exercises the multi-byte DER lengths.
|
||||
big := append(bytes.Clone(ntlm), make([]byte, 1000)...)
|
||||
tok, ok = parseSPNEGO(negTokenResp(negAcceptIncomplete, false, big, nil))
|
||||
if !ok || !bytes.Equal(tok.mechToken, big) {
|
||||
t.Fatal("long token")
|
||||
}
|
||||
|
||||
for _, bad := range [][]byte{nil, {0x60}, {0x60, 0x05, 1, 2}, {0x30, 0}, {0xA1, 0x82, 0xFF, 0xFF}, {0xA1, 0x84, 0, 0, 0, 1, 0}} {
|
||||
if _, ok := parseSPNEGO(bad); ok {
|
||||
t.Errorf("parseSPNEGO accepted %x", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorBody(t *testing.T) {
|
||||
b := errorBody(nil)
|
||||
if len(b) != headerSize+9 || le.Uint16(b[headerSize:]) != 9 {
|
||||
t.Fatalf("empty error body: %x", b[headerSize:])
|
||||
}
|
||||
b = errorBody([]byte{1, 2, 3, 4})
|
||||
if len(b) != headerSize+12 || le.Uint32(b[headerSize+4:]) != 4 {
|
||||
t.Fatalf("error body with data: %x", b[headerSize:])
|
||||
}
|
||||
}
|
||||
|
||||
func TestLockOverlap(t *testing.T) {
|
||||
top := ^uint64(0)
|
||||
for _, c := range []struct {
|
||||
off, n, off2, n2 uint64
|
||||
want bool
|
||||
}{
|
||||
{0, 10, 10, 10, false},
|
||||
{0, 10, 9, 1, true},
|
||||
{5, 1, 0, 10, true},
|
||||
{0, 0, 0, 10, false},
|
||||
{top - 1, 1, top - 1, 1, true},
|
||||
{top - 9, 10, 0, 10, false},
|
||||
{0, top, top - 1, 1, true},
|
||||
} {
|
||||
l := rangeLock{off: c.off, n: c.n}
|
||||
if got := l.overlaps(c.off2, c.n2); got != c.want {
|
||||
t.Errorf("[%d,+%d) vs [%d,+%d) = %v", c.off, c.n, c.off2, c.n2, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"time"
|
||||
"unicode/utf16"
|
||||
)
|
||||
|
||||
var le = binary.LittleEndian
|
||||
|
||||
// SMB2 command codes ([MS-SMB2] 2.2.1).
|
||||
const (
|
||||
cmdNegotiate uint16 = iota
|
||||
cmdSessionSetup
|
||||
cmdLogoff
|
||||
cmdTreeConnect
|
||||
cmdTreeDisconnect
|
||||
cmdCreate
|
||||
cmdClose
|
||||
cmdFlush
|
||||
cmdRead
|
||||
cmdWrite
|
||||
cmdLock
|
||||
cmdIoctl
|
||||
cmdCancel
|
||||
cmdEcho
|
||||
cmdQueryDirectory
|
||||
cmdChangeNotify
|
||||
cmdQueryInfo
|
||||
cmdSetInfo
|
||||
cmdOplockBreak
|
||||
)
|
||||
|
||||
const (
|
||||
headerSize = 64
|
||||
|
||||
flagResponse uint32 = 0x00000001
|
||||
flagAsync uint32 = 0x00000002
|
||||
flagRelated uint32 = 0x00000004
|
||||
flagSigned uint32 = 0x00000008
|
||||
)
|
||||
|
||||
const (
|
||||
dialect202 uint16 = 0x0202
|
||||
dialect210 uint16 = 0x0210
|
||||
dialect300 uint16 = 0x0300
|
||||
dialect302 uint16 = 0x0302
|
||||
dialect311 uint16 = 0x0311
|
||||
// dialectAny is the wildcard a server answers to an SMB1 multi-protocol
|
||||
// negotiate, telling the client to continue with an SMB2 NEGOTIATE.
|
||||
dialectAny uint16 = 0x02FF
|
||||
)
|
||||
|
||||
// header is the decoded 64-byte SMB2 packet header. In a request the status
|
||||
// field carries the channel sequence, which this server ignores.
|
||||
type header struct {
|
||||
creditCharge uint16
|
||||
status ntStatus
|
||||
command uint16
|
||||
credits uint16
|
||||
flags uint32
|
||||
next uint32
|
||||
messageID uint64
|
||||
asyncID uint64
|
||||
treeID uint32
|
||||
sessionID uint64
|
||||
}
|
||||
|
||||
func parseHeader(b []byte) (h header, ok bool) {
|
||||
if len(b) < headerSize || b[0] != 0xFE || b[1] != 'S' || b[2] != 'M' || b[3] != 'B' || le.Uint16(b[4:]) != headerSize {
|
||||
return h, false
|
||||
}
|
||||
h.creditCharge = le.Uint16(b[6:])
|
||||
h.status = ntStatus(le.Uint32(b[8:]))
|
||||
h.command = le.Uint16(b[12:])
|
||||
h.credits = le.Uint16(b[14:])
|
||||
h.flags = le.Uint32(b[16:])
|
||||
h.next = le.Uint32(b[20:])
|
||||
h.messageID = le.Uint64(b[24:])
|
||||
if h.flags&flagAsync != 0 {
|
||||
h.asyncID = le.Uint64(b[32:])
|
||||
} else {
|
||||
h.treeID = le.Uint32(b[36:])
|
||||
}
|
||||
h.sessionID = le.Uint64(b[40:])
|
||||
return h, true
|
||||
}
|
||||
|
||||
// put writes the header into the first 64 bytes of b, leaving the signature
|
||||
// zeroed.
|
||||
func (h *header) put(b []byte) {
|
||||
clear(b[:headerSize])
|
||||
b[0], b[1], b[2], b[3] = 0xFE, 'S', 'M', 'B'
|
||||
le.PutUint16(b[4:], headerSize)
|
||||
le.PutUint16(b[6:], h.creditCharge)
|
||||
le.PutUint32(b[8:], uint32(h.status))
|
||||
le.PutUint16(b[12:], h.command)
|
||||
le.PutUint16(b[14:], h.credits)
|
||||
le.PutUint32(b[16:], h.flags)
|
||||
le.PutUint32(b[20:], h.next)
|
||||
le.PutUint64(b[24:], h.messageID)
|
||||
if h.flags&flagAsync != 0 {
|
||||
le.PutUint64(b[32:], h.asyncID)
|
||||
} else {
|
||||
le.PutUint32(b[36:], h.treeID)
|
||||
}
|
||||
le.PutUint64(b[40:], h.sessionID)
|
||||
}
|
||||
|
||||
// sub returns b[off:off+n] when that range lies inside b. Every offset and
|
||||
// length a client sends goes through it, so a malformed packet yields an
|
||||
// error status instead of a panic.
|
||||
func sub(b []byte, off, n uint32) ([]byte, bool) {
|
||||
if uint64(off)+uint64(n) > uint64(len(b)) {
|
||||
return nil, false
|
||||
}
|
||||
return b[off : off+n], true
|
||||
}
|
||||
|
||||
// newMsg allocates a response with room for the header in front of an n-byte
|
||||
// body, so that offsets inside handlers match the offsets of the protocol,
|
||||
// which all count from the start of the header.
|
||||
func newMsg(n int) []byte {
|
||||
return make([]byte, headerSize+n)
|
||||
}
|
||||
|
||||
func encodeUTF16(s string) []byte {
|
||||
u := utf16.Encode([]rune(s))
|
||||
b := make([]byte, 2*len(u))
|
||||
for i, v := range u {
|
||||
le.PutUint16(b[2*i:], v)
|
||||
}
|
||||
return b
|
||||
}
|
||||
|
||||
func decodeUTF16(b []byte) string {
|
||||
u := make([]uint16, len(b)/2)
|
||||
for i := range u {
|
||||
u[i] = le.Uint16(b[2*i:])
|
||||
}
|
||||
return string(utf16.Decode(u))
|
||||
}
|
||||
|
||||
// filetimeEpoch is the number of 100ns intervals between 1601-01-01 and the
|
||||
// Unix epoch.
|
||||
const filetimeEpoch = 116444736000000000
|
||||
|
||||
func filetime(t time.Time) uint64 {
|
||||
if t.IsZero() {
|
||||
return 0
|
||||
}
|
||||
return uint64(t.Unix()*10000000 + int64(t.Nanosecond()/100) + filetimeEpoch)
|
||||
}
|
||||
|
||||
// fromFiletime converts a FILETIME sent by a client. Zero and the negative
|
||||
// sentinels of [MS-FSCC] ("do not change") map to the zero time.
|
||||
func fromFiletime(v uint64) time.Time {
|
||||
if v == 0 || int64(v) < 0 || v < filetimeEpoch {
|
||||
return time.Time{}
|
||||
}
|
||||
v -= filetimeEpoch
|
||||
return time.Unix(int64(v/10000000), int64(v%10000000)*100)
|
||||
}
|
||||
|
||||
func pad8(b []byte) []byte {
|
||||
for len(b)%8 != 0 {
|
||||
b = append(b, 0)
|
||||
}
|
||||
return b
|
||||
}
|
||||
Reference in new issue
Block a user