跳到主要内容

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

浏览文件

validate.go

208 行 · 7.4 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package networks
5
6import (
7 "errors"
8 "fmt"
9 "io/fs"
10 "os"
11 "path/filepath"
12 "reflect"
13 "runtime"
14 "strings"
15
16 "github.com/lima-vm/lima/v2/pkg/identifiers"
17 "github.com/lima-vm/lima/v2/pkg/osutil"
18)
19
20func (c *Config) Validate() error {
21 // The group name and the per-network name/mode/interface are interpolated
22 // verbatim into the sudoers file (sudoers.go) and into the socket_vmnet
23 // command that reconcile.go runs via sudo after splitting it on spaces
24 // (commands.go). A value with whitespace injects an extra argument, and a
25 // newline in a network name adds an arbitrary directive to the generated
26 // sudoers file, so require them to be valid identifiers. Interface is empty
27 // for non-bridged networks, and group defaults to "admin" when unset, so
28 // only validate those when a value is actually present.
29 if c.Group != "" {
30 if err := identifiers.Validate(c.Group); err != nil {
31 return fmt.Errorf("invalid group %#q: %w", c.Group, err)
32 }
33 }
34 for name, nw := range c.Networks {
35 if err := identifiers.Validate(name); err != nil {
36 return fmt.Errorf("invalid network name %#q: %w", name, err)
37 }
38 // On Linux the name of the bridge is derived from the network name, and the
39 // kernel truncates anything longer than IFNAMSIZ-1. Only enforced here so
40 // that existing macOS configurations, where no bridge is created, keep
41 // working.
42 if runtime.GOOS == "linux" && nw.Mode != ModeUserV2 && nw.Mode != ModeBridged {
43 if bridge := bridgePrefix + name; len(bridge) > maxIfNameLen {
44 return fmt.Errorf("network name %#q is too long: the bridge %#q would exceed %d characters", name, bridge, maxIfNameLen)
45 }
46 }
47 if nw.Mode != "" {
48 if err := identifiers.Validate(nw.Mode); err != nil {
49 return fmt.Errorf("invalid mode %#q for network %#q: %w", nw.Mode, name, err)
50 }
51 }
52 if nw.Interface != "" {
53 if err := identifiers.Validate(nw.Interface); err != nil {
54 return fmt.Errorf("invalid interface %#q for network %#q: %w", nw.Interface, name, err)
55 }
56 }
57 }
58
59 // validate all paths.* values
60 paths := reflect.ValueOf(&c.Paths).Elem()
61 pathsMap := make(map[string]string, paths.NumField())
62 var socketVMNetNotFound bool
63 for i := range paths.NumField() {
64 // extract YAML name from struct tag; strip options like "omitempty"
65 name := paths.Type().Field(i).Tag.Get("yaml")
66 if i := strings.IndexRune(name, ','); i > -1 {
67 name = name[:i]
68 }
69 path := paths.Field(i).Interface().(string)
70 pathsMap[name] = path
71 // varPath will be created securely, but any existing parent directories must already be secure
72 if name == "varRun" {
73 // findBaseDirectory drops the trailing components that don't exist yet,
74 // so the whole value has to be checked before it is trimmed: it is
75 // interpolated into the sudoers file and into the sudo command line
76 // long before the directory is created.
77 if err := validateVarRunString(path); err != nil {
78 return fmt.Errorf("networks.yaml field `paths.%s` error: %w", name, err)
79 }
80 path = findBaseDirectory(path)
81 }
82 err := validatePath(path, name == "varRun")
83 if err != nil {
84 if errors.Is(err, os.ErrNotExist) {
85 switch name {
86 // sudoers file does not need to exist; otherwise `limactl sudoers` couldn't bootstrap
87 case "sudoers":
88 continue
89 case "socketVMNet":
90 socketVMNetNotFound = true
91 continue
92 }
93 }
94 return fmt.Errorf("networks.yaml field `paths.%s` error: %w", name, err)
95 }
96 }
97 if socketVMNetNotFound {
98 return fmt.Errorf("networks.yaml: %#q (`paths.socketVMNet`) has to be installed", pathsMap["socketVMNet"])
99 }
100 return nil
101}
102
103// findBaseDirectory removes non-existing directories from the end of the path.
104func findBaseDirectory(path string) string {
105 if _, err := os.Lstat(path); errors.Is(err, os.ErrNotExist) {
106 if path != "/" {
107 return findBaseDirectory(filepath.Dir(path))
108 }
109 }
110 return path
111}
112
113// validateVarRunString validates the parts of paths.varRun that don't depend on
114// the filesystem, so it can be applied to the whole value before findBaseDirectory
115// trims the components that don't exist yet. varRun is interpolated verbatim into
116// the sudoers file, which has no quoting: whitespace ends the command token, a
117// newline starts a directive of its own, and a comma ends the command list entry.
118// reconcile.go also splits the command line on " " before handing it to sudo.
119// Rather than enumerating those metacharacters, require every component to be an
120// identifier, the same way the network name, mode, interface and group are.
121//
122// This is deliberately stricter than validatePath: it only applies to varRun,
123// so existing socketVMNet/sudoers layouts with dotted components keep validating.
124//
125// The raw value is what reaches the sudoers file, so it is checked as-is rather
126// than after filepath.Clean, which would collapse a ".." component.
127func validateVarRunString(varRun string) error {
128 if varRun == "" {
129 return nil
130 }
131 if !filepath.IsAbs(varRun) {
132 return fmt.Errorf("path %#q is not an absolute path", varRun)
133 }
134 for component := range strings.SplitSeq(varRun, "/") {
135 if component == "" {
136 // leading, trailing and repeated separators
137 continue
138 }
139 if err := identifiers.Validate(component); err != nil {
140 return fmt.Errorf("path %#q has an invalid component: %w", varRun, err)
141 }
142 }
143 return nil
144}
145
146func validatePath(path string, allowDaemonGroupWritable bool) error {
147 if path == "" {
148 return nil
149 }
150 if path[0] != '/' {
151 return fmt.Errorf("path %#q is not an absolute path", path)
152 }
153 if strings.ContainsRune(path, ' ') {
154 return fmt.Errorf("path %#q contains whitespace", path)
155 }
156 fi, err := os.Lstat(path)
157 if err != nil {
158 return err
159 }
160 file := "file"
161 if fi.Mode().IsDir() {
162 file = "dir"
163 }
164 // TODO: should we allow symlinks when both the link and the target are secure?
165 // E.g. on macOS /var is a symlink to /private/var, /etc to /private/etc
166 if (fi.Mode() & fs.ModeSymlink) != 0 {
167 return fmt.Errorf("%s %#q is a symlink", file, path)
168 }
169 stat, ok := osutil.SysStat(fi)
170 if !ok {
171 // should never happen
172 return fmt.Errorf("could not retrieve stat buffer for %#q", path)
173 }
174 if runtime.GOOS != "darwin" {
175 return errors.New("vmnet code must not be called on non-Darwin") // TODO: move to *_darwin.go
176 }
177 // TODO: cache looked up UIDs/GIDs
178 root, err := osutil.LookupUser("root")
179 if err != nil {
180 return err
181 }
182 if stat.Uid != root.Uid {
183 return fmt.Errorf(`%s %#q is not owned by %#q (uid: %d), but by uid %d`, file, path, root.User, root.Uid, stat.Uid)
184 }
185 if allowDaemonGroupWritable {
186 daemon, err := osutil.LookupUser("daemon")
187 if err != nil {
188 return err
189 }
190 if fi.Mode()&0o20 != 0 && stat.Gid != root.Gid && stat.Gid != daemon.Gid {
191 return fmt.Errorf(`%s %#q is group-writable and group is neither %#q (gid: %d) nor %#q (gid: %d), but is gid: %d`,
192 file, path, root.User, root.Gid, daemon.User, daemon.Gid, stat.Gid)
193 }
194 if fi.Mode().IsDir() && fi.Mode()&1 == 0 && (fi.Mode()&0o010 == 0 || stat.Gid != daemon.Gid) {
195 return fmt.Errorf(`%s %#q is not executable by the %#q (gid: %d)" group`, file, path, daemon.User, daemon.Gid)
196 }
197 } else if fi.Mode()&0o20 != 0 && stat.Gid != root.Gid {
198 return fmt.Errorf(`%s %#q is group-writable and group is not %#q (gid: %d), but is gid: %d`,
199 file, path, root.User, root.Gid, stat.Gid)
200 }
201 if fi.Mode()&0o02 != 0 {
202 return fmt.Errorf("%s %#q is world-writable", file, path)
203 }
204 if path != "/" {
205 return validatePath(filepath.Dir(path), allowDaemonGroupWritable)
206 }
207 return nil
208}