跳到主要内容

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

浏览文件

0001-mounts-add-sshfs.readonlyNames.patch

426 行 · 18.2 KB历史下载
1From c9a1b6c423390fcfe60a106c8b985b011045fd9a Mon Sep 17 00:00:00 2001
2From: Sylvain Zimmer <[email protected]>
3Date: Wed, 23 Sep 2026 22:56:03 +0200
4Subject: [PATCH 1/2] mounts: add sshfs.readonlyNames
5
6A writable project mount lets the guest write .git/hooks or .git/config,
7which then run on the host the next time git is used in the project.
8
9sshfs.readonlyNames lists file names that the guest cannot modify, at
10any depth of the mount. The builtin SFTP server of sshocker enforces
11it on the host, so it holds against a compromised guest.
12
13Validation requires mountType reverse-sshfs, and sftpDriver builtin on
14every mount, because the OpenSSH sftp-server serves any host path to
15the guest. It also rejects entries that are not plain file names.
16
17A writable mount of a folder that holds another writable mount reaches
18the inner one's files too, so it must list the same names.
19
20Assisted-by: Claude Opus 5.5 (1M context) <[email protected]>
21Signed-off-by: Sylvain Zimmer <[email protected]>
22---
23 pkg/hostagent/mount.go | 1
24 pkg/limatmpl/embed.go | 4 +
25 pkg/limatmpl/embed_test.go | 4 +
26 pkg/limatype/lima_yaml.go | 2 +
27 pkg/limayaml/defaults.go | 3 +
28 pkg/limayaml/defaults_test.go | 2 +
29 pkg/limayaml/validate.go | 54 +++++++++++++++++++
30 pkg/limayaml/validate_test.go | 89 +++++++++++++++++++++++++++++++
31 templates/default.yaml | 5 ++
32 website/content/en/docs/config/mount.md | 33 +++++++++++
33 website/content/en/docs/examples/ai.md | 47 ++++++++++++++++
34 11 files changed, 241 insertions(+), 3 deletions(-)
35
36diff --git a/pkg/hostagent/mount.go b/pkg/hostagent/mount.go
37index 4bc058f2..ebc4b77c 100644
38--- a/pkg/hostagent/mount.go
39+++ b/pkg/hostagent/mount.go
40@@ -91,6 +91,7 @@ func (a *HostAgent) setupMount(ctx context.Context, m limatype.Mount) (*mount, e
41 Port: sshPort,
42 RemotePath: *m.MountPoint,
43 Readonly: !(*m.Writable),
44+ ReadonlyNames: m.SSHFS.ReadonlyNames,
45 SSHFSAdditionalArgs: []string{"-o", sshfsOptions},
46 }
47 if runtime.GOOS == "windows" {
48diff --git a/pkg/limatmpl/embed.go b/pkg/limatmpl/embed.go
49index c269d41c..7ef2e999 100644
50--- a/pkg/limatmpl/embed.go
51+++ b/pkg/limatmpl/embed.go
52@@ -466,6 +466,10 @@ func (tmpl *Template) combineMounts() {
53 tmpl.copyListEntryField(mounts, dst, src, "sshfs.sftpDriver")
54 dest.SSHFS.SFTPDriver = mount.SSHFS.SFTPDriver
55 }
56+ if dest.SSHFS.ReadonlyNames == nil && mount.SSHFS.ReadonlyNames != nil {
57+ tmpl.copyListEntryField(mounts, dst, src, "sshfs.readonlyNames")
58+ dest.SSHFS.ReadonlyNames = mount.SSHFS.ReadonlyNames
59+ }
60 // NineP
61 if dest.NineP.SecurityModel == nil && mount.NineP.SecurityModel != nil {
62 tmpl.copyListEntryField(mounts, dst, src, "9p.securityModel")
63diff --git a/pkg/limatmpl/embed_test.go b/pkg/limatmpl/embed_test.go
64index c3d5916d..c9776854 100644
65--- a/pkg/limatmpl/embed_test.go
66+++ b/pkg/limatmpl/embed_test.go
67@@ -189,8 +189,8 @@ mounts:
68 // This entry can be deleted when the previous one no longer fails
69 "mounts append, but merge fields on shared mountPoint (no comments version)",
70 `mounts: [{location: loc1}, {location: loc1, mountPoint: loc2}]`,
71- `mounts: [{location: loc1, mountPoint: loc2, writable: true, sshfs: {followSymlinks: true}}, {location: loc1, mountPoint: loc3, writable: true}]`,
72- `mounts: [{location: loc1}, {location: loc1, mountPoint: loc2, writable: true, sshfs: {followSymlinks: true}}, {location: loc1, mountPoint: loc3, writable: true}]`,
73+ `mounts: [{location: loc1, mountPoint: loc2, writable: true, sshfs: {followSymlinks: true, readonlyNames: [.git]}}, {location: loc1, mountPoint: loc3, writable: true}]`,
74+ `mounts: [{location: loc1}, {location: loc1, mountPoint: loc2, writable: true, sshfs: {followSymlinks: true, readonlyNames: [.git]}}, {location: loc1, mountPoint: loc3, writable: true}]`,
75 },
76 {
77 "template: URLs are not embedded when embedAll is false",
78diff --git a/pkg/limatype/lima_yaml.go b/pkg/limatype/lima_yaml.go
79index f0d53fb2..a155e40c 100644
80--- a/pkg/limatype/lima_yaml.go
81+++ b/pkg/limatype/lima_yaml.go
82@@ -186,6 +186,8 @@ type SSHFS struct {
83 Cache *bool `yaml:"cache,omitempty" json:"cache,omitempty" jsonschema:"nullable"`
84 FollowSymlinks *bool `yaml:"followSymlinks,omitempty" json:"followSymlinks,omitempty" jsonschema:"nullable"`
85 SFTPDriver *SFTPDriver `yaml:"sftpDriver,omitempty" json:"sftpDriver,omitempty" jsonschema:"nullable"`
86+ // ReadonlyNames makes every path with a component matching one of these names read-only.
87+ ReadonlyNames []string `yaml:"readonlyNames,omitempty" json:"readonlyNames,omitempty"`
88 }
89
90 type NineP struct {
91diff --git a/pkg/limayaml/defaults.go b/pkg/limayaml/defaults.go
92index 28492d2b..1984575b 100644
93--- a/pkg/limayaml/defaults.go
94+++ b/pkg/limayaml/defaults.go
95@@ -767,6 +767,9 @@ func FillDefault(ctx context.Context, y, d, o *limatype.LimaYAML, filePath strin
96 if mount.SSHFS.SFTPDriver != nil {
97 mounts[i].SSHFS.SFTPDriver = mount.SSHFS.SFTPDriver
98 }
99+ if mount.SSHFS.ReadonlyNames != nil {
100+ mounts[i].SSHFS.ReadonlyNames = mount.SSHFS.ReadonlyNames
101+ }
102 if mount.NineP.SecurityModel != nil {
103 mounts[i].NineP.SecurityModel = mount.NineP.SecurityModel
104 }
105diff --git a/pkg/limayaml/defaults_test.go b/pkg/limayaml/defaults_test.go
106index 916e4d8a..e6666be8 100644
107--- a/pkg/limayaml/defaults_test.go
108+++ b/pkg/limayaml/defaults_test.go
109@@ -621,6 +621,7 @@ func TestFillDefault(t *testing.T) {
110 SSHFS: limatype.SSHFS{
111 Cache: new(false),
112 FollowSymlinks: new(true),
113+ ReadonlyNames: []string{".git"},
114 },
115 NineP: limatype.NineP{
116 SecurityModel: new("mapped-file"),
117@@ -724,6 +725,7 @@ func TestFillDefault(t *testing.T) {
118 expect.Mounts[0].Writable = new(true)
119 expect.Mounts[0].SSHFS.Cache = new(false)
120 expect.Mounts[0].SSHFS.FollowSymlinks = new(true)
121+ expect.Mounts[0].SSHFS.ReadonlyNames = []string{".git"}
122 expect.Mounts[0].NineP.SecurityModel = new("mapped-file")
123 expect.Mounts[0].NineP.ProtocolVersion = new("9p2000")
124 expect.Mounts[0].NineP.Msize = new("8KiB")
125diff --git a/pkg/limayaml/validate.go b/pkg/limayaml/validate.go
126index 5a6aaee0..33cefd5d 100644
127--- a/pkg/limayaml/validate.go
128+++ b/pkg/limayaml/validate.go
129@@ -178,6 +178,10 @@ func Validate(y *limatype.LimaYAML, warn bool) error {
130 }
131 }
132
133+ if err := validateReadonlyNames(y); err != nil {
134+ errs = errors.Join(errs, err)
135+ }
136+
137 if warn && runtime.GOOS != "linux" {
138 for i, mount := range y.Mounts {
139 if mount.Virtiofs.QueueSize != nil {
140@@ -654,6 +658,56 @@ func validateParamIsUsed(y *limatype.LimaYAML) error {
141 return nil
142 }
143
144+// validateReadonlyNames rejects configurations where `sshfs.readonlyNames` would not be enforced on the host.
145+// Every mount must use the builtin SFTP driver, as the OpenSSH sftp-server lets a compromised guest
146+// access any host path, including the read-only ones of the other mounts.
147+func validateReadonlyNames(y *limatype.LimaYAML) error {
148+ used := slices.ContainsFunc(y.Mounts, func(m limatype.Mount) bool { return len(m.SSHFS.ReadonlyNames) > 0 })
149+ if !used {
150+ return nil
151+ }
152+ var errs error
153+ if y.MountType == nil || *y.MountType != limatype.REVSSHFS {
154+ errs = errors.Join(errs, fmt.Errorf("field `mounts[*].sshfs.readonlyNames` requires `mountType` to be %#q", limatype.REVSSHFS))
155+ }
156+ for i, m := range y.Mounts {
157+ if m.SSHFS.SFTPDriver == nil || *m.SSHFS.SFTPDriver != limatype.SFTPDriverBuiltin {
158+ errs = errors.Join(errs, fmt.Errorf("field `mounts[%d].sshfs.sftpDriver` must be %#q when any mount sets `sshfs.readonlyNames`", i, limatype.SFTPDriverBuiltin))
159+ }
160+ for _, name := range m.SSHFS.ReadonlyNames {
161+ if name == "" || name == "." || name == ".." || strings.ContainsAny(name, `/\`) {
162+ errs = errors.Join(errs, fmt.Errorf("field `mounts[%d].sshfs.readonlyNames` must contain file names, got %#q", i, name))
163+ }
164+ }
165+ }
166+ // A writable mount of a folder holding another writable mount reaches
167+ // its files too: it has to protect the same names.
168+ for i, outer := range y.Mounts {
169+ for j, inner := range y.Mounts {
170+ if i == j || outer.Writable == nil || !*outer.Writable || inner.Writable == nil || !*inner.Writable ||
171+ !isWithin(outer.Location, inner.Location) {
172+ continue
173+ }
174+ for _, name := range inner.SSHFS.ReadonlyNames {
175+ if !slices.Contains(outer.SSHFS.ReadonlyNames, name) {
176+ errs = errors.Join(errs, fmt.Errorf("field `mounts[%d].sshfs.readonlyNames` must contain %#q, as the writable mount `mounts[%d]` inside it does", i, name, j))
177+ }
178+ }
179+ }
180+ }
181+ return errs
182+}
183+
184+// isWithin reports whether the folder child is parent or under it. Case is
185+// ignored where the file systems usually do.
186+func isWithin(parent, child string) bool {
187+ if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
188+ parent, child = strings.ToLower(parent), strings.ToLower(child)
189+ }
190+ rel, err := filepath.Rel(parent, child)
191+ return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))
192+}
193+
194 func validatePort(field string, port int) error {
195 switch {
196 case port < 0:
197diff --git a/pkg/limayaml/validate_test.go b/pkg/limayaml/validate_test.go
198index 38c3503f..8040c296 100644
199--- a/pkg/limayaml/validate_test.go
200+++ b/pkg/limayaml/validate_test.go
201@@ -5,6 +5,8 @@ package limayaml
202
203 import (
204 "fmt"
205+ "os"
206+ "path/filepath"
207 "runtime"
208 "testing"
209
210@@ -302,6 +304,93 @@ additionalDisks:
211 assert.Error(t, err, "field `additionalDisks[0].name is invalid`: identifier must not be empty")
212 }
213
214+func TestValidateReadonlyNames(t *testing.T) {
215+ images := `images: [{"location": "/"}]`
216+ dir1, dir2 := t.TempDir(), t.TempDir()
217+ mounts := func(sshfs1, sshfs2 string) string {
218+ return fmt.Sprintf("mounts: [{location: %q, writable: true, sshfs: %s}, {location: %q, sshfs: %s}]", dir1, sshfs1, dir2, sshfs2)
219+ }
220+ builtin := "{sftpDriver: builtin}"
221+ protected := "{sftpDriver: builtin, readonlyNames: [.git]}"
222+ tests := []struct {
223+ name string
224+ config string
225+ wantErr string
226+ }{
227+ {
228+ name: "valid",
229+ config: "mountType: reverse-sshfs\n" + mounts(protected, builtin),
230+ },
231+ {
232+ name: "virtiofs",
233+ config: "mountType: virtiofs\n" + mounts(protected, builtin),
234+ wantErr: "field `mounts[*].sshfs.readonlyNames` requires `mountType` to be `reverse-sshfs`",
235+ },
236+ {
237+ name: "default driver",
238+ config: "mountType: reverse-sshfs\n" + mounts("{readonlyNames: [.git]}", builtin),
239+ wantErr: "field `mounts[0].sshfs.sftpDriver` must be `builtin` when any mount sets `sshfs.readonlyNames`",
240+ },
241+ {
242+ name: "other mount with openssh-sftp-server",
243+ config: "mountType: reverse-sshfs\n" + mounts(protected, "{sftpDriver: openssh-sftp-server}"),
244+ wantErr: "field `mounts[1].sshfs.sftpDriver` must be `builtin` when any mount sets `sshfs.readonlyNames`",
245+ },
246+ {
247+ name: "path instead of name",
248+ config: "mountType: reverse-sshfs\n" + mounts("{sftpDriver: builtin, readonlyNames: [.git/hooks]}", builtin),
249+ wantErr: "field `mounts[0].sshfs.readonlyNames` must contain file names, got `.git/hooks`",
250+ },
251+ }
252+ for _, tt := range tests {
253+ t.Run(tt.name, func(t *testing.T) {
254+ y, err := Load(t.Context(), []byte(tt.config+"\n"+images), "lima.yaml")
255+ assert.NilError(t, err)
256+ err = Validate(y, false)
257+ if tt.wantErr == "" {
258+ assert.NilError(t, err)
259+ } else {
260+ assert.Error(t, err, tt.wantErr)
261+ }
262+ })
263+ }
264+}
265+
266+// A writable mount of a parent folder must protect the names of the writable
267+// mounts inside it.
268+func TestValidateReadonlyNamesNested(t *testing.T) {
269+ images := `images: [{"location": "/"}]`
270+ parent := t.TempDir()
271+ child := filepath.Join(parent, "child")
272+ assert.NilError(t, os.Mkdir(child, 0o755))
273+ protected := "{sftpDriver: builtin, readonlyNames: [.git]}"
274+ builtin := "{sftpDriver: builtin}"
275+ config := func(parentWritable bool, parentSSHFS string) string {
276+ return fmt.Sprintf("mountType: reverse-sshfs\nmounts: [{location: %q, writable: true, sshfs: %s}, {location: %q, writable: %v, sshfs: %s}]",
277+ child, protected, parent, parentWritable, parentSSHFS)
278+ }
279+ for _, tt := range []struct {
280+ name string
281+ config string
282+ wantErr string
283+ }{
284+ {"parent protects the same names", config(true, protected), ""},
285+ {"parent is read-only", config(false, builtin), ""},
286+ {"parent writes .git", config(true, builtin), "field `mounts[1].sshfs.readonlyNames` must contain `.git`, as the writable mount `mounts[0]` inside it does"},
287+ } {
288+ t.Run(tt.name, func(t *testing.T) {
289+ y, err := Load(t.Context(), []byte(tt.config+"\n"+images), "lima.yaml")
290+ assert.NilError(t, err)
291+ err = Validate(y, false)
292+ if tt.wantErr == "" {
293+ assert.NilError(t, err)
294+ } else {
295+ assert.Error(t, err, tt.wantErr)
296+ }
297+ })
298+ }
299+}
300+
301 func TestValidateParamName(t *testing.T) {
302 images := `images: [{"location": "/"}]`
303 validProvision := `provision: [{"script": "echo $PARAM_name $PARAM_NAME $PARAM_Name_123"}]`
304diff --git a/templates/default.yaml b/templates/default.yaml
305index bd00a66f..39caeb37 100644
306--- a/templates/default.yaml
307+++ b/templates/default.yaml
308@@ -81,6 +81,11 @@ mounts: []
309 # # SFTP driver, "builtin" or "openssh-sftp-server". "openssh-sftp-server" is recommended.
310 # # 🟢 Builtin default: "openssh-sftp-server" if OpenSSH SFTP Server binary is found, otherwise "builtin"
311 # sftpDriver: null
312+# # File names that are read-only at any depth, enforced by the host even against a compromised guest.
313+# # Requires `sftpDriver: builtin` on every mount, and a writable mount of a folder holding another
314+# # one must list the same names.
315+# # 🟢 Builtin default: []
316+# readonlyNames: []
317 # 9p:
318 # # Supported security models are "passthrough", "mapped-xattr", "mapped-file" and "none".
319 # # "mapped-xattr" and "mapped-file" are useful for persistent chown but incompatible with symlinks.
320diff --git a/website/content/en/docs/config/mount.md b/website/content/en/docs/config/mount.md
321index 8b9a177d..88d16af9 100644
322--- a/website/content/en/docs/config/mount.md
323+++ b/website/content/en/docs/config/mount.md
324@@ -65,9 +65,40 @@ Cygwin-based one. Only if that finds nothing does the generic search apply.
325 This matters when a Cygwin-based OpenSSH (Git for Windows, MSYS2) and the native Windows OpenSSH are both
326 installed. The host path handed to the server is always the native `C:/Users/USER` form, which both kinds resolve.
327
328+#### Read-only names
329+
330+`sshfs.readonlyNames` lists file names that the guest cannot modify, at any depth of the mount.
331+For example, `.git` keeps a repository's hooks and config out of reach of the guest, while the
332+working tree stays writable:
333+
334+```yaml
335+mountType: "reverse-sshfs"
336+mounts:
337+- location: "~/src/project"
338+ writable: true
339+ sshfs:
340+ sftpDriver: "builtin"
341+ readonlyNames: [".git"]
342+```
343+
344+This is enforced by the builtin SFTP server on the host, so it also holds against a compromised guest.
345+The server does not follow symlinks when writing, and matches names case-insensitively.
346+Reading is still allowed, so tools such as `git status` work in the guest, while `git commit` does not.
347+
348+[`mountInotify`](#mount-inotify) also works for read-only names: the server accepts setting the access and
349+modification times of such a file to its current modification time, without modifying the file.
350+
351+Every mount of the instance must use `sftpDriver: "builtin"`, as the OpenSSH SFTP server lets
352+a compromised guest access any host path.
353+
354+On Windows hosts, the server also denies 8.3 short names (e.g. `GIT~1`) and NTFS streams
355+(e.g. `.git::$INDEX_ALLOCATION`) of read-only names, and does not write through junctions.
356+The builtin SFTP driver does not support creating symlinks on Windows hosts.
357+
358 #### Caveats
359 - A mount is disabled when the SSH connection was shut down.
360-- A compromised `sshfs` process in the guest may have access to unexposed host directories.
361+- With `sftpDriver: "openssh-sftp-server"`, a compromised `sshfs` process in the guest may have access to unexposed host directories.
362+ The builtin driver only serves the mounted directory on Linux and macOS hosts.
363
364 ### 9p
365
366diff --git a/website/content/en/docs/examples/ai.md b/website/content/en/docs/examples/ai.md
367index 2d8b985e..65f84599 100644
368--- a/website/content/en/docs/examples/ai.md
369+++ b/website/content/en/docs/examples/ai.md
370@@ -131,6 +131,53 @@ See also <https://github.com/anomalyco/opencode>.
371 {{< /tabpane >}}
372
373
374+# Protecting `.git` from the agent
375+
376+ | ⚡ Requirement | Lima >= 2.3 |
377+ |----------------|-------------|
378+
379+A writable project mount lets the agent write `.git/hooks/*` or `.git/config` (e.g., `core.fsmonitor`),
380+which run on the host the next time you use `git` in the project.
381+`sshfs.readonlyNames` keeps the working tree writable, with live updates on both sides,
382+while `.git` stays read-only for the guest:
383+
384+```yaml
385+# agent.yaml
386+# Unlike template:default, this base does not mount the home directory.
387+base: template:_images/ubuntu
388+mountType: "reverse-sshfs"
389+mountInotify: true
390+mounts:
391+- location: "~/my-project"
392+ writable: true
393+ sshfs:
394+ sftpDriver: "builtin"
395+ readonlyNames: [".git"]
396+```
397+
398+```bash
399+limactl start --name=agent ./agent.yaml
400+cd ~/my-project
401+limactl shell agent claude
402+```
403+
404+The project must be the only host directory mounted in the guest, and every mount must use `sftpDriver: "builtin"`.
405+
406+This is enforced by the SFTP server running on the host, not by the guest, so it also holds when the agent gains root
407+in the guest.
408+`.git` is protected at any depth, including nested repositories and names differing only by case.
409+See [Filesystem mounts » Read-only names](../config/mount.md#read-only-names) for details.
410+
411+The agent can still read `.git` and run `git status`, `git diff` and `git log`, but not `git commit`.
412+Review and commit its changes from the host.
413+
414+Other files in the working tree remain writable by the agent, so be careful with files that tools run on the host:
415+- `core.hooksPath` pointing into the working tree (e.g., `.husky`)
416+- `.envrc` (direnv), `.vscode/tasks.json`, `Makefile`, `package.json` scripts, etc.
417+
418+Setting `git config --global safe.bareRepository explicit` on the host also prevents `git` from using a bare repository
419+that the agent could create outside of `.git`.
420+
421 # Syncing Working Directory
422
423 | ⚡ Requirement | Lima >= 2.1 |
424--
4252.47.3
426