跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

0006-robustness.patch

783 行 · 24.7 KB历史下载
1diff --git a/pkg/reversesshfs/reversesshfs.go b/pkg/reversesshfs/reversesshfs.go
2index d59def7..fe77c0f 100644
3--- a/pkg/reversesshfs/reversesshfs.go
4+++ b/pkg/reversesshfs/reversesshfs.go
5@@ -250,6 +250,9 @@ func (rsf *ReverseSSHFS) Start() error {
6 }
7 logrus.Debugf("executing ssh for remote sshfs: %s %v", rsf.sshCmd.Path, rsf.sshCmd.Args)
8 if err := rsf.sshCmd.Start(); err != nil {
9+ if rooted != nil {
10+ rooted.Close()
11+ }
12 return err
13 }
14 logrus.Debugf("starting sftp server for %v", rsf.LocalPath)
15@@ -339,17 +342,19 @@ done
16 }
17
18 func (rsf *ReverseSSHFS) Close() error {
19- logrus.Debugf("killing processes for remote sshfs: %s %v", rsf.sshCmd.Path, rsf.sshCmd.Args)
20+ if rsf.sshCmd != nil {
21+ logrus.Debugf("killing processes for remote sshfs: %s %v", rsf.sshCmd.Path, rsf.sshCmd.Args)
22+ }
23 var errors []error
24- if rsf.sshCmd != nil && rsf.sshCmd.Process != nil {
25- if err := rsf.sshCmd.Process.Kill(); err != nil {
26- errors = append(errors, err)
27+ for _, cmd := range []*exec.Cmd{rsf.sshCmd, rsf.opensshSftpServerCmd} {
28+ if cmd == nil || cmd.Process == nil {
29+ continue
30 }
31- }
32- if rsf.opensshSftpServerCmd != nil && rsf.opensshSftpServerCmd.Process != nil {
33- if err := rsf.opensshSftpServerCmd.Process.Kill(); err != nil {
34+ if err := cmd.Process.Kill(); err != nil {
35 errors = append(errors, err)
36 }
37+ // Reap it, and close its pipes. The error is the kill itself, or a second Close.
38+ _ = cmd.Wait()
39 }
40 if len(errors) > 0 {
41 return fmt.Errorf("%v", errors)
42diff --git a/pkg/reversesshfs/reversesshfs_test.go b/pkg/reversesshfs/reversesshfs_test.go
43index eb6c323..8a6c37f 100644
44--- a/pkg/reversesshfs/reversesshfs_test.go
45+++ b/pkg/reversesshfs/reversesshfs_test.go
46@@ -1,10 +1,42 @@
47 package reversesshfs
48
49 import (
50+ "os"
51+ "os/exec"
52 "runtime"
53 "testing"
54+ "time"
55 )
56
57+// TestHelperProcess is a child that waits to be killed, for TestCloseReaps.
58+func TestHelperProcess(t *testing.T) {
59+ if os.Getenv("REVERSESSHFS_TEST_SLEEP") == "" {
60+ return
61+ }
62+ time.Sleep(time.Minute)
63+}
64+
65+// Close kills the processes and reaps them: a killed child left unwaited stays a zombie, with its pipes.
66+func TestCloseReaps(t *testing.T) {
67+ start := func() *exec.Cmd {
68+ cmd := exec.Command(os.Args[0], "-test.run=^TestHelperProcess$")
69+ cmd.Env = append(os.Environ(), "REVERSESSHFS_TEST_SLEEP=1")
70+ if err := cmd.Start(); err != nil {
71+ t.Fatal(err)
72+ }
73+ return cmd
74+ }
75+ rsf := &ReverseSSHFS{sshCmd: start(), opensshSftpServerCmd: start()}
76+ if err := rsf.Close(); err != nil {
77+ t.Fatal(err)
78+ }
79+ for _, cmd := range []*exec.Cmd{rsf.sshCmd, rsf.opensshSftpServerCmd} {
80+ if cmd.ProcessState == nil {
81+ t.Error("a killed process was not waited for")
82+ }
83+ }
84+}
85+
86 func TestAddQuotes(t *testing.T) {
87 type testCase struct {
88 input string
89diff --git a/pkg/reversesshfs/rooted.go b/pkg/reversesshfs/rooted.go
90index 3fdc9fa..d3d3a5b 100644
91--- a/pkg/reversesshfs/rooted.go
92+++ b/pkg/reversesshfs/rooted.go
93@@ -34,6 +34,9 @@ type rootedHandlers struct {
94 noopRemovals map[string]time.Time // expiry, keyed by request path
95 }
96
97+// maxHandles bounds the files and directories a client keeps open.
98+const maxHandles = 4096
99+
100 // noopRemovalTTL bounds how long an ExpectRemove token waits for the guest.
101 const noopRemovalTTL = 5 * time.Second
102
103@@ -58,7 +61,11 @@ func newRootedServer(rwc io.ReadWriteCloser, localPath string, readonly bool, re
104 handlers := sftp.Handlers{FileGet: h, FilePut: h, FileCmd: h, FileList: h}
105 // Sequential, as OpenSSH's sftp-server: otherwise two writes to the same range, or a write
106 // and the FSTAT or FSETSTAT sent after it, can run in either order.
107- srv := sftp.NewRequestServer(rwc, handlers, sftp.WithStartDirectory(startDirectory(h.rootPath)), sftp.WithRSSequential())
108+ srv := sftp.NewRequestServer(rwc, handlers, sftp.WithStartDirectory(startDirectory(h.rootPath)), sftp.WithRSSequential(),
109+ // Each handle holds a file descriptor of this process, which may be the one running the VM.
110+ sftp.WithRSMaxHandles(maxHandles),
111+ // sshfs reads up to 64 KiB (max_read), and takes a shorter answer for the end of the file.
112+ sftp.WithRSMaxTxPacket(64*1024))
113 return srv, h, nil
114 }
115
116@@ -158,7 +165,30 @@ func (h *rootedHandlers) Fileread(r *sftp.Request) (io.ReaderAt, error) {
117 if err != nil {
118 return nil, err
119 }
120- return h.root.Open(rel)
121+ f, err := h.openRead(rel)
122+ if err != nil {
123+ return nil, err
124+ }
125+ return f, nil
126+}
127+
128+// openRead opens rel for reading, if it is a regular file or a directory.
129+// Opening a FIFO, or a device, could block the server, which handles one request at a time.
130+func (h *rootedHandlers) openRead(rel string) (*os.File, error) {
131+ f, err := h.root.OpenFile(rel, os.O_RDONLY|openNonblock, 0)
132+ if err != nil {
133+ return nil, err
134+ }
135+ fi, err := f.Stat()
136+ if err != nil {
137+ f.Close()
138+ return nil, err
139+ }
140+ if !fi.Mode().IsRegular() && !fi.IsDir() {
141+ f.Close()
142+ return nil, &os.PathError{Op: "open", Path: rel, Err: errDenied}
143+ }
144+ return f, nil
145 }
146
147 // writableFile is a file opened by openFile: checked against readonlyNames, without following symlinks.
148@@ -205,6 +235,10 @@ func (h *rootedHandlers) OpenFile(r *sftp.Request) (sftp.WriterAtReaderAt, error
149 return f, nil
150 }
151
152+// permMask is the part of a mode the client may set: never setuid, setgid or sticky, which
153+// would give a file the host runs the privileges of its owner.
154+const permMask = 0o777
155+
156 // openMode returns the permissions sent with an Open request.
157 // For Open, pkg/sftp puts the open flags in r.Flags and drops the attribute flags,
158 // so r.AttrFlags and r.Attributes must not be used: SSH_FXF_APPEND reads as permissions.
159@@ -213,7 +247,7 @@ func openMode(r *sftp.Request) (uint32, bool) {
160 if len(r.Attrs) != 4 {
161 return 0, false
162 }
163- return binary.BigEndian.Uint32(r.Attrs) & 0o7777, true
164+ return binary.BigEndian.Uint32(r.Attrs) & permMask, true
165 }
166
167 // Filecmd implements sftp.FileCmder.
168@@ -224,6 +258,10 @@ func (h *rootedHandlers) Filecmd(r *sftp.Request) error {
169 if f, ok := r.HandleFile().(writableFile); ok {
170 return h.fsetstat(f.File, r)
171 }
172+ // A read handle keeps the path checks, but only for the file it is open on.
173+ if f, ok := r.HandleFile().(*os.File); ok && !h.isOpenAt(f, r.Filepath) {
174+ return &os.PathError{Op: "setstat", Path: r.Filepath, Err: os.ErrNotExist}
175+ }
176 if h.isNoopTimes(r) {
177 return nil
178 }
179@@ -252,6 +290,20 @@ func (h *rootedHandlers) PosixRename(r *sftp.Request) error {
180 return h.rename(r, false)
181 }
182
183+// isOpenAt reports whether f is the file at p, a request path, without following a symlink at p.
184+func (h *rootedHandlers) isOpenAt(f *os.File, p string) bool {
185+ rel, err := h.rel(p)
186+ if err != nil {
187+ return false
188+ }
189+ fi, err := f.Stat()
190+ if err != nil {
191+ return false
192+ }
193+ at, err := h.root.Lstat(rel)
194+ return err == nil && os.SameFile(fi, at)
195+}
196+
197 // isNoopTimes reports whether r only sets the access and modification times of a
198 // read-only name to its current modification time. Such a request is answered
199 // without touching the file, so that the guest kernel still emits IN_ATTRIB:
200@@ -283,16 +335,11 @@ func (h *rootedHandlers) Filelist(r *sftp.Request) (sftp.ListerAt, error) {
201 }
202 switch r.Method {
203 case "List":
204- f, err := h.root.Open(rel)
205+ f, err := h.openRead(rel)
206 if err != nil {
207 return nil, err
208 }
209- defer f.Close()
210- fis, err := f.Readdir(-1)
211- if err != nil {
212- return nil, err
213- }
214- return listerAt(fis), nil
215+ return &dirLister{f: f}, nil
216 case "Stat":
217 // FSTAT: r.Filepath is where the file was opened, which may now be another file.
218 var f *os.File
219@@ -346,6 +393,49 @@ func (h *rootedHandlers) RealPath(p string) (string, error) {
220 return realPath(h.rootPath, p), nil
221 }
222
223+// dirLister reads a directory as the client lists it, instead of all of it when it is opened:
224+// a huge directory takes neither the memory nor the time of a full read up front.
225+// pkg/sftp lists sequentially from offset 0, and closes it with the handle.
226+//
227+// Readdir looks the entries up relative to the open directory f (Go 1.26.9 and later: before,
228+// by the path f was opened with, which the client could have made a symlink to a folder
229+// outside the root), so the entries are those of f whatever it was renamed to.
230+type dirLister struct {
231+ mu sync.Mutex
232+ f *os.File
233+ buf []os.FileInfo // read, not listed yet
234+ next int64 // offset of buf[0]
235+ eof bool
236+}
237+
238+func (d *dirLister) ListAt(ls []os.FileInfo, offset int64) (int, error) {
239+ d.mu.Lock()
240+ defer d.mu.Unlock()
241+ if offset != d.next {
242+ return 0, &os.PathError{Op: "readdir", Path: d.f.Name(), Err: errors.ErrUnsupported}
243+ }
244+ for len(d.buf) < len(ls) && !d.eof {
245+ fis, err := d.f.Readdir(len(ls) - len(d.buf))
246+ d.buf = append(d.buf, fis...)
247+ if errors.Is(err, io.EOF) {
248+ d.eof = true
249+ } else if err != nil {
250+ return 0, err
251+ }
252+ }
253+ n := copy(ls, d.buf)
254+ d.buf = d.buf[n:]
255+ d.next += int64(n)
256+ if n < len(ls) && d.eof {
257+ return n, io.EOF
258+ }
259+ return n, nil
260+}
261+
262+func (d *dirLister) Close() error {
263+ return d.f.Close()
264+}
265+
266 type listerAt []os.FileInfo
267
268 func (l listerAt) ListAt(ls []os.FileInfo, offset int64) (int, error) {
269diff --git a/pkg/reversesshfs/rooted_darwin.go b/pkg/reversesshfs/rooted_darwin.go
270index d81d06e..589c215 100644
271--- a/pkg/reversesshfs/rooted_darwin.go
272+++ b/pkg/reversesshfs/rooted_darwin.go
273@@ -16,10 +16,15 @@ func statVFS(st *unix.Statfs_t) *sftp.StatVFS {
274 Ffree: st.Ffree,
275 Favail: st.Ffree,
276 Flag: uint64(st.Flags),
277- Namemax: 1024,
278+ Namemax: 255, // APFS and HFS+ names are at most 255 UTF-16 code units
279 }
280 }
281
282+// renameNoReplace renames, failing with EEXIST when the new path exists, atomically.
283+func renameNoReplace(oldfd int, oldBase string, newfd int, newBase string) error {
284+ return unix.RenameatxNp(oldfd, oldBase, newfd, newBase, unix.RENAME_EXCL)
285+}
286+
287 // fchmodatNoFollow never follows a symlink at base, and fails on one, as on Linux.
288 // If base is replaced by a symlink after the check, fchmodat changes the mode of the symlink itself.
289 func fchmodatNoFollow(dirfd int, base string, mode uint32) error {
290diff --git a/pkg/reversesshfs/rooted_linux.go b/pkg/reversesshfs/rooted_linux.go
291index 7ad5fd0..2ae2e83 100644
292--- a/pkg/reversesshfs/rooted_linux.go
293+++ b/pkg/reversesshfs/rooted_linux.go
294@@ -23,6 +23,11 @@ func statVFS(st *unix.Statfs_t) *sftp.StatVFS {
295 }
296 }
297
298+// renameNoReplace renames, failing with EEXIST when the new path exists, atomically.
299+func renameNoReplace(oldfd int, oldBase string, newfd int, newBase string) error {
300+ return unix.Renameat2(oldfd, oldBase, newfd, newBase, unix.RENAME_NOREPLACE)
301+}
302+
303 // fchmodatNoFollow never follows a symlink at base, and fails on one.
304 // Only fchmodat2 (kernel 6.6+) supports AT_SYMLINK_NOFOLLOW, and it fails with EOPNOTSUPP on a symlink.
305 func fchmodatNoFollow(dirfd int, base string, mode uint32) error {
306diff --git a/pkg/reversesshfs/rooted_robust_test.go b/pkg/reversesshfs/rooted_robust_test.go
307new file mode 100644
308index 0000000..a5d6e3f
309--- /dev/null
310+++ b/pkg/reversesshfs/rooted_robust_test.go
311@@ -0,0 +1,115 @@
312+//go:build linux || darwin || windows
313+
314+package reversesshfs
315+
316+import (
317+ "os"
318+ "path/filepath"
319+ "runtime"
320+ "strings"
321+ "testing"
322+
323+ "github.com/pkg/sftp"
324+)
325+
326+// An opened directory renamed, with a symlink to a folder outside the root put in its place,
327+// must not list the metadata of the files outside. (This holds because Go's File.Readdir stats
328+// relative to the directory; go.mod requires a Go that does.)
329+func TestRootedListNoEscape(t *testing.T) {
330+ if runtime.GOOS == "windows" {
331+ t.Skip("no symlinks")
332+ }
333+ _, root, h := setupRootedHandlers(t, false)
334+ outside := filepath.Join(filepath.Dir(root), "outside")
335+ if err := os.Mkdir(filepath.Join(root, "d"), 0o755); err != nil {
336+ t.Fatal(err)
337+ }
338+ for _, f := range []struct{ path, content string }{
339+ {filepath.Join(root, "d", "a"), "x"},
340+ {filepath.Join(root, "d", "b"), "x"},
341+ {filepath.Join(outside, "a"), strings.Repeat("secret", 100)},
342+ } {
343+ if err := os.WriteFile(f.path, []byte(f.content), 0o644); err != nil {
344+ t.Fatal(err)
345+ }
346+ }
347+ l, err := h.Filelist(sftp.NewRequest("List", filepath.Join(root, "d")))
348+ if err != nil {
349+ t.Fatal(err)
350+ }
351+ defer l.(interface{ Close() error }).Close()
352+ if err := os.Rename(filepath.Join(root, "d"), filepath.Join(root, "d2")); err != nil {
353+ t.Fatal(err)
354+ }
355+ if err := os.Symlink(outside, filepath.Join(root, "d")); err != nil {
356+ t.Fatal(err)
357+ }
358+ ls := make([]os.FileInfo, 10)
359+ n, _ := l.ListAt(ls, 0)
360+ for _, fi := range ls[:n] {
361+ if fi.Size() != 1 {
362+ t.Errorf("%s: size %d, the metadata of a file outside the root", fi.Name(), fi.Size())
363+ }
364+ }
365+}
366+
367+// The setuid, setgid and sticky bits are never set by the client.
368+func TestRootedNoSpecialBits(t *testing.T) {
369+ if runtime.GOOS == "windows" {
370+ t.Skip("no mode bits")
371+ }
372+ c, root, h := setupRootedHandlers(t, false)
373+ p := func(s string) string { return filepath.Join(root, s) }
374+ special := func(s string) os.FileMode {
375+ t.Helper()
376+ fi, err := os.Stat(p(s))
377+ if err != nil {
378+ t.Fatal(err)
379+ }
380+ return fi.Mode() & (os.ModeSetuid | os.ModeSetgid | os.ModeSticky)
381+ }
382+ const mode = 0o7755
383+ attrs := []byte{0, 0, byte(mode >> 8), byte(mode & 0xff)}
384+
385+ r := sftp.NewRequest("Put", p("src/open"))
386+ r.Flags = 0x2 | 0x8 // write, creat
387+ r.Attrs = attrs
388+ f, err := h.openFile(r)
389+ if err != nil {
390+ t.Fatal(err)
391+ }
392+ f.Close()
393+ if m := special("src/open"); m != 0 {
394+ t.Errorf("open: %v", m)
395+ }
396+
397+ if err := c.Chmod(p("src/main.go"), mode); err != nil {
398+ t.Fatal(err)
399+ }
400+ if m := special("src/main.go"); m != 0 {
401+ t.Errorf("chmod: %v", m)
402+ }
403+
404+ hf, err := c.OpenFile(p("src/main.go"), os.O_RDWR)
405+ if err != nil {
406+ t.Fatal(err)
407+ }
408+ if err := hf.Chmod(mode); err != nil {
409+ t.Fatal(err)
410+ }
411+ hf.Close()
412+ if m := special("src/main.go"); m != 0 {
413+ t.Errorf("fchmod: %v", m)
414+ }
415+
416+ // Mkdir takes its attributes through the sftp package; the handler applies them.
417+ mk := sftp.NewRequest("Mkdir", p("src/dir"))
418+ mk.Flags = 0x4 // permissions
419+ mk.Attrs = append(make([]byte, 0, 4), attrs...)
420+ if err := h.Filecmd(mk); err != nil {
421+ t.Fatal(err)
422+ }
423+ if m := special("src/dir"); m != 0 {
424+ t.Errorf("mkdir: %v", m)
425+ }
426+}
427diff --git a/pkg/reversesshfs/rooted_test.go b/pkg/reversesshfs/rooted_test.go
428index dd69d52..945d244 100644
429--- a/pkg/reversesshfs/rooted_test.go
430+++ b/pkg/reversesshfs/rooted_test.go
431@@ -3,6 +3,7 @@
432 package reversesshfs
433
434 import (
435+ "fmt"
436 "io"
437 "os"
438 "path/filepath"
439@@ -339,6 +340,105 @@ func TestRootedFsetstatReadHandle(t *testing.T) {
440 assertUnchanged(t, root)
441 }
442
443+// FSETSTAT on a read handle applies only while the handle's file is still at its path.
444+func TestRootedReadHandleSetstatAfterRename(t *testing.T) {
445+ c, root := setupRooted(t, false)
446+ p := func(s string) string { return filepath.Join(root, s) }
447+ f, err := c.Open(p("src/main.go"))
448+ if err != nil {
449+ t.Fatal(err)
450+ }
451+ defer f.Close()
452+ if err := c.PosixRename(p("src/main.go"), p("src/moved.go")); err != nil {
453+ t.Fatal(err)
454+ }
455+ if err := os.WriteFile(p("src/main.go"), []byte("other file"), 0o644); err != nil {
456+ t.Fatal(err)
457+ }
458+ if err := f.Chmod(0o400); err == nil {
459+ t.Fatal("Chmod through the handle changed the file now at its path")
460+ }
461+ if fi, err := os.Stat(p("src/main.go")); err != nil || fi.Mode().Perm()&0o200 == 0 {
462+ t.Fatalf("src/main.go: %v, %v", fi, err)
463+ }
464+}
465+
466+// Directories are listed as the client asks, and the handle's descriptor is released on close.
467+func TestRootedListLarge(t *testing.T) {
468+ c, root := setupRooted(t, false)
469+ dir := filepath.Join(root, "src", "many")
470+ if err := os.Mkdir(dir, 0o755); err != nil {
471+ t.Fatal(err)
472+ }
473+ const n = 1234
474+ for i := 0; i < n; i++ {
475+ if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("f%04d", i)), nil, 0o644); err != nil {
476+ t.Fatal(err)
477+ }
478+ }
479+ before := openFDs()
480+ for i := 0; i < 3; i++ {
481+ fis, err := c.ReadDir(dir)
482+ if err != nil || len(fis) != n {
483+ t.Fatalf("ReadDir: %d entries, %v", len(fis), err)
484+ }
485+ seen := make(map[string]bool, n)
486+ for _, fi := range fis {
487+ seen[fi.Name()] = true
488+ }
489+ if len(seen) != n {
490+ t.Fatalf("%d distinct entries", len(seen))
491+ }
492+ }
493+ if after := openFDs(); after > before {
494+ t.Fatalf("descriptors: %d before, %d after", before, after)
495+ }
496+}
497+
498+// openFDs counts the descriptors of this process, or returns 0 where it cannot.
499+func openFDs() int {
500+ fis, err := os.ReadDir("/proc/self/fd")
501+ if err != nil {
502+ return 0
503+ }
504+ return len(fis)
505+}
506+
507+func TestRootedMaxHandles(t *testing.T) {
508+ c, root := setupRooted(t, false)
509+ p := filepath.Join(root, "src", "main.go")
510+ files := make([]*sftp.File, 0, maxHandles)
511+ defer func() {
512+ for _, f := range files {
513+ f.Close()
514+ }
515+ }()
516+ for i := 0; i < maxHandles; i++ {
517+ f, err := c.Open(p)
518+ if err != nil {
519+ t.Fatalf("handle %d: %v", i, err)
520+ }
521+ files = append(files, f)
522+ }
523+ if f, err := c.Open(p); err == nil {
524+ f.Close()
525+ t.Fatal("one handle over the limit")
526+ }
527+ files[0].Close()
528+ files = files[1:]
529+ f, err := c.Open(p)
530+ if err != nil {
531+ t.Fatal(err)
532+ }
533+ files = append(files, f)
534+}
535+
536+func TestReverseSSHFSCloseNotStarted(t *testing.T) {
537+ if err := (&ReverseSSHFS{}).Close(); err != nil {
538+ t.Fatal(err)
539+ }
540+}
541+
542 // sshfs sends its open flags with the permissions alone as attributes.
543 func TestRootedOpenMode(t *testing.T) {
544 if runtime.GOOS == "windows" {
545diff --git a/pkg/reversesshfs/rooted_unix.go b/pkg/reversesshfs/rooted_unix.go
546index e9a71a8..9221504 100644
547--- a/pkg/reversesshfs/rooted_unix.go
548+++ b/pkg/reversesshfs/rooted_unix.go
549@@ -3,6 +3,7 @@
550 package reversesshfs
551
552 import (
553+ "errors"
554 "os"
555 "path"
556 "path/filepath"
557@@ -14,6 +15,9 @@ import (
558
559 var errDenied error = unix.EACCES
560
561+// openNonblock: see openRead.
562+const openNonblock = unix.O_NONBLOCK
563+
564 // appendWrite writes b at the end of f, which openFile opened with O_APPEND.
565 // pwrite(2) would honor its offset on macOS.
566 func appendWrite(f *os.File, b []byte) (int, error) {
567@@ -121,10 +125,20 @@ func (h *rootedHandlers) openFile(r *sftp.Request) (*os.File, error) {
568 return nil, err
569 }
570 defer unix.Close(dirfd)
571- fd, err := unix.Openat(dirfd, base, flags, mode)
572+ // O_NONBLOCK: a FIFO would block the server, which handles one request at a time.
573+ // It has no effect on regular files, the only ones served.
574+ fd, err := unix.Openat(dirfd, base, flags|unix.O_NONBLOCK, mode)
575 if err != nil {
576 return nil, &os.PathError{Op: "open", Path: r.Filepath, Err: err}
577 }
578+ var st unix.Stat_t
579+ if err := unix.Fstat(fd, &st); err != nil || st.Mode&unix.S_IFMT != unix.S_IFREG {
580+ unix.Close(fd)
581+ if err == nil {
582+ err = errDenied
583+ }
584+ return nil, &os.PathError{Op: "open", Path: r.Filepath, Err: err}
585+ }
586 return os.NewFile(uintptr(fd), r.Filepath), nil
587 }
588
589@@ -158,7 +172,7 @@ func (h *rootedHandlers) remove(r *sftp.Request) error {
590 func (h *rootedHandlers) mkdir(r *sftp.Request) error {
591 var mode uint32 = 0o755
592 if a := r.Attributes(); a != nil && r.AttrFlags().Permissions {
593- mode = a.Mode & 0o7777
594+ mode = a.Mode & permMask
595 }
596 return h.inParent("mkdir", r.Filepath, func(dirfd int, base string) error {
597 return unix.Mkdirat(dirfd, base, mode)
598@@ -181,6 +195,11 @@ func (h *rootedHandlers) link(r *sftp.Request) error {
599 func (h *rootedHandlers) rename(r *sftp.Request, noReplace bool) error {
600 return h.twoPaths(r.Filepath, r.Target, func(oldfd int, oldBase string, newfd int, newBase string) error {
601 if noReplace {
602+ err := renameNoReplace(oldfd, oldBase, newfd, newBase)
603+ if !errors.Is(err, unix.EINVAL) && !errors.Is(err, unix.ENOSYS) && !errors.Is(err, unix.ENOTSUP) && !errors.Is(err, unix.EOPNOTSUPP) {
604+ return err
605+ }
606+ // The file system cannot do it atomically.
607 var st unix.Stat_t
608 if err := unix.Fstatat(newfd, newBase, &st, unix.AT_SYMLINK_NOFOLLOW); err == nil {
609 return os.ErrExist
610@@ -242,7 +261,7 @@ func (h *rootedHandlers) setstat(r *sftp.Request) error {
611 }
612 }
613 if flags.Permissions {
614- if err := fchmodatNoFollow(dirfd, base, attrs.Mode&0o7777); err != nil {
615+ if err := fchmodatNoFollow(dirfd, base, attrs.Mode&permMask); err != nil {
616 return &os.PathError{Op: "chmod", Path: r.Filepath, Err: err}
617 }
618 }
619@@ -277,7 +296,7 @@ func (h *rootedHandlers) fsetstat(f *os.File, r *sftp.Request) error {
620 }
621 }
622 if flags.Permissions {
623- if err := unix.Fchmod(fd, attrs.Mode&0o7777); err != nil {
624+ if err := unix.Fchmod(fd, attrs.Mode&permMask); err != nil {
625 return &os.PathError{Op: "chmod", Path: f.Name(), Err: err}
626 }
627 }
628diff --git a/pkg/reversesshfs/rooted_unix_test.go b/pkg/reversesshfs/rooted_unix_test.go
629new file mode 100644
630index 0000000..3067a7d
631--- /dev/null
632+++ b/pkg/reversesshfs/rooted_unix_test.go
633@@ -0,0 +1,72 @@
634+//go:build linux || darwin
635+
636+package reversesshfs
637+
638+import (
639+ "errors"
640+ "os"
641+ "path/filepath"
642+ "testing"
643+ "time"
644+
645+ "golang.org/x/sys/unix"
646+)
647+
648+// Opening a FIFO must fail, not block the server: it handles one request at a time.
649+func TestRootedFifo(t *testing.T) {
650+ c, root := setupRooted(t, false)
651+ fifo := filepath.Join(root, "src", "fifo")
652+ if err := unix.Mkfifo(fifo, 0o644); err != nil {
653+ t.Fatal(err)
654+ }
655+ done := make(chan error, 1)
656+ go func() {
657+ if f, err := c.Open(fifo); err == nil {
658+ f.Close()
659+ done <- errors.New("Open (read) succeeded")
660+ return
661+ }
662+ if f, err := c.OpenFile(fifo, os.O_WRONLY); err == nil {
663+ f.Close()
664+ done <- errors.New("OpenFile (write) succeeded")
665+ return
666+ }
667+ if _, err := c.ReadDir(fifo); err == nil {
668+ done <- errors.New("ReadDir succeeded")
669+ return
670+ }
671+ _, err := c.Stat(filepath.Join(root, "src", "main.go"))
672+ done <- err
673+ }()
674+ select {
675+ case err := <-done:
676+ if err != nil {
677+ t.Fatal(err)
678+ }
679+ case <-time.After(5 * time.Second):
680+ t.Fatal("the server blocked on a FIFO")
681+ }
682+}
683+
684+func TestRenameNoReplace(t *testing.T) {
685+ dir := t.TempDir()
686+ for _, n := range []string{"a", "b"} {
687+ if err := os.WriteFile(filepath.Join(dir, n), []byte(n), 0o644); err != nil {
688+ t.Fatal(err)
689+ }
690+ }
691+ fd, err := unix.Open(dir, unix.O_RDONLY|unix.O_DIRECTORY, 0)
692+ if err != nil {
693+ t.Fatal(err)
694+ }
695+ defer unix.Close(fd)
696+ if err := renameNoReplace(fd, "a", fd, "b"); !errors.Is(err, unix.EEXIST) {
697+ t.Fatalf("over an existing file: %v", err)
698+ }
699+ if err := renameNoReplace(fd, "a", fd, "c"); err != nil {
700+ t.Fatal(err)
701+ }
702+ if b, err := os.ReadFile(filepath.Join(dir, "b")); err != nil || string(b) != "b" {
703+ t.Fatalf("b: %q, %v", b, err)
704+ }
705+}
706diff --git a/pkg/reversesshfs/rooted_windows.go b/pkg/reversesshfs/rooted_windows.go
707index c17dc25..94394a4 100644
708--- a/pkg/reversesshfs/rooted_windows.go
709+++ b/pkg/reversesshfs/rooted_windows.go
710@@ -15,6 +15,9 @@ import (
711
712 var errDenied error = windows.ERROR_ACCESS_DENIED
713
714+// openNonblock: opening a file never blocks on Windows.
715+const openNonblock = 0
716+
717 // appendWrite writes b at the end of f, as it is when the write happens.
718 func appendWrite(f *os.File, b []byte) (int, error) {
719 var n uint32
720@@ -93,8 +96,37 @@ func realPath(rootPath, p string) string {
721
722 // writableName rejects backslashes, which are separators on Windows,
723 // and colons, which name NTFS streams (e.g. .git::$INDEX_ALLOCATION, see CVE-2019-1352).
724+// It also rejects names NtCreateFile creates but Win32 tools cannot open or delete:
725+// trailing dots or spaces, and device names (NUL, nul.txt, COM1...).
726 func writableName(rel string) bool {
727- return !strings.ContainsAny(rel, `\:`)
728+ if strings.ContainsAny(rel, `\:`) {
729+ return false
730+ }
731+ for _, c := range strings.Split(rel, "/") {
732+ if c == "." {
733+ continue
734+ }
735+ if strings.HasSuffix(c, ".") || strings.HasSuffix(c, " ") || isDeviceName(c) {
736+ return false
737+ }
738+ }
739+ return true
740+}
741+
742+func isDeviceName(c string) bool {
743+ stem, _, _ := strings.Cut(c, ".")
744+ stem = strings.ToUpper(strings.TrimRight(stem, " "))
745+ switch stem {
746+ case "CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$":
747+ return true
748+ }
749+ if len(stem) >= 4 && (strings.HasPrefix(stem, "COM") || strings.HasPrefix(stem, "LPT")) {
750+ switch stem[3:] {
751+ case "1", "2", "3", "4", "5", "6", "7", "8", "9", "¹", "²", "³":
752+ return true
753+ }
754+ }
755+ return false
756 }
757
758 func normalizedName(h windows.Handle) (string, error) {
759diff --git a/pkg/reversesshfs/rooted_windows_test.go b/pkg/reversesshfs/rooted_windows_test.go
760index df0f179..78824d0 100644
761--- a/pkg/reversesshfs/rooted_windows_test.go
762+++ b/pkg/reversesshfs/rooted_windows_test.go
763@@ -159,6 +159,20 @@ func TestRootedDeniesWindowsNames(t *testing.T) {
764 }
765 }
766
767+// Names NtCreateFile creates but Win32 tools cannot open or delete.
768+func TestWritableNameWin32(t *testing.T) {
769+ for _, rel := range []string{"src/a.", "src/a ", "a./b", "NUL", "src/nul.txt", "aux", "Con .txt", "COM1", "lpt9.log", "COM¹", "CONIN$"} {
770+ if writableName(rel) {
771+ t.Errorf("%q: writable", rel)
772+ }
773+ }
774+ for _, rel := range []string{".", "src/main.go", "src/.a", "console", "COM10", "COMx", "nulx", "src/a.b"} {
775+ if !writableName(rel) {
776+ t.Errorf("%q: not writable", rel)
777+ }
778+ }
779+}
780+
781 func TestRootedSymlinkUnsupported(t *testing.T) {
782 c, root := setupRooted(t, false)
783 if err := c.Symlink("main.go", filepath.Join(root, "src", "link")); err == nil {