跳到主要内容

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

浏览文件

commands.go

253 行 · 8.2 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package networks
5
6import (
7 "crypto/sha256"
8 "errors"
9 "fmt"
10 "io/fs"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "regexp"
15 "runtime"
16 "strings"
17
18 "github.com/opencontainers/go-digest"
19
20 "github.com/lima-vm/lima/v2/pkg/limatype/dirnames"
21 "github.com/lima-vm/lima/v2/pkg/osutil"
22)
23
24const (
25 SocketVMNet = "socket_vmnet"
26 LimaPrivilegedNet = "lima-privileged-net"
27
28 // maxIfNameLen is the longest name the kernel accepts for a network
29 // interface (IFNAMSIZ-1). Both the bridge and the tap names below have to fit
30 // into it; Validate() rejects network names that would overflow the bridge.
31 maxIfNameLen = 15
32 // bridgePrefix is prepended to the network name to name the bridge that
33 // lima-privileged-net creates for "shared" and "host" networks.
34 bridgePrefix = "lima-"
35 // tapPrefix is prepended to a hash of the instance and network name.
36 tapPrefix = "limatap"
37 // tapDigits is the number of hex digits following tapPrefix.
38 // len(tapPrefix)+tapDigits must not exceed maxIfNameLen.
39 tapDigits = 8
40
41 // privilegedSubdir is the libexec/lima subdirectory reserved for the helpers
42 // that run with elevated privileges.
43 privilegedSubdir = "privileged"
44)
45
46// RequiredDaemons returns the privileged helpers needed by the non-usernet
47// networks on this host: socket_vmnet on macOS, lima-privileged-net on Linux.
48// Everything else in this package is generic over the daemon name.
49func RequiredDaemons() []string {
50 switch runtime.GOOS {
51 case "darwin":
52 return []string{SocketVMNet}
53 case "linux":
54 return []string{LimaPrivilegedNet}
55 default:
56 return nil
57 }
58}
59
60// Commands in `sudoers` cannot use quotes, so all arguments are printed via "%s"
61// and not "%q". cfg.Paths.* entries must not include any whitespace!
62
63func (c *Config) Check(name string) error {
64 if _, ok := c.Networks[name]; ok {
65 return nil
66 }
67 return fmt.Errorf("network %#q is not defined", name)
68}
69
70// Usernet returns true if the mode of given network is ModeUserV2.
71func (c *Config) Usernet(name string) (bool, error) {
72 if nw, ok := c.Networks[name]; ok {
73 return nw.Mode == ModeUserV2, nil
74 }
75 return false, fmt.Errorf("network %#q is not defined", name)
76}
77
78// DaemonPath returns the daemon path.
79func (c *Config) DaemonPath(daemon string) (string, error) {
80 switch daemon {
81 case SocketVMNet:
82 return c.Paths.SocketVMNet, nil
83 case LimaPrivilegedNet:
84 return limaPrivilegedNetPath()
85 default:
86 return "", fmt.Errorf("unknown daemon type %#q", daemon)
87 }
88}
89
90// DigestSpec returns the sudoers `Digest_Spec` pinning the contents of the daemon
91// binary. sudo (>= 1.8.7) hashes the file immediately before executing it and
92// refuses to run it when the digest no longer matches, so an attacker who manages
93// to replace the helper cannot get the replacement executed as root. Unlike the
94// ownership checks in validate.go, this is enforced inside sudo itself and is
95// therefore not subject to a time-of-check/time-of-use race with limactl.
96func (c *Config) DigestSpec(daemon string) (string, error) {
97 path, err := c.DaemonPath(daemon)
98 if err != nil {
99 return "", err
100 }
101 f, err := os.Open(path)
102 if err != nil {
103 return "", err
104 }
105 defer f.Close()
106 d, err := digest.FromReader(f)
107 if err != nil {
108 return "", err
109 }
110 return d.String(), nil
111}
112
113// IsDaemonInstalled checks whether the daemon is installed.
114func (c *Config) IsDaemonInstalled(daemon string) (bool, error) {
115 p, err := c.DaemonPath(daemon)
116 if err != nil {
117 return false, err
118 }
119 if p == "" {
120 return false, nil
121 }
122 if _, err := exec.LookPath(p); err != nil {
123 if errors.Is(err, fs.ErrNotExist) {
124 return false, nil
125 }
126 return false, err
127 }
128 return true, nil
129}
130
131// Sock returns a socket_vmnet socket.
132func (c *Config) Sock(name string) string {
133 return filepath.Join(c.Paths.VarRun, fmt.Sprintf("socket_vmnet.%s", name))
134}
135
136func (c *Config) PIDFile(name, daemon string) string {
137 return filepath.Join(c.Paths.VarRun, fmt.Sprintf("%s_%s.pid", name, daemon))
138}
139
140func (c *Config) LogFile(name, daemon, stream string) string {
141 networksDir, _ := dirnames.LimaNetworksDir()
142 return filepath.Join(networksDir, fmt.Sprintf("%s_%s.%s.log", name, daemon, stream))
143}
144
145func (c *Config) User(daemon string) (osutil.User, error) {
146 if ok, _ := c.IsDaemonInstalled(daemon); !ok {
147 daemonPath, _ := c.DaemonPath(daemon)
148 return osutil.User{}, fmt.Errorf("daemon %#q (path=%#q) is not available", daemon, daemonPath)
149 }
150 switch daemon {
151 case SocketVMNet, LimaPrivilegedNet:
152 return osutil.LookupUser("root")
153 }
154 return osutil.User{}, fmt.Errorf("daemon %#q not defined", daemon)
155}
156
157func (c *Config) MkdirCmd() string {
158 return fmt.Sprintf("/bin/mkdir -m 775 -p %s", c.Paths.VarRun)
159}
160
161func (c *Config) StartCmd(name, daemon string) string {
162 if ok, _ := c.IsDaemonInstalled(daemon); !ok {
163 panic(fmt.Errorf("daemon %#q is not available", daemon))
164 }
165 var cmd string
166 switch daemon {
167 case SocketVMNet:
168 nw := c.Networks[name]
169 if c.Paths.SocketVMNet == "" {
170 panic("c.Paths.SocketVMNet is empty")
171 }
172 cmd = fmt.Sprintf("%s --pidfile=%s --socket-group=%s --vmnet-mode=%s",
173 c.Paths.SocketVMNet, c.PIDFile(name, SocketVMNet), c.Group, nw.Mode)
174 switch nw.Mode {
175 case ModeBridged:
176 cmd += fmt.Sprintf(" --vmnet-interface=%s", nw.Interface)
177 case ModeHost, ModeShared:
178 cmd += fmt.Sprintf(" --vmnet-gateway=%s --vmnet-dhcp-end=%s --vmnet-mask=%s",
179 nw.Gateway, nw.DHCPEnd, nw.NetMask)
180 }
181 cmd += " " + c.Sock(name)
182 case LimaPrivilegedNet:
183 nw := c.Networks[name]
184 privilegedNetPath, err := limaPrivilegedNetPath()
185 if err != nil {
186 panic(fmt.Errorf("failed to get lima-privileged-net path: %w", err))
187 }
188 cmd = fmt.Sprintf("%s start --pidfile=%s --mode=%s --bridge=%s",
189 privilegedNetPath, c.PIDFile(name, LimaPrivilegedNet), nw.Mode, c.BridgeName(name))
190 if nw.Mode != ModeBridged {
191 cmd += fmt.Sprintf(" --gateway=%s --dhcp-end=%s --netmask=%s",
192 nw.Gateway, nw.DHCPEnd, nw.NetMask)
193 }
194 default:
195 panic(fmt.Errorf("unexpected daemon %#q", daemon))
196 }
197 return cmd
198}
199
200func (c *Config) StopCmd(name, daemon string) string {
201 return fmt.Sprintf("/usr/bin/pkill -F %s", c.PIDFile(name, daemon))
202}
203
204// IsManagedBridge reports whether the interface is a bridge created by
205// lima-privileged-net.
206func IsManagedBridge(name string) bool {
207 return strings.HasPrefix(name, bridgePrefix)
208}
209
210var tapNameRegex = regexp.MustCompile(fmt.Sprintf(`^%s[0-9a-f]{%d}$`, regexp.QuoteMeta(tapPrefix), tapDigits))
211
212// IsTapName reports whether the interface name could have been generated by
213// TapName, i.e. whether the interface belongs to Lima.
214func IsTapName(name string) bool {
215 return tapNameRegex.MatchString(name)
216}
217
218// BridgeName returns the bridge that the instances of a network are attached to:
219// the pre-existing bridge named by `interface` for "bridged" networks, and the
220// Lima-managed "lima-<name>" bridge otherwise.
221func (c *Config) BridgeName(name string) string {
222 if nw := c.Networks[name]; nw.Mode == ModeBridged {
223 return nw.Interface
224 }
225 return bridgePrefix + name
226}
227
228// TapCmd returns the command creating the tap device that connects an instance
229// to the bridge of a network. Passing TapNamePattern renders the sudoers entry.
230func (c *Config) TapCmd(name, tap string) string {
231 privilegedNetPath, err := limaPrivilegedNetPath()
232 if err != nil {
233 panic(fmt.Errorf("failed to get lima-privileged-net path: %w", err))
234 }
235 return fmt.Sprintf("%s tap --bridge=%s %s", privilegedNetPath, c.BridgeName(name), tap)
236}
237
238// TapName returns the name of the tap device connecting an instance to a
239// network. A hash keeps the name within the maxIfNameLen limit and within the
240// fixed shape that TapNamePattern pins down in the sudoers file. The uid is part
241// of the hash because the bridges are shared between all users of the sudoers
242// group, and a tap device may only ever be used by its owner.
243func TapName(instName, netName string) string {
244 sum := sha256.Sum256(fmt.Appendf(nil, "%d/%s/%s", os.Getuid(), instName, netName))
245 return fmt.Sprintf("%s%x", tapPrefix, sum)[:len(tapPrefix)+tapDigits]
246}
247
248// TapNamePattern is the sudoers wildcard matching exactly the names generated by
249// TapName. Character classes are used instead of "*" because "*" would also
250// match whitespace, which would allow smuggling extra arguments into the command.
251func TapNamePattern() string {
252 return tapPrefix + strings.Repeat("[0-9a-f]", tapDigits)
253}