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

+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")
}
}