跳到主要内容

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

浏览文件

network_linux.go

448 行 · 15.4 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package main
5
6import (
7 "context"
8 "errors"
9 "fmt"
10 "net"
11 "net/netip"
12 "os"
13 "os/exec"
14 "os/signal"
15 "path/filepath"
16 "regexp"
17 "slices"
18 "strconv"
19 "strings"
20 "syscall"
21
22 "github.com/sirupsen/logrus"
23
24 "github.com/lima-vm/lima/v2/pkg/networks"
25)
26
27// netConfig is the fully resolved description of a Lima network. Every value is
28// passed on the command line so that the sudoers file can pin it; the helper never
29// reads the (user-writable) networks.yaml itself.
30type netConfig struct {
31 pidFile string
32 mode string
33 bridge string
34 gateway string
35 netmask string
36 dhcpEnd string
37
38 // parsed by validate
39 ip net.IP
40 mask net.IPMask
41 end net.IP
42 subnet *net.IPNet
43
44 enabledForwarding bool
45}
46
47// ifNameRegex matches the interface names the kernel and a command line both
48// accept. A leading dash is excluded because `ip` would parse it as an option,
49// and "." and ".." are excluded because they are the /sys/class/net entries of
50// the directory itself and its parent.
51var ifNameRegex = regexp.MustCompile(`^[0-9a-zA-Z_.][0-9a-zA-Z_.-]{0,14}$`)
52
53// validIfName reports whether name is a valid network interface name: at most 15
54// characters (IFNAMSIZ-1) of the characters that both the kernel and a command line accept.
55func validIfName(name string) bool {
56 return name != "." && name != ".." && ifNameRegex.MatchString(name)
57}
58
59func (c *netConfig) validate() error {
60 if !filepath.IsAbs(c.pidFile) || strings.ContainsAny(c.pidFile, " \t\n") {
61 return fmt.Errorf("invalid pidfile %#q", c.pidFile)
62 }
63 if !validIfName(c.bridge) {
64 return fmt.Errorf("invalid bridge name %#q", c.bridge)
65 }
66 if c.mode == networks.ModeBridged {
67 return nil
68 }
69 if c.mode != networks.ModeShared && c.mode != networks.ModeHost {
70 return fmt.Errorf("unsupported mode %#q", c.mode)
71 }
72 if c.ip = net.ParseIP(c.gateway).To4(); c.ip == nil {
73 return fmt.Errorf("gateway %#q is not an IPv4 address", c.gateway)
74 }
75 mask := net.ParseIP(c.netmask).To4()
76 if mask == nil {
77 return fmt.Errorf("netmask %#q is not an IPv4 address", c.netmask)
78 }
79 c.mask = net.IPMask(mask)
80 if ones, bits := c.mask.Size(); bits != 32 || ones < 8 || ones > 30 {
81 return fmt.Errorf("netmask %#q is not a valid IPv4 netmask", c.netmask)
82 }
83 if c.end = net.ParseIP(c.dhcpEnd).To4(); c.end == nil {
84 return fmt.Errorf("dhcpEnd %#q is not an IPv4 address", c.dhcpEnd)
85 }
86 c.subnet = &net.IPNet{IP: c.ip.Mask(c.mask), Mask: c.mask}
87 if !c.subnet.Contains(c.end) {
88 return fmt.Errorf("dhcpEnd %v is outside of subnet %v", c.end, c.subnet)
89 }
90 return nil
91}
92
93// run brings the network up and then blocks until limactl terminates the process
94// (via `pkill -F <pidfile>`).
95func (c *netConfig) run(ctx context.Context) error {
96 if err := c.validate(); err != nil {
97 return err
98 }
99 if err := ensureRunDir(filepath.Dir(c.pidFile)); err != nil {
100 return err
101 }
102 sig := make(chan os.Signal, 1)
103 signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
104
105 // Teardown must run to completion even if ctx is already done, or the bridge
106 // and the firewall rules would be left behind on the host.
107 downCtx := context.WithoutCancel(ctx)
108
109 if err := c.up(ctx); err != nil {
110 return errors.Join(err, c.down(downCtx))
111 }
112 dnsmasq, err := c.startDnsmasq(ctx)
113 if err != nil {
114 return errors.Join(err, c.down(downCtx))
115 }
116 if err := os.WriteFile(c.pidFile, fmt.Appendf(nil, "%d\n", os.Getpid()), 0o644); err != nil {
117 return errors.Join(err, stopDnsmasq(dnsmasq), c.down(downCtx))
118 }
119 logrus.Infof("Network is up on bridge %#q", c.bridge)
120
121 <-sig
122 logrus.Infof("Shutting down the network on bridge %#q", c.bridge)
123 return errors.Join(os.Remove(c.pidFile), stopDnsmasq(dnsmasq), c.down(downCtx))
124}
125
126// up creates the bridge and, for "shared" networks, the NAT rules. Every step is
127// skipped when it has already been performed.
128func (c *netConfig) up(ctx context.Context) error {
129 if c.mode == networks.ModeBridged {
130 // The bridge belongs to the host administrator: only verify it, never touch it.
131 if !isBridge(c.bridge) {
132 return fmt.Errorf("%#q is not an existing bridge: the `interface` of a %#q network must be a bridge created by the host administrator",
133 c.bridge, networks.ModeBridged)
134 }
135 return nil
136 }
137 if err := c.ensureBridge(ctx); err != nil {
138 return err
139 }
140 if err := c.firewall(ctx, true); err != nil {
141 return err
142 }
143 return c.forwarding(ctx, true)
144}
145
146// down removes everything up() created, plus the tap devices that Lima attached
147// to the bridge. Every step is attempted so that one failure does not strand the
148// rest.
149func (c *netConfig) down(ctx context.Context) error {
150 var errs []error
151 for _, port := range bridgePorts(c.bridge) {
152 if networks.IsTapName(port) {
153 errs = append(errs, run(ctx, "ip", "link", "delete", port))
154 }
155 }
156 if c.mode == networks.ModeBridged {
157 return errors.Join(errs...)
158 }
159 errs = append(errs, c.firewall(ctx, false))
160 if interfaceExists(c.bridge) {
161 errs = append(errs, run(ctx, "ip", "link", "delete", c.bridge))
162 }
163 // After the bridge is gone, so that restoreForwarding() no longer counts it.
164 errs = append(errs, c.forwarding(ctx, false))
165 return errors.Join(errs...)
166}
167
168func (c *netConfig) ensureBridge(ctx context.Context) error {
169 if interfaceExists(c.bridge) {
170 if !isBridge(c.bridge) {
171 return fmt.Errorf("interface %#q already exists but is not a bridge", c.bridge)
172 }
173 } else if err := run(ctx, "ip", "link", "add", "name", c.bridge, "type", "bridge"); err != nil {
174 return err
175 }
176 if !interfaceHasAddress(c.bridge, c.ip) {
177 ones, _ := c.mask.Size()
178 if err := run(ctx, "ip", "address", "add", fmt.Sprintf("%s/%d", c.ip, ones), "dev", c.bridge); err != nil {
179 return err
180 }
181 }
182 if interfaceIsUp(c.bridge) {
183 return nil
184 }
185 return run(ctx, "ip", "link", "set", "dev", c.bridge, "up")
186}
187
188// forwarding adds or removes the FORWARD (and, for "shared", the NAT) rules of
189// the network. They are needed even when a firewall manager already accepts the
190// bridge's traffic, because net.ipv4.ip_forward is global: once any "shared"
191// network has enabled it, the host routes between all of its bridges.
192func (c *netConfig) forwarding(ctx context.Context, add bool) error {
193 if c.mode == networks.ModeHost {
194 // An isolated network reaches the host itself (INPUT, not FORWARD) and the
195 // guests on its own bridge, and nothing else. Inserted at the top so that
196 // these rules win over the ACCEPT rules of a "shared" network, no matter
197 // which network was started first.
198 return iptablesRules(ctx, add, "-I",
199 []string{"filter", "FORWARD", "-i", c.bridge, "-o", c.bridge, "-j", "ACCEPT"},
200 []string{"filter", "FORWARD", "-i", c.bridge, "-j", "REJECT"},
201 []string{"filter", "FORWARD", "-o", c.bridge, "-j", "REJECT"},
202 )
203 }
204 if add {
205 if !ipForwardEnabled() {
206 if err := run(ctx, "sysctl", "-q", "-w", "net.ipv4.ip_forward=1"); err != nil {
207 return err
208 }
209 c.enabledForwarding = true
210 }
211 } else {
212 defer c.restoreForwarding(ctx)
213 }
214 // Appended rather than inserted, so that the reject rules of an isolated
215 // network stay above them.
216 subnet := c.subnet.String()
217 return iptablesRules(ctx, add, "-A",
218 []string{"nat", "POSTROUTING", "-s", subnet, "!", "-d", subnet, "-j", "MASQUERADE"},
219 // The FORWARD policy is DROP on hosts running Docker, so the bridge needs
220 // explicit permission in both directions.
221 []string{"filter", "FORWARD", "-i", c.bridge, "-s", subnet, "-j", "ACCEPT"},
222 []string{"filter", "FORWARD", "-o", c.bridge, "-d", subnet, "-j", "ACCEPT"},
223 )
224}
225
226// restoreForwarding turns net.ipv4.ip_forward back off, but only when this
227// process turned it on and no other Lima bridge is left that might still need
228// it. Leaving it on would silently keep the host a router after teardown.
229func (c *netConfig) restoreForwarding(ctx context.Context) {
230 if !c.enabledForwarding {
231 return
232 }
233 if others := otherLimaBridges(c.bridge); len(others) > 0 {
234 logrus.Debugf("Leaving net.ipv4.ip_forward enabled: %v are still up", others)
235 return
236 }
237 if err := run(ctx, "sysctl", "-q", "-w", "net.ipv4.ip_forward=0"); err != nil {
238 logrus.WithError(err).Warn("Failed to restore net.ipv4.ip_forward")
239 }
240}
241
242// firewallZones are the firewalld zones the Lima bridge is bound to, in order of
243// preference. They all have target=ACCEPT, so the guests' forwarded traffic
244// passes, while a low priority reject rule leaves only DHCP, DNS and ICMP
245// reachable on the host itself. "lima" is not shipped by firewalld and only
246// exists when an administrator (or ensureFirewallZone) created it; the other two
247// are built in. The "trusted" zone is deliberately not used: it would expose
248// every service listening on the host to the guests.
249var firewallZones = []string{"lima", "nm-shared", "libvirt"}
250
251// firewalldZone returns the zone to bind the bridge to, creating "lima" when the
252// host has none of the built-in ones.
253func firewalldZone(ctx context.Context) (string, error) {
254 out, err := output(ctx, "firewall-cmd", "--get-zones")
255 if err != nil {
256 return "", err
257 }
258 existing := strings.Fields(out)
259 for _, zone := range firewallZones {
260 if slices.Contains(existing, zone) {
261 return zone, nil
262 }
263 }
264 return firewallZones[0], ensureFirewallZone(ctx, firewallZones[0])
265}
266
267// ensureFirewallZone creates a zone modelled on the built-in libvirt zone. New
268// zones can only be defined permanently, so firewalld has to be reloaded once
269// for the zone to become effective.
270func ensureFirewallZone(ctx context.Context, zone string) error {
271 permanent := []string{"--permanent", "--zone=" + zone}
272 steps := [][]string{
273 {"--permanent", "--new-zone=" + zone},
274 append(slices.Clone(permanent), "--set-target=ACCEPT"),
275 append(slices.Clone(permanent), "--add-service=dhcp", "--add-service=dns"),
276 append(slices.Clone(permanent), "--add-protocol=icmp", "--add-protocol=ipv6-icmp"),
277 append(slices.Clone(permanent), "--add-rich-rule=rule priority=\"32767\" reject"),
278 {"--reload"},
279 }
280 logrus.Infof("Creating the %#q firewalld zone", zone)
281 for _, step := range steps {
282 if err := run(ctx, "firewall-cmd", step...); err != nil {
283 return err
284 }
285 }
286 return nil
287}
288
289// firewall opens the guest's DHCP (UDP 67) and DNS (port 53) packets towards the
290// host. Without this, firewalld and ufw silently reject them even though they
291// are visible on the bridge. Nothing else on the host is exposed.
292func (c *netConfig) firewall(ctx context.Context, add bool) error {
293 switch {
294 case runOK(ctx, "firewall-cmd", "--state"):
295 zone, err := firewalldZone(ctx)
296 if err != nil {
297 return err
298 }
299 action := "--change-interface=" + c.bridge
300 if !add {
301 action = "--remove-interface=" + c.bridge
302 }
303 // The permanent binding only survives a firewalld reload while the
304 // interface exists, so a failure to persist it must not be fatal.
305 for _, permanent := range []bool{false, true} {
306 args := []string{"--zone=" + zone}
307 if permanent {
308 args = append(args, "--permanent")
309 }
310 // Removing an interface that is not bound is an error, and down() runs
311 // even when up() never got as far as binding it.
312 if !add && !runOK(ctx, "firewall-cmd", append(slices.Clone(args), "--query-interface="+c.bridge)...) {
313 continue
314 }
315 if err := run(ctx, "firewall-cmd", append(args, action)...); err != nil {
316 if !permanent {
317 return err
318 }
319 logrus.WithError(err).Debugf("Failed to persist the firewalld zone of %#q", c.bridge)
320 }
321 }
322 return nil
323 case ufwActive(ctx):
324 var errs []error
325 for _, rule := range [][]string{
326 {"in", "on", c.bridge, "to", "any", "port", "67", "proto", "udp"},
327 {"in", "on", c.bridge, "to", "any", "port", "53", "proto", "udp"},
328 {"in", "on", c.bridge, "to", "any", "port", "53", "proto", "tcp"},
329 } {
330 args := []string{"--force"}
331 if !add {
332 args = append(args, "delete")
333 }
334 args = append(args, "allow")
335 errs = append(errs, run(ctx, "ufw", append(args, rule...)...))
336 }
337 return errors.Join(errs...)
338 default:
339 // No firewall manager: open just DHCP and DNS on the bridge.
340 return iptablesRules(ctx, add, "-I",
341 []string{"filter", "INPUT", "-i", c.bridge, "-p", "udp", "--dport", "67", "-j", "ACCEPT"},
342 []string{"filter", "INPUT", "-i", c.bridge, "-p", "udp", "--dport", "53", "-j", "ACCEPT"},
343 []string{"filter", "INPUT", "-i", c.bridge, "-p", "tcp", "--dport", "53", "-j", "ACCEPT"},
344 )
345 }
346}
347
348// startDnsmasq starts the DHCP and DNS server as a child process, so that it is
349// terminated together with lima-privileged-net instead of leaking.
350func (c *netConfig) startDnsmasq(ctx context.Context) (*exec.Cmd, error) {
351 if c.mode == networks.ModeBridged {
352 return nil, nil // DHCP is provided by the outside network
353 }
354 args := []string{
355 "--keep-in-foreground", // stay a child of this process
356 "--conf-file=/dev/null",
357 "--bind-dynamic",
358 "--except-interface=lo",
359 "--interface=" + c.bridge,
360 "--log-facility=-", // log to stderr, which limactl captures
361 "--dhcp-leasefile=" + strings.TrimSuffix(c.pidFile, ".pid") + ".leases",
362 fmt.Sprintf("--dhcp-range=%s,%s,%s,1h", nextIP(c.ip), c.end, net.IP(c.mask)),
363 "--dhcp-authoritative",
364 "--dhcp-option=option:dns-server," + c.ip.String(),
365 }
366 if c.mode == networks.ModeHost {
367 // An isolated network has no route to the outside, so advertise no default
368 // route and never forward queries to the upstream resolvers.
369 args = append(args, "--dhcp-option=option:router", "--no-resolv")
370 } else {
371 args = append(args, "--dhcp-option=option:router,"+c.ip.String())
372 }
373 cmd, err := command(ctx, "dnsmasq", args...)
374 if err != nil {
375 return nil, err
376 }
377 cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
378
379 // Without this, a crash of lima-privileged-net leaves a root dnsmasq behind.
380 if cmd.SysProcAttr == nil {
381 cmd.SysProcAttr = &syscall.SysProcAttr{}
382 }
383 cmd.SysProcAttr.Pdeathsig = syscall.SIGTERM
384
385 logrus.Debugf("Starting: %v", cmd.Args)
386 if err := cmd.Start(); err != nil {
387 return nil, fmt.Errorf("failed to run %v: %w", cmd.Args, err)
388 }
389 return cmd, nil
390}
391
392func stopDnsmasq(cmd *exec.Cmd) error {
393 if cmd == nil {
394 return nil
395 }
396 if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
397 return err
398 }
399 if err := cmd.Wait(); err != nil {
400 logrus.WithError(err).Debug("dnsmasq exited with an error")
401 }
402 return nil
403}
404
405// tapUp creates the tap device connecting an instance to the bridge, owned by the
406// user who invoked sudo so that QEMU can open it without any privileges.
407func tapUp(ctx context.Context, tap, bridge string) error {
408 if !networks.IsTapName(tap) {
409 return fmt.Errorf("%#q is not a Lima tap device name", tap)
410 }
411 if !validIfName(bridge) || !isBridge(bridge) {
412 return fmt.Errorf("%#q is not an existing bridge", bridge)
413 }
414 // SUDO_UID is set by sudo itself, so the caller cannot forge it.
415 uid, err := strconv.ParseUint(os.Getenv("SUDO_UID"), 10, 32)
416 if err != nil || uid == 0 {
417 return fmt.Errorf("invalid SUDO_UID %#q in the environment", os.Getenv("SUDO_UID"))
418 }
419 if interfaceExists(tap) {
420 // Another user may own a device of the same name; never hand it to this
421 // caller, and never take it away from its owner.
422 owner, err := tapOwner(tap)
423 if err != nil {
424 return err
425 }
426 if owner != int64(uid) {
427 return fmt.Errorf("tap device %#q is owned by uid %d, not by uid %d", tap, owner, uid)
428 }
429 } else if err := createTap(ctx, tap, uid); err != nil {
430 return err
431 }
432 if interfaceMaster(tap) != bridge {
433 if err := run(ctx, "ip", "link", "set", "dev", tap, "master", bridge); err != nil {
434 return err
435 }
436 }
437 if interfaceIsUp(tap) {
438 return nil
439 }
440 return run(ctx, "ip", "link", "set", "dev", tap, "up")
441}
442
443// nextIP returns the address right after ip, which validate() has already
444// checked to be an IPv4 address.
445func nextIP(ip net.IP) net.IP {
446 addr, _ := netip.AddrFromSlice(ip.To4())
447 return net.IP(addr.Next().AsSlice())
448}