feat: add experimental standalone SMB service for Finder

This commit is contained in:
Meghdad committed 2026-10-16 15:09:41 +03:30
1 parent c9006c11dd
commit b9cb187f0d
55 files changed
+7961 -10

No files matched your search

+5
View File
@@ -34,3 +34,8 @@ RS_PUBLIC_HTTP_PORT=80
RS_PUBLIC_HTTPS_PORT=443 RS_PUBLIC_HTTPS_PORT=443
RS_PUBLIC_SSH_PORT=222 RS_PUBLIC_SSH_PORT=222
RS_SSH_TARGET_PORT=22 RS_SSH_TARGET_PORT=22
# Optional independent SMB service uses a separate protected JSON file.
# Web startup does not start SMB or consume these settings; see docs/smb.md.
# RS_SMB_CONFIG=/etc/storage/routershelf-smb.json
# RS_SMB_BINARY=/media/DISK_ID/.smb-service/routershelf-smb
+2 -1
View File
@@ -13,4 +13,5 @@ jobs:
with: with:
go-version: '1.26.x' go-version: '1.26.x'
- run: make test - run: make test
- run: make build-mipsle - run: make build-mipsle build-smb-mipsle
- run: go test -race ./cmd/routershelf-smb ./internal/smbwire
+9
View File
@@ -31,3 +31,12 @@ dist/
# Python development artifacts # Python development artifacts
__pycache__/ __pycache__/
*.py[cod] *.py[cod]
# SMB private credentials (NT hashes are password-equivalent)
smb.json
smb.*.json
.smb.json
/routershelf-smb
routershelf-smb*.json
.smb.*.json
!/.smb.example.json
+24
View File
@@ -0,0 +1,24 @@
{
"listen": "127.0.0.1:1445",
"storage_mount": "/media/DISK_ID",
"root": "/media/DISK_ID/private-storage",
"share": "Storage",
"user": "storage",
"nt_hash": "00000000000000000000000000000000",
"read_only": true,
"allow": [
"127.0.0.1/32"
],
"public_roots": [
"/media/DISK_ID/public-storage"
],
"allow_public_overlap": false,
"uid": 65533,
"gid": 65533,
"case_insensitive": true,
"protected_paths": [
"/media/DISK_ID/.public-share-service",
"/media/DISK_ID/.smb-service"
],
"diagnostics": false
}
+6 -1
View File
@@ -18,6 +18,7 @@ Read the relevant guide before changing a component:
## Repository layout ## Repository layout
- `cmd/routershelf/`: application, environment/flag parsing, handler and configuration tests. - `cmd/routershelf/`: application, environment/flag parsing, handler and configuration tests.
- `cmd/routershelf-smb/`, `internal/smbwire/`: independent private SMB executable and adapted Apache-2.0 protocol implementation. Read `docs/smb.md`, `docs/smb-implementation.md`, `docs/smb-validation.md` and `internal/smbwire/UPSTREAM.md` before changing it; preserve license/provenance.
- `internal/theme/assets.go`: embeds assets under `internal/theme/nais/`. - `internal/theme/assets.go`: embeds assets under `internal/theme/nais/`.
- `deploy/padavan/`: environment-driven supervisor and host firewall lifecycle. - `deploy/padavan/`: environment-driven supervisor and host firewall lifecycle.
- `scripts/nat-plan.sh`: prints gateway configuration guidance; it does not modify the gateway. - `scripts/nat-plan.sh`: prints gateway configuration guidance; it does not modify the gateway.
@@ -30,7 +31,7 @@ Keep changes in the appropriate layer. The Go server must not provision DHCP, ch
## Configuration contract ## Configuration contract
Network-specific domains, IPs, subnets, interfaces, ports, USB paths and runtime options belong in `RS_*` environment settings, not per-installation source edits. Use public placeholders in `.env.example` and documentation. Defaults should be generic and safe; the standalone Go listener defaults to loopback. Per-installation settings never require source edits. The existing web service keeps its `RS_*` environment contract for domains, IPs, subnets, interfaces, ports, USB paths and runtime options. The independent SMB service uses protected JSON selected by `RS_SMB_CONFIG`, with its own tracked template and configuration reference. Use public placeholders in `.env.example` and documentation. Defaults should be generic and safe; the standalone Go listener defaults to loopback.
The supervisor sources a trusted administrator-owned env file, normally `/etc/storage/routershelf.env`; `ROUTERSHELF_ENV_FILE` overrides its location. It exports values and passes application flags. The Go binary reads exported environment values but does **not** load or execute `.env` itself. CLI flags override environment defaults. Keep these representations consistent. The supervisor sources a trusted administrator-owned env file, normally `/etc/storage/routershelf.env`; `ROUTERSHELF_ENV_FILE` overrides its location. It exports values and passes application flags. The Go binary reads exported environment values but does **not** load or execute `.env` itself. CLI flags override environment defaults. Keep these representations consistent.
@@ -80,3 +81,7 @@ Installed names such as `public-directory`, `public-share-service.sh` and `/tmp/
Keep diffs focused and update user-facing documentation/metadata when behavior changes. Preserve user edits. Do not assume a remote, version, release or successful publication. Commit or publish only within the requested scope. Follow `.github/PULL_REQUEST_TEMPLATE.md` for descriptions: problem, resulting behavior, actual validation and deployment/rollback impact. Keep diffs focused and update user-facing documentation/metadata when behavior changes. Preserve user edits. Do not assume a remote, version, release or successful publication. Commit or publish only within the requested scope. Follow `.github/PULL_REQUEST_TEMPLATE.md` for descriptions: problem, resulting behavior, actual validation and deployment/rollback impact.
Before publishing or refreshing a public archive, exclude private env, keys, cache, router exports, USB data, logs, screenshots and build output. Include `.env.example`. `.gitignore` does not protect secrets already tracked: inspect the export/staged files. Never claim the public sample supervisor was tested unchanged on every supported device. Before publishing or refreshing a public archive, exclude private env, keys, cache, router exports, USB data, logs, screenshots and build output. Include `.env.example`. `.gitignore` does not protect secrets already tracked: inspect the export/staged files. Never claim the public sample supervisor was tested unchanged on every supported device.
## SMB independence
Keep SMB JSON/account/source policy and supervision independent of the web env, domain, certificates, public NAT and compatibility paths. SMB is experimental until actual native Finder and target checks are observed. Run `make build-smb-mipsle` in addition to the web build and SMB race tests for relevant changes. NT hashes are password-equivalent secrets; never publish actual configs. Only localhost native-client tests are implicitly part of local validation; target writes/execution require authorization.
+6
View File
@@ -21,3 +21,9 @@ Never attach private keys, certificate caches, full router exports, USB files, u
Before the first publication, review staged files and metadata, configure the actual Git remote, and replace publication placeholders where needed. There is no automatic deploy or publish action in this project. Before the first publication, review staged files and metadata, configure the actual Git remote, and replace publication placeholders where needed. There is no automatic deploy or publish action in this project.
Stress-runner changes should be tested with `make test-stress-tool` against localhost and synthetic telemetry, not by loading the live deployment. Only run a live workload when requested, with the target and bounds clear. See [stress testing](docs/stress-testing.md). Stress-runner changes should be tested with `make test-stress-tool` against localhost and synthetic telemetry, not by loading the live deployment. Only run a live workload when requested, with the target and bounds clear. See [stress testing](docs/stress-testing.md).
## SMB contributions
Keep `cmd/routershelf-smb` independent of web configuration/certificates/public exposure. Protocol code in `internal/smbwire` is an adapted Apache-2.0 dependency; preserve its license, provenance and adaptation inventory. Run `make test`, `go test -race ./cmd/routershelf-smb ./internal/smbwire`, and `make build-mipsle build-smb-mipsle`. Add meaningful authentication/signing, read-only, confinement, sharing/locking, file mutation, interruption and bounded-resource tests for affected behavior. Never replace disk metadata with successful volatile writes.
Native macOS checks are opt-in: build the desktop SMB executable and run `python3 -B scripts/test_smb_macos.py /absolute/path/to/routershelf-smb`; it mounts only a temporary localhost share with synthetic credentials. Repeat with `--read-only` to check native mutation refusals. Native Finder GUI, actual exFAT, router kernel, resource/coexistence, USB loss, reboot and interrupted native-client tests are separate checks and must be recorded honestly. Read-only router inspection does not authorize executing a new binary or writing test data there. Keep real `smb.json`, hashes and logs private.
+6 -1
View File
@@ -2,13 +2,14 @@ GO ?= go
PYTHON ?= python3 PYTHON ?= python3
BINARY := dist/routershelf-linux-mipsle BINARY := dist/routershelf-linux-mipsle
.PHONY: test build-mipsle check-shell check-config nat-plan test-stress-tool .PHONY: test build-mipsle check-shell check-config nat-plan test-stress-tool build-smb-mipsle
test: check-shell check-config test-stress-tool test: check-shell check-config test-stress-tool
$(GO) test ./... $(GO) test ./...
check-shell: check-shell:
sh -n deploy/padavan/supervisor.example.sh sh -n deploy/padavan/supervisor.example.sh
sh -n deploy/padavan/smb-supervisor.example.sh
sh -n scripts/nat-plan.sh sh -n scripts/nat-plan.sh
sh -n examples/status-dashboard/scripts/status-service.sh sh -n examples/status-dashboard/scripts/status-service.sh
sh -n examples/status-dashboard/scripts/status-response.sh sh -n examples/status-dashboard/scripts/status-response.sh
@@ -25,3 +26,7 @@ nat-plan:
test-stress-tool: test-stress-tool:
$(PYTHON) -B -m unittest discover -s scripts/tests -p 'test_*.py' -v $(PYTHON) -B -m unittest discover -s scripts/tests -p 'test_*.py' -v
build-smb-mipsle:
mkdir -p dist
GOOS=linux GOARCH=mipsle GOMIPS=softfloat CGO_ENABLED=0 $(GO) build -trimpath -ldflags='-s -w' -o dist/routershelf-smb-linux-mipsle ./cmd/routershelf-smb
+12 -3
View File
@@ -1,11 +1,15 @@
# RouterShelf # RouterShelf
**Read-only HTTPS file sharing from USB storage on a small Linux router.** **USB file sharing for small Linux routers: public read-only web access and optional private Finder access over SMB.**
RouterShelf serves a chosen directory with a dark [NAIS](https://github.com/meghdadfadaee/nais) listing, file downloads, copied links, and DPL playlists. It uses a small Go executable, automatic Let's Encrypt certificates, and an optional Padavan-style supervisor. A MikroTik gateway provides public port forwarding and LAN hairpin access. RouterShelf serves a chosen directory with a dark [NAIS](https://github.com/meghdadfadaee/nais) listing, file downloads, copied links, and DPL playlists. It uses a small Go executable, automatic Let's Encrypt certificates, and an optional Padavan-style supervisor. A MikroTik gateway provides public port forwarding and LAN hairpin access.
This repository includes the implementation and the practical guide for configuring, operating, backing up, and removing it. It also preserves an earlier LAN status-dashboard experiment as a standalone example. This repository includes the implementation and the practical guide for configuring, operating, backing up, and removing it. It also preserves an earlier LAN status-dashboard experiment as a standalone example.
RouterShelf is one product with two independently runnable executables. The web service remains public, unauthenticated and read-only. The new experimental `routershelf-smb` service provides authenticated browsing and optional file management through Finder, without a web domain or certificates.
For private Finder access, start with the [SMB guide](docs/smb.md), [implementation decision](docs/smb-implementation.md), and [validation limits](docs/smb-validation.md).
## Capabilities ## Capabilities
- Directory navigation and file downloads, with HEAD and byte-range support. - Directory navigation and file downloads, with HEAD and byte-range support.
@@ -13,6 +17,7 @@ This repository includes the implementation and the practical guide for configur
- Automatic HTTPS for one configured hostname; HTTP challenge handling and HTTPS redirects. - Automatic HTTPS for one configured hostname; HTTP challenge handling and HTTPS redirects.
- Embedded theme assets; no nginx, PHP runtime, database, or frontend build required. - Embedded theme assets; no nginx, PHP runtime, database, or frontend build required.
- GET/HEAD only, hidden-path filtering, escaped filenames, and filesystem root confinement. - GET/HEAD only, hidden-path filtering, escaped filenames, and filesystem root confinement.
- Optional independent SMB executable with signed authentication, explicit folder selection and read-only/read-write modes.
- Optional USB-aware restart supervision and dedicated IPv4/IPv6 firewall rules on the tested firmware. - Optional USB-aware restart supervision and dedicated IPv4/IPv6 firewall rules on the tested firmware.
The public file service has **no authentication**. HTTPS protects transport; every file placed in the shared directory is available to anyone who can reach the service. Read [security boundaries](SECURITY.md) before deploying. The public file service has **no authentication**. HTTPS protects transport; every file placed in the shared directory is available to anyone who can reach the service. Read [security boundaries](SECURITY.md) before deploying.
@@ -28,6 +33,7 @@ Build and test from the repository root:
```sh ```sh
make test make test
make build-mipsle make build-mipsle
make build-smb-mipsle # optional independent Finder service
``` ```
The cross-build writes `dist/routershelf-linux-mipsle`. The deployment guide explains its installed filename and router paths. Configure deployment without editing source or supervisor code: The cross-build writes `dist/routershelf-linux-mipsle`. The deployment guide explains its installed filename and router paths. Configure deployment without editing source or supervisor code:
@@ -49,6 +55,8 @@ Use the [stress-test guide](docs/stress-testing.md) for bounded load phases, rou
```text ```text
cmd/routershelf/ HTTP/HTTPS application and behavior tests cmd/routershelf/ HTTP/HTTPS application and behavior tests
cmd/routershelf-smb/ Independent private SMB executable and config tests
internal/smbwire/ Adapted Apache-2.0 SMB protocol source and tests
internal/theme/nais/ Licensed NAIS assets embedded in the executable internal/theme/nais/ Licensed NAIS assets embedded in the executable
internal/theme/assets.go Asset embedding boundary internal/theme/assets.go Asset embedding boundary
deploy/padavan/ Environment-driven firmware supervisor deploy/padavan/ Environment-driven firmware supervisor
@@ -56,7 +64,8 @@ examples/status-dashboard/ Separate legacy BusyBox/Netcat dashboard
docs/ Setup, operations, architecture, and deployment history docs/ Setup, operations, architecture, and deployment history
.github/ CI and issue/pull-request templates .github/ CI and issue/pull-request templates
scripts/nat-plan.sh Gateway plan derived from private environment scripts/nat-plan.sh Gateway plan derived from private environment
.env.example Public configuration template .env.example Public web configuration template
.smb.example.json Public SMB template; real credentials stay private
Makefile Local checks and MIPS little-endian build Makefile Local checks and MIPS little-endian build
project.json Project identity and compatibility metadata project.json Project identity and compatibility metadata
``` ```
@@ -73,4 +82,4 @@ On the original device, HTTPS issuance, trusted downloads, HTTP redirects, read-
Read [CONTRIBUTING.md](CONTRIBUTING.md). Keep deployment configuration, certificate caches, keys, router exports, USB data, logs, and generated binaries out of Git. All tracked deployment examples use placeholder values. This local repository has no configured remote and has not been published. Read [CONTRIBUTING.md](CONTRIBUTING.md). Keep deployment configuration, certificate caches, keys, router exports, USB data, logs, and generated binaries out of Git. All tracked deployment examples use placeholder values. This local repository has no configured remote and has not been published.
Project code is [MIT licensed](LICENSE). NAIS retains its [upstream MIT license](internal/theme/nais/LICENSE). Dependency and theme attribution is collected in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). Project code is [MIT licensed](LICENSE); the embedded SMB implementation retains its [Apache-2.0 license](internal/smbwire/LICENSE). NAIS retains its [upstream MIT license](internal/theme/nais/LICENSE). Dependency and theme attribution is collected in [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
+8
View File
@@ -26,3 +26,11 @@ The original firmware/kernel are old. This project does not make an unsupported
Use example-only addresses and hostnames. Exclude private config, keys/certificates, cache directories, firmware exports, logs, disk data, screenshots, build outputs, and IDE state. Review staged files. Never paste full router dumps into an issue; provide sanitized diagnostic excerpts. Use example-only addresses and hostnames. Exclude private config, keys/certificates, cache directories, firmware exports, logs, disk data, screenshots, build outputs, and IDE state. Review staged files. Never paste full router dumps into an issue; provide sanitized diagnostic excerpts.
See [operations](docs/operations.md) for backup, rollback, and removal instructions, and [deployment history](docs/deployment-history.md) for validation limits. See [operations](docs/operations.md) for backup, rollback, and removal instructions, and [deployment history](docs/deployment-history.md) for validation limits.
## Optional private SMB service
`routershelf-smb` is an experimental separately configured authenticated service; it does not add authentication or writes to HTTP. It binds a specific private/loopback IPv4 address, requires explicit trusted-source CIDRs, NTLMv2 and signed packets, and drops OS privileges before serving a selected `os.Root` directory. Signing does not encrypt data. Do not expose SMB through WAN forwards/public tunnels or the web firewall chain.
Private JSON contains a password-equivalent NT hash: require protected file modes/ownership on permission-enforcing storage outside all shares. exFAT mount permissions do not isolate service secrets from broadly authorized accounts. Read-only sharing is enforced by the service; per-file ACL changes are unsupported. SMB includes hidden files and allows writes only when explicitly configured. Keep private/public storage separate, list customized public roots, and opt in explicitly to overlap; an upload into a public root can immediately publish its content.
Server-local locks do not coordinate FTP/SFTP/local writers or multiple independent SMB processes. Interrupted writes can leave partial files; exFAT/power loss has no transactional recovery guarantee. Back up data, preserve sources and verify transfers before replacement. Bounds and the Go memory target cannot prevent all resource exhaustion. This backend needs independent security review and target validation before stronger support claims. See [SMB security and limitations](docs/smb.md#privacy-and-filesystem-behavior).
+4
View File
@@ -13,3 +13,7 @@ The application uses `golang.org/x/crypto/acme/autocert` and its Go module depen
## Operational downloads ## Operational downloads
The CA root bundle is obtained separately during deployment. It is not committed to this repository. Review its source and license separately when redistributing it. Runtime certificates and account keys are private deployment material, not source assets. The CA root bundle is obtained separately during deployment. It is not committed to this repository. Review its source and license separately when redistributing it. Runtime certificates and account keys are private deployment material, not source assets.
## Embedded SMB server
`internal/smbwire` derives from [Softwarity smbserver v0.1.1](https://github.com/softwarity/smbserver/tree/v0.1.1), commit `88586e668400859c882428b308408c26086bb1d5`, under Apache License 2.0. The complete license is retained at `internal/smbwire/LICENSE`. This is modified source; [UPSTREAM.md](internal/smbwire/UPSTREAM.md) records provenance and RouterShelf adaptations. Include that license and this attribution when distributing SMB source/binaries. The SMB code uses the existing BSD-licensed `golang.org/x/crypto/md4` dependency; module versions/checksums remain in go.mod/go.sum. Apache-licensed embedded code retains its own license while RouterShelf project code remains MIT.
+197
View File
@@ -0,0 +1,197 @@
package main
import (
"encoding/hex"
"encoding/json"
"errors"
"flag"
"io"
"net"
"net/netip"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"unicode"
)
// SMB deliberately has no defaults derived from the web service's settings.
type config struct {
Listen string `json:"listen"`
Mount string `json:"storage_mount"`
Root string `json:"root"`
Share string `json:"share"`
User string `json:"user"`
Hash string `json:"nt_hash"`
ReadOnly bool `json:"read_only"`
Allow []string `json:"allow"`
ProtectedPaths []string `json:"protected_paths"`
PublicRoots []string `json:"public_roots"`
AllowPublicOverlap bool `json:"allow_public_overlap"`
UID int `json:"uid"`
GID int `json:"gid"`
Diagnostics bool `json:"diagnostics"`
CaseInsensitive bool `json:"case_insensitive"`
prefixes []netip.Prefix
ntHash [16]byte
ready func()
path string
}
func within(parent, child string) bool {
rel, err := filepath.Rel(parent, child)
return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(os.PathSeparator))
}
func overlap(a, b string) bool { return within(a, b) || within(b, a) }
func canonical(p string) (string, error) {
if !filepath.IsAbs(p) || filepath.Clean(p) != p {
return "", errors.New("paths must be clean and absolute")
}
return filepath.EvalSymlinks(p)
}
func loadConfig(args []string) (config, bool, error) {
c := config{Listen: "127.0.0.1:1445", Share: "Storage", ReadOnly: true, UID: 65533, GID: 65533, CaseInsensitive: true}
fs := flag.NewFlagSet("routershelf-smb", flag.ContinueOnError)
fs.SetOutput(io.Discard)
path := fs.String("config", os.Getenv("RS_SMB_CONFIG"), "Private JSON configuration (RS_SMB_CONFIG)")
check := fs.Bool("check-config", false, "Validate without listening or writing")
if err := fs.Parse(args); err != nil {
return c, false, err
}
if len(fs.Args()) != 0 || *path == "" {
return c, false, errors.New("use -config /absolute/private/smb.json or RS_SMB_CONFIG; see docs/smb.md")
}
p, err := canonical(*path)
if err != nil {
return c, false, errors.New("configuration must exist at an absolute path")
}
c.path = p
f, err := os.Open(p)
if err != nil {
return c, false, errors.New("cannot open private SMB configuration")
}
defer f.Close()
fi, err := f.Stat()
if err != nil || !fi.Mode().IsRegular() || fi.Mode().Perm()&0077 != 0 || fi.Size() > 32768 {
return c, false, errors.New("SMB configuration must be a regular file with mode 0600 or 0400 on a permission-enforcing filesystem")
}
if st, ok := fi.Sys().(*syscall.Stat_t); ok && st.Uid != 0 && int(st.Uid) != os.Geteuid() {
return c, false, errors.New("configuration must be owned by root or the current account")
}
dec := json.NewDecoder(io.LimitReader(f, 32769))
dec.DisallowUnknownFields()
if err := dec.Decode(&c); err != nil {
return c, false, errors.New("invalid SMB JSON configuration (unknown field, type, or syntax)")
}
var extra any
if dec.Decode(&extra) != io.EOF {
return c, false, errors.New("configuration must contain one JSON object under 32 KiB")
}
if err := c.validate(); err != nil {
return c, false, err
}
return c, *check, nil
}
func (c *config) validate() error {
host, port, err := net.SplitHostPort(c.Listen)
ip, e := netip.ParseAddr(host)
n, pe := strconv.Atoi(port)
if err != nil || e != nil || !ip.Is4() || ip.IsUnspecified() || ip.IsMulticast() || pe != nil || n < 1 || n > 65535 {
return errors.New("listen must be a specific numeric IPv4 address and valid port")
}
// Never permit a public address or a wildcard listener. Prefixes also filter peers.
if !ip.IsPrivate() && !ip.IsLoopback() {
return errors.New("SMB listener must be private IPv4 or loopback")
}
if len(c.Allow) == 0 {
return errors.New("allow must explicitly list trusted private IPv4 client prefixes")
}
for _, v := range c.Allow {
p, err := netip.ParsePrefix(v)
if err != nil || !p.Addr().Is4() || p != p.Masked() || p.Bits() < 8 {
return errors.New("invalid trusted client prefix")
}
last := p.Addr().As4()
bits := p.Bits()
for i := bits; i < 32; i++ {
last[i/8] |= 1 << uint(7-i%8)
}
if !(p.Addr().IsPrivate() && netip.AddrFrom4(last).IsPrivate() || p.Addr().IsLoopback() && netip.AddrFrom4(last).IsLoopback()) {
return errors.New("client prefixes must stay inside private IPv4 or loopback space")
}
c.prefixes = append(c.prefixes, p)
}
if c.UID <= 0 || c.GID <= 0 || c.UID > 2147483647 || c.GID > 2147483647 {
return errors.New("uid and gid must be non-root positive IDs")
}
for _, s := range []string{c.Share, c.User} {
if strings.IndexFunc(s, unicode.IsControl) >= 0 || len(s) < 1 || len(s) > 64 || strings.ContainsAny(s, "\\/:*?\"<>| \t\r\n\x00") {
return errors.New("share and user require 1–64 plain characters without spaces or separators")
}
}
if strings.EqualFold(c.Share, "IPC$") {
return errors.New("reserved share name")
}
hash, err := hex.DecodeString(c.Hash)
if err != nil || len(hash) != 16 {
return errors.New("nt_hash must contain 32 hexadecimal characters")
}
copy(c.ntHash[:], hash)
if c.Hash == "00000000000000000000000000000000" || strings.EqualFold(c.Hash, "31d6cfe0d16ae931b73c59d7e0c089c0") {
return errors.New("replace placeholder or empty-password NT hash")
}
if c.Mount == "/" {
return errors.New("storage_mount must select storage, not the system root")
}
c.Mount, err = canonical(c.Mount)
if err != nil || c.Mount == "/" {
return errors.New("storage_mount must be an existing absolute storage directory outside the system root")
}
c.Root, err = canonical(c.Root)
if err != nil {
return errors.New("selected root is unavailable")
}
fi, err := os.Stat(c.Root)
if err != nil || !fi.IsDir() || c.Root == c.Mount || !within(c.Mount, c.Root) {
return errors.New("root must be an existing directory strictly below storage_mount; it is never created automatically")
}
if within(c.Root, c.path) {
return errors.New("private SMB configuration cannot be inside the share")
}
protected := append([]string{filepath.Join(c.Mount, ".public-share-service"), filepath.Join(c.Mount, ".smb-service")}, c.ProtectedPaths...)
if exe, err := os.Executable(); err == nil {
protected = append(protected, exe)
}
for _, p := range protected {
if !filepath.IsAbs(p) || filepath.Clean(p) != p {
return errors.New("protected_paths must use clean absolute paths")
}
if resolved, err := filepath.EvalSymlinks(p); err == nil {
p = resolved
} else if !os.IsNotExist(err) {
return errors.New("cannot resolve a protected path")
}
if within(c.Root, p) || within(p, c.Root) {
return errors.New("SMB root overlaps a private service or protected path")
}
}
public := append([]string{filepath.Join(c.Mount, "public-storage")}, c.PublicRoots...)
for _, p := range public {
if !filepath.IsAbs(p) || filepath.Clean(p) != p {
return errors.New("public_roots must use clean absolute paths")
}
resolved, err := filepath.EvalSymlinks(p)
if err == nil {
p = resolved
} else if !os.IsNotExist(err) {
return errors.New("cannot resolve a public root")
}
if overlap(c.Root, p) && !c.AllowPublicOverlap {
return errors.New("SMB overlaps public web storage; select a private sibling or explicitly set allow_public_overlap")
}
}
return nil
}
+131
View File
@@ -0,0 +1,131 @@
package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
)
func fixture(t *testing.T) (config, string) {
t.Helper()
mount, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
root := filepath.Join(mount, "private-storage")
if err := os.Mkdir(root, 0700); err != nil {
t.Fatal(err)
}
dir, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
}
p := filepath.Join(dir, "smb.json")
// Public synthetic credential fixture; never deploy it.
c := config{Mount: mount, Root: root, User: "storage", Hash: "9b675d1cbdc67f1620c6442c7b07bc63", Allow: []string{"127.0.0.1/32"}}
return c, p
}
func saveConfig(t *testing.T, c config, p string) {
t.Helper()
b, err := json.Marshal(c)
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, b, 0600); err != nil {
t.Fatal(err)
}
}
func TestConfigurationAndIndependence(t *testing.T) {
c, p := fixture(t)
// Omit fields to exercise secure defaults, even with conflicting web settings.
b := `{"storage_mount":` + quote(c.Mount) + `,"root":` + quote(c.Root) + `,"user":"storage","nt_hash":` + quote(c.Hash) + `,"allow":["127.0.0.1/32"]}`
if err := os.WriteFile(p, []byte(b), 0600); err != nil {
t.Fatal(err)
}
t.Setenv("RS_DOMAIN", "invalid.example")
t.Setenv("RS_ROOT", "/nonexistent/web")
t.Setenv("RS_USB_MOUNT", "/missing")
t.Setenv("RS_SMB_CONFIG", "/missing")
got, check, err := loadConfig([]string{"-config", p, "-check-config"})
if err != nil {
t.Fatal(err)
}
if !check || !got.ReadOnly || got.Listen != "127.0.0.1:1445" || got.Root != c.Root || got.UID != 65533 || got.GID != 65533 {
t.Fatalf("defaults/precedence: %+v", got)
}
t.Setenv("RS_SMB_CONFIG", p)
if _, _, err := loadConfig([]string{"-check-config"}); err != nil {
t.Fatal(err)
}
}
func quote(s string) string { b, _ := json.Marshal(s); return string(b) }
func TestUnsafeConfiguration(t *testing.T) {
tests := map[string]func(*config, string){
"protected root": func(c *config, _ string) { c.ProtectedPaths = []string{c.Root} },
"system mount": func(c *config, _ string) { c.Mount = "/" },
"uid overflow": func(c *config, _ string) { value := int64(2147483648); c.UID = int(value) },
"control name": func(c *config, _ string) { c.User = "bad\x01user" },
"wildcard": func(c *config, _ string) { c.Listen = "0.0.0.0:445" },
"public": func(c *config, _ string) { c.Listen = "203.0.113.1:445" },
"named port": func(c *config, _ string) { c.Listen = "127.0.0.1:http" },
"all peers": func(c *config, _ string) { c.Allow = []string{"0.0.0.0/0"} },
"cross boundary": func(c *config, _ string) { c.Allow = []string{"172.0.0.0/8"} },
"no peers": func(c *config, _ string) { c.Allow = nil },
"root account": func(c *config, _ string) { c.UID = 0 },
"placeholder": func(c *config, _ string) { c.Hash = strings.Repeat("0", 32) },
"empty password": func(c *config, _ string) { c.Hash = "31d6cfe0d16ae931b73c59d7e0c089c0" },
"mount root": func(c *config, _ string) { c.Root = c.Mount },
"missing storage": func(c *config, _ string) { c.Root = filepath.Join(c.Mount, "missing") },
"credentials shared": func(c *config, p string) { c.Root = filepath.Dir(p); c.Mount = filepath.Dir(c.Root) },
"public overlap": func(c *config, _ string) { c.PublicRoots = []string{c.Root} },
"public parent": func(c *config, _ string) { c.PublicRoots = []string{c.Mount} },
"bad share": func(c *config, _ string) { c.Share = "IPC$" },
}
for name, change := range tests {
t.Run(name, func(t *testing.T) {
c, p := fixture(t)
c.Listen = "127.0.0.1:1445"
c.Share = "Storage"
c.UID = 65534
c.GID = 65534
change(&c, p)
saveConfig(t, c, p)
if _, _, err := loadConfig([]string{"-config", p}); err == nil {
t.Fatal("accepted unsafe config")
}
})
}
}
func TestSecretFileAndOverlap(t *testing.T) {
c, p := fixture(t)
c.Listen = "127.0.0.1:1445"
c.Share = "Storage"
c.UID = 65534
c.GID = 65534
c.PublicRoots = []string{c.Root}
c.AllowPublicOverlap = true
saveConfig(t, c, p)
if _, _, err := loadConfig([]string{"-config", p}); err != nil {
t.Fatal(err)
}
if err := os.Chmod(p, 0644); err != nil {
t.Fatal(err)
}
if _, _, err := loadConfig([]string{"-config", p}); err == nil {
t.Fatal("accepted readable credentials")
}
if err := os.Chmod(p, 0600); err != nil {
t.Fatal(err)
}
for _, content := range []string{`{"password":"do-not-log-this"}`, `{} {}`, strings.Repeat(" ", 32769)} {
if err := os.WriteFile(p, []byte(content), 0600); err != nil {
t.Fatal(err)
}
_, _, err := loadConfig([]string{"-config", p})
if err == nil || strings.Contains(err.Error(), "do-not-log-this") {
t.Fatal("invalid config accepted or secret leaked")
}
}
}
+163
View File
@@ -0,0 +1,163 @@
// routershelf-smb is an independent private file service. It never changes
// firewall, routing, firmware settings, or the web service.
package main
import (
"bufio"
"context"
"encoding/hex"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"os/signal"
"runtime"
"runtime/debug"
"strings"
"syscall"
"time"
smb "routershelf/internal/smbwire"
)
func mounted(path string) bool {
if runtime.GOOS != "linux" {
return true
}
f, err := os.Open("/proc/mounts")
if err != nil {
return false
}
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
v := strings.Fields(sc.Text())
if len(v) > 1 {
p := strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`).Replace(v[1])
if p == path {
return true
}
}
}
return false
}
func drop(c config) error {
if os.Geteuid() != 0 {
if os.Geteuid() != c.UID || os.Getegid() != c.GID {
return errors.New("run as configured uid/gid or start as root to bind and drop privileges")
}
return nil
}
if err := syscall.Setgroups([]int{}); err != nil {
return err
}
if err := syscall.Setgid(c.GID); err != nil {
return err
}
return syscall.Setuid(c.UID)
}
func serve(ctx context.Context, c config) error {
if !mounted(c.Mount) {
return errors.New("expected USB mount is unavailable; refusing underlying mount directory")
}
initial, err := os.Stat(c.Root)
if err != nil {
return errors.New("share unavailable")
}
ln, err := net.Listen("tcp4", c.Listen)
if err != nil {
return errors.New("cannot bind SMB listener; check address, privileges and existing SMB services")
}
defer ln.Close()
if err := drop(c); err != nil {
return fmt.Errorf("cannot drop SMB privileges: %w", err)
}
// Confirm the dropped account can read this directory before announcing ready.
d, err := os.Open(c.Root)
if err != nil {
return errors.New("share is unreadable by configured account")
}
_, err = d.Readdirnames(1)
d.Close()
if err != nil && err != io.EOF {
return errors.New("share cannot be listed")
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
lost := make(chan struct{})
go func() {
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
current, err := os.Stat(c.Root)
if err != nil || !os.SameFile(initial, current) || !mounted(c.Mount) {
close(lost)
cancel()
return
}
}
}
}()
var diagnostic func(string, ...any)
if c.Diagnostics {
diagnostic = log.Printf
}
err = smb.Serve(ctx, ln, smb.Config{ExpectedRoot: initial, Ready: func() {
log.Print("SMB ready; authenticated signing required; read_only=", c.ReadOnly)
if c.ready != nil {
c.ready()
}
}, Logf: diagnostic, Root: c.Root, Share: c.Share, User: c.User, NTHash: c.ntHash, Allow: c.prefixes, ReadOnly: c.ReadOnly, DiskMetadata: true, CaseInsensitive: c.CaseInsensitive})
select {
case <-lost:
return errors.New("USB storage disappeared or changed; sessions closed; reconnect after storage recovers")
default:
return err
}
}
func run() error {
if len(os.Args) == 2 && (os.Args[1] == "-h" || os.Args[1] == "--help" || os.Args[1] == "-help") {
fmt.Println("RouterShelf SMB (experimental)\nUsage: routershelf-smb -config /absolute/private/smb.json [-check-config]\n routershelf-smb -hash-password < password-from-hidden-prompt\nRS_SMB_CONFIG supplies the default config path. No web configuration is required.\nSee docs/smb.md for Finder setup, permissions, updates and recovery.")
return nil
}
if len(os.Args) == 2 && os.Args[1] == "-hash-password" {
// Pipe from a hidden terminal prompt; never put a password in argv/env.
b, err := io.ReadAll(io.LimitReader(os.Stdin, 1025))
if err != nil {
return err
}
b = []byte(strings.TrimSuffix(strings.TrimSuffix(string(b), "\n"), "\r"))
if len(b) < 12 || len(b) > 1024 {
return errors.New("use a unique password of 12–1024 bytes")
}
h := smb.NTHash(string(b))
clear(b)
fmt.Println(hex.EncodeToString(h[:]))
return nil
}
c, check, err := loadConfig(os.Args[1:])
if err != nil {
return err
}
if check {
fmt.Println("SMB configuration valid; no service started")
return nil
}
runtime.GOMAXPROCS(1)
debug.SetMemoryLimit(20 << 20)
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
return serve(ctx, c)
}
func main() {
if err := run(); err != nil {
log.Print(err)
os.Exit(1)
}
}
+81
View File
@@ -0,0 +1,81 @@
package main
import (
"context"
"net"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestStorageReplacementClosesIndependentService(t *testing.T) {
if os.Geteuid() == 0 {
t.Skip("do not drop the test process's root privileges")
}
root := filepath.Join(t.TempDir(), "share")
if err := os.Mkdir(root, 0700); err != nil {
t.Fatal(err)
}
probe, err := net.Listen("tcp4", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := probe.Addr().String()
probe.Close()
c := config{Mount: "/", Root: root, Listen: addr, UID: os.Geteuid(), GID: os.Getegid(), Share: "Storage", User: "storage", ReadOnly: true}
ready := make(chan struct{})
c.ready = func() { close(ready) }
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
done := make(chan error, 1)
go func() { done <- serve(ctx, c) }()
select {
case <-ready:
case err := <-done:
t.Fatalf("startup failed: %v", err)
case <-time.After(3 * time.Second):
t.Fatal("startup never ready")
}
deadline := time.Now().Add(3 * time.Second)
for {
nc, err := net.DialTimeout("tcp4", addr, 100*time.Millisecond)
if err == nil {
nc.Close()
break
}
select {
case err := <-done:
t.Fatalf("service exited: %v", err)
default:
}
if time.Now().After(deadline) {
t.Fatal("service never listened")
}
time.Sleep(10 * time.Millisecond)
}
if err := os.Rename(root, root+"-removed"); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(root, 0700); err != nil {
t.Fatal(err)
}
select {
case err := <-done:
if err == nil || !strings.Contains(err.Error(), "disappeared or changed") {
t.Fatalf("expected storage loss: %v", err)
}
case <-time.After(4 * time.Second):
t.Fatal("storage replacement did not close service")
}
nc, err := net.DialTimeout("tcp4", addr, 100*time.Millisecond)
if err == nil {
nc.Close()
t.Fatal("listener survived storage replacement")
}
entries, err := os.ReadDir(root)
if err != nil || len(entries) != 0 {
t.Fatal("replacement storage was initialized")
}
}
+4
View File
@@ -5,3 +5,7 @@ The supervisor loads the private `/etc/storage/routershelf.env` file. Use the un
Copy `.env.example` to `.env` in the repository root. Run `--check-config` with `ROUTERSHELF_ENV_FILE` pointing to that file before installation. See [environment configuration](../../docs/configuration.md), [installation](../../docs/getting-started.md), and [operations](../../docs/operations.md). Copy `.env.example` to `.env` in the repository root. Run `--check-config` with `ROUTERSHELF_ENV_FILE` pointing to that file before installation. See [environment configuration](../../docs/configuration.md), [installation](../../docs/getting-started.md), and [operations](../../docs/operations.md).
The script targets the observed firmware hooks and firewall commands. No project edit automatically changes a running router. The script targets the observed firmware hooks and firewall commands. No project edit automatically changes a running router.
## Optional independent SMB service
`smb-supervisor.example.sh` supervises only `routershelf-smb`, using `RS_SMB_BINARY` and `RS_SMB_CONFIG`. It does not load the web env, configure NTP/firewall, or touch public-share paths. See [SMB installation, lifecycle and rollback](../../docs/smb.md). Validate/approve target deployment separately; existing web hooks remain compatible.
+52
View File
@@ -0,0 +1,52 @@
#!/bin/sh
# Independent USB-aware SMB supervisor. No web environment, firewall or NTP.
# Administrator supplies absolute paths. Run foreground from the USB hook.
set -eu
: "${RS_SMB_BINARY:?set RS_SMB_BINARY to the installed SMB executable}"
: "${RS_SMB_CONFIG:?set RS_SMB_CONFIG to private JSON on protected storage}"
case "$RS_SMB_BINARY:$RS_SMB_CONFIG" in *'
'*|*' '*|*'..'*) echo 'Use absolute paths without spaces or ..' >&2; exit 1;; esac
case "$RS_SMB_BINARY" in /*) ;; *) exit 1;; esac
case "$RS_SMB_CONFIG" in /*) ;; *) exit 1;; esac
if [ "${1:-}" = --check-config ]; then
exec "$RS_SMB_BINARY" -config "$RS_SMB_CONFIG" -check-config
fi
if [ "$#" -ne 0 ]; then echo 'Only --check-config is supported' >&2; exit 1; fi
# mkdir is atomic: fail on an existing instance rather than trust reused PIDs.
# This directory is distinct from all public-share compatibility paths.
runtime=/tmp/routershelf-smb
umask 077
if ! mkdir "$runtime" 2>/dev/null; then
echo 'SMB supervisor lock exists; inspect its PID command line before recovery' >&2
exit 1
fi
child=
cleanup() {
trap '' INT TERM
if [ -n "$child" ]; then
# Only the direct child launched by this shell; never read a PID to kill.
kill -TERM "$child" 2>/dev/null || :
wait "$child" 2>/dev/null || :
fi
rm -f "$runtime/child.pid" "$runtime/supervisor.pid"
rmdir "$runtime" 2>/dev/null || :
}
trap 'exit 0' INT TERM
trap cleanup 0
printf '%s\n' "$$" > "$runtime/supervisor.pid"
while :; do
if [ -x "$RS_SMB_BINARY" ] && [ -f "$RS_SMB_CONFIG" ]; then
"$RS_SMB_BINARY" -config "$RS_SMB_CONFIG" &
child=$!
printf '%s\n' "$child" > "$runtime/child.pid"
wait "$child" || :
child=
rm -f "$runtime/child.pid"
fi
# The binary verifies exact mount presence before binding, never mkdirs a
# missing share, and exits on mount/root replacement. Retry is independent.
sleep 10 &
child=$!
wait "$child" || :
child=
done
+6 -1
View File
@@ -1,10 +1,11 @@
# Architecture # Architecture
RouterShelf has four operational layers: RouterShelf has independent web and SMB service executables within these operational layers:
| Layer | Responsibility | Repository location | | Layer | Responsibility | Repository location |
| --- | --- | --- | | --- | --- | --- |
| Go application | Safe directory reads, HTTP responses, TLS and ACME, connection limits, privilege drop | `cmd/routershelf` | | Go application | Safe directory reads, HTTP responses, TLS and ACME, connection limits, privilege drop | `cmd/routershelf` |
| Private SMB application | Independent account/config, selected root, signed SMB, write policy and privilege drop | `cmd/routershelf-smb`, `internal/smbwire` |
| Embedded theme | NAIS styling, favicon, copied links, playlist generation | `internal/theme` | | Embedded theme | NAIS styling, favicon, copied links, playlist generation | `internal/theme` |
| Router lifecycle | USB checks, process restart, time startup, host firewall hooks, flash persistence | `deploy/padavan` | | Router lifecycle | USB checks, process restart, time startup, host firewall hooks, flash persistence | `deploy/padavan` |
| Network gateway | Public DNS destination, destination NAT, LAN hairpin reply routing | Configuration documented in `docs/getting-started.md` | | Network gateway | Public DNS destination, destination NAT, LAN hairpin reply routing | Configuration documented in `docs/getting-started.md` |
@@ -28,3 +29,7 @@ The legacy dashboard is a separate Netcat/shell example, with its own configurat
The Go module path is currently `routershelf`, a local standalone module identity. If a real repository remote is established later, change the module path and the `routershelf/internal/theme` import together if a hosted module path is desired. No remote namespace is assumed. The Go module path is currently `routershelf`, a local standalone module identity. If a real repository remote is established later, change the module path and the `routershelf/internal/theme` import together if a hosted module path is desired. No remote namespace is assumed.
Read [setup](getting-started.md), [operations](operations.md), and [security](../SECURITY.md) for configuration and maintenance boundaries. Read [setup](getting-started.md), [operations](operations.md), and [security](../SECURITY.md) for configuration and maintenance boundaries.
## Independent private SMB path
`Finder -> specific private IPv4 SMB listener -> os.Root selected private USB folder`. This path needs no web server, certificates, NTP startup or gateway NAT. The SMB supervisor uses its own JSON path, executable, process tree and `/tmp/routershelf-smb/` lock. It never sources the web environment, changes firewall rules or signals the web service. The web binary does not import SMB code. Both may access USB storage, so resource pressure and deliberately overlapping data remain shared operational risks. See [SMB setup and lifecycle](smb.md) and [implementation decision](smb-implementation.md).
+2
View File
@@ -1,5 +1,7 @@
# Environment configuration # Environment configuration
This guide describes the web service. The independent SMB service uses private JSON and `RS_SMB_CONFIG`; its supervisor also accepts `RS_SMB_BINARY`. Neither reads the web settings. See the [SMB configuration reference](smb.md#configuration-reference).
Network-specific settings live in a private `.env` file. The public `.env.example` contains only illustrative values. Changing a domain, subnet, USB mount, or port does not require editing Go or shell source and does not require rebuilding the application. Network-specific settings live in a private `.env` file. The public `.env.example` contains only illustrative values. Changing a domain, subnet, USB mount, or port does not require editing Go or shell source and does not require rebuilding the application.
## Loading and precedence ## Loading and precedence
+6
View File
@@ -78,3 +78,9 @@ Validated: example and live config checks, invalid-port rejection, Go environmen
The application now renders a directory's readable regular `index.html` before listing it, and serves direct HTML requests inline. Recognized CSS/JavaScript/image/font assets have explicit MIME types. Other files retain attachment downloads. No separate root or URL prefix, new env settings, or gateway rules were added. The application now renders a directory's readable regular `index.html` before listing it, and serves direct HTML requests inline. Recognized CSS/JavaScript/image/font assets have explicit MIME types. Other files retain attachment downloads. No separate root or URL prefix, new env settings, or gateway rules were added.
The binary was deployed with the previous version kept for rollback. Tests covered folder/root index precedence, direct HTML and assets, HEAD, preserved downloads, listing link attributes, and an escaping index symlink. A temporary live page rendered over HTTPS with CSS and JavaScript; its direct HTML link rendered too. HEAD confirmed HTML without attachment disposition, a normal text file still had attachment disposition, and PUT remained 405. Temporary probe files were removed after testing. Static pages intentionally permit browser-side active content; no PHP/CGI/server-side execution was added. The binary was deployed with the previous version kept for rollback. Tests covered folder/root index precedence, direct HTML and assets, HEAD, preserved downloads, listing link attributes, and an escaping index symlink. A temporary live page rendered over HTTPS with CSS and JavaScript; its direct HTML link rendered too. HEAD confirmed HTML without attachment disposition, a normal text file still had attachment disposition, and PUT remained 405. Temporary probe files were removed after testing. Static pages intentionally permit browser-side active content; no PHP/CGI/server-side execution was added.
## 10. Optional SMB repository implementation (2026-10-16)
A separate experimental SMB executable, private JSON configuration, source-confined protocol implementation, independent supervisor, templates and guides were added to the repository. Existing web implementation/configuration and installed paths remain unchanged. Local protocol/race/fuzz checks, native macOS SMB operations and actual Finder browsing/copy/rename/metadata sample checks passed; both static MIPS builds compile. See the detailed [SMB validation record](smb-validation.md).
Router access for this change was read-only inspection of kernel, RAM, BusyBox, SMB command/listener availability and exFAT mount behavior. No SMB binary was deployed or executed there. Target kernel/resource/exFAT/Finder/coexistence/boot/rollback validation requires a separately approved session.
+3
View File
@@ -1,5 +1,8 @@
# Deploy the public HTTPS directory service # Deploy the public HTTPS directory service
For authenticated Finder access without web setup, follow the independent [SMB installation guide](smb.md). This page installs the public web service.
## Architecture and paths ## Architecture and paths
```text ```text
+3
View File
@@ -1,5 +1,8 @@
# Maintenance and recovery # Maintenance and recovery
This page covers the existing web installation. SMB has separate [status, update, rollback and removal procedures](smb.md#install-status-update-and-remove); stopping or updating one service does not operate the other.
## Routine care ## Routine care
| Frequency / event | Check | | Frequency / event | Check |
+29
View File
@@ -0,0 +1,29 @@
# SMB implementation decision
RouterShelf retains its MIT project license and one repository. A second Go executable embeds a narrowly adapted Apache-2.0 SMB implementation; it has no web package imports, certificate logic, public NAT or shared lifecycle. The web executable does not import SMB. Their configuration files, process trees, installed names and runtime directories are separate. SMB uses size-bounded, strictly typed JSON rather than shell configuration: share policy and password-equivalent hashes stay out of environment/argument values, configuration is never executed, and the only application environment input is the independent `RS_SMB_CONFIG` path. The existing web environment contract remains compatible.
## Candidates investigated
| Candidate | Suitability for this initial target |
| --- | --- |
| [Samba](https://www.samba.org/samba/docs/current/man-html/smbd.8.html) | Established implementation with mature authentication, locking and Mac integration. A preferred comparison baseline. A reproducible, maintained static MIPS build with its required dependencies, Linux 3.4 support, exFAT policy and measured combined memory footprint was not established here. Shipping a guessed firmware binary or requiring package installation would not meet this task. GPL obligations would also need a complete corresponding-source distribution plan if bundled. It remains a possible future backend after those checks. |
| [ksmbd](https://www.kernel.org/doc/html/latest/filesystems/smb/ksmbd.html) | Kernel SMB implementation plus userspace utilities, rather than an independent static userspace service for the unmodified 3.4 kernel. Introducing a kernel component is outside this device's constraints. |
| [macos-fuse-t/go-smb2](https://github.com/macos-fuse-t/go-smb2) | Mac-oriented implementation, dual AGPL/commercial licensed. Upstream explicitly identifies authentication, impersonation, parallel connections and locking as early or incomplete. Those are central requirements here; it was not chosen. |
| [go-filesystems/smb](https://github.com/go-filesystems/smb) | Pure Go, BSD-3-Clause, filesystem abstraction with authentication and signing. Young project; would require a separately verified host-filesystem driver and bounded positional I/O throughout. Not integrated during this change. |
| [softwarity/smbserver v0.1.1](https://github.com/softwarity/smbserver/tree/v0.1.1) | Chosen as an experimental implementation base: pure Go, existing pinned x/crypto dependency, os.Root, NTLMv2, required signing, source filtering, read-only mode, real-socket/fuzz tests and reported native-client CI. One user/share scope is explicit. Upstream defaults and ephemeral metadata are inappropriate for this router, so a local source adaptation is maintained with its license and provenance. Upstream CI claims are not RouterShelf validation. |
This choice favors a locally buildable executable with inspectable policy over introducing deployment dependencies. It does **not** establish production readiness or substitute for a security audit. SMB is a large protocol; the young backend and local modifications need continued maintenance, fuzzing, independent review and real-client coverage. See [upstream adaptation inventory](../internal/smbwire/UPSTREAM.md).
## Resource and persistence decisions
The binary targets Go 1.26, Linux/MIPS LE soft-float, CGO disabled. Kernel availability, RSS, throughput, CPU impact on routing, disk failure behavior and boot recovery must be measured on the actual router after approval. No performance estimate is inferred from desktop tests or upstream benchmarks.
Protocol allocations are bounded by request size, connections and handles, not file length. Fixed low limits and a 20 MiB GC target leave room for testing alongside the web service, but cannot guarantee a combined hard quota. Exceeding directory limits returns an error rather than silently omitting names. Server-local sharing checks and byte-range locks protect cooperating SMB clients; external writers bypass those checks. SMB2 packet signing is mandatory, but there is no SMB encryption, so network privacy remains a LAN/VPN responsibility.
exFAT metadata is represented by ordinary disk sidecars where supported by the client, not acknowledged into temporary RAM streams. Do not promise persistent ACLs, Finder tags, resource-fork compatibility, Time Machine or application-specific safe saving until those paths are verified. Close/flush/write-through failures are reported. Transfer interruption and power loss still require file verification and backups; this is not an atomic upload API.
## Maintenance and distribution
Keep upstream source provenance, retained tests and Apache license together; review both upstream fixes and local policy changes when upgrading. Protocol source is embedded under `internal/smbwire`, not fetched at deployment. `go.mod`/`go.sum` remain compatible with the existing web dependencies. Distributors must include the project MIT license, NAIS license where distributing web assets, SMB Apache-2.0 license and Go-module license notices. No binaries have been published by this change.
Never ship real JSON config or NT hashes. Include only `.smb.example.json`, `.env.example`, source, licenses and documentation in public source archives. Generated `dist/` executables are local validation artifacts and must be packaged separately with their notices if a binary release is later authorized. Inspect archive contents; Git ignore rules alone are insufficient.
+56
View File
@@ -0,0 +1,56 @@
# SMB validation record
Recorded 2026-10-16. SMB remains experimental. No SMB executable, configuration or test data was copied to the router, and no router process, firewall, mount, startup hook or routing configuration was changed.
## Actual local checks
Development host: macOS 27.0.1, ARM64, Go 1.26.5. Test data and account credentials were synthetic and temporary; no private web settings were needed.
| Check | Observed result |
| --- | --- |
| `make test` | Shell syntax, unchanged public web sample config validation, seven Python localhost stress-runner tests, web regression tests and SMB Go tests pass |
| `go test -race ./cmd/routershelf-smb ./internal/smbwire` | Pass, including startup/root replacement shutdown, authenticated operations, read-only policy, confinement, locks, sharing, concurrent writes and close/delete errors |
| `make build-mipsle build-smb-mipsle` | Both build with CGO disabled, Linux/MIPS little-endian, soft-float; file inspection reports statically linked ELF32 MIPS binaries. SMB executable is approximately 3.6 MiB; this is disk size, not RSS |
| Protocol fuzzing | Ten seconds, two workers of `FuzzMessage`, 554,883 executions; no failure. This is bounded smoke fuzzing, not exhaustive protocol/security validation |
| Native macOS writable smoke script | Built-in `mount_smbfs`: rejects incorrect password, mounts with correct account, creates folder, uploads, moves/renames, downloads with matching SHA-256, deletes files/folder and unmounts successfully |
| Native macOS read-only smoke script | Reads succeed; incorrect password, write, mkdir, rename and delete refused |
| Actual Finder GUI, localhost | Shows selected share and file, Quick Look displays expected text, creates/names a folder, renames a file, copies a folder into the share and back to local storage |
| Finder copy integrity / metadata sample | 2,228,224-byte synthetic file matches SHA-256 after upload and download; a custom extended attribute survives the round trip using an on-disk `._` AppleDouble sidecar |
| Interrupted protocol transfer | 12 MiB written in 64 KiB chunks, connection closed halfway, a new authenticated connection explicitly reopens and writes remaining offsets; on-disk SHA-256 matches. This tests controlled protocol reconnection, not Finder's automatic resume |
| Concurrent operations | Two clients write disjoint 64 KiB ranges to one file, rename through an open handle, close and verify all bytes; conflicting share modes and byte-range locked I/O/truncation fail |
| Confinement | Traversal, encoded traversal, escaping symlinks, rename escape, nonregular data files and writes outside selected root refused; valid internal links remain usable |
| Service independence | SMB config ignores poisoned web domain/root/mount environment values; starts and stops without web service or TLS config. Web tests/build remain independent and its application/supervisor implementation is unchanged |
| Repository hygiene | Public templates have placeholders only; real JSON/hash files, binaries and diagnostic output are excluded from public source distribution; whitespace and local documentation links checked |
The first native attempt used a 16-credit server window: mount/authentication succeeded but mkdir stalled. The final implementation grants up to 128 credits and subsequent normal native mounts passed. The original temporary mount was detached, the recovery server stopped, and temporary files removed. This failure is why native tests accompany protocol tests. Transfer allocations remain separately bounded by the 64 KiB I/O/frame limits and synchronous request handling.
Native command reproduction (development Mac only):
```sh
go build -o dist/routershelf-smb ./cmd/routershelf-smb
python3 -B scripts/test_smb_macos.py "$PWD/dist/routershelf-smb"
python3 -B scripts/test_smb_macos.py "$PWD/dist/routershelf-smb" --read-only
```
The script contacts localhost only and uses a temporary account/share. Its operation worker and mount commands have deadlines. A kernel filesystem operation may still require manual ejection on a client/kernel bug; inspect only the printed/temporary test volume, never unmount a real share to clean up this test. Do not run it on the router.
## Read-only target inspection
SSH inspection confirmed Linux 3.4.113, MIPS, BusyBox 1.24.2 and 126,280 KiB total RAM. The USB filesystem reports exFAT, read/write, `fmask=0000,dmask=0000` and `errors=remount-ro`. Thus mode bits do not isolate private data on that mount; a storage error may change it to read-only. No `smbd`/`smbpasswd` command was found in the inspected PATH, and no TCP 445/1445 listener appeared at that inspection. This is not a complete firmware binary/service inventory.
These read-only observations confirm constraints, not SMB execution compatibility. Private addresses, mount identifiers, credentials and raw router dumps are deliberately absent from this record.
## Outstanding checks requiring an approved device session
Do not infer these results from compilation or desktop checks:
- Execute the new MIPS binary on Linux 3.4.113 and verify kernel/syscall compatibility, dropped UID/GID and supplementary groups, random source and startup behavior.
- Verify exact USB mount identity, configured selected-root and protected-path checks, exFAT naming/case behavior, disk-full and remount-read-only error reporting, non-root write permissions and metadata sidecar persistence.
- Connect from Finder over the actual LAN and chosen port: registered login, bad password, read-only and writable sharing; folder/file operations, Unicode/case-only renames, packages, tagged/resource-fork files, metadata after restart and application-specific saves. The local custom-attribute sample is not comprehensive Mac metadata validation.
- Transfer large scratch files in both directions with independent checksums; interrupt transfers and service/network connections at bounded points, inspect partial destinations, reconnect and verify safe retry. No automatic native resume or atomic overwrite guarantee is established.
- Coordinate simultaneous client operations with expected locks/share access. Keep other local/FTP/SFTP writers away from the test roots.
- With explicit load bounds and stop criteria, measure resident memory, peak memory, CPU, free space, routing latency and Wi-Fi/SSH health with SMB alone, web alone, and both. Check behavior at connection/handle/directory bounds. A 20 MiB GC target is not a measured memory ceiling.
- Exercise approved USB unavailable/reinsert, supervisor crash/restart, configuration error, binary rollback, independent web/SMB stop/update, host-firewall reload and controlled reboot cases. Do not unplug valuable storage during writes; use backed-up scratch media/data and a deliberate plan.
- Check that allowed private clients connect while guest/WAN/untrusted sources are denied, with no gateway SMB forwarding and no change to web exposure or unrelated rules.
Use [deployment and rollback](smb.md#install-status-update-and-remove). Upload to new names, retain known-good private backups, validate, stop only the verified SMB supervisor, rename into place, restart and verify. Revert the binary/config/script independently if a check fails. No target load, reboot, kernel compatibility, USB loss recovery or production-readiness claim is made by this change.
+140
View File
@@ -0,0 +1,140 @@
# Finder access with RouterShelf SMB
RouterShelf has two independent executables. `routershelf` publishes unauthenticated read-only web content. `routershelf-smb` provides authenticated private storage access through Finder's built-in SMB client. Either works alone. SMB requires no web domain, certificates, web environment file, gateway forwarding, Mac extensions, or additional Mac software.
**Experimental:** local protocol tests and cross-compilation are separate from native-client and hardware validation. See [SMB validation](smb-validation.md) for actual results. Back up valuable data before enabling writes. This release supports one selected directory, one account, and one read-only/read-write policy per instance. It is not a multi-user ACL server, Time Machine target, domain server, or highly available NAS.
## Choose private storage
Use separate sibling directories on USB, for example:
```text
/media/DISK_ID/private-storage/ authenticated SMB files
/media/DISK_ID/public-storage/ deliberately public web files
/media/DISK_ID/.smb-service/ executable and private update backups
/etc/storage/routershelf-smb.json administrator-owned credentials/config
```
Replace `DISK_ID` with your actual mount. Create the selected private directory deliberately while the disk is mounted. The service never creates a missing root or serves the whole mount. Never share `/`, the USB mount itself, a service directory, certificate cache, backup directory, or administrator home. Select one root containing the folders you want available; every descendant, including hidden files, is available to the authenticated account. Symlinks cannot escape that root. On filesystems supporting hard links, an administrator must also exclude hard links to sensitive files.
`public_roots` must list every web root on this storage, especially a customized `RS_ROOT`. The standard `public-storage` sibling is checked automatically. Default private service directories, this executable and the config are excluded; add customized certificate/cache/binary/backup paths to `protected_paths`. These exclusions cannot be overridden by allowing public overlap. Overlap is refused unless `allow_public_overlap` is explicitly true. Separate processes cannot discover arbitrary web installations: listing the actual public roots is the administrator's responsibility. If you deliberately share a web root, **every SMB upload/rename into it may immediately publish the file without web authentication**. Use a private staging directory and move reviewed files into publication deliberately. The web service retains its own existing path filtering and GET/HEAD policy; SMB credentials do not protect web copies.
exFAT has mount-wide ownership/mode behavior, limited Unix metadata and no POSIX ACL isolation. A separate non-root service UID reduces process privilege but does not isolate secrets on a broadly writable exFAT mount. Put credentials on a permission-enforcing administrator-owned filesystem such as `/etc/storage`; do not rely on `chmod` on exFAT. Restrict other disk accounts and local writers separately. Use only one RouterShelf SMB instance per writable root; independent instances and FTP/SFTP/local programs do not share its locks.
## Build and configure
On the development computer, with Go 1.26+:
```sh
make test
make build-smb-mipsle
# For a local desktop executable:
go build -o dist/routershelf-smb ./cmd/routershelf-smb
umask 077
cp .smb.example.json smb.json
chmod 600 smb.json
```
Edit private `smb.json`. The sample intentionally has an unusable hash and placeholder paths. Keep its mode 0600. On macOS use a hidden terminal prompt to generate a password-equivalent NT hash without putting the password in arguments or shell history:
```sh
read -r -s 'smb_password?New unique SMB password (12+ characters): '
printf '\n'
printf '%s' "$smb_password" | ./dist/routershelf-smb -hash-password
unset smb_password
```
Paste the output into `nt_hash` privately. Do not reuse a router/admin password. The hash is as sensitive as the password: anyone holding it can authenticate. Do not put it in issues, screenshots, logs, archives or backups intended for publication. Finder receives the original password; the server verifies NTLMv2 challenge responses using the hash. There is no guest, anonymous or empty-password mode.
For LAN access set `listen` to the router's specific private IPv4 and port 445; put your trusted client subnet(s) in `allow`. `127.0.0.1:1445` and `127.0.0.1/32` are safe local defaults. Start read-only. Set `read_only` to false only after verifying the selected root and backup. Use a dedicated available non-root UID/GID if supported by the mount; the defaults are 65533, distinct from the web service’s 65534; verify that this ID is available on your firmware. Root is used only to read protected config, bind a privileged port and drop supplementary groups/UID/GID before serving files. An already unprivileged process must match both configured IDs and use an available unprivileged port. Do not disable privilege dropping.
Check on the machine with the real paths (the computer cannot validate a router-only USB path):
```sh
./dist/routershelf-smb -config /absolute/private/smb.json -check-config
```
Validation does not listen, write files, change firewall or check password strength from its hash. It requires existing paths and a protected regular config file. On Linux the running service additionally requires `storage_mount` to be an exact `/proc/mounts` mountpoint. On a desktop Mac this mountpoint requirement is omitted for local testing.
## Configuration reference
The only environment setting is `RS_SMB_CONFIG`, the absolute JSON config path. `-config` overrides it; `-check-config` validates and exits. No web `RS_*` setting is consulted, and no shell file is sourced. Unknown JSON fields, extra objects, and configs above 32 KiB are rejected without echoing input. Change configuration by restarting only SMB. Credentials are read once at startup.
| JSON field | Default / contract |
| --- | --- |
| `listen` | `127.0.0.1:1445`; a specific private/loopback IPv4 and numeric port; no wildcard, DNS, public IPv4 or IPv6 |
| `storage_mount` | Required existing absolute USB mount; exact Linux mount presence checked before listening and every two seconds |
| `root` | Required existing directory strictly under that mount; selected explicitly; never created automatically |
| `share` | `Storage`; direct Finder share name; no separators/spaces or reserved `IPC$` |
| `user` | Required single account name; no OS account/password database needed |
| `nt_hash` | Required 32 hex digits; placeholders and empty-password hash refused |
| `read_only` | `true`; refuses data, directory, metadata, rename and delete mutations |
| `allow` | Required explicit private/loopback IPv4 CIDRs; applied before authentication; no unrestricted prefixes |
| `protected_paths` | Additional sensitive paths that must not overlap the share; default service directories and running executable are also excluded |
| `public_roots` | Additional actual public roots; standard `storage_mount/public-storage` always checked |
| `allow_public_overlap` | `false`; deliberate opt-in to overlapping publication |
| `uid`, `gid` | 65533; positive non-root IDs, applied before file service starts |
| `diagnostics` | `false`; opt-in command/status/credit and peer-event logging without filenames or NTLM tokens; use bounded private logs |
| `case_insensitive` | `true` for exFAT; use false for a case-sensitive filesystem |
Paths must be clean and absolute. Root/config symlinks are resolved during validation. Existing inaccessible public-root paths cause validation failure. Private config cannot reside inside the share. The web `.env.example`, deployed binary name, environment precedence and `/tmp/public-share-*` paths remain unchanged.
## Finder
With SMB running, in Finder choose **Go → Connect to Server** (⌘K):
```text
smb://ROUTER_LAN_IP/Storage
```
Replace `ROUTER_LAN_IP`; do not type that placeholder literally. For an explicitly configured high port, use `smb://ROUTER_LAN_IP:1445/Storage`. Enter the configured account and original password as a registered user. Use the complete share URL: automatic network discovery and browsing a server's share list are not implemented. Save to Keychain only on a trusted Mac. Eject the share before service updates or removing USB storage.
Browse/open/download in either mode. With writes enabled you can upload, create folders, rename, move within the share and delete. Moving across shares/filesystems is a client copy then deletion and is not atomic. Deletions are permanent; this service has no recycle bin or snapshots. Finder may keep cached views until refresh/reconnect. After a password change, eject and replace stale Keychain credentials.
## Privacy and filesystem behavior
SMB2.0.2/2.1 (SMB3.0 fallback) uses NTLMv2 and mandatory packet signing. **Signing does not encrypt filenames or contents.** Use a trusted isolated LAN, or an independently secured VPN for access from elsewhere. Never forward TCP 445/1445, enable a public tunnel, add SMB to the web NAT plan, or reuse the web service's public firewall allowance. SMB binds IPv4 only and checks peer source prefixes; a source-masquerading proxy can defeat source-based distinctions, so also keep gateway and host firewall exposure private.
The service changes no firewall rules. If existing firewall policy blocks LAN SMB, an administrator must allow only the chosen IPv4/interface/client subnet and service port, with an explicit drop for other sources to that port. Use a separately owned SMB chain/hook, preserve SSH and unrelated rules, and test denied guest/WAN sources. Do not flush tables or permit SMB through the existing public web chain. If firmware already listens on 445, leave it alone and select a high port for this initial service. Firewall/persistence changes need separate deployment approval and firmware-specific review.
The exFAT profile advertises case-insensitive, case-preserving names. There are no persistent named streams or ACLs. Per-file read-only/locked mode changes are refused rather than acknowledged on a mount that may ignore them; use the share’s `read_only` policy. Finder can create `._filename` AppleDouble sidecars and `.DS_Store` files on disk; retain these with their files if metadata matters. Some applications may require streams, ACLs, resource forks or Apple extensions that this profile cannot provide. Unsupported requests return errors; no metadata is acknowledged into volatile streams. Finder tags, resource-fork round trips, packages and application-specific saves still require native testing. Do not clean sidecars automatically. Files visible through SMB include dotfiles; the web service still filters them.
Writes use bounded 64 KiB chunks, not whole-file memory. Four connections, 64 total handles, eight compound commands and 1,024 entries per scanned directory bound work. Larger directories return a resource error, rather than an incomplete successful listing; divide large collections into folders. Authentication has a 30-second per-frame deadline and authenticated reads a five-minute idle deadline; reconnect idle clients as needed. The Go memory target is 20 MiB, **not a hard quota**. Protocol state, filesystem caches, firmware and the web process need additional RAM; target resource measurements remain required before enabling both under load.
SMB share access checks and byte-range locks coordinate clients of this instance; unlocked applications may still overwrite each other by design. Writes acknowledge OS writes, honor write-through, and synchronize writable handles on explicit close/flush; errors are returned. OS/device caching, exFAT and power failure can still lose data. A network cut may leave a partial destination file or an uncertain last write; it is not a transaction and does not roll back an overwrite. Keep the source, retry to a distinct temporary name, compare length/checksum and then rename into place. No durable handles, transactional uploads, crash recovery, or automatic resume are promised. Never unplug a disk during writes; back up and check it after an unsafe disconnect.
The executable closes sessions and exits when the root identity or mount disappears/changes (poll interval two seconds). It retains an `os.Root` descriptor rather than falling back to a RAM directory. A kernel/device I/O hang can delay shutdown; do not force router reboots or kill unrelated services as an automatic recovery action. The supervisor retries after ten seconds; it never initializes a missing disk. Finder may reconnect by path; failed copies must still be verified and retried.
## Install, status, update and remove
These are procedures for an approved deployment, **not actions performed by the repository implementation**. First inspect firmware USB/startup hooks, current port listeners, mount ownership/free space, available UID/GID and firewall policy read-only. Do not stop firmware Samba or any web process. Build the static Linux/MIPS little-endian soft-float executable; no router compiler/runtime/library/package installation is needed. Cross-compilation alone does not prove Linux 3.4 compatibility.
1. Back up USB data, and the existing SMB binary/config/script privately if present. Eject any connected Finder share. Keep binaries/backups outside both shared roots.
2. Upload the binary using SCP to a new filename such as `routershelf-smb.new` in the private service directory. Upload config to a new protected file on permission-enforcing storage, and the supervisor to a new filename. Inspect permissions and checksums. Do not overwrite a running binary in place.
3. Validate the new binary with `-config /absolute/private/routershelf-smb.json.new -check-config` on the router. This only reads configuration and paths. Run target smoke/Finder checks only with approval. Preserve the previous names privately, then rename the validated files into their installed paths on their respective filesystems.
4. For foreground startup, export `RS_SMB_BINARY` (absolute installed executable) and `RS_SMB_CONFIG` (absolute private JSON), then run `sh /absolute/path/routershelf-smb-service.sh`, installed from `deploy/padavan/smb-supervisor.example.sh`. It needs neither web supervisor nor web environment. Observe the ready/error message; logs can contain private diagnostics, so do not publish them. For background operation route output to an existing bounded private firmware log facility (for example BusyBox `logger`), not an unbounded RAM log.
5. Only after successful manual checks, add a separate invocation with those two variables to the verified USB-aware hook. Do not replace existing web, Wi-Fi, NTP or SSH hooks. Save changed `/etc/storage` config/scripts/hooks using the firmware's normal persistence action only when needed; USB binary updates alone do not require a flash save. Full reboot behavior remains a target check.
The supervisor owns `/tmp/routershelf-smb/` exclusively; `supervisor.pid` and `child.pid` are diagnostic, never authorization to signal a process. Inspect `/proc/PID/cmdline` before sending SIGTERM to the supervisor. It signals/waits only for the child it launched and removes its runtime lock. Wait for cleanup before starting one replacement. After a crash or SIGKILL a stale lock refuses startup; verify both processes are gone, then remove only the stale SMB runtime files/directory. Do not remove live lock directories or web PID files.
For status check the verified supervisor/child command lines, UID/GID and `VmRSS` in `/proc/PID/status`, exact mount, free space and logs, then try Finder login and a read. A PID is not a readiness guarantee; a waiting supervisor may have no child while storage/config is unavailable. Do not include full config, hash, private filenames or raw logs in a public support request.
For updates, stop only the verified SMB supervisor and wait for child cleanup, rename a checked new binary/config into place, restart only SMB and verify login/file checks. To roll back, stop SMB, restore the known-good private binary/config/script, restart it and check again. Keep the same data root and data; binary rollback cannot undo deleted/overwritten files. Restore user data from backup separately if necessary. The certificate cache and web service need no change.
For removal, eject Finder shares, remove only the SMB hook invocation, stop the verified SMB supervisor, wait for child/lock cleanup, remove its executable/config/script and any separately owned SMB firewall rules. Save flash once if persistent hooks/config changed. Keep USB data and private backups until intentionally retired. Web installation paths, startup, NAT, certificates and sharing continue independently.
## Troubleshooting
| Symptom | Check |
| --- | --- |
| Cannot connect | Exact private IPv4, port, complete share URL, USB availability, matching `allow`, narrow host firewall policy, another listener on 445 |
| Login fails | Registered user, original password, correct NT hash, stale Keychain entry; no guest mode |
| Read works but upload fails | `read_only`, disk full/read-only mount, UID/GID mount permissions, directory entry/handle/lock limits |
| Config validation fails | Protected regular file, absolute existing paths, replaced hash placeholder, unknown fields, public overlap |
| Supervisor runs without child | Missing executable/config/storage or repeated startup errors; inspect private diagnostics |
| Finder metadata/app save fails | No native streams/ACLs/AAPL/leases; keep sidecars; test that application on a scratch share |
| Copy interrupted | Retain source, reconnect, inspect partial destination, retry under a distinct name and verify checksum |
| Directory fails to list | More than 1,024 entries, exhausted handles, storage I/O error; split folders, close extra clients and check disk |
| Memory pressure/routing lag | Stop SMB first, preserve web/routing, inspect actual RSS and firmware memory; reduce client activity and avoid simultaneous large workloads |
Read [implementation decision](smb-implementation.md), [security boundaries](../SECURITY.md), and [validation record](smb-validation.md) before distributing or deploying.
+202
View File
@@ -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.
+16
View File
@@ -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.
+434
View File
@@ -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()
}
+76
View File
@@ -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
}
}
+197
View File
@@ -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...)
}
+222
View File
@@ -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)
})
}
+555
View File
@@ -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
}
+156
View File
@@ -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()
}
+81
View File
@@ -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
}
+103
View File
@@ -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
}
+139
View File
@@ -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)
}
+127
View File
@@ -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...)
}
+227
View File
@@ -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)
}
+656
View File
@@ -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
}
+154
View File
@@ -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
}
+31
View File
@@ -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
}
+269
View File
@@ -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
+311
View File
@@ -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
}
+259
View File
@@ -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
}
}
}
+155
View File
@@ -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))
}
+105
View File
@@ -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))
}
+33
View File
@@ -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
}
+32
View File
@@ -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
}
+18
View File
@@ -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
}
+97
View File
@@ -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
}
+233
View File
@@ -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
}
+434
View File
@@ -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)
}
}
}
+170
View File
@@ -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
}
+21 -3
View File
@@ -1,7 +1,7 @@
{ {
"name": "routershelf", "name": "routershelf",
"displayName": "RouterShelf", "displayName": "RouterShelf",
"description": "Read-only HTTPS directory sharing and static-page serving from USB storage on constrained Linux routers, with NAIS styling and environment-based deployment.", "description": "Public read-only HTTP/HTTPS sharing and independent authenticated private SMB access to selected USB storage on constrained Linux routers.",
"status": "experimental", "status": "experimental",
"license": "MIT", "license": "MIT",
"language": "Go", "language": "Go",
@@ -17,7 +17,10 @@
"padavan", "padavan",
"mikrotik", "mikrotik",
"nais", "nais",
"static-site" "static-site",
"smb",
"finder",
"exfat"
], ],
"testedTarget": { "testedTarget": {
"hardware": "Neterbit NW-651D", "hardware": "Neterbit NW-651D",
@@ -28,5 +31,20 @@
}, },
"repository": null, "repository": null,
"homepage": null, "homepage": null,
"configuration": ".env.example" "configuration": ".env.example",
"services": {
"web": {
"entrypoint": "cmd/routershelf",
"configuration": ".env.example",
"access": "public unauthenticated read-only",
"targetStatus": "observed; see docs/deployment-history.md"
},
"smb": {
"entrypoint": "cmd/routershelf-smb",
"configuration": ".smb.example.json",
"access": "private authenticated; read-only by default",
"targetStatus": "experimental; cross-build only pending target execution approval",
"documentation": "docs/smb.md"
}
}
} }
+135
View File
@@ -0,0 +1,135 @@
#!/usr/bin/env python3
"""Opt-in native macOS SMB smoke test, localhost + temporary data only.
Usage: python3 scripts/test_smb_macos.py /absolute/path/to/routershelf-smb [--read-only]
Uses a disposable test account/password, never a router or private configuration.
Requires macOS mount_smbfs and permission to mount a local network filesystem.
"""
import hashlib
import json
import os
from pathlib import Path
import platform
import socket
import subprocess
import sys
import tempfile
import time
def main():
if platform.system() != "Darwin" or len(sys.argv) not in (2, 3):
raise SystemExit("Use on macOS with one absolute local executable path")
readonly = len(sys.argv) == 3 and sys.argv[2] == "--read-only"
if len(sys.argv) == 3 and not readonly:
raise SystemExit("Only --read-only is supported")
binary = Path(sys.argv[1]).resolve(strict=True)
password = "RouterShelf-local-test-only-123" # public synthetic credential
digest = subprocess.check_output(
[str(binary), "-hash-password"], input=password.encode(), timeout=10
).decode().strip()
with tempfile.TemporaryDirectory(prefix="routershelf-smb-native-") as temp:
base = Path(temp).resolve()
root, mount = base / "storage", base / "client"
root.mkdir()
(root / "read-only-probe.txt").write_text("RouterShelf read-only probe")
mount.mkdir()
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
port = probe.getsockname()[1]
cfg = base / "smb.json"
settings = dict(listen=f"127.0.0.1:{port}", storage_mount=str(base),
root=str(root), user="storage", nt_hash=digest,
read_only=readonly, allow=["127.0.0.1/32"],
uid=os.getuid(), gid=os.getgid())
cfg.write_text(json.dumps(settings))
cfg.chmod(0o600)
subprocess.run([str(binary), "-config", str(cfg), "-check-config"],
check=True, timeout=10)
proc = subprocess.Popen([str(binary), "-config", str(cfg)],
stdout=subprocess.DEVNULL)
mounted = False
try:
deadline = time.monotonic() + 10
while True:
if proc.poll() is not None:
raise RuntimeError("local SMB server exited")
try:
with socket.create_connection(("127.0.0.1", port), timeout=1):
break
except OSError:
if time.monotonic() > deadline:
raise
time.sleep(0.1)
# Password in this URL is synthetic and used for this temp test only.
# Interactive product instructions use Finder and a hidden prompt.
bad = subprocess.run(["/sbin/mount_smbfs", "-N",
f"//storage:wrong-fixture-password@127.0.0.1:{port}/Storage", str(mount)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20)
if bad.returncode == 0:
mounted = True
raise RuntimeError("native client accepted an incorrect password")
print("PASS native macOS rejects incorrect password", flush=True)
url = f"//storage:{password}@127.0.0.1:{port}/Storage"
subprocess.run(["/sbin/mount_smbfs", "-N", "-o", "nobrowse", url, str(mount)],
check=True, timeout=30)
mounted = True
subprocess.run([sys.executable, __file__, "--read-only-operations" if readonly else "--operations", str(mount)],
check=True, timeout=30)
finally:
try:
if mounted:
subprocess.run(["/sbin/umount", str(mount)], check=True, timeout=30)
finally:
proc.terminate()
try:
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=10)
def operations(mount):
(mount / "folder").mkdir()
block = b"RouterShelf-integrity-probe-" * 2048
expected = hashlib.sha256()
with (mount / "folder" / "upload.partial").open("wb") as out:
for _ in range(256):
out.write(block)
expected.update(block)
(mount / "folder" / "upload.partial").rename(mount / "download.bin")
actual = hashlib.sha256()
with (mount / "download.bin").open("rb") as source:
for chunk in iter(lambda: source.read(65536), b""):
actual.update(chunk)
if actual.digest() != expected.digest():
raise RuntimeError("native transfer checksum mismatch")
(mount / "download.bin").unlink()
(mount / "folder").rmdir()
print("PASS native macOS mount, mkdir, upload, rename/move, download/hash, delete")
print("Finder GUI, metadata, interruption and router resource checks remain separate")
def readonly_operations(mount):
probe = mount / "read-only-probe.txt"
if probe.read_text() != "RouterShelf read-only probe":
raise RuntimeError("read-only probe read failed")
for action in [lambda: probe.write_text("forbidden"),
lambda: (mount / "forbidden-folder").mkdir(),
lambda: probe.rename(mount / "forbidden-rename"),
lambda: probe.unlink()]:
try:
action()
except OSError:
continue
raise RuntimeError("native read-only mutation succeeded")
print("PASS native macOS read-only read; write/mkdir/rename/delete refused", flush=True)
if __name__ == "__main__":
if len(sys.argv) == 3 and sys.argv[1] == "--operations":
operations(Path(sys.argv[2]))
elif len(sys.argv) == 3 and sys.argv[1] == "--read-only-operations":
readonly_operations(Path(sys.argv[2]))
else:
main()