跳到主要内容

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

浏览文件

rooted.go

471 行 · 13.7 KB历史下载
1//go:build linux || darwin || windows
2
3package reversesshfs
4
5import (
6 "encoding/binary"
7 "errors"
8 "io"
9 "os"
10 "path"
11 "path/filepath"
12 "slices"
13 "strings"
14 "sync"
15 "time"
16
17 "github.com/pkg/sftp"
18)
19
20// rootedHandlers serves only the files under rootPath.
21//
22// Reads go through os.Root, which follows symlinks but never outside the root.
23// Writes open the parent directory without following any symlink,
24// and are denied when any path component matches readonlyNames.
25// Following no symlink on writes is what prevents the client from
26// swapping a directory for a symlink into a read-only one.
27// The OS-specific part is in rootedSys.
28type rootedHandlers struct {
29 rootPath string // slash-separated, cleaned
30 root *os.Root
31 cloud bool // stricter checks for the remote desktop project transport
32 readonly bool
33 readonlyNames []string
34 foldedNames []string // readonlyNames as FoldName gives them
35 guardRoot string // the served directory as Guard is told
36 rootedSys
37
38 mu sync.Mutex // protects relay
39 relay *relay
40 now func() time.Time
41}
42
43// maxHandles bounds the files and directories a client keeps open.
44const maxHandles = 4096
45
46func newRootedServer(rwc io.ReadWriteCloser, localPath string, readonly bool, readonlyNames []string) (*sftp.RequestServer, *rootedHandlers, error) {
47 return newRootedServerAt(rwc, localPath, slashPath(localPath), readonly, readonlyNames)
48}
49
50func newRootedServerAt(rwc io.ReadWriteCloser, localPath, exportedPath string, readonly bool, readonlyNames []string) (*sftp.RequestServer, *rootedHandlers, error) {
51 root, err := os.OpenRoot(localPath)
52 if err != nil {
53 return nil, nil, err
54 }
55 sys, err := openRootedSys(localPath)
56 if err != nil {
57 root.Close()
58 return nil, nil, err
59 }
60 h := &rootedHandlers{
61 rootPath: exportedPath,
62 root: root,
63 readonly: readonly,
64 readonlyNames: readonlyNames,
65 guardRoot: filepath.Clean(localPath),
66 rootedSys: sys,
67 relay: newRelay(),
68 now: time.Now,
69 }
70 for _, n := range readonlyNames {
71 h.foldedNames = append(h.foldedNames, FoldName(n))
72 }
73 handlers := sftp.Handlers{FileGet: h, FilePut: h, FileCmd: h, FileList: h}
74 // Sequential, as OpenSSH's sftp-server: otherwise two writes to the same range, or a write
75 // and the FSTAT or FSETSTAT sent after it, can run in either order.
76 srv := sftp.NewRequestServer(rwc, handlers, sftp.WithStartDirectory(startDirectory(h.rootPath)), sftp.WithRSSequential(),
77 // Each handle holds a file descriptor of this process, which may be the one running the VM.
78 sftp.WithRSMaxHandles(maxHandles),
79 // sshfs reads up to 64 KiB (max_read), and takes a shorter answer for the end of the file.
80 sftp.WithRSMaxTxPacket(64*1024))
81 return srv, h, nil
82}
83
84func (h *rootedHandlers) Close() error {
85 return errors.Join(h.root.Close(), h.rootedSys.close())
86}
87
88// rel maps a request path to a path relative to the root.
89// The result has no "." or ".." component, except "." for the root itself.
90func (h *rootedHandlers) rel(p string) (string, error) {
91 if !path.IsAbs(p) {
92 p = path.Join(h.rootPath, p)
93 }
94 p = path.Clean(p)
95 if p == h.rootPath {
96 return ".", nil
97 }
98 prefix := h.rootPath
99 if prefix != "/" {
100 prefix += "/"
101 }
102 if r, ok := strings.CutPrefix(p, prefix); ok {
103 return r, nil
104 }
105 return "", errDenied
106}
107
108// writableRel is the path relative to the root of the request path p, if it may be written.
109// entry: see Guard.
110func (h *rootedHandlers) writableRel(p string, entry bool) (string, error) {
111 if h.readonly {
112 return "", errDenied
113 }
114 r, err := h.rel(p)
115 if err != nil {
116 return "", err
117 }
118 if h.isReadonlyName(r) || !writableName(r) || (h.cloud && 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.
140var Guard func(root, rel string, entry bool) bool
141
142func (h *rootedHandlers) guard(rel string, entry bool) error {
143 if !h.cloud && Guard != nil && !Guard(h.guardRoot, rel, entry) {
144 return errDenied
145 }
146 return nil
147}
148
149func (h *rootedHandlers) isReadonlyName(rel string) bool {
150 for _, c := range strings.Split(rel, "/") {
151 fc := FoldName(c)
152 if slices.Contains(h.foldedNames, fc) {
153 return true
154 }
155 }
156 return false
157}
158
159// sameName reports whether a file name may refer to the same entry as name
160// on a case-insensitive (APFS, HFS+, NTFS, casefold ext4) file system.
161func sameName(s, name string) bool {
162 return FoldName(s) == FoldName(name)
163}
164
165// Fileread implements sftp.FileReader.
166func (h *rootedHandlers) Fileread(r *sftp.Request) (io.ReaderAt, error) {
167 rel, err := h.rel(r.Filepath)
168 if err != nil {
169 return nil, err
170 }
171 f, err := h.openRead(rel)
172 if err != nil {
173 return nil, err
174 }
175 return f, nil
176}
177
178// openRead opens rel for reading, if it is a regular file or a directory.
179// Opening a FIFO, or a device, could block the server, which handles one request at a time.
180func (h *rootedHandlers) openRead(rel string) (*os.File, error) {
181 f, err := h.root.OpenFile(rel, os.O_RDONLY|openNonblock, 0)
182 if err != nil {
183 return nil, err
184 }
185 fi, err := f.Stat()
186 if err != nil {
187 f.Close()
188 return nil, err
189 }
190 if !fi.Mode().IsRegular() && !fi.IsDir() {
191 f.Close()
192 return nil, &os.PathError{Op: "open", Path: rel, Err: errDenied}
193 }
194 return f, nil
195}
196
197// writableFile is a file opened by openFile: checked against readonlyNames, without following symlinks.
198// FSETSTAT applies to it directly. Files opened for reading only may have been opened through a symlink
199// to a read-only name, so FSETSTAT on them goes through the path checks of setstat.
200type writableFile struct {
201 *os.File
202 appends bool // opened with SSH_FXF_APPEND
203}
204
205// WriteAt ignores off for a file opened with SSH_FXF_APPEND, and writes at the end of the file
206// as it is on the host, as OpenSSH's sftp-server does: the client computed off from the size it
207// knew, and the host may have grown the file since. Requests are processed in order, so writes keep theirs.
208func (f writableFile) WriteAt(b []byte, off int64) (int, error) {
209 if f.appends {
210 return appendWrite(f.File, b)
211 }
212 return f.File.WriteAt(b, off)
213}
214
215func (h *rootedHandlers) openWritable(r *sftp.Request) (writableFile, error) {
216 if !h.cloud && r.Pflags().Creat {
217 h.creating(r.Filepath)
218 }
219 f, err := h.openFile(r)
220 if err != nil {
221 return writableFile{}, err
222 }
223 return writableFile{File: f, appends: r.Pflags().Append}, nil
224}
225
226// Filewrite implements sftp.FileWriter.
227func (h *rootedHandlers) Filewrite(r *sftp.Request) (io.WriterAt, error) {
228 f, err := h.openWritable(r)
229 if err != nil {
230 return nil, err
231 }
232 return f, nil
233}
234
235// OpenFile implements sftp.OpenFileWriter.
236func (h *rootedHandlers) OpenFile(r *sftp.Request) (sftp.WriterAtReaderAt, error) {
237 f, err := h.openWritable(r)
238 if err != nil {
239 return nil, err
240 }
241 return f, nil
242}
243
244// permMask is the part of a mode the client may set: never setuid, setgid or sticky, which
245// would give a file the host runs the privileges of its owner.
246const permMask = 0o777
247
248// openMode returns the permissions sent with an Open request.
249// For Open, pkg/sftp puts the open flags in r.Flags and drops the attribute flags,
250// so r.AttrFlags and r.Attributes must not be used: SSH_FXF_APPEND reads as permissions.
251// Permissions alone are the only 4-byte attributes, which is what sshfs always sends.
252func openMode(r *sftp.Request) (uint32, bool) {
253 if len(r.Attrs) != 4 {
254 return 0, false
255 }
256 return binary.BigEndian.Uint32(r.Attrs) & permMask, true
257}
258
259// Filecmd implements sftp.FileCmder.
260func (h *rootedHandlers) Filecmd(r *sftp.Request) error {
261 switch r.Method {
262 case "Setstat":
263 // FSETSTAT: r.Filepath is where the file was opened, which may now be another file.
264 if f, ok := r.HandleFile().(writableFile); ok {
265 return h.fsetstat(f.File, r)
266 }
267 // A read handle keeps the path checks, but only for the file it is open on.
268 if f, ok := r.HandleFile().(*os.File); ok && !h.isOpenAt(f, r.Filepath) {
269 return &os.PathError{Op: "setstat", Path: r.Filepath, Err: os.ErrNotExist}
270 }
271 if h.isNoopTimes(r) {
272 return nil
273 }
274 return h.setstat(r)
275 case "Rename":
276 return h.renaming(r, true)
277 case "Link":
278 h.creating(r.Target)
279 return h.link(r)
280 case "Remove", "Rmdir":
281 // The guest agent removes a path deleted on the host, so that the guest emits IN_DELETE.
282 // The path may have been created again on the host since, so it must not be removed.
283 if h.consumeNoopRemoval(r.Filepath) {
284 return nil
285 }
286 h.removing(r.Filepath)
287 return h.removalFailed(r.Filepath, h.remove(r))
288 case "Mkdir":
289 h.creating(r.Filepath)
290 return h.mkdir(r)
291 case "Symlink":
292 h.creating(r.Target)
293 return h.symlink(r)
294 }
295 return sftp.ErrSSHFxOpUnsupported
296}
297
298// PosixRename implements sftp.PosixRenameFileCmder.
299func (h *rootedHandlers) PosixRename(r *sftp.Request) error {
300 return h.renaming(r, false)
301}
302
303func (h *rootedHandlers) renaming(r *sftp.Request, noReplace bool) error {
304 h.removing(r.Filepath)
305 h.creating(r.Target)
306 return h.removalFailed(r.Filepath, h.rename(r, noReplace))
307}
308
309// isOpenAt reports whether f is the file at p, a request path, without following a symlink at p.
310func (h *rootedHandlers) isOpenAt(f *os.File, p string) bool {
311 rel, err := h.rel(p)
312 if err != nil {
313 return false
314 }
315 fi, err := f.Stat()
316 if err != nil {
317 return false
318 }
319 at, err := h.root.Lstat(rel)
320 return err == nil && os.SameFile(fi, at)
321}
322
323// isNoopTimes reports whether r only sets the access and modification times of a
324// read-only name to its current modification time. Such a request is answered
325// without touching the file, so that the guest kernel still emits IN_ATTRIB:
326// this is how the guest agent relays host inotify events (mountInotify).
327func (h *rootedHandlers) isNoopTimes(r *sftp.Request) bool {
328 flags := r.AttrFlags()
329 if h.readonly || flags.Size || flags.UidGid || flags.Permissions || !flags.Acmodtime {
330 return false
331 }
332 rel, err := h.rel(r.Filepath)
333 if err != nil || !h.isReadonlyName(rel) {
334 return false
335 }
336 fi, err := h.root.Lstat(rel)
337 if err != nil {
338 return false
339 }
340 // SFTP v3 times are in seconds.
341 mtime := uint32(fi.ModTime().Unix())
342 attrs := r.Attributes()
343 return attrs != nil && attrs.Atime == mtime && attrs.Mtime == mtime
344}
345
346// Filelist implements sftp.FileLister.
347func (h *rootedHandlers) Filelist(r *sftp.Request) (sftp.ListerAt, error) {
348 rel, err := h.rel(r.Filepath)
349 if err != nil {
350 return nil, err
351 }
352 switch r.Method {
353 case "List":
354 f, err := h.openRead(rel)
355 if err != nil {
356 return nil, err
357 }
358 return &dirLister{f: f}, nil
359 case "Stat":
360 // FSTAT: r.Filepath is where the file was opened, which may now be another file.
361 var f *os.File
362 switch hf := r.HandleFile().(type) {
363 case writableFile:
364 f = hf.File
365 case *os.File:
366 f = hf
367 }
368 if f != nil {
369 fi, err := f.Stat()
370 if err != nil {
371 return nil, err
372 }
373 return listerAt{fi}, nil
374 }
375 fi, err := h.root.Stat(rel)
376 if err != nil {
377 return nil, err
378 }
379 return listerAt{fi}, nil
380 }
381 return nil, sftp.ErrSSHFxOpUnsupported
382}
383
384// Lstat implements sftp.LstatFileLister.
385func (h *rootedHandlers) Lstat(r *sftp.Request) (sftp.ListerAt, error) {
386 rel, err := h.rel(r.Filepath)
387 if err != nil {
388 return nil, err
389 }
390 fi, err := h.root.Lstat(rel)
391 if err != nil {
392 return nil, err
393 }
394 return listerAt{fi}, nil
395}
396
397// Readlink implements sftp.ReadlinkFileLister.
398func (h *rootedHandlers) Readlink(p string) (string, error) {
399 rel, err := h.rel(p)
400 if err != nil {
401 return "", err
402 }
403 return h.root.Readlink(rel)
404}
405
406// RealPath implements sftp.RealPathFileLister.
407// It does not resolve symlinks, and does not access the file system.
408func (h *rootedHandlers) RealPath(p string) (string, error) {
409 return realPath(h.rootPath, p), nil
410}
411
412// dirLister reads a directory as the client lists it, instead of all of it when it is opened:
413// a huge directory takes neither the memory nor the time of a full read up front.
414// pkg/sftp lists sequentially from offset 0, and closes it with the handle.
415//
416// Readdir looks the entries up relative to the open directory f (Go 1.26.9 and later: before,
417// by the path f was opened with, which the client could have made a symlink to a folder
418// outside the root), so the entries are those of f whatever it was renamed to.
419type dirLister struct {
420 cloud bool
421 mu sync.Mutex
422 f *os.File
423 buf []os.FileInfo // read, not listed yet
424 next int64 // offset of buf[0]
425 eof bool
426}
427
428func (d *dirLister) ListAt(ls []os.FileInfo, offset int64) (int, error) {
429 d.mu.Lock()
430 defer d.mu.Unlock()
431 if offset != d.next {
432 return 0, &os.PathError{Op: "readdir", Path: d.f.Name(), Err: errors.ErrUnsupported}
433 }
434 for len(d.buf) < len(ls) && !d.eof {
435 fis, err := d.f.Readdir(len(ls) - len(d.buf))
436 d.buf = append(d.buf, fis...)
437 if errors.Is(err, io.EOF) {
438 d.eof = true
439 } else if err != nil {
440 return 0, err
441 }
442 }
443 n := copy(ls, d.buf)
444 d.buf = d.buf[n:]
445 d.next += int64(n)
446 if n < len(ls) && d.eof {
447 return n, io.EOF
448 }
449 return n, nil
450}
451
452func (d *dirLister) Close() error {
453 err := d.f.Close()
454 if d.cloud {
455 <-cloudSlots
456 }
457 return err
458}
459
460type listerAt []os.FileInfo
461
462func (l listerAt) ListAt(ls []os.FileInfo, offset int64) (int, error) {
463 if offset >= int64(len(l)) {
464 return 0, io.EOF
465 }
466 n := copy(ls, l[offset:])
467 if n < len(ls) {
468 return n, io.EOF
469 }
470 return n, nil
471}