| 1 | |
| 2 | |
| 3 | |
| 4 | package main |
| 5 | |
| 6 | import ( |
| 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 | |
| 28 | |
| 29 | |
| 30 | type netConfig struct { |
| 31 | pidFile string |
| 32 | mode string |
| 33 | bridge string |
| 34 | gateway string |
| 35 | netmask string |
| 36 | dhcpEnd string |
| 37 | |
| 38 | |
| 39 | ip net.IP |
| 40 | mask net.IPMask |
| 41 | end net.IP |
| 42 | subnet *net.IPNet |
| 43 | |
| 44 | enabledForwarding bool |
| 45 | } |
| 46 | |
| 47 | |
| 48 | |
| 49 | |
| 50 | |
| 51 | var ifNameRegex = regexp.MustCompile(`^[0-9a-zA-Z_.][0-9a-zA-Z_.-]{0,14}$`) |
| 52 | |
| 53 | |
| 54 | |
| 55 | func validIfName(name string) bool { |
| 56 | return name != "." && name != ".." && ifNameRegex.MatchString(name) |
| 57 | } |
| 58 | |
| 59 | func (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 | |
| 94 | |
| 95 | func (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 | |
| 106 | |
| 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 | |
| 127 | |
| 128 | func (c *netConfig) up(ctx context.Context) error { |
| 129 | if c.mode == networks.ModeBridged { |
| 130 | |
| 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 | |
| 147 | |
| 148 | |
| 149 | func (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 | |
| 164 | errs = append(errs, c.forwarding(ctx, false)) |
| 165 | return errors.Join(errs...) |
| 166 | } |
| 167 | |
| 168 | func (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 | |
| 189 | |
| 190 | |
| 191 | |
| 192 | func (c *netConfig) forwarding(ctx context.Context, add bool) error { |
| 193 | if c.mode == networks.ModeHost { |
| 194 | |
| 195 | |
| 196 | |
| 197 | |
| 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 | |
| 215 | |
| 216 | subnet := c.subnet.String() |
| 217 | return iptablesRules(ctx, add, "-A", |
| 218 | []string{"nat", "POSTROUTING", "-s", subnet, "!", "-d", subnet, "-j", "MASQUERADE"}, |
| 219 | |
| 220 | |
| 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 | |
| 227 | |
| 228 | |
| 229 | func (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 | |
| 243 | |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 248 | |
| 249 | var firewallZones = []string{"lima", "nm-shared", "libvirt"} |
| 250 | |
| 251 | |
| 252 | |
| 253 | func 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 | |
| 268 | |
| 269 | |
| 270 | func 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 | |
| 290 | |
| 291 | |
| 292 | func (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 | |
| 304 | |
| 305 | for _, permanent := range []bool{false, true} { |
| 306 | args := []string{"--zone=" + zone} |
| 307 | if permanent { |
| 308 | args = append(args, "--permanent") |
| 309 | } |
| 310 | |
| 311 | |
| 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 | |
| 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 | |
| 349 | |
| 350 | func (c *netConfig) startDnsmasq(ctx context.Context) (*exec.Cmd, error) { |
| 351 | if c.mode == networks.ModeBridged { |
| 352 | return nil, nil |
| 353 | } |
| 354 | args := []string{ |
| 355 | "--keep-in-foreground", |
| 356 | "--conf-file=/dev/null", |
| 357 | "--bind-dynamic", |
| 358 | "--except-interface=lo", |
| 359 | "--interface=" + c.bridge, |
| 360 | "--log-facility=-", |
| 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 | |
| 368 | |
| 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 | |
| 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 | |
| 392 | func 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 | |
| 406 | |
| 407 | func 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 | |
| 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 | |
| 421 | |
| 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 | |
| 444 | |
| 445 | func nextIP(ip net.IP) net.IP { |
| 446 | addr, _ := netip.AddrFromSlice(ip.To4()) |
| 447 | return net.IP(addr.Next().AsSlice()) |
| 448 | } |