跳到主要内容

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

浏览文件

0007-name-folding-fuzz.patch

485 行 · 14.4 KB历史下载
1diff --git a/go.mod b/go.mod
2index 252115b..1226b15 100644
3--- a/go.mod
4+++ b/go.mod
5@@ -7,6 +7,7 @@ require (
6 github.com/sirupsen/logrus v1.9.4
7 github.com/urfave/cli/v2 v2.27.7
8 golang.org/x/sys v0.47.0
9+ golang.org/x/text v0.42.0
10 )
11
12 require (
13diff --git a/pkg/reversesshfs/fold.go b/pkg/reversesshfs/fold.go
14new file mode 100644
15index 0000000..64c778e
16--- /dev/null
17+++ b/pkg/reversesshfs/fold.go
18@@ -0,0 +1,52 @@
19+package reversesshfs
20+
21+import (
22+ "strings"
23+ "unicode"
24+
25+ "golang.org/x/text/cases"
26+ "golang.org/x/text/unicode/norm"
27+)
28+
29+// FoldName is s as a case-insensitive or normalization-insensitive file system compares it, or wider:
30+// two names such a file system takes as one entry have the same FoldName.
31+//
32+// It drops the default-ignorable code points (HFS+ and the casefold feature of ext4, f2fs and tmpfs ignore
33+// them; git's utf8.c has HFS+'s list), canonically decomposes (APFS, HFS+ and casefold ignore
34+// normalization) and fully case-folds (APFS folds "ß" as "ss"). Dotless "ı" is "i", as in NTFS's
35+// upcase table. Names that differ only in these ways are the same name here, even where the
36+// host's file system keeps them apart: that only makes more paths protected.
37+//
38+// Not covered: a code point the file system's Unicode tables know and Go's do not (the kernel's are older),
39+// and a volume with a customized NTFS upcase table. On Windows the protection does not rest on this
40+// alone: handles are checked by their normalized names.
41+func FoldName(s string) string {
42+ if isPlainASCII(s) {
43+ return strings.ToLower(s)
44+ }
45+ s = strings.Map(foldRune, s)
46+ s = norm.NFD.String(cases.Fold().String(norm.NFD.String(s)))
47+ return strings.Map(foldRune, s)
48+}
49+
50+func isPlainASCII(s string) bool {
51+ for i := 0; i < len(s); i++ {
52+ if s[i] >= 0x80 {
53+ return false
54+ }
55+ }
56+ return true
57+}
58+
59+// foldRune drops what is ignorable in a name, and maps dotless i.
60+func foldRune(r rune) rune {
61+ switch {
62+ case r == 'ı':
63+ return 'i'
64+ case r < 0x80:
65+ return r
66+ case unicode.Is(unicode.Cf, r), unicode.Is(unicode.Variation_Selector, r), unicode.Is(unicode.Other_Default_Ignorable_Code_Point, r):
67+ return -1
68+ }
69+ return r
70+}
71diff --git a/pkg/reversesshfs/rooted.go b/pkg/reversesshfs/rooted.go
72index d3d3a5b..d135e58 100644
73--- a/pkg/reversesshfs/rooted.go
74+++ b/pkg/reversesshfs/rooted.go
75@@ -8,6 +8,7 @@ import (
76 "io"
77 "os"
78 "path"
79+ "slices"
80 "strings"
81 "sync"
82 "time"
83@@ -28,6 +29,7 @@ type rootedHandlers struct {
84 root *os.Root
85 readonly bool
86 readonlyNames []string
87+ foldedNames []string // readonlyNames as FoldName gives them
88 rootedSys
89
90 mu sync.Mutex
91@@ -58,6 +60,9 @@ func newRootedServer(rwc io.ReadWriteCloser, localPath string, readonly bool, re
92 rootedSys: sys,
93 noopRemovals: make(map[string]time.Time),
94 }
95+ for _, n := range readonlyNames {
96+ h.foldedNames = append(h.foldedNames, FoldName(n))
97+ }
98 handlers := sftp.Handlers{FileGet: h, FilePut: h, FileCmd: h, FileList: h}
99 // Sequential, as OpenSSH's sftp-server: otherwise two writes to the same range, or a write
100 // and the FSTAT or FSETSTAT sent after it, can run in either order.
101@@ -136,27 +141,18 @@ func (h *rootedHandlers) writableRel(p string) (string, error) {
102
103 func (h *rootedHandlers) isReadonlyName(rel string) bool {
104 for _, c := range strings.Split(rel, "/") {
105- for _, name := range h.readonlyNames {
106- if sameName(c, name) {
107- return true
108- }
109+ fc := FoldName(c)
110+ if slices.Contains(h.foldedNames, fc) {
111+ return true
112 }
113 }
114 return false
115 }
116
117 // sameName reports whether a file name may refer to the same entry as name
118-// on a case-insensitive (APFS, HFS+, NTFS) file system.
119-// The ignored code points are the ones listed in next_hfs_char() of git's utf8.c.
120+// on a case-insensitive (APFS, HFS+, NTFS, casefold ext4) file system.
121 func sameName(s, name string) bool {
122- s = strings.Map(func(r rune) rune {
123- switch {
124- case r >= 0x200c && r <= 0x200f, r >= 0x202a && r <= 0x202e, r >= 0x206a && r <= 0x206f, r == 0xfeff:
125- return -1
126- }
127- return r
128- }, s)
129- return strings.EqualFold(s, name)
130+ return FoldName(s) == FoldName(name)
131 }
132
133 // Fileread implements sftp.FileReader.
134diff --git a/pkg/reversesshfs/rooted_casefold_linux_test.go b/pkg/reversesshfs/rooted_casefold_linux_test.go
135new file mode 100644
136index 0000000..e81abec
137--- /dev/null
138+++ b/pkg/reversesshfs/rooted_casefold_linux_test.go
139@@ -0,0 +1,61 @@
140+//go:build linux
141+
142+package reversesshfs
143+
144+import (
145+ "os"
146+ "os/exec"
147+ "path/filepath"
148+ "strings"
149+ "testing"
150+)
151+
152+// Every spelling of ".git" that a casefold directory (ext4, f2fs, tmpfs with the feature) takes as
153+// the same entry is the same name for sameName. The directory is made under $CASEFOLD_DIR, or the
154+// temporary folder; the test is skipped where that is not a file system with the feature.
155+// To get one: mke2fs -t ext4 -O casefold -E encoding=utf8 image, mounted.
156+func TestSameNameCasefold(t *testing.T) {
157+ if testing.Short() {
158+ t.Skip("short")
159+ }
160+ base := os.Getenv("CASEFOLD_DIR")
161+ if base == "" {
162+ base = t.TempDir()
163+ }
164+ dir := filepath.Join(base, "cf")
165+ if err := os.MkdirAll(dir, 0o755); err != nil {
166+ t.Skip(err)
167+ }
168+ t.Cleanup(func() { os.RemoveAll(dir) })
169+ if out, err := exec.Command("chattr", "+F", dir).CombinedOutput(); err != nil {
170+ t.Skipf("no casefold directory here: %v: %s", err, out)
171+ }
172+ if err := os.Mkdir(filepath.Join(dir, ".git"), 0o755); err != nil {
173+ t.Fatal(err)
174+ }
175+ if _, err := os.Lstat(filepath.Join(dir, ".GIT")); err != nil {
176+ t.Skip("the directory is case sensitive")
177+ }
178+ var found int
179+ for r := rune(0x80); r <= 0x10ffff; r++ {
180+ if r >= 0xd800 && r <= 0xdfff {
181+ continue
182+ }
183+ s := string(r)
184+ for _, name := range []string{".g" + s + "it", ".gi" + s + "t", ".git" + s, s + ".git", s + "git", ".g" + s + "t", ".gi" + s, "." + s + "it"} {
185+ if strings.Contains(name, "/") {
186+ continue
187+ }
188+ if _, err := os.Lstat(filepath.Join(dir, name)); err != nil {
189+ continue
190+ }
191+ found++
192+ if !sameName(name, ".git") {
193+ t.Errorf("%+q is .git on this file system, and sameName says it is not", name)
194+ }
195+ }
196+ }
197+ if found == 0 {
198+ t.Error("no spelling found: the test does not reach the file system")
199+ }
200+}
201diff --git a/pkg/reversesshfs/rooted_fold_test.go b/pkg/reversesshfs/rooted_fold_test.go
202new file mode 100644
203index 0000000..f6c8bb1
204--- /dev/null
205+++ b/pkg/reversesshfs/rooted_fold_test.go
206@@ -0,0 +1,48 @@
207+//go:build linux || darwin || windows
208+
209+package reversesshfs
210+
211+import (
212+ "testing"
213+)
214+
215+func TestFoldNameIgnorables(t *testing.T) {
216+ // Spellings that a casefold ext4, f2fs or tmpfs, or HFS+, takes as ".git".
217+ for _, r := range []rune{
218+ 0x200b, 0x200c, 0x200d, 0x200e, 0x200f, 0x202a, 0x202e, 0x2060, 0x2061, 0x2064, 0x206a, 0x206f, 0xfeff,
219+ 0xad, 0x34f, 0x61c, 0x115f, 0x1160, 0x17b4, 0x17b5, 0x180b, 0x180e, 0x180f, 0x3164, 0xfe00, 0xfe0f, 0xffa0,
220+ 0xfff0, 0xe0001, 0xe0020, 0xe0100, 0xe01ef,
221+ } {
222+ s := string(r)
223+ for _, name := range []string{".g" + s + "it", ".gi" + s + "t", ".git" + s, s + ".git", ".GIT" + s} {
224+ if !sameName(name, ".git") {
225+ t.Errorf("%+q should match .git", name)
226+ }
227+ }
228+ }
229+ // Dotless i is "i" in NTFS's upcase table; long s folds to s.
230+ if !sameName(".gıt", ".git") || !sameName("ſrc", "src") {
231+ t.Error("dotless i or long s")
232+ }
233+ for _, name := range []string{".gt", ".gitt", ".gi.t", ".ǵit", ".g it"} {
234+ if sameName(name, ".git") {
235+ t.Errorf("%+q should not match .git", name)
236+ }
237+ }
238+}
239+
240+func FuzzFoldIgnorables(f *testing.F) {
241+ for _, s := range []string{".git", ".g​it", "Aㅤb", "é", "é"} {
242+ f.Add(s, uint8(1))
243+ }
244+ f.Fuzz(func(t *testing.T, s string, at uint8) {
245+ // An ignorable code point anywhere changes nothing.
246+ i := int(at) % (len(s) + 1)
247+ for i > 0 && i < len(s) && s[i]&0xc0 == 0x80 {
248+ i--
249+ }
250+ if got, want := FoldName(s[:i]+"​️ㅤ"+s[i:]), FoldName(s); got != want {
251+ t.Errorf("FoldName(%q with ignorables at %d) = %q, want %q", s, i, got, want)
252+ }
253+ })
254+}
255diff --git a/pkg/reversesshfs/rooted_fuzz_test.go b/pkg/reversesshfs/rooted_fuzz_test.go
256new file mode 100644
257index 0000000..cd328e9
258--- /dev/null
259+++ b/pkg/reversesshfs/rooted_fuzz_test.go
260@@ -0,0 +1,196 @@
261+//go:build linux || darwin || windows
262+
263+package reversesshfs
264+
265+import (
266+ "io"
267+ "os"
268+ "path/filepath"
269+ "strings"
270+ "testing"
271+ "unicode/utf8"
272+)
273+
274+var sameNameSeeds = [][2]string{
275+ {".git", ".GIT"},
276+ {".git", ".g" + zwnj + "it"},
277+ {".git", bom + ".git"},
278+ {"café", "café"},
279+ {"glass", "glaß"},
280+ {"k", "K"},
281+ {"hooks", "HOOKS"},
282+ {".husky", ".Husky"},
283+ {"tools", "toòls"},
284+}
285+
286+// Whatever the host's file system takes as the same entry, sameName must
287+// too: otherwise the client writes a read-only name under another spelling.
288+// The file system decides: on a case-sensitive one, only identical names
289+// meet; on macOS and Windows, case, normalization and ignored code points.
290+func FuzzSameNameFS(f *testing.F) {
291+ for _, s := range sameNameSeeds {
292+ f.Add(s[0], s[1])
293+ }
294+ dir := f.TempDir()
295+ f.Fuzz(func(t *testing.T, name, other string) {
296+ if !utf8.ValidString(name) || !utf8.ValidString(other) || !plainName(name) || !plainName(other) {
297+ return
298+ }
299+ d, err := os.MkdirTemp(dir, "")
300+ if err != nil {
301+ t.Fatal(err)
302+ }
303+ defer os.RemoveAll(d)
304+ if err := os.Mkdir(filepath.Join(d, name), 0o755); err != nil {
305+ return // a name this file system refuses
306+ }
307+ a, err := os.Stat(filepath.Join(d, name))
308+ if err != nil {
309+ t.Fatal(err)
310+ }
311+ b, err := os.Stat(filepath.Join(d, other))
312+ if err != nil || !os.SameFile(a, b) {
313+ return
314+ }
315+ if !sameName(other, name) {
316+ t.Errorf("%q opens %q on this file system, and sameName says it does not", other, name)
317+ }
318+ })
319+}
320+
321+// A name in one path component, which the file system takes as itself.
322+func plainName(s string) bool {
323+ return s != "" && s != "." && s != ".." && len(s) < 200 && !strings.ContainsAny(s, "/\\:\x00") &&
324+ !strings.HasSuffix(s, ".") && !strings.HasSuffix(s, " ")
325+}
326+
327+// FuzzRootedOps plays a hostile client: any sequence of requests, on paths
328+// made of "..", symlinks, absolute paths and spellings of .git. Whatever it
329+// sends, nothing outside the root changes or is read, and .git stays as it
330+// was.
331+func FuzzRootedOps(f *testing.F) {
332+ for _, seed := range [][]byte{
333+ {0, 3, 1, 2, 5}, // write .git/config
334+ {5, 9, 0, 4, 7, 2, 6, 0},
335+ {6, 2, 2, 3, 1, 0, 0, 9, 3},
336+ {7, 8, 10, 0, 12, 1, 1, 0},
337+ {3, 9, 2, 0, 0, 11, 10, 0, 0, 13},
338+ } {
339+ f.Add(seed)
340+ }
341+ f.Fuzz(func(t *testing.T, ops []byte) {
342+ if len(ops) > 64 {
343+ return
344+ }
345+ c, root := setupRooted(t, false)
346+ secretDir := filepath.Join(filepath.Dir(root), "secret-dir")
347+ if err := os.MkdirAll(secretDir, 0o755); err != nil {
348+ t.Fatal(err)
349+ }
350+ // Told apart by its size: the client writes 3 bytes at a time.
351+ secret := strings.Repeat("SECRET", 200)[:1000]
352+ if err := os.WriteFile(filepath.Join(secretDir, "s"), []byte(secret), 0o644); err != nil {
353+ t.Fatal(err)
354+ }
355+ comps := []string{"", ".", "..", ".git", ".GIT", ".g" + zwnj + "it", "hooks", "config", "src", "gitlink", "configlink", "outside", "secret-dir", "s", "x"}
356+ bases := []string{"", root + "/", "/", filepath.Dir(root) + "/"}
357+ next := func() byte {
358+ if len(ops) == 0 {
359+ return 0
360+ }
361+ b := ops[0]
362+ ops = ops[1:]
363+ return b
364+ }
365+ pathOf := func() string {
366+ b := next()
367+ p := bases[int(b>>4)%len(bases)]
368+ for i := 0; i <= int(b&3); i++ {
369+ if i > 0 {
370+ p += "/"
371+ }
372+ p += comps[int(next())%len(comps)]
373+ }
374+ if p == "" {
375+ p = "."
376+ }
377+ return p
378+ }
379+ seen := func(b []byte) {
380+ if strings.Contains(string(b), "SECRET") {
381+ t.Fatalf("read a file outside the root: %q", b)
382+ }
383+ }
384+ for len(ops) > 0 {
385+ switch next() % 13 {
386+ case 0:
387+ if fh, err := c.OpenFile(pathOf(), os.O_WRONLY|os.O_CREATE|os.O_TRUNC); err == nil {
388+ fh.Write([]byte("PWN"))
389+ fh.Close()
390+ }
391+ case 1:
392+ if fh, err := c.OpenFile(pathOf(), os.O_WRONLY|os.O_APPEND); err == nil {
393+ fh.Write([]byte("PWN"))
394+ fh.Close()
395+ }
396+ case 2:
397+ if fh, err := c.Open(pathOf()); err == nil {
398+ b, _ := io.ReadAll(fh)
399+ fh.Close()
400+ seen(b)
401+ }
402+ case 3:
403+ c.Mkdir(pathOf())
404+ case 4:
405+ c.Remove(pathOf())
406+ case 5:
407+ c.PosixRename(pathOf(), pathOf())
408+ case 6:
409+ c.Rename(pathOf(), pathOf())
410+ case 7:
411+ c.Symlink(pathOf(), pathOf())
412+ case 8:
413+ c.Link(pathOf(), pathOf())
414+ case 9:
415+ c.Chmod(pathOf(), 0o777)
416+ case 10:
417+ c.Truncate(pathOf(), 0)
418+ case 11:
419+ if ents, err := c.ReadDir(pathOf()); err == nil {
420+ for _, e := range ents {
421+ if e.Size() == int64(len(secret)) {
422+ t.Fatalf("listed a folder outside the root")
423+ }
424+ }
425+ }
426+ case 12:
427+ if l, err := c.ReadLink(pathOf()); err == nil {
428+ seen([]byte(l))
429+ }
430+ }
431+ }
432+ assertUnchanged(t, root)
433+ if b, err := os.ReadFile(filepath.Join(secretDir, "s")); err != nil || string(b) != secret {
434+ t.Fatalf("secret-dir/s changed: %q, %v", b, err)
435+ }
436+ if ents, err := os.ReadDir(secretDir); err != nil || len(ents) != 1 {
437+ t.Fatalf("secret-dir changed: %v, %v", ents, err)
438+ }
439+ })
440+}
441+
442+// agent-vm decides which names to give from strings.EqualFold: every name it
443+// takes as the same, the server must take as the same too.
444+func FuzzSameNameEqualFold(f *testing.F) {
445+ for _, s := range sameNameSeeds {
446+ f.Add(s[0], s[1])
447+ }
448+ f.Fuzz(func(t *testing.T, a, b string) {
449+ if strings.EqualFold(a, b) && !sameName(a, b) {
450+ t.Errorf("EqualFold(%q, %q), and sameName says they differ", a, b)
451+ }
452+ if sameName(a, b) != sameName(b, a) {
453+ t.Errorf("sameName(%q, %q) is not symmetric", a, b)
454+ }
455+ })
456+}
457diff --git a/pkg/reversesshfs/rooted_test.go b/pkg/reversesshfs/rooted_test.go
458index 945d244..01fe96a 100644
459--- a/pkg/reversesshfs/rooted_test.go
460+++ b/pkg/reversesshfs/rooted_test.go
461@@ -678,4 +678,16 @@ func TestSameName(t *testing.T) {
462 t.Errorf("%q should not match .git", s)
463 }
464 }
465+ // Names APFS takes as one: either normalization, full case folding.
466+ for _, c := range [][2]string{
467+ {"café", "café"},
468+ {"CAFÉ", "café"},
469+ {"glaß", "glass"},
470+ {"GLASS", "glaß"},
471+ {"K", "k"}, // KELVIN SIGN
472+ } {
473+ if !sameName(c[0], c[1]) {
474+ t.Errorf("%q should match %q", c[0], c[1])
475+ }
476+ }
477 }
478diff --git a/pkg/reversesshfs/testdata/fuzz/FuzzRootedOps/4bd352fd398dba68 b/pkg/reversesshfs/testdata/fuzz/FuzzRootedOps/4bd352fd398dba68
479new file mode 100644
480index 0000000..ba58ab5
481--- /dev/null
482+++ b/pkg/reversesshfs/testdata/fuzz/FuzzRootedOps/4bd352fd398dba68
483@@ -0,0 +1,2 @@
484+go test fuzz v1
485+[]byte("7A00")