feat: add protected SMB disk-root sharing
This commit is contained in:
18 files changed
+479
-20
No files matched your search
+2
-1
@@ -20,5 +20,6 @@
|
||||
"/media/DISK_ID/.public-share-service",
|
||||
"/media/DISK_ID/.smb-service"
|
||||
],
|
||||
"diagnostics": false
|
||||
"diagnostics": false,
|
||||
"allow_storage_root": false
|
||||
}
|
||||
@@ -85,3 +85,5 @@ Before publishing or refreshing a public archive, exclude private env, keys, cac
|
||||
## 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.
|
||||
|
||||
Explicit SMB disk-root sharing requires `allow_storage_root`, deliberate public-overlap acknowledgment, and descriptor-safe protected-path exclusions. Preserve alias/ancestor-rename protection; a lexical path filter alone is insufficient. Record observed exFAT timestamp limitations without raising process privileges or acknowledging metadata changes that did not occur.
|
||||
@@ -34,3 +34,5 @@ See [operations](docs/operations.md) for backup, rollback, and removal instructi
|
||||
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).
|
||||
|
||||
An explicitly enabled disk-root SMB view keeps mandatory service directories and configured protected subtrees hidden and inaccessible. Parent descriptors are pinned with os.Root; symlinks and hard-linked regular files are refused in that view, and protected ancestors cannot be renamed/deleted. `allow_storage_root` and public-overlap acknowledgment are required; default private-folder policy remains unchanged. This application boundary does not isolate secrets from other broadly authorized exFAT accounts.
|
||||
@@ -17,3 +17,5 @@ The CA root bundle is obtained separately during deployment. It is not committed
|
||||
## 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.
|
||||
|
||||
The protected SMB disk-root view also uses `golang.org/x/sys/unix` (Go project BSD-style license), pinned in `go.mod`/`go.sum`. It supplies descriptor-relative filesystem operations and introduces no router runtime or shared-library dependency.
|
||||
@@ -28,11 +28,13 @@ type config struct {
|
||||
Allow []string `json:"allow"`
|
||||
ProtectedPaths []string `json:"protected_paths"`
|
||||
PublicRoots []string `json:"public_roots"`
|
||||
AllowStorageRoot bool `json:"allow_storage_root"`
|
||||
AllowPublicOverlap bool `json:"allow_public_overlap"`
|
||||
UID int `json:"uid"`
|
||||
GID int `json:"gid"`
|
||||
Diagnostics bool `json:"diagnostics"`
|
||||
CaseInsensitive bool `json:"case_insensitive"`
|
||||
protectedRelative []string
|
||||
prefixes []netip.Prefix
|
||||
ntHash [16]byte
|
||||
ready func()
|
||||
@@ -154,7 +156,7 @@ func (c *config) validate() error {
|
||||
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) {
|
||||
if err != nil || !fi.IsDir() || (c.Root == c.Mount && !c.AllowStorageRoot) || !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) {
|
||||
@@ -174,9 +176,16 @@ func (c *config) validate() error {
|
||||
} else if !os.IsNotExist(err) {
|
||||
return errors.New("cannot resolve a protected path")
|
||||
}
|
||||
if within(c.Root, p) || within(p, c.Root) {
|
||||
if within(p, c.Root) {
|
||||
return errors.New("SMB root is inside a private service or protected path")
|
||||
}
|
||||
if within(c.Root, p) {
|
||||
if c.Root != c.Mount || !c.AllowStorageRoot {
|
||||
return errors.New("SMB root overlaps a private service or protected path")
|
||||
}
|
||||
rel, _ := filepath.Rel(c.Root, p)
|
||||
c.protectedRelative = append(c.protectedRelative, filepath.ToSlash(rel))
|
||||
}
|
||||
}
|
||||
public := append([]string{filepath.Join(c.Mount, "public-storage")}, c.PublicRoots...)
|
||||
for _, p := range public {
|
||||
|
||||
@@ -129,3 +129,34 @@ func TestSecretFileAndOverlap(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExplicitDiskRootView(t *testing.T) {
|
||||
c, p := fixture(t)
|
||||
c.Listen = "127.0.0.1:1445"
|
||||
c.Share = "Storage"
|
||||
c.UID = 65533
|
||||
c.GID = 65533
|
||||
c.Root = c.Mount
|
||||
c.AllowStorageRoot = true
|
||||
saveConfig(t, c, p)
|
||||
if _, _, err := loadConfig([]string{"-config", p}); err == nil {
|
||||
t.Fatal("root view must explicitly allow public overlap too")
|
||||
}
|
||||
c.AllowPublicOverlap = true
|
||||
saveConfig(t, c, p)
|
||||
got, _, err := loadConfig([]string{"-config", p})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got.protectedRelative) < 2 {
|
||||
t.Fatal("disk root lacks mandatory service exclusions")
|
||||
}
|
||||
c.Root = filepath.Join(c.Mount, ".smb-service")
|
||||
if err := os.Mkdir(c.Root, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saveConfig(t, c, p)
|
||||
if _, _, err := loadConfig([]string{"-config", p}); err == nil {
|
||||
t.Fatal("protected service directory became a share")
|
||||
}
|
||||
}
|
||||
@@ -108,7 +108,7 @@ func serve(ctx context.Context, c config) error {
|
||||
if c.Diagnostics {
|
||||
diagnostic = log.Printf
|
||||
}
|
||||
err = smb.Serve(ctx, ln, smb.Config{ExpectedRoot: initial, Ready: func() {
|
||||
err = smb.Serve(ctx, ln, smb.Config{ProtectedPaths: c.protectedRelative, ExpectedRoot: initial, Ready: func() {
|
||||
log.Print("SMB ready; authenticated signing required; read_only=", c.ReadOnly)
|
||||
if c.ready != nil {
|
||||
c.ready()
|
||||
|
||||
@@ -84,3 +84,7 @@ The binary was deployed with the previous version kept for rollback. Tests cover
|
||||
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.
|
||||
|
||||
## 11. Authorized SMB installation and protected disk-root view (2026-10-16)
|
||||
|
||||
At the user’s request, SMB was installed independently with authenticated read/write access to a protected disk-root view. Service/certificate directories and firmware account metadata remain inaccessible through SMB. Dedicated LAN-only firewall rules, USB-aware supervision and separate startup/firewall hooks were configured; the web process and HTTPS behavior stayed intact. Native Mac file-operation checks, a bounded checksum transfer, actual Finder copy/Quick Look and independent SMB restart passed. Timestamp restoration is limited by exFAT ownership. See the [detailed validation record](smb-validation.md) for observations and outstanding reboot, USB failure and load checks.
|
||||
@@ -24,6 +24,6 @@ exFAT metadata is represented by ordinary disk sidecars where supported by the c
|
||||
|
||||
## 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.
|
||||
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` pin the existing web dependencies plus Go’s BSD-licensed `golang.org/x/sys` for protected-view descriptor operations; the web implementation does not import the new SMB backend. 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.
|
||||
+47
-4
@@ -1,6 +1,6 @@
|
||||
# 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.
|
||||
Recorded 2026-10-16. SMB remains experimental. Initial implementation validation was local only; a subsequent user-authorized target deployment is recorded below.
|
||||
|
||||
## Actual local checks
|
||||
|
||||
@@ -40,9 +40,9 @@ SSH inspection confirmed Linux 3.4.113, MIPS, BusyBox 1.24.2 and 126,280 KiB tot
|
||||
|
||||
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
|
||||
## Initial target checklist (see subsequent deployment results)
|
||||
|
||||
Do not infer these results from compilation or desktop checks:
|
||||
This checklist was written before deployment. Completed smoke checks are recorded below; the remaining failure, load and reboot checks are listed at the end. Do not infer target 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.
|
||||
@@ -53,4 +53,47 @@ Do not infer these results from compilation or desktop checks:
|
||||
- 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.
|
||||
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. Target observations are recorded separately below; smoke checks do not establish unobserved load, reboot, USB-loss or production-readiness guarantees.
|
||||
|
||||
## Authorized target deployment and protected root view (2026-10-16)
|
||||
|
||||
The user requested read/write access to the USB disk root. Explicit protected
|
||||
root sharing was added, with separate opt-ins for disk root and public overlap.
|
||||
Mandatory service directories plus configured firmware metadata are hidden and
|
||||
inaccessible. Descriptor-pinned parent traversal, no-follow file opens, link
|
||||
refusal and protected-ancestor rename/delete checks prevent path-only exclusions
|
||||
from being bypassed. Protocol/race tests cover access, Unicode case variants,
|
||||
symlink/hardlink aliases, ancestor renames and ordinary cross-directory moves.
|
||||
Native macOS localhost testing also passed for the protected root profile.
|
||||
|
||||
After authorization, the static MIPS binary was staged to a new USB filename;
|
||||
local/remote SHA-256 matched and target configuration validation passed. It now
|
||||
runs independently with a separate supervisor/account, UID/GID 65533, no
|
||||
supplementary groups and a dedicated IPv4 LAN-only firewall chain. Web PID and
|
||||
configuration were preserved; an HTTPS HEAD check succeeded. Startup/firewall
|
||||
hooks were extended without executing unrelated startup commands, and the
|
||||
private configuration/hooks were saved using firmware persistence. The
|
||||
SMB-only stop/restart command verified process identity and cleanup; native
|
||||
client access worked after an independent restart.
|
||||
|
||||
Observed on the actual device: wrong password refused; native Mac mount;
|
||||
protected paths absent/unreadable; scratch mkdir, upload, move/rename,
|
||||
checksum-verified download and deletion. The bounded transfer was 256 KiB,
|
||||
not a sustained load test. Actual Finder copied a text file to a unique
|
||||
scratch folder, Quick Look displayed expected content, and the file checksum
|
||||
matched. Scratch files, sidecars and Mac mounts were cleaned up.
|
||||
|
||||
**Observed limitation:** the exFAT mount is owned by another UID and refuses
|
||||
arbitrary timestamp restoration by the non-root service. Finder copy/open
|
||||
completed, but the original modification time was not preserved. No silent
|
||||
metadata-success workaround or privilege increase was introduced. After the
|
||||
small checks the process used about 6 MiB RSS with a measured high-water mark
|
||||
near 7 MiB; after restart and a repeat transfer it used about 4.4 MiB. These
|
||||
snapshots are not a memory ceiling or a routing/load benchmark.
|
||||
|
||||
Reboot, USB removal/reinsertion, disk-full/remount-read-only failure, large-file
|
||||
transfer, native interruption/recovery, complete Mac metadata/application
|
||||
compatibility and sustained combined resource/load checks remain unperformed.
|
||||
Private device addresses, disk identifiers, account hashes, passwords, hook
|
||||
backups and detailed operational instructions remain only in ignored local
|
||||
outputs and protected router configuration, not in public source examples.
|
||||
+13
-4
@@ -15,12 +15,20 @@ Use separate sibling directories on USB, for example:
|
||||
/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.
|
||||
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. It refuses the whole mount by default; an explicitly protected disk-root view is described below. Never share `/`, a service directory, certificate cache, backup directory, or administrator home. Keep the default private sibling unless disk-root access is deliberately required. 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.
|
||||
|
||||
## Optional protected disk-root view
|
||||
|
||||
To manage ordinary folders across an entire disk, explicitly set `root` equal to `storage_mount`, `allow_storage_root: true`, and `allow_public_overlap: true`. This also includes public web folders, so writes there may immediately publish content. The default template keeps this mode disabled.
|
||||
|
||||
In this mode, private service directories and every configured `protected_paths` subtree are hidden and inaccessible over SMB. The running executable is excluded automatically. Add firmware metadata, customized service/cache paths and backups to that list. Excluded ancestors cannot be moved or deleted to bypass the policy. The protected view refuses symlinks and hard-linked regular files, including aliases to private data; ordinary private-subdirectory shares retain their previous confinement behavior. Parent directories are pinned using `os.Root` and file operations use descriptors rather than a path-only filter.
|
||||
|
||||
This is an SMB access boundary, not isolation from other router accounts that can write the exFAT disk. Keep credentials on protected storage outside the disk and restrict other broad disk access separately.
|
||||
|
||||
## Build and configure
|
||||
|
||||
On the development computer, with Go 1.26+:
|
||||
@@ -64,13 +72,14 @@ The only environment setting is `RS_SMB_CONFIG`, the absolute JSON config path.
|
||||
| --- | --- |
|
||||
| `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 |
|
||||
| `root` | Required existing selected directory under the mount; the mount itself requires explicit protected disk-root mode; never created automatically |
|
||||
| `allow_storage_root` | `false`; explicit opt-in to a protected disk-root view; public overlap must also be acknowledged |
|
||||
| `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 |
|
||||
| `protected_paths` | Additional sensitive paths; overlap refused normally, or hidden/blocked in explicit disk-root mode; default service directories and running executable always 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 |
|
||||
@@ -97,7 +106,7 @@ SMB2.0.2/2.1 (SMB3.0 fallback) uses NTLMv2 and mandatory packet signing. **Signi
|
||||
|
||||
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.
|
||||
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. On exFAT mounts owned by another UID, the non-root service may be unable to restore arbitrary original timestamps even when data writes succeed. Permission failures are returned; copied files can retain their new write time. Finder copy and Quick Look passed on the initial target despite this limitation. 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.
|
||||
|
||||
|
||||
@@ -6,5 +6,6 @@ require golang.org/x/crypto v0.57.0
|
||||
|
||||
require (
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/sys v0.48.0
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
)
|
||||
@@ -2,5 +2,7 @@ golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
@@ -14,3 +14,5 @@ This is a maintained local adaptation, not an unmodified dependency. RouterShelf
|
||||
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.
|
||||
|
||||
RouterShelf also adds `guarded_root.go` and its tests for explicit disk-root views: protected relative subtrees are hidden/blocked, aliases refused, protected ancestors cannot be renamed/deleted, and parent descriptors are pinned with os.Root. Cross-directory rename and descriptor timestamp operations use BSD-licensed golang.org/x/sys/unix. Default subdirectory shares preserve the original os.Root behavior.
|
||||
@@ -0,0 +1,247 @@
|
||||
// RouterShelf addition. Licensed under Apache-2.0; see LICENSE.
|
||||
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// guardedRoot keeps excluded service subtrees inaccessible in an explicitly
|
||||
// selected disk-root view. Parent directories are pinned with os.Root, and
|
||||
// symlinks/hard-linked regular files are refused in this profile. A lexical
|
||||
// filter alone would let aliases and renames expose credentials.
|
||||
type guardedRoot struct {
|
||||
*os.Root
|
||||
denied []string
|
||||
}
|
||||
|
||||
func foldedPrefix(p, prefix string) bool {
|
||||
if prefix == "." {
|
||||
return true
|
||||
}
|
||||
a, b := strings.Split(p, "/"), strings.Split(prefix, "/")
|
||||
if len(a) < len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range b {
|
||||
if !strings.EqualFold(a[i], b[i]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func (r *guardedRoot) allowed(p string, ancestors bool) bool {
|
||||
if p != "." && !fs.ValidPath(p) {
|
||||
return false
|
||||
}
|
||||
for _, d := range r.denied {
|
||||
if foldedPrefix(p, d) || ancestors && foldedPrefix(d, p) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (r *guardedRoot) parent(p string) (*os.Root, string, func(), error) {
|
||||
if !r.allowed(p, false) {
|
||||
return nil, "", nil, fs.ErrPermission
|
||||
}
|
||||
dir, leaf := path.Dir(p), path.Base(p)
|
||||
current := r.Root
|
||||
cleanup := func() {
|
||||
if current != r.Root {
|
||||
current.Close()
|
||||
}
|
||||
}
|
||||
if dir == "." {
|
||||
return current, leaf, cleanup, nil
|
||||
}
|
||||
for _, part := range strings.Split(dir, "/") {
|
||||
before, err := current.Lstat(part)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, "", nil, err
|
||||
}
|
||||
if !before.IsDir() {
|
||||
cleanup()
|
||||
return nil, "", nil, fs.ErrPermission
|
||||
}
|
||||
next, err := current.OpenRoot(part)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, "", nil, err
|
||||
}
|
||||
actual, err := next.Stat(".")
|
||||
if err != nil || !os.SameFile(before, actual) {
|
||||
next.Close()
|
||||
cleanup()
|
||||
return nil, "", nil, fs.ErrPermission
|
||||
}
|
||||
cleanup()
|
||||
current = next
|
||||
}
|
||||
return current, leaf, cleanup, nil
|
||||
}
|
||||
func safeInfo(fi os.FileInfo) bool {
|
||||
if fi.Mode()&os.ModeSymlink != 0 {
|
||||
return false
|
||||
}
|
||||
if fi.Mode().IsRegular() {
|
||||
if st, ok := sysStat(fi); ok && st.nlink > 1 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
func (r *guardedRoot) Stat(p string) (os.FileInfo, error) {
|
||||
if len(r.denied) == 0 {
|
||||
return r.Root.Stat(p)
|
||||
}
|
||||
return r.Lstat(p)
|
||||
}
|
||||
func (r *guardedRoot) Lstat(p string) (os.FileInfo, error) {
|
||||
if len(r.denied) == 0 {
|
||||
return r.Root.Lstat(p)
|
||||
}
|
||||
parent, leaf, close, err := r.parent(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer close()
|
||||
fi, err := parent.Lstat(leaf)
|
||||
if err == nil && !safeInfo(fi) {
|
||||
return nil, fs.ErrPermission
|
||||
}
|
||||
return fi, err
|
||||
}
|
||||
func (r *guardedRoot) Open(p string) (*os.File, error) { return r.OpenFile(p, os.O_RDONLY, 0) }
|
||||
func (r *guardedRoot) OpenFile(p string, flags int, mode os.FileMode) (*os.File, error) {
|
||||
if len(r.denied) == 0 {
|
||||
return r.Root.OpenFile(p, flags, mode)
|
||||
}
|
||||
parent, leaf, close, err := r.parent(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer close()
|
||||
f, err := parent.OpenFile(leaf, flags&^os.O_TRUNC|unix.O_NOFOLLOW|unix.O_NONBLOCK, mode)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fi, err := f.Stat()
|
||||
if err != nil || !safeInfo(fi) || !(fi.IsDir() || fi.Mode().IsRegular()) {
|
||||
f.Close()
|
||||
return nil, fs.ErrPermission
|
||||
}
|
||||
if flags&os.O_TRUNC != 0 {
|
||||
if err := f.Truncate(0); err != nil {
|
||||
f.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
func (r *guardedRoot) Mkdir(p string, mode os.FileMode) error {
|
||||
if len(r.denied) == 0 {
|
||||
return r.Root.Mkdir(p, mode)
|
||||
}
|
||||
parent, leaf, close, err := r.parent(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer close()
|
||||
return parent.Mkdir(leaf, mode)
|
||||
}
|
||||
func (r *guardedRoot) Remove(p string) error {
|
||||
if len(r.denied) == 0 {
|
||||
return r.Root.Remove(p)
|
||||
}
|
||||
if !r.allowed(p, true) {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
parent, leaf, close, err := r.parent(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer close()
|
||||
return parent.Remove(leaf)
|
||||
}
|
||||
func (r *guardedRoot) Rename(from, to string) error {
|
||||
if len(r.denied) == 0 {
|
||||
return r.Root.Rename(from, to)
|
||||
}
|
||||
if !r.allowed(from, true) || !r.allowed(to, true) {
|
||||
return fs.ErrPermission
|
||||
}
|
||||
a, old, closeA, err := r.parent(from)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer closeA()
|
||||
b, newName, closeB, err := r.parent(to)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer closeB()
|
||||
ad, err := a.Open(".")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer ad.Close()
|
||||
bd, err := b.Open(".")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer bd.Close()
|
||||
return unix.Renameat(int(ad.Fd()), old, int(bd.Fd()), newName)
|
||||
}
|
||||
func (r *guardedRoot) Chmod(p string, mode os.FileMode) error {
|
||||
if len(r.denied) == 0 {
|
||||
return r.Root.Chmod(p, mode)
|
||||
}
|
||||
f, err := r.Open(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
return f.Chmod(mode)
|
||||
}
|
||||
func (r *guardedRoot) Chtimes(p string, atime, mtime time.Time) error {
|
||||
if len(r.denied) == 0 {
|
||||
return r.Root.Chtimes(p, atime, mtime)
|
||||
}
|
||||
f, err := r.Open(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if atime.IsZero() {
|
||||
atime = fi.ModTime()
|
||||
if st, ok := sysStat(fi); ok {
|
||||
atime = st.atime
|
||||
}
|
||||
}
|
||||
if mtime.IsZero() {
|
||||
mtime = fi.ModTime()
|
||||
}
|
||||
return unix.Futimes(int(f.Fd()), []unix.Timeval{unix.NsecToTimeval(atime.UnixNano()), unix.NsecToTimeval(mtime.UnixNano())})
|
||||
}
|
||||
func newGuardedRoot(root *os.Root, denied []string) (*guardedRoot, error) {
|
||||
for _, p := range denied {
|
||||
if !fs.ValidPath(p) || p == "." {
|
||||
return nil, errors.New("invalid protected relative path")
|
||||
}
|
||||
}
|
||||
return &guardedRoot{Root: root, denied: append([]string(nil), denied...)}, nil
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// RouterShelf addition. Licensed under Apache-2.0; see LICENSE.
|
||||
|
||||
package smbserver
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestProtectedDiskRootProtocol(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
for _, d := range []string{".smb-service", ".public-share-service", "parent/private", "ordinary", "destination"} {
|
||||
if err := os.MkdirAll(filepath.Join(root, d), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, p := range []string{".smb-service/binary", ".public-share-service/key", "parent/private/secret"} {
|
||||
if err := os.WriteFile(filepath.Join(root, p), []byte("private sentinel"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := os.Symlink(".public-share-service", filepath.Join(root, "alias")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Link(filepath.Join(root, "parent/private/secret"), filepath.Join(root, "hardlink")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := connect(t, startServer(t, Config{Root: root, DiskMetadata: true, ProtectedPaths: []string{".smb-service", ".public-share-service", "parent/private"}}))
|
||||
for _, name := range []string{".smb-service/binary", ".public-share-service/key", "alias/key", "hardlink", "parent/private/secret", ".SMB-SERVICE/binary", ".ſmb-service/binary"} {
|
||||
name = strings.ReplaceAll(name, "/", `\`)
|
||||
for _, disp := range []uint32{dispOpen, dispOpenIf, dispOverwriteIf} {
|
||||
if id, st := c.create(name, accessRW, disp, 0); st == statusSuccess {
|
||||
c.close(id)
|
||||
t.Fatalf("protected path opened: %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, name := range c.list("") {
|
||||
if strings.EqualFold(name, ".smb-service") || name == ".public-share-service" || name == "alias" || name == "hardlink" {
|
||||
t.Fatalf("protected name listed: %q", name)
|
||||
}
|
||||
}
|
||||
for _, name := range c.list("parent") {
|
||||
if name == "private" {
|
||||
t.Fatal("nested protected directory listed")
|
||||
}
|
||||
}
|
||||
parent, st := c.create("parent", accessRW, dispOpen, optDirectory)
|
||||
if st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
if st, _ := c.do(cmdSetInfo, setInfoBody(parent, fileRename, renameData("relocated", false))); st == statusSuccess {
|
||||
t.Fatal("renamed ancestor of protected data")
|
||||
}
|
||||
c.close(parent)
|
||||
id, st := c.create(`ordinary\file`, accessRW, dispCreate, 0)
|
||||
if st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
if st := c.write(id, 0, []byte("ordinary data")); st != statusSuccess {
|
||||
t.Fatal(st)
|
||||
}
|
||||
basic := make([]byte, 40)
|
||||
le.PutUint64(basic[16:], filetime(time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)))
|
||||
if st, _ := c.do(cmdSetInfo, setInfoBody(id, fileBasic, basic)); st != statusSuccess {
|
||||
t.Fatalf("descriptor timestamps: %x", st)
|
||||
}
|
||||
if st, _ := c.do(cmdSetInfo, setInfoBody(id, fileRename, renameData(`destination\moved`, false))); st != statusSuccess {
|
||||
t.Fatalf("cross-directory rename: %x", st)
|
||||
}
|
||||
if st, _ := c.do(cmdSetInfo, setInfoBody(id, fileRename, renameData(`.smb-service\replacement`, true))); st == statusSuccess {
|
||||
t.Fatal("renamed into protected service directory")
|
||||
}
|
||||
c.close(id)
|
||||
if data, err := os.ReadFile(filepath.Join(root, "destination/moved")); err != nil || !bytes.Equal(data, []byte("ordinary data")) {
|
||||
t.Fatalf("ordinary file corrupted: %q %v", data, err)
|
||||
}
|
||||
for _, p := range []string{".smb-service/binary", ".public-share-service/key", "parent/private/secret"} {
|
||||
if b, err := os.ReadFile(filepath.Join(root, p)); err != nil || string(b) != "private sentinel" {
|
||||
t.Fatalf("private data modified: %s", p)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,8 @@ type Config struct {
|
||||
// Root is the directory to serve. Nothing outside of it is reachable,
|
||||
// including through symbolic links.
|
||||
Root string
|
||||
// ProtectedPaths excludes relative subtrees in an explicit disk-root view.
|
||||
ProtectedPaths []string
|
||||
// ExpectedRoot prevents serving a replacement between validation and open.
|
||||
ExpectedRoot os.FileInfo
|
||||
// Ready runs after confinement and cancellation are initialized.
|
||||
@@ -71,7 +73,7 @@ const (
|
||||
|
||||
type server struct {
|
||||
cfg Config
|
||||
root *os.Root
|
||||
root *guardedRoot
|
||||
rootPath string
|
||||
guid [16]byte
|
||||
start time.Time
|
||||
@@ -172,9 +174,14 @@ func newServer(cfg Config) (*server, error) {
|
||||
return nil, errors.New("smbserver: storage identity changed before startup")
|
||||
}
|
||||
}
|
||||
guarded, err := newGuardedRoot(root, cfg.ProtectedPaths)
|
||||
if err != nil {
|
||||
root.Close()
|
||||
return nil, err
|
||||
}
|
||||
s := &server{
|
||||
cfg: cfg,
|
||||
root: root,
|
||||
root: guarded,
|
||||
rootPath: abs,
|
||||
start: time.Now(),
|
||||
conns: make(map[*conn]struct{}),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/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]
|
||||
Usage: python3 scripts/test_smb_macos.py /absolute/path/to/routershelf-smb [--read-only] [--disk-root]
|
||||
Uses a disposable test account/password, never a router or private configuration.
|
||||
Requires macOS mount_smbfs and permission to mount a local network filesystem.
|
||||
"""
|
||||
@@ -18,11 +18,12 @@ import time
|
||||
|
||||
|
||||
def main():
|
||||
if platform.system() != "Darwin" or len(sys.argv) not in (2, 3):
|
||||
if platform.system() != "Darwin" or len(sys.argv) < 2:
|
||||
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")
|
||||
options=set(sys.argv[2:])
|
||||
if options-{"--read-only","--disk-root"}: raise SystemExit("Only --read-only and --disk-root are supported")
|
||||
readonly="--read-only" in options
|
||||
diskroot="--disk-root" in options
|
||||
binary = Path(sys.argv[1]).resolve(strict=True)
|
||||
password = "RouterShelf-local-test-only-123" # public synthetic credential
|
||||
digest = subprocess.check_output(
|
||||
@@ -42,6 +43,10 @@ def main():
|
||||
root=str(root), user="storage", nt_hash=digest,
|
||||
read_only=readonly, allow=["127.0.0.1/32"],
|
||||
uid=os.getuid(), gid=os.getgid())
|
||||
if diskroot:
|
||||
settings.update(storage_mount=str(root),allow_storage_root=True,allow_public_overlap=True)
|
||||
(root/".smb-service").mkdir()
|
||||
(root/".smb-service"/"private-sentinel").write_text("must stay private")
|
||||
cfg.write_text(json.dumps(settings))
|
||||
cfg.chmod(0o600)
|
||||
subprocess.run([str(binary), "-config", str(cfg), "-check-config"],
|
||||
@@ -90,6 +95,11 @@ def main():
|
||||
|
||||
|
||||
def operations(mount):
|
||||
if ".smb-service" in {p.name for p in mount.iterdir()}: raise RuntimeError("private service directory exposed")
|
||||
try:
|
||||
(mount/".smb-service"/"private-sentinel").read_bytes()
|
||||
except OSError: pass
|
||||
else: raise RuntimeError("private service data exposed")
|
||||
(mount / "folder").mkdir()
|
||||
block = b"RouterShelf-integrity-probe-" * 2048
|
||||
expected = hashlib.sha256()
|
||||
|
||||
Reference in new issue
Block a user