跳到主要内容

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

浏览文件

sys_linux.go

325 行 · 9.9 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package main
5
6import (
7 "bytes"
8 "context"
9 "errors"
10 "fmt"
11 "io/fs"
12 "net"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "slices"
17 "strconv"
18 "strings"
19
20 "github.com/sirupsen/logrus"
21 "golang.org/x/sys/unix"
22
23 "github.com/lima-vm/lima/v2/pkg/networks"
24 "github.com/lima-vm/lima/v2/pkg/osutil"
25)
26
27const sysClassNet = "/sys/class/net"
28
29// safeDirs are the only directories the privileged commands are looked up in.
30// This process runs as root, so resolving them through the PATH inherited from
31// the unprivileged caller would hand that caller arbitrary root code execution
32// on any host where sudo has no secure_path.
33var safeDirs = []string{"/usr/sbin", "/usr/bin", "/sbin", "/bin"}
34
35func lookTool(name string) (string, error) {
36 if strings.ContainsRune(name, os.PathSeparator) {
37 return "", fmt.Errorf("invalid command name %#q", name)
38 }
39 for _, dir := range safeDirs {
40 path := filepath.Join(dir, name)
41 if fi, err := os.Stat(path); err == nil && fi.Mode().IsRegular() && fi.Mode()&0o111 != 0 {
42 return path, nil
43 }
44 }
45 return "", fmt.Errorf("command %#q not found in %v", name, safeDirs)
46}
47
48// command builds an *exec.Cmd for a tool resolved to an absolute path.
49func command(ctx context.Context, name string, args ...string) (*exec.Cmd, error) {
50 path, err := lookTool(name)
51 if err != nil {
52 return nil, err
53 }
54 return exec.CommandContext(ctx, path, args...), nil
55}
56
57// run executes a command and includes its output in the error, if any.
58func run(ctx context.Context, name string, args ...string) error {
59 cmd, err := command(ctx, name, args...)
60 if err != nil {
61 return err
62 }
63 var out bytes.Buffer
64 cmd.Stdout, cmd.Stderr = &out, &out
65 logrus.Debugf("Running: %v", cmd.Args)
66 if err := cmd.Run(); err != nil {
67 return fmt.Errorf("failed to run %v: %w (output: %s)", cmd.Args, err, strings.TrimSpace(out.String()))
68 }
69 return nil
70}
71
72// output runs a command and returns its standard output.
73func output(ctx context.Context, name string, args ...string) (string, error) {
74 cmd, err := command(ctx, name, args...)
75 if err != nil {
76 return "", err
77 }
78 var stderr bytes.Buffer
79 cmd.Stderr = &stderr
80 logrus.Debugf("Running: %v", cmd.Args)
81 out, err := cmd.Output()
82 if err != nil {
83 return "", fmt.Errorf("failed to run %v: %w (output: %s)", cmd.Args, err, strings.TrimSpace(stderr.String()))
84 }
85 return string(out), nil
86}
87
88// runOK reports whether the command exited with status 0. It is used for the
89// probing commands (`iptables -C`, `firewall-cmd --state`) whose non-zero exit
90// status is an expected answer rather than a failure.
91func runOK(ctx context.Context, name string, args ...string) bool {
92 cmd, err := command(ctx, name, args...)
93 if err != nil {
94 logrus.WithError(err).Debugf("Cannot probe with %#q", name)
95 return false
96 }
97 logrus.Debugf("Probing: %v", cmd.Args)
98 return cmd.Run() == nil
99}
100
101func ufwActive(ctx context.Context) bool {
102 cmd, err := command(ctx, "ufw", "status")
103 if err != nil {
104 return false
105 }
106 out, err := cmd.Output()
107 return err == nil && strings.Contains(string(out), "Status: active")
108}
109
110// iptablesRules adds or deletes rules, unless they are already in the desired
111// state. Every rule is "<table> <chain> <args>...". addOp is "-A" to append or
112// "-I" to insert at the top; inserted rules are applied in reverse, so that the
113// resulting order in the chain matches the order they are listed in here.
114func iptablesRules(ctx context.Context, add bool, addOp string, rules ...[]string) error {
115 if add && addOp == "-I" {
116 rules = slices.Clone(rules)
117 slices.Reverse(rules)
118 }
119 var errs []error
120 for _, rule := range rules {
121 table, chain, args := rule[0], rule[1], rule[2:]
122 if runOK(ctx, "iptables", append([]string{"-w", "-t", table, "-C", chain}, args...)...) == add {
123 continue
124 }
125 op := "-D"
126 if add {
127 op = addOp
128 }
129 errs = append(errs, run(ctx, "iptables", append([]string{"-w", "-t", table, op, chain}, args...)...))
130 }
131 return errors.Join(errs...)
132}
133
134// createTap creates a persistent tap device owned by uid.
135//
136// `ip tuntap` is the obvious way to do this, but it is one of the subcommands
137// that busybox's `ip` applet does not implement, so fall back to the
138// /dev/net/tun ioctls that iproute2 itself uses. The fallback is second because
139// `ip` reports its own failures much more legibly than a bare errno does.
140func createTap(ctx context.Context, tap string, uid uint64) error {
141 err := run(ctx, "ip", "tuntap", "add", "dev", tap, "mode", "tap", "user", strconv.FormatUint(uid, 10))
142 if err != nil {
143 logrus.WithError(err).Debugf("Falling back to the /dev/net/tun ioctls to create %#q", tap)
144 if err2 := createTapIoctl(tap, uid); err2 != nil {
145 return errors.Join(err, err2)
146 }
147 }
148 return nil
149}
150
151func createTapIoctl(tap string, uid uint64) error {
152 fd, err := unix.Open("/dev/net/tun", unix.O_RDWR|unix.O_CLOEXEC, 0)
153 if err != nil {
154 return fmt.Errorf("cannot open /dev/net/tun: %w", err)
155 }
156 defer unix.Close(fd)
157 ifr, err := unix.NewIfreq(tap)
158 if err != nil {
159 return err
160 }
161 ifr.SetUint16(unix.IFF_TAP | unix.IFF_NO_PI)
162 if err := unix.IoctlIfreq(fd, unix.TUNSETIFF, ifr); err != nil {
163 return fmt.Errorf("TUNSETIFF %#q: %w", tap, err)
164 }
165 if err := unix.IoctlSetInt(fd, unix.TUNSETOWNER, int(uid)); err != nil {
166 return fmt.Errorf("TUNSETOWNER %#q: %w", tap, err)
167 }
168 // Without this the device would disappear again when fd is closed.
169 if err := unix.IoctlSetInt(fd, unix.TUNSETPERSIST, 1); err != nil {
170 return fmt.Errorf("TUNSETPERSIST %#q: %w", tap, err)
171 }
172 return nil
173}
174
175func interfaceExists(name string) bool {
176 _, err := os.Lstat(filepath.Join(sysClassNet, name))
177 return err == nil
178}
179
180func isBridge(name string) bool {
181 st, err := os.Stat(filepath.Join(sysClassNet, name, "bridge"))
182 return err == nil && st.IsDir()
183}
184
185// tapOwner returns the uid a tun/tap device was created for, or -1 when it has
186// no owner (which the caller must treat as "not ours").
187func tapOwner(name string) (int64, error) {
188 b, err := os.ReadFile(filepath.Join(sysClassNet, name, "owner"))
189 if err != nil {
190 return -1, fmt.Errorf("interface %#q is not a tap device: %w", name, err)
191 }
192 owner, err := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64)
193 if err != nil {
194 return -1, fmt.Errorf("cannot parse the owner of %#q: %w", name, err)
195 }
196 return owner, nil
197}
198
199func ipForwardEnabled() bool {
200 b, err := os.ReadFile("/proc/sys/net/ipv4/ip_forward")
201 return err == nil && strings.TrimSpace(string(b)) == "1"
202}
203
204// verifySelf refuses to run when this executable, or any directory leading to
205// it, is writable by anyone but root. This helper runs as root, so a writable path
206// hands root to whoever can write there. The sudoers file additionally pins the
207// SHA-256 of the binary, but that only covers hosts that use it: a host with
208// blanket password-less sudo has no sudoers entry to pin.
209func verifySelf() error {
210 // On Linux this reads /proc/self/exe, which is the path of the running inode
211 // (already fully resolved), not something the caller can influence.
212 exe, err := os.Executable()
213 if err != nil {
214 return err
215 }
216 for path := exe; path != "/"; path = filepath.Dir(path) {
217 fi, err := os.Lstat(path)
218 if err != nil {
219 return err
220 }
221 st, ok := osutil.SysStat(fi)
222 if !ok {
223 return fmt.Errorf("could not retrieve stat buffer for %#q", path)
224 }
225 if st.Uid != 0 {
226 return fmt.Errorf("%#q is owned by uid %d, not by root", path, st.Uid)
227 }
228 if fi.Mode()&0o022 != 0 {
229 return fmt.Errorf("%#q is writable by non-root users (mode %#o)", path, fi.Mode().Perm())
230 }
231 }
232 return nil
233}
234
235// ensureRunDir creates the directory holding the PID file and verifies that only
236// root can write to it: a user-writable PID file would let `pkill -F` kill any
237// process as root.
238func ensureRunDir(dir string) error {
239 if err := os.MkdirAll(dir, 0o755); err != nil {
240 return err
241 }
242 // MkdirAll leaves a pre-existing directory alone, so the mode is not implied.
243 if err := os.Chmod(dir, 0o755); err != nil {
244 return err
245 }
246 fi, err := os.Lstat(dir)
247 if err != nil {
248 return err
249 }
250 if fi.Mode()&fs.ModeSymlink != 0 {
251 return fmt.Errorf("runtime directory %#q is a symlink", dir)
252 }
253 st, ok := osutil.SysStat(fi)
254 if !ok {
255 return fmt.Errorf("could not retrieve stat buffer for %#q", dir)
256 }
257 if st.Uid != 0 {
258 return fmt.Errorf("runtime directory %#q is owned by uid %d, not by root", dir, st.Uid)
259 }
260 if fi.Mode()&0o022 != 0 {
261 return fmt.Errorf("runtime directory %#q is writable by non-root users (mode %o)", dir, fi.Mode().Perm())
262 }
263 return nil
264}
265
266// bridgePorts returns the names of the interfaces enslaved to the given bridge.
267func bridgePorts(bridge string) []string {
268 ents, err := os.ReadDir(filepath.Join(sysClassNet, bridge, "brif"))
269 if err != nil {
270 return nil
271 }
272 ports := make([]string, 0, len(ents))
273 for _, ent := range ents {
274 ports = append(ports, ent.Name())
275 }
276 return ports
277}
278
279// otherLimaBridges returns the Lima-managed bridges other than the given one
280// that are still present on the host.
281func otherLimaBridges(except string) []string {
282 ents, err := os.ReadDir(sysClassNet)
283 if err != nil {
284 return nil
285 }
286 var bridges []string
287 for _, ent := range ents {
288 if name := ent.Name(); name != except && networks.IsManagedBridge(name) && isBridge(name) {
289 bridges = append(bridges, name)
290 }
291 }
292 return bridges
293}
294
295// interfaceMaster returns the name of the bridge the interface is enslaved to,
296// or "" when it is not enslaved to any.
297func interfaceMaster(name string) string {
298 link, err := os.Readlink(filepath.Join(sysClassNet, name, "master"))
299 if err != nil {
300 return ""
301 }
302 return filepath.Base(link)
303}
304
305func interfaceIsUp(name string) bool {
306 iface, err := net.InterfaceByName(name)
307 return err == nil && iface.Flags&net.FlagUp != 0
308}
309
310func interfaceHasAddress(name string, ip net.IP) bool {
311 iface, err := net.InterfaceByName(name)
312 if err != nil {
313 return false
314 }
315 addrs, err := iface.Addrs()
316 if err != nil {
317 return false
318 }
319 for _, addr := range addrs {
320 if ipNet, ok := addr.(*net.IPNet); ok && ipNet.IP.Equal(ip) {
321 return true
322 }
323 }
324 return false
325}