跳到主要内容

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

浏览文件

0008-write-guard.patch

525 行 · 17.5 KB历史下载
1diff --git a/pkg/reversesshfs/guard_test.go b/pkg/reversesshfs/guard_test.go
2new file mode 100644
3index 0000000..f3055dc
4--- /dev/null
5+++ b/pkg/reversesshfs/guard_test.go
6@@ -0,0 +1,71 @@
7+//go:build linux || darwin || windows
8+
9+package reversesshfs
10+
11+import (
12+ "os"
13+ "path/filepath"
14+ "slices"
15+ "testing"
16+)
17+
18+// Guard is asked before each write the read-only names allow, with the path
19+// relative to the served directory; a no refuses it and nothing changes.
20+// Reads never ask.
21+func TestRootedGuard(t *testing.T) {
22+ var asked []string
23+ allow := false
24+ Guard = func(root, rel string, entry bool) bool {
25+ asked = append(asked, rel)
26+ return allow || rel != ".envrc" && rel != "src/new"
27+ }
28+ t.Cleanup(func() { Guard = nil })
29+ c, root := setupRooted(t, false)
30+ os.WriteFile(filepath.Join(root, ".envrc"), []byte("orig"), 0o644)
31+ p := func(s string) string { return filepath.Join(root, s) }
32+
33+ for _, op := range []struct {
34+ name string
35+ rel string
36+ f func() error
37+ }{
38+ {"write", ".envrc", func() error {
39+ f, err := c.OpenFile(p(".envrc"), os.O_WRONLY|os.O_TRUNC)
40+ if err == nil {
41+ f.Close()
42+ }
43+ return err
44+ }},
45+ {"remove", ".envrc", func() error { return c.Remove(p(".envrc")) }},
46+ {"rename onto", ".envrc", func() error { return c.PosixRename(p("src/main.go"), p(".envrc")) }},
47+ {"chmod", ".envrc", func() error { return c.Chmod(p(".envrc"), 0o755) }},
48+ {"mkdir", "src/new", func() error { return c.Mkdir(p("src/new")) }},
49+ } {
50+ asked = nil
51+ if err := op.f(); err == nil {
52+ t.Errorf("%s: allowed though Guard said no", op.name)
53+ }
54+ if !slices.Contains(asked, op.rel) {
55+ t.Errorf("%s: Guard asked %q, not %q", op.name, asked, op.rel)
56+ }
57+ }
58+ if b, _ := os.ReadFile(p(".envrc")); string(b) != "orig" {
59+ t.Errorf(".envrc changed: %q", b)
60+ }
61+ if _, err := os.Stat(p("src/main.go")); err != nil {
62+ t.Error("src/main.go moved")
63+ }
64+ asked = nil
65+ f, err := c.Open(p(".envrc"))
66+ if err != nil {
67+ t.Fatal(err)
68+ }
69+ f.Close()
70+ if len(asked) != 0 {
71+ t.Errorf("a read asked: %q", asked)
72+ }
73+ allow = true
74+ if err := c.Chmod(p(".envrc"), 0o600); err != nil {
75+ t.Errorf("allowed: %v", err)
76+ }
77+}
78diff --git a/pkg/reversesshfs/rooted.go b/pkg/reversesshfs/rooted.go
79index d135e58..77b9ce8 100644
80--- a/pkg/reversesshfs/rooted.go
81+++ b/pkg/reversesshfs/rooted.go
82@@ -8,6 +8,7 @@ import (
83 "io"
84 "os"
85 "path"
86+ "path/filepath"
87 "slices"
88 "strings"
89 "sync"
90@@ -30,6 +31,7 @@ type rootedHandlers struct {
91 readonly bool
92 readonlyNames []string
93 foldedNames []string // readonlyNames as FoldName gives them
94+ guardRoot string // the served directory as Guard is told
95 rootedSys
96
97 mu sync.Mutex
98@@ -57,6 +59,7 @@ func newRootedServer(rwc io.ReadWriteCloser, localPath string, readonly bool, re
99 root: root,
100 readonly: readonly,
101 readonlyNames: readonlyNames,
102+ guardRoot: filepath.Clean(localPath),
103 rootedSys: sys,
104 noopRemovals: make(map[string]time.Time),
105 }
106@@ -125,7 +128,9 @@ func (h *rootedHandlers) rel(p string) (string, error) {
107 return "", errDenied
108 }
109
110-func (h *rootedHandlers) writableRel(p string) (string, error) {
111+// writableRel is the path relative to the root of the request path p, if it may be written.
112+// entry: see Guard.
113+func (h *rootedHandlers) writableRel(p string, entry bool) (string, error) {
114 if h.readonly {
115 return "", errDenied
116 }
117@@ -136,9 +141,34 @@ func (h *rootedHandlers) writableRel(p string) (string, error) {
118 if h.isReadonlyName(r) || !writableName(r) {
119 return "", errDenied
120 }
121+ if lexicalGuard {
122+ if err := h.guard(r, entry); err != nil {
123+ return "", err
124+ }
125+ }
126 return r, nil
127 }
128
129+// Guard, when set by the program running the server, is asked before every
130+// write that the read-only names allow, with the served directory and the
131+// path relative to it: false refuses the write (EACCES). It may block, to ask
132+// the user; the client's requests wait meanwhile.
133+//
134+// entry is true when rel is a name being created, removed, moved or linked, as opposed to
135+// a file whose content or attributes change: then a directory that holds protected paths
136+// matters as well, since creating or moving it creates or moves them.
137+//
138+// rel is spelled as the file system has it where the server can tell (Windows: the
139+// normalized name, in which 8.3 short names are replaced by long ones), otherwise as the client sent it.
140+var Guard func(root, rel string, entry bool) bool
141+
142+func (h *rootedHandlers) guard(rel string, entry bool) error {
143+ if Guard != nil && !Guard(h.guardRoot, rel, entry) {
144+ return errDenied
145+ }
146+ return nil
147+}
148+
149 func (h *rootedHandlers) isReadonlyName(rel string) bool {
150 for _, c := range strings.Split(rel, "/") {
151 fc := FoldName(c)
152diff --git a/pkg/reversesshfs/rooted_guard_test.go b/pkg/reversesshfs/rooted_guard_test.go
153new file mode 100644
154index 0000000..27b844b
155--- /dev/null
156+++ b/pkg/reversesshfs/rooted_guard_test.go
157@@ -0,0 +1,101 @@
158+//go:build linux || darwin || windows
159+
160+package reversesshfs
161+
162+import (
163+ "os"
164+ "path/filepath"
165+ "runtime"
166+ "slices"
167+ "strings"
168+ "testing"
169+)
170+
171+type guardCall struct {
172+ rel string
173+ entry bool
174+}
175+
176+// A guest builds a guarded file's parent folder elsewhere and moves it into place: Guard is told
177+// that the names are being created, moved, linked or removed (entry), so it can refuse the
178+// parent folder of a guarded path, which a write-only check on the path would not see.
179+func TestRootedGuardParents(t *testing.T) {
180+ if runtime.GOOS == "windows" {
181+ t.Skip("Windows has no symlinks here and asks with normalized names")
182+ }
183+ var calls []guardCall
184+ allow := false
185+ Guard = func(root, rel string, entry bool) bool {
186+ calls = append(calls, guardCall{rel, entry})
187+ parts := strings.Split(strings.ToLower(rel), "/")
188+ last := parts[len(parts)-1]
189+ if allow {
190+ return true
191+ }
192+ if last == ".vscode" && entry {
193+ return false
194+ }
195+ return !(last == "tasks.json" && len(parts) > 1 && parts[len(parts)-2] == ".vscode")
196+ }
197+ t.Cleanup(func() { Guard = nil })
198+ c, root := setupRooted(t, false)
199+ p := func(s string) string { return filepath.Join(root, s) }
200+ must := func(err error) {
201+ t.Helper()
202+ if err != nil {
203+ t.Fatal(err)
204+ }
205+ }
206+ must(os.MkdirAll(p(".vscode"), 0o755))
207+ must(os.WriteFile(p(".vscode/tasks.json"), []byte("orig"), 0o644))
208+ must(c.Mkdir(p("evil")))
209+ f, err := c.Create(p("evil/tasks.json"))
210+ must(err)
211+ _, _ = f.Write([]byte("pwn"))
212+ must(f.Close())
213+ if !slices.Contains(calls, guardCall{"evil/tasks.json", false}) {
214+ t.Errorf("a write is not an entry: %v", calls)
215+ }
216+
217+ for _, op := range []struct {
218+ name string
219+ rel string
220+ f func() error
221+ }{
222+ {"rename onto the parent", ".vscode", func() error { return c.PosixRename(p("evil"), p(".vscode")) }},
223+ {"rename onto the parent, no replace", ".vscode", func() error { return c.Rename(p("evil"), p(".vscode")) }},
224+ {"symlink as the parent", ".vscode", func() error { return c.Symlink("evil", p(".vscode")) }},
225+ {"rename the parent away", ".vscode", func() error { return c.PosixRename(p(".vscode"), p("old")) }},
226+ {"remove the parent", ".vscode", func() error { return c.RemoveDirectory(p(".vscode")) }},
227+ {"hard link to the file", ".vscode/tasks.json", func() error { return c.Link(p(".vscode/tasks.json"), p("evil/alias")) }},
228+ {"mkdir the parent", "sub/.vscode", func() error { return c.Mkdir(p("sub/.vscode")) }},
229+ } {
230+ if op.rel == "sub/.vscode" {
231+ must(os.Mkdir(p("sub"), 0o755))
232+ }
233+ calls = nil
234+ if err := op.f(); err == nil {
235+ t.Errorf("%s: allowed though Guard said no", op.name)
236+ }
237+ if !slices.Contains(calls, guardCall{op.rel, true}) {
238+ t.Errorf("%s: Guard asked %v, not %q as an entry", op.name, calls, op.rel)
239+ }
240+ }
241+ if b, _ := os.ReadFile(p(".vscode/tasks.json")); string(b) != "orig" {
242+ t.Errorf("tasks.json: %q", b)
243+ }
244+ if fi, err := os.Lstat(p(".vscode")); err != nil || !fi.IsDir() {
245+ t.Errorf(".vscode: %v, %v", fi, err)
246+ }
247+ if _, err := os.Lstat(p("evil/alias")); err == nil {
248+ t.Error("hard link made")
249+ }
250+
251+ // With Guard saying yes, the same moves work: they were refused by Guard alone.
252+ allow = true
253+ must(c.PosixRename(p(".vscode"), p("old")))
254+ must(c.PosixRename(p("evil"), p(".vscode")))
255+ if b, _ := os.ReadFile(p(".vscode/tasks.json")); string(b) != "pwn" {
256+ t.Errorf("tasks.json: %q", b)
257+ }
258+}
259diff --git a/pkg/reversesshfs/rooted_unix.go b/pkg/reversesshfs/rooted_unix.go
260index 9221504..6515874 100644
261--- a/pkg/reversesshfs/rooted_unix.go
262+++ b/pkg/reversesshfs/rooted_unix.go
263@@ -15,6 +15,10 @@ import (
264
265 var errDenied error = unix.EACCES
266
267+// lexicalGuard: Guard is asked about the path as the client sent it, and compares it folded (see FoldName).
268+// On Windows the names are asked after the handles are open instead.
269+const lexicalGuard = true
270+
271 // openNonblock: see openRead.
272 const openNonblock = unix.O_NONBLOCK
273
274@@ -89,7 +93,7 @@ func (h *rootedHandlers) openParent(rel string) (int, string, error) {
275 }
276
277 func (h *rootedHandlers) openFile(r *sftp.Request) (*os.File, error) {
278- rel, err := h.writableRel(r.Filepath)
279+ rel, err := h.writableRel(r.Filepath, false)
280 if err != nil {
281 return nil, err
282 }
283@@ -144,7 +148,7 @@ func (h *rootedHandlers) openFile(r *sftp.Request) (*os.File, error) {
284
285 // inParent calls f with the parent directory fd and the base name of the writable path p.
286 func (h *rootedHandlers) inParent(op, p string, f func(dirfd int, base string) error) error {
287- rel, err := h.writableRel(p)
288+ rel, err := h.writableRel(p, true)
289 if err != nil {
290 return err
291 }
292@@ -210,11 +214,11 @@ func (h *rootedHandlers) rename(r *sftp.Request, noReplace bool) error {
293 }
294
295 func (h *rootedHandlers) twoPaths(oldPath, newPath string, f func(oldfd int, oldBase string, newfd int, newBase string) error) error {
296- oldRel, err := h.writableRel(oldPath)
297+ oldRel, err := h.writableRel(oldPath, true)
298 if err != nil {
299 return err
300 }
301- newRel, err := h.writableRel(newPath)
302+ newRel, err := h.writableRel(newPath, true)
303 if err != nil {
304 return err
305 }
306@@ -235,7 +239,7 @@ func (h *rootedHandlers) twoPaths(oldPath, newPath string, f func(oldfd int, old
307 }
308
309 func (h *rootedHandlers) setstat(r *sftp.Request) error {
310- rel, err := h.writableRel(r.Filepath)
311+ rel, err := h.writableRel(r.Filepath, false)
312 if err != nil {
313 return err
314 }
315diff --git a/pkg/reversesshfs/rooted_windows.go b/pkg/reversesshfs/rooted_windows.go
316index 94394a4..e4c87c1 100644
317--- a/pkg/reversesshfs/rooted_windows.go
318+++ b/pkg/reversesshfs/rooted_windows.go
319@@ -15,6 +15,10 @@ import (
320
321 var errDenied error = windows.ERROR_ACCESS_DENIED
322
323+// lexicalGuard is false: a short name (VSCODE~1) hides the entry from the request path, so Guard
324+// is asked with normalized names, by guardAt and guardHandle.
325+const lexicalGuard = false
326+
327 // openNonblock: opening a file never blocks on Windows.
328 const openNonblock = 0
329
330@@ -143,20 +147,56 @@ func normalizedName(h windows.Handle) (string, error) {
331 }
332 }
333
334-// checkHandle denies fh when its normalized path has a read-only component, or is not under the root.
335-func (h *rootedHandlers) checkHandle(fh windows.Handle) error {
336+// normalizedRel is the path of fh relative to the root, slash-separated, with the file system's own spelling.
337+func (h *rootedHandlers) normalizedRel(fh windows.Handle) (string, error) {
338 name, err := normalizedName(fh)
339 if err != nil {
340- return err
341+ return "", err
342 }
343 if name == h.rootName {
344- return nil
345+ return ".", nil
346 }
347 rel, ok := strings.CutPrefix(name, h.rootName+`\`)
348 if !ok {
349- return errDenied
350+ return "", errDenied
351+ }
352+ return strings.ReplaceAll(rel, `\`, "/"), nil
353+}
354+
355+// guardAt asks Guard about base in the directory parent, by the normalized name of parent.
356+func (h *rootedHandlers) guardAt(parent windows.Handle, base string, entry bool) error {
357+ if Guard == nil {
358+ return nil
359+ }
360+ dir, err := h.normalizedRel(parent)
361+ if err != nil {
362+ return err
363+ }
364+ return h.guard(path.Join(dir, base), entry)
365+}
366+
367+// guardHandle asks Guard about the file of fh, by its normalized name.
368+func (h *rootedHandlers) guardHandle(fh windows.Handle, entry bool) error {
369+ if Guard == nil {
370+ return nil
371+ }
372+ rel, err := h.normalizedRel(fh)
373+ if err != nil {
374+ return err
375+ }
376+ return h.guard(rel, entry)
377+}
378+
379+// checkHandle denies fh when its normalized path has a read-only component, or is not under the root.
380+func (h *rootedHandlers) checkHandle(fh windows.Handle) error {
381+ rel, err := h.normalizedRel(fh)
382+ if err != nil {
383+ return err
384+ }
385+ if rel == "." {
386+ return nil
387 }
388- for _, c := range strings.Split(rel, `\`) {
389+ for _, c := range strings.Split(rel, "/") {
390 c, _, _ = strings.Cut(c, ":")
391 if h.isReadonlyName(c) {
392 return errDenied
393@@ -231,8 +271,8 @@ func (h *rootedHandlers) openParent(rel string) (windows.Handle, string, error)
394
395 // openChecked opens the writable path p, which must not be a reparse point unless options has FILE_OPEN_REPARSE_POINT.
396 // The caller must close both handles.
397-func (h *rootedHandlers) openChecked(p string, access, options uint32) (parent, fh windows.Handle, err error) {
398- rel, err := h.writableRel(p)
399+func (h *rootedHandlers) openChecked(p string, access, options uint32, entry bool) (parent, fh windows.Handle, err error) {
400+ rel, err := h.writableRel(p, entry)
401 if err != nil {
402 return windows.InvalidHandle, windows.InvalidHandle, err
403 }
404@@ -240,6 +280,10 @@ func (h *rootedHandlers) openChecked(p string, access, options uint32) (parent,
405 if err != nil {
406 return windows.InvalidHandle, windows.InvalidHandle, err
407 }
408+ if err := h.guardAt(parent, base, entry); err != nil {
409+ windows.CloseHandle(parent)
410+ return windows.InvalidHandle, windows.InvalidHandle, err
411+ }
412 var objFlags uint32
413 if options&windows.FILE_OPEN_REPARSE_POINT == 0 {
414 objFlags = windows.OBJ_DONT_REPARSE
415@@ -247,6 +291,9 @@ func (h *rootedHandlers) openChecked(p string, access, options uint32) (parent,
416 fh, err = ntCreate(parent, base, access, 0, windows.FILE_OPEN, options, objFlags)
417 if err == nil {
418 err = h.checkHandle(fh)
419+ if err == nil {
420+ err = h.guardHandle(fh, entry)
421+ }
422 if err != nil {
423 windows.CloseHandle(fh)
424 }
425@@ -259,7 +306,7 @@ func (h *rootedHandlers) openChecked(p string, access, options uint32) (parent,
426 }
427
428 func (h *rootedHandlers) openFile(r *sftp.Request) (*os.File, error) {
429- rel, err := h.writableRel(r.Filepath)
430+ rel, err := h.writableRel(r.Filepath, false)
431 if err != nil {
432 return nil, err
433 }
434@@ -268,6 +315,9 @@ func (h *rootedHandlers) openFile(r *sftp.Request) (*os.File, error) {
435 return nil, err
436 }
437 defer windows.CloseHandle(parent)
438+ if err := h.guardAt(parent, base, false); err != nil {
439+ return nil, err
440+ }
441 pf := r.Pflags()
442 var access, options uint32
443 switch {
444@@ -298,7 +348,11 @@ func (h *rootedHandlers) openFile(r *sftp.Request) (*os.File, error) {
445 return nil, &os.PathError{Op: "open", Path: r.Filepath, Err: err}
446 }
447 // Checked before truncating: base may be the short name of an existing read-only name.
448- if err := h.checkHandle(fh); err != nil {
449+ err = h.checkHandle(fh)
450+ if err == nil {
451+ err = h.guardHandle(fh, false)
452+ }
453+ if err != nil {
454 windows.CloseHandle(fh)
455 return nil, err
456 }
457@@ -316,7 +370,7 @@ func (h *rootedHandlers) remove(r *sftp.Request) error {
458 if r.Method == "Rmdir" {
459 options |= windows.FILE_DIRECTORY_FILE
460 }
461- parent, fh, err := h.openChecked(r.Filepath, windows.DELETE|windows.FILE_READ_ATTRIBUTES, options)
462+ parent, fh, err := h.openChecked(r.Filepath, windows.DELETE|windows.FILE_READ_ATTRIBUTES, options, true)
463 if err != nil {
464 return err
465 }
466@@ -356,7 +410,7 @@ func deleteHandle(fh windows.Handle) error {
467 }
468
469 func (h *rootedHandlers) mkdir(r *sftp.Request) error {
470- rel, err := h.writableRel(r.Filepath)
471+ rel, err := h.writableRel(r.Filepath, true)
472 if err != nil {
473 return err
474 }
475@@ -365,6 +419,9 @@ func (h *rootedHandlers) mkdir(r *sftp.Request) error {
476 return err
477 }
478 defer windows.CloseHandle(parent)
479+ if err := h.guardAt(parent, base, true); err != nil {
480+ return err
481+ }
482 // A base that is the short name of an existing entry fails with STATUS_OBJECT_NAME_COLLISION.
483 fh, err := ntCreate(parent, base, fileDirectoryAccess, fileAttributeNormal, windows.FILE_CREATE,
484 windows.FILE_DIRECTORY_FILE, windows.OBJ_DONT_REPARSE)
485@@ -410,11 +467,11 @@ func (h *rootedHandlers) rename(r *sftp.Request, noReplace bool) error {
486 func (h *rootedHandlers) twoPaths(oldPath, newPath string, access, options uint32, noReplace bool,
487 f func(src, newParent windows.Handle, newBase string) error,
488 ) error {
489- newRel, err := h.writableRel(newPath)
490+ newRel, err := h.writableRel(newPath, true)
491 if err != nil {
492 return err
493 }
494- oldParent, src, err := h.openChecked(oldPath, access, options|windows.FILE_OPEN_REPARSE_POINT)
495+ oldParent, src, err := h.openChecked(oldPath, access, options|windows.FILE_OPEN_REPARSE_POINT, true)
496 if err != nil {
497 return err
498 }
499@@ -425,11 +482,17 @@ func (h *rootedHandlers) twoPaths(oldPath, newPath string, access, options uint3
500 return err
501 }
502 defer windows.CloseHandle(newParent)
503+ if err := h.guardAt(newParent, newBase, true); err != nil {
504+ return err
505+ }
506 // newBase may be the short name of an existing read-only name, which would be replaced.
507 dst, err := ntCreate(newParent, newBase, windows.FILE_READ_ATTRIBUTES, 0, windows.FILE_OPEN, windows.FILE_OPEN_REPARSE_POINT, 0)
508 switch {
509 case err == nil:
510 err = h.checkHandle(dst)
511+ if err == nil {
512+ err = h.guardHandle(dst, true)
513+ }
514 windows.CloseHandle(dst)
515 if err != nil {
516 return err
517@@ -488,7 +551,7 @@ func (h *rootedHandlers) setstat(r *sftp.Request) error {
518 if flags.Size {
519 access |= windows.FILE_WRITE_DATA
520 }
521- parent, fh, err := h.openChecked(r.Filepath, access, 0)
522+ parent, fh, err := h.openChecked(r.Filepath, access, 0, false)
523 if err != nil {
524 return err
525 }