From 75c45a0720bbb8f4f0401e814d8f8f7004583c9d Mon Sep 17 00:00:00 2001 From: steigr Date: Wed, 18 Nov 2026 21:32:58 +0100 Subject: [PATCH] actornet: give actors IPv6 when the worker pod has it Actors only got the IPv4 /30, so an IPv6-only cluster could not run them and a dual-stack one gave them no IPv6 egress. The sandbox now follows the worker pod's IP families: IPv4 169.254.17.0/30, IPv6 fd00:a7e:17::/126, or both. Each family gets its own nftables table, /etc/hosts entry and wakeup probe address. Dialing a family the sandbox lacks fails with ENETUNREACH. Both workers pass the families to actornet, and the e2e tests no longer assume IPv4 addresses. Signed-off-by: steigr --- AGENTS.md | 2 +- .../atunnel/internal/workerhost/workerhost.go | 8 +- cmd/ateworker-gvisor/hosted.go | 1 + cmd/ateworker-gvisor/main.go | 22 +- cmd/ateworker-gvisor/rootfs.go | 4 +- cmd/ateworker-microvm/hosted.go | 1 + .../internal/kata/agentclient.go | 4 +- cmd/ateworker-microvm/main.go | 14 +- cmd/ateworker-microvm/net.go | 16 +- cmd/ateworker-microvm/net_linux_test.go | 44 +- cmd/ateworker-microvm/restore.go | 5 +- cmd/ateworker-microvm/restore_linux_test.go | 3 +- cmd/ateworker-microvm/run.go | 68 ++- cmd/ateworker-microvm/run_test.go | 10 +- docs/guides/network-egress.md | 4 +- internal/ateworker/actornet/etcfiles.go | 11 +- internal/ateworker/actornet/net.go | 123 +++++- internal/ateworker/actornet/resolvconf.go | 25 +- .../ateworker/actornet/resolvconf_test.go | 30 +- internal/ateworker/actornet/sandbox.go | 201 +++++---- .../actornet/sandbox_atunnel_linux_test.go | 198 ++++++--- .../ateworker/actornet/sandbox_linux_test.go | 399 ++++++++++++++---- internal/atunnel/dns/relay_linux.go | 1 + .../e2e/suites/egressmitm/egressmitm_test.go | 22 +- internal/e2e/suites/identity/identity_test.go | 10 +- internal/wakeupprobe/wakeupprobe.go | 3 +- internal/wakeupprobe/wakeupprobe_test.go | 6 + 27 files changed, 904 insertions(+), 331 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 97e3f8aae6..45c0141125 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -158,4 +158,4 @@ Agent Substrate is built for zero-trust, multi-tenant execution of untrusted act - **Workload & Storage Isolation**: Actors run strictly inside `gVisor` (`cmd/ateworker-gvisor`) or `Cloud Hypervisor` microVM (`cmd/ateworker-microvm`) sandboxes; plain Linux containers are not supported. `atelet` scrubs actor directories across lifecycle transitions (`resetActorDirs`), and snapshots are stamped with `ActorSandboxRuntime` metadata and transferred via `cmd/objectstore-plugin`. - **Component & Actor Identity (mTLS, JWTs, and JWKs)**: Inter-component communication uses mTLS backed by `cmd/podcertcontroller` (`podid`, `servicedns`, and `postgres` signers). Actor JWT signing (`internal/localjwtauthority`), verification (`internal/oidcjwt`), and key discovery (served via `cmd/ate-idp-server`) are built on the standard library's crypto packages. Extend those packages rather than adding `go-jose` or another JOSE library, so the code that decides whether a token is valid stays small and supports only the algorithms Substrate uses. - **Control-Plane Authentication & Authorization**: `ate-api-server` checks every Control RPC against an embedded OpenFGA model (`cmd/ateapi/internal/authz/model.fga`), always enforced. Every served unary RPC needs an entry in `defaultRPCPermissions` (`registry.go`): an RPC without one is denied, and a test fails the build. Access is granted per global scope and atespace through AccessPolicy (`kubectl ate access-policy`); the install's bootstrap owner is the shared `ate-client` ServiceAccount that `kubectl ate` uses. See `docs/guides/authorization.md` for roles and known gaps. Callers are authenticated via `SPIFFE` mTLS or configured OIDC `JWTProvider`s (`cmd/ateapi/internal/apiauthn`). -- **Network Isolation, Ingress, & Egress**: `manifests/ate-install/ate-system-networkpolicies.yaml` enforces default-deny ingress across `ate-system`, and `cmd/atecontroller` reconciles per-`WorkerPool` `NetworkPolicy` objects. Actors run in private `/30` point-to-point veth network namespaces (`internal/ateworker/actornet`) with link-local blocking, policy-enforced DNS filtering (`internal/atunnel/dns`), and zero ambient credentials. Outbound traffic traverses `atunnel` to `atenet-egress`, which enforces per-actor `EgressPolicy` and injects credentials out-of-band via `cmd/credential-provider/kubernetes-secrets` (`k8s-credential-provider`) or actor JWT minting. +- **Network Isolation, Ingress, & Egress**: `manifests/ate-install/ate-system-networkpolicies.yaml` enforces default-deny ingress across `ate-system`, and `cmd/atecontroller` reconciles per-`WorkerPool` `NetworkPolicy` objects. Actors run in private point-to-point veth network namespaces (`internal/ateworker/actornet`), an IPv4 `/30`, an IPv6 `/126`, or both, following the worker pod's IP families, with link-local blocking, policy-enforced DNS filtering (`internal/atunnel/dns`), and zero ambient credentials. Outbound traffic traverses `atunnel` to `atenet-egress`, which enforces per-actor `EgressPolicy` and injects credentials out-of-band via `cmd/credential-provider/kubernetes-secrets` (`k8s-credential-provider`) or actor JWT minting. diff --git a/benchmarking/atunnel/internal/workerhost/workerhost.go b/benchmarking/atunnel/internal/workerhost/workerhost.go index 232e0f4499..45f12bb8df 100644 --- a/benchmarking/atunnel/internal/workerhost/workerhost.go +++ b/benchmarking/atunnel/internal/workerhost/workerhost.go @@ -40,9 +40,12 @@ import ( const Atespace = "bench" // ActorPort is where the ingress actor listens inside each sandbox: the port -// of actornet.ActorHTTPUpstream, which ingress proxies to. +// of families.HTTPUpstream, which ingress proxies to. const ActorPort = 80 +// families are those of an IPv4 cluster's sandboxes. +var families = actornet.Families{IPv4: true} + // Sandbox is one hosted actor, as a process placing an ingress actor in it needs it. type Sandbox struct { // Actor is atespace/name, the value of the routing header. @@ -76,7 +79,7 @@ type actor struct { // Start starts atunnel from cfg, as a worker's main does, and hosts actors // actors whose egress tunnels to gatewayAddress. func Start(ctx context.Context, cfg atunnel.Config, actors int, gatewayAddress string) (*Host, error) { - t, err := atunnel.Start(ctx, cfg, actornet.ActorHTTPUpstream) + t, err := atunnel.Start(ctx, cfg, families.HTTPUpstream()) if err != nil { return nil, err } @@ -108,6 +111,7 @@ func (h *Host) host(ctx context.Context, attribution resources.ActorAttribution, session, err := actornet.ServeSandbox(ctx, actornet.SandboxNetworkConfig{ ActorUID: attribution.UID, Veth: true, + Families: families, EgressPort: h.tunnel.EgressPort, DNSPolicy: h.tunnel.ActorEgressPolicy(attribution), }, h.tunnel.Egress, h.tunnel.DNSRelay) diff --git a/cmd/ateworker-gvisor/hosted.go b/cmd/ateworker-gvisor/hosted.go index 7dff0694ca..53ff47e6cd 100644 --- a/cmd/ateworker-gvisor/hosted.go +++ b/cmd/ateworker-gvisor/hosted.go @@ -112,6 +112,7 @@ func (s *AteWorkerService) hostActor(ctx context.Context, attribution resources. session, err := actornet.ServeSandbox(ctx, actornet.SandboxNetworkConfig{ ActorUID: uid, Veth: true, + Families: s.families, EgressPort: s.tunnel.EgressPort, DNSPolicy: s.tunnel.ActorEgressPolicy(attribution), }, s.tunnel.Egress, s.tunnel.DNSRelay) diff --git a/cmd/ateworker-gvisor/main.go b/cmd/ateworker-gvisor/main.go index d42598a5cd..6599e70952 100644 --- a/cmd/ateworker-gvisor/main.go +++ b/cmd/ateworker-gvisor/main.go @@ -263,11 +263,15 @@ func do(ctx context.Context) error { } actorLogger := actorlog.NewActorLogger(syncedWriter, metadata.OnGCE()) - tunnel, err := atunnel.Start(ctx, *tunnelConfig, actornet.ActorHTTPUpstream) + families, err := actornet.PodFamilies(register.ParsePodIPs(*podIPs)) if err != nil { return err } - ateworkerService := NewService(tunnel, actorLogger, *maxActors, flags, bootID) + tunnel, err := atunnel.Start(ctx, *tunnelConfig, families.HTTPUpstream()) + if err != nil { + return err + } + ateworkerService := NewService(tunnel, actorLogger, *maxActors, families, flags, bootID) ateworkerService.throttleMemory = cgroup.PSIEnabled(defaultCgroupRoot) if !ateworkerService.throttleMemory { slog.WarnContext(ctx, "Kernel has no cgroup memory pressure (PSI), so sandboxes keep memory.max and an OOM kill in one can restart the worker") @@ -366,6 +370,9 @@ type workloadSession struct { type AteWorkerService struct { ateworkerpb.UnimplementedWorkerServer + // families are the IP families each sandbox carries, those of this pod. + families actornet.Families + // Serializes lifecycle RPCs per actor. locks *actorlock.Locks // Tracks lifecycle RPCs for shutdown cancellation and draining. @@ -428,8 +435,9 @@ type AteWorkerService struct { var _ ateworkerpb.WorkerServer = (*AteWorkerService)(nil) // NewService creates a new AteWorkerService. -func NewService(tunnel *atunnel.Tunnel, actorLogger *actorlog.ActorLogger, maxActors int, flags *flagStore, bootID string) *AteWorkerService { +func NewService(tunnel *atunnel.Tunnel, actorLogger *actorlog.ActorLogger, maxActors int, families actornet.Families, flags *flagStore, bootID string) *AteWorkerService { s := &AteWorkerService{ + families: families, locks: actorlock.New(), inFlight: actorlock.NewInFlight(), actors: map[string]*hostedActor{}, @@ -776,7 +784,7 @@ func (s *AteWorkerService) RunWorkload(ctx context.Context, req *ateworkerpb.Run return nil, fmt.Errorf("while starting json log pipe for %q: %w", ac.GetName(), err) } defer pw.Close() - if err := setupAppRootfs(req.GetActorDirs(), ac.GetName()); err != nil { + if err := setupAppRootfs(req.GetActorDirs(), ac.GetName(), s.families); err != nil { return nil, fmt.Errorf("while composing %q rootfs: %w", ac.GetName(), err) } containersToDelete = append(containersToDelete, ac.GetName()) @@ -789,7 +797,7 @@ func (s *AteWorkerService) RunWorkload(ctx context.Context, req *ateworkerpb.Run } // Block until every wakeup-probe-enabled container reports 200. - if err := wakeupprobe.WaitAll(ctx, req.GetSpec().GetContainers(), actornet.ActorVethIP, wakeupprobe.DialFunc(s.sandboxDialer(req.GetActorUid()))); err != nil { + if err := wakeupprobe.WaitAll(ctx, req.GetSpec().GetContainers(), s.families.ActorIP(), wakeupprobe.DialFunc(s.sandboxDialer(req.GetActorUid()))); err != nil { return nil, fmt.Errorf("while waiting for container wakeup probe: %w", err) } if err := s.tunnel.ActivateIngress(attribution, s.sandboxDialer(req.GetActorUid())); err != nil { @@ -1279,7 +1287,7 @@ func (s *AteWorkerService) RestoreWorkload(ctx context.Context, req *ateworkerpb return nil, fmt.Errorf("while starting json log pipe for %q: %w", ac.GetName(), err) } defer pw.Close() - err = setupAppRootfs(req.GetActorDirs(), ac.GetName()) + err = setupAppRootfs(req.GetActorDirs(), ac.GetName(), s.families) timing.appRootfs += lap(&tLast) if err != nil { return nil, fmt.Errorf("while composing %q rootfs: %w", ac.GetName(), err) @@ -1307,7 +1315,7 @@ func (s *AteWorkerService) RestoreWorkload(ctx context.Context, req *ateworkerpb } // Block until every wakeup-probe-enabled container reports 200. - err = wakeupprobe.WaitAll(ctx, containers, actornet.ActorVethIP, wakeupprobe.DialFunc(s.sandboxDialer(req.GetActorUid()))) + err = wakeupprobe.WaitAll(ctx, containers, s.families.ActorIP(), wakeupprobe.DialFunc(s.sandboxDialer(req.GetActorUid()))) timing.wakeupProbe = lap(&tLast) if err != nil { return nil, fmt.Errorf("while waiting for container wakeup probe: %w", err) diff --git a/cmd/ateworker-gvisor/rootfs.go b/cmd/ateworker-gvisor/rootfs.go index ffc565e53c..3fe28c707d 100644 --- a/cmd/ateworker-gvisor/rootfs.go +++ b/cmd/ateworker-gvisor/rootfs.go @@ -27,10 +27,10 @@ import ( // setupAppRootfs composes an application container's bundle rootfs, the base // layer under the sandbox's restored rootfs writes, and writes its /etc files. -func setupAppRootfs(actorDirs *ateworkerpb.ActorDirs, containerName string) error { +func setupAppRootfs(actorDirs *ateworkerpb.ActorDirs, containerName string, families actornet.Families) error { bundle := ociBundlePath(actorDirs, containerName) if err := imagecache.SetupBundleRootfs(bundle); err != nil { return err } - return actornet.WriteRootfsEtcFiles(filepath.Join(bundle, "rootfs"), ocispec.Hostname) + return actornet.WriteRootfsEtcFiles(filepath.Join(bundle, "rootfs"), ocispec.Hostname, families) } diff --git a/cmd/ateworker-microvm/hosted.go b/cmd/ateworker-microvm/hosted.go index b7576810ab..85da7d996a 100644 --- a/cmd/ateworker-microvm/hosted.go +++ b/cmd/ateworker-microvm/hosted.go @@ -92,6 +92,7 @@ func (s *AteWorkerService) hostActor(ctx context.Context, attribution resources. // The tap and atunnel share a namespace; the guest owns the other end. session, err := actornet.ServeSandbox(ctx, actornet.SandboxNetworkConfig{ ActorUID: uid, + Families: s.families, EgressPort: s.tunnel.EgressPort, DNSPolicy: s.tunnel.ActorEgressPolicy(attribution), }, s.tunnel.Egress, s.tunnel.DNSRelay) diff --git a/cmd/ateworker-microvm/internal/kata/agentclient.go b/cmd/ateworker-microvm/internal/kata/agentclient.go index ad8eed991f..08c25c4d97 100644 --- a/cmd/ateworker-microvm/internal/kata/agentclient.go +++ b/cmd/ateworker-microvm/internal/kata/agentclient.go @@ -204,8 +204,8 @@ func (a *AgentClient) UpdateRoutes(ctx context.Context, routes []*agentpb.Route) return nil } -// AddARPNeighbors installs static ARP entries in the guest — used to pin the -// gateway (169.254.17.1) to its FIXED MAC so a restored guest's frozen neighbor +// AddARPNeighbors installs static ARP and NDP entries in the guest — used to pin +// the gateway's addresses to its FIXED MAC so a restored guest's frozen neighbor // entry stays valid across pods. Mirrors grpc.AgentService/AddARPNeighbors. func (a *AgentClient) AddARPNeighbors(ctx context.Context, neighbors []*agentpb.ARPNeighbor) error { req := &agentpb.AddARPNeighborsRequest{Neighbors: &agentpb.ARPNeighbors{ARPNeighbors: neighbors}} diff --git a/cmd/ateworker-microvm/main.go b/cmd/ateworker-microvm/main.go index 845f26d006..b7503bb314 100644 --- a/cmd/ateworker-microvm/main.go +++ b/cmd/ateworker-microvm/main.go @@ -234,11 +234,15 @@ func do(ctx context.Context) error { return fmt.Errorf("while delegating the worker cgroup: %w", err) } - tunnel, err := atunnel.Start(ctx, *tunnelConfig, actornet.ActorHTTPUpstream) + families, err := actornet.PodFamilies(register.ParsePodIPs(*podIPs)) if err != nil { return err } - ateworkerService := NewService(*podUID, *chBinary, *guestDebug, *maxActors, tunnel, actorLogger, bootID) + tunnel, err := atunnel.Start(ctx, *tunnelConfig, families.HTTPUpstream()) + if err != nil { + return err + } + ateworkerService := NewService(*podUID, *chBinary, *guestDebug, *maxActors, families, tunnel, actorLogger, bootID) ateworkerService.throttleMemory = cgroup.PSIEnabled(cgroup.Root) if !ateworkerService.throttleMemory { slog.WarnContext(ctx, "Kernel has no cgroup memory pressure (PSI), so actor cgroups get no memory limit and an actor over its booking can restart the worker") @@ -362,6 +366,9 @@ const ( type AteWorkerService struct { ateworkerpb.UnimplementedWorkerServer + // families are the IP families each sandbox carries, those of this pod. + families actornet.Families + // Serializes lifecycle RPCs per actor. locks *actorlock.Locks // Tracks lifecycle RPCs for shutdown cancellation and draining. @@ -420,8 +427,9 @@ type AteWorkerService struct { var _ ateworkerpb.WorkerServer = (*AteWorkerService)(nil) // NewService creates a new AteWorkerService. -func NewService(podUID, chBinary string, guestDebug bool, maxActors int, tunnel *atunnel.Tunnel, actorLogger *actorlog.ActorLogger, bootID string) *AteWorkerService { +func NewService(podUID, chBinary string, guestDebug bool, maxActors int, families actornet.Families, tunnel *atunnel.Tunnel, actorLogger *actorlog.ActorLogger, bootID string) *AteWorkerService { s := &AteWorkerService{ + families: families, locks: actorlock.New(), inFlight: actorlock.NewInFlight(), actors: map[string]*hostedActor{}, diff --git a/cmd/ateworker-microvm/net.go b/cmd/ateworker-microvm/net.go index bd95abad45..bee08839e4 100644 --- a/cmd/ateworker-microvm/net.go +++ b/cmd/ateworker-microvm/net.go @@ -31,9 +31,9 @@ import ( const ( // gatewayMAC is deliberately FIXED (locally administered), unlike // ateworker-gvisor where a random veth MAC is fine. A CH snapshot freezes the - // guest kernel's ARP cache, including the entry for the gateway - // 169.254.17.1; restoring against a tap with a fresh random MAC would - // blackhole guest egress until that entry expired. + // guest kernel's neighbor cache, including the entries for the gateway's + // addresses; restoring against a tap with a fresh random MAC would + // blackhole guest egress until those entries expired. gatewayMAC = "02:a8:1e:00:00:01" // actorGuestMAC is the FIXED MAC for the guest's eth0 (the CH virtio-net). @@ -49,9 +49,9 @@ const ( var gatewayHWAddr = actornet.MustParseMAC(gatewayMAC) -// setupActorTap creates the guest's tap with a fixed gateway address and MAC. +// setupActorTap creates the guest's tap with fixed gateway addresses and MAC. // Returns the FDs cloud-hypervisor adopts on boot or restore. -func setupActorTap(ctx context.Context, actorNetNS netns.Handle, name string, queuePairs int) ([]*os.File, error) { +func setupActorTap(ctx context.Context, actorNetNS netns.Handle, name string, queuePairs int, families actornet.Families) ([]*os.File, error) { var fds []*os.File err := netns.Do(ctx, actorNetNS, func(ctx context.Context) error { if old, lerr := netlink.LinkByName(name); lerr == nil { @@ -80,8 +80,10 @@ func setupActorTap(ctx context.Context, actorNetNS netns.Handle, name string, qu if err := netlink.LinkSetHardwareAddr(link, gatewayHWAddr); err != nil { return fmt.Errorf("setting the gateway MAC on tap %q: %w", name, err) } - if err := netlink.AddrReplace(link, actornet.HostVethAddr); err != nil { - return fmt.Errorf("assigning the gateway address to tap %q: %w", name, err) + for _, addr := range families.GatewayAddrs() { + if err := netlink.AddrReplace(link, addr); err != nil { + return fmt.Errorf("assigning the gateway address %s to tap %q: %w", addr, name, err) + } } if err := netlink.LinkSetUp(link); err != nil { return fmt.Errorf("bringing up tap %q: %w", name, err) diff --git a/cmd/ateworker-microvm/net_linux_test.go b/cmd/ateworker-microvm/net_linux_test.go index becf6e78d1..af38a2573e 100644 --- a/cmd/ateworker-microvm/net_linux_test.go +++ b/cmd/ateworker-microvm/net_linux_test.go @@ -45,6 +45,7 @@ func TestHostActorReplacesSameActor(t *testing.T) { tunnel: &atunnel.Tunnel{Egress: egressProxy, EgressPort: 15001}, actors: map[string]*hostedActor{}, maxActors: 1, + families: actornet.Families{IPv4: true, IPv6: true}, } const actorUID = "microvm-network-replace" t.Cleanup(func() { @@ -86,10 +87,23 @@ func tapNetNS(t *testing.T, name string) netns.Handle { // address and the MAC the guest's snapshot froze into its ARP cache. func TestSetupActorTap(t *testing.T) { roottest.Require(t, "creates network namespaces and tap devices") + for _, tc := range []struct { + name string + families actornet.Families + }{ + {"ipv4", actornet.Families{IPv4: true}}, + {"ipv6", actornet.Families{IPv6: true}}, + {"dual", actornet.Families{IPv4: true, IPv6: true}}, + } { + t.Run(tc.name, func(t *testing.T) { testSetupActorTap(t, tc.families) }) + } +} + +func testSetupActorTap(t *testing.T, families actornet.Families) { ctx := context.Background() ns := tapNetNS(t, "microvm-tap-test") - fds, err := setupActorTap(ctx, ns, "tap0_kata", 1) + fds, err := setupActorTap(ctx, ns, "tap0_kata", 1, families) if err != nil { t.Fatalf("setupActorTap: %v", err) } @@ -116,18 +130,26 @@ func TestSetupActorTap(t *testing.T) { if got := link.Attrs().MTU; got != actorTapMTU { t.Errorf("tap MTU = %d, want %d, the value the guest was snapshotted against", got, actorTapMTU) } - addrs, err := netlink.AddrList(link, netlink.FAMILY_V4) + addrs, err := netlink.AddrList(link, netlink.FAMILY_ALL) if err != nil { return err } - var found bool - for _, a := range addrs { - if a.IPNet.String() == actornet.HostVethAddr.IPNet.String() { - found = true + for _, f := range []struct { + addr *netlink.Addr + want bool + }{ + {actornet.HostVethAddr, families.IPv4}, + {actornet.HostVethAddrV6, families.IPv6}, + } { + var found bool + for _, a := range addrs { + if a.IPNet.String() == f.addr.IPNet.String() { + found = true + } + } + if found != f.want { + t.Errorf("tap addresses = %v, gateway %s present = %v, want %v", addrs, f.addr, found, f.want) } - } - if !found { - t.Errorf("tap addresses = %v, want the gateway %s the guest routes to", addrs, actornet.HostVethAddr) } return nil }); err != nil { @@ -147,7 +169,7 @@ func TestSetupActorTapReplacesALeftover(t *testing.T) { ctx := context.Background() ns := tapNetNS(t, "microvm-tap-replace") - first, err := setupActorTap(ctx, ns, "tap0_kata", 1) + first, err := setupActorTap(ctx, ns, "tap0_kata", 1, actornet.Families{IPv4: true, IPv6: true}) if err != nil { t.Fatalf("first setupActorTap: %v", err) } @@ -155,7 +177,7 @@ func TestSetupActorTapReplacesALeftover(t *testing.T) { defer f.Close() } - second, err := setupActorTap(ctx, ns, "tap0_kata", 2) + second, err := setupActorTap(ctx, ns, "tap0_kata", 2, actornet.Families{IPv4: true, IPv6: true}) if err != nil { t.Fatalf("second setupActorTap over a leftover: %v", err) } diff --git a/cmd/ateworker-microvm/restore.go b/cmd/ateworker-microvm/restore.go index 33e718a657..47b11b7963 100644 --- a/cmd/ateworker-microvm/restore.go +++ b/cmd/ateworker-microvm/restore.go @@ -32,7 +32,6 @@ import ( "go.ate.dev/substrate/internal/ateworker/phaselog" "go.ate.dev/substrate/internal/workerstats" - "go.ate.dev/substrate/internal/ateworker/actornet" "go.ate.dev/substrate/internal/ateworker/cgroup" "go.ate.dev/substrate/cmd/ateworker-microvm/internal/ch" @@ -377,7 +376,7 @@ func (s *AteWorkerService) restoreMemoryFidelity(ctx context.Context, p actorBoo } }() for i, nd := range netDevs { - files, terr := setupActorTap(ctx, s.sandboxNetNS(actorUID), fmt.Sprintf("tap%d_kata", i), nd.QueuePairs) + files, terr := setupActorTap(ctx, s.sandboxNetNS(actorUID), fmt.Sprintf("tap%d_kata", i), nd.QueuePairs, s.families) if terr != nil { return fmt.Errorf("while building restore tap for %s: %w", nd.ID, terr) } @@ -481,7 +480,7 @@ func (s *AteWorkerService) restoreMemoryFidelity(ctx context.Context, p actorBoo tReseeded := time.Now() // Block until every wakeup-probe-enabled container reports 200. - if err := wakeupprobe.WaitAll(ctx, containers, actornet.ActorVethIP, wakeupprobe.DialFunc(s.sandboxDialer(actorUID))); err != nil { + if err := wakeupprobe.WaitAll(ctx, containers, s.families.ActorIP(), wakeupprobe.DialFunc(s.sandboxDialer(actorUID))); err != nil { return fmt.Errorf("while waiting for container wakeup probe: %w", err) } diff --git a/cmd/ateworker-microvm/restore_linux_test.go b/cmd/ateworker-microvm/restore_linux_test.go index 20665004a9..ad731a1e7a 100644 --- a/cmd/ateworker-microvm/restore_linux_test.go +++ b/cmd/ateworker-microvm/restore_linux_test.go @@ -25,6 +25,7 @@ import ( "github.com/google/uuid" "go.ate.dev/substrate/cmd/ateworker-microvm/internal/kata" + "go.ate.dev/substrate/internal/ateworker/actornet" "go.ate.dev/substrate/internal/imagecache" "go.ate.dev/substrate/internal/proto/ateworkerpb" "go.ate.dev/substrate/internal/roottest" @@ -61,7 +62,7 @@ func failedRestoreRootfs(t *testing.T, actorUID string, overlays bool) *ateworke // t.TempDir can remove the bundle. t.Cleanup(func() { _ = imagecache.UnmountAllUnder(dirs.GetOciBundleDir()) }) } - if _, err := (&AteWorkerService{}).buildActorContainers(actorUID, dirs, containers); err != nil { + if _, err := (&AteWorkerService{families: actornet.Families{IPv4: true, IPv6: true}}).buildActorContainers(actorUID, dirs, containers); err != nil { t.Fatalf("buildActorContainers: %v", err) } return dirs diff --git a/cmd/ateworker-microvm/run.go b/cmd/ateworker-microvm/run.go index 058849dd20..d943c1fcf5 100644 --- a/cmd/ateworker-microvm/run.go +++ b/cmd/ateworker-microvm/run.go @@ -541,7 +541,7 @@ func (s *AteWorkerService) coldBootActor(ctx context.Context, p actorBootParams) // Network device: build the actor's tap and add a virtio-net to the created // (pre-boot) VM with its FDs (SCM_RIGHTS). - tapFiles, err := setupActorTap(ctx, s.sandboxNetNS(actorUID), "tap0_kata", 1) + tapFiles, err := setupActorTap(ctx, s.sandboxNetNS(actorUID), "tap0_kata", 1, s.families) if err != nil { return fmt.Errorf("while building tap: %w", err) } @@ -597,7 +597,7 @@ func (s *AteWorkerService) coldBootActor(ctx context.Context, p actorBootParams) tContainers := time.Now() // Block until every wakeup-probe-enabled container reports 200. - if err := wakeupprobe.WaitAll(ctx, containers, actornet.ActorVethIP, wakeupprobe.DialFunc(s.sandboxDialer(actorUID))); err != nil { + if err := wakeupprobe.WaitAll(ctx, containers, s.families.ActorIP(), wakeupprobe.DialFunc(s.sandboxDialer(actorUID))); err != nil { return fmt.Errorf("while waiting for container wakeup probe: %w", err) } @@ -668,7 +668,7 @@ func (s *AteWorkerService) buildActorContainers(actorUID string, actorDirs *atew } bundleRootfs := filepath.Join(bundle, "rootfs") // Set guest DNS and hosts before serving the rootfs over virtio-fs, on boot and restore. - if err := actornet.WriteRootfsEtcFiles(bundleRootfs, ocispec.Hostname); err != nil { + if err := actornet.WriteRootfsEtcFiles(bundleRootfs, ocispec.Hostname, s.families); err != nil { return nil, fmt.Errorf("while writing guest /etc files for %q: %w", cn, err) } ctrs[i] = actorContainer{ @@ -801,9 +801,15 @@ func initParams(agentInit bool) string { // with earlycon (and pays the ~800ms) for diagnosing a guest that dies before then. // // swiotlb=noforce skips the software bounce buffer. +// +// The guest skips duplicate address detection on eth0, which would hold the +// agent's IPv6 address tentative for a second after boot. The kernel applies +// sysctl. parameters after probing devices, so it names the link: eth0 has +// already copied conf/default by then. func buildVMConfig(id, kernel, image, kparams, consoleLog string, memMiB, vcpus int, agentInit, debug bool) ch.VmConfig { cmdline := "root=/dev/pmem0p1 rootflags=dax,data=ordered,errors=remount-ro ro rootfstype=ext4 " + "panic=1 no_timer_check noreplace-smp console=hvc0 swiotlb=noforce " + + "sysctl.net.ipv6.conf." + actornet.ActorVethName + ".accept_dad=0 " + initParams(agentInit) if kparams != "" { cmdline += " " + kparams @@ -1040,32 +1046,50 @@ func tailString(s string, n int) string { // configureGuestNetwork replicates the kata shim's guest network setup over the // agent: configure eth0 (IP/MAC/MTU), install the connected + default routes, and -// pin the gateway's ARP entry to its fixed MAC (so a restored guest's frozen -// neighbor entry stays valid). +// pin the gateway's neighbor entries to its fixed MAC (so a restored guest's +// frozen neighbor entries stay valid). The guest gets the sandbox's families, +// those setupActorTap gives the tap a gateway address in. func (s *AteWorkerService) configureGuestNetwork(ctx context.Context, ac *kata.AgentClient, mtu uint64) error { + var addresses []*agentpb.IPAddress + var routes []*agentpb.Route + var neighbors []*agentpb.ARPNeighbor + for _, f := range []struct { + enabled bool + family agentpb.IPFamily + ip, mask, subnet string + gateway string + }{ + {s.families.IPv4, agentpb.IPFamily_v4, actornet.ActorVethIP, "30", actornet.ActorVethSubnet, actornet.ActorVethGateway}, + {s.families.IPv6, agentpb.IPFamily_v6, actornet.ActorVethIPv6, "126", actornet.ActorVethSubnetV6, actornet.ActorVethGatewayV6}, + } { + if !f.enabled { + continue + } + addresses = append(addresses, &agentpb.IPAddress{Family: f.family, Address: f.ip, Mask: f.mask}) + routes = append(routes, + &agentpb.Route{Dest: f.subnet, Device: actornet.ActorVethName, Scope: uint32(unix.RT_SCOPE_LINK), Family: f.family}, + &agentpb.Route{Dest: "", Gateway: f.gateway, Device: actornet.ActorVethName, Family: f.family}, + ) + neighbors = append(neighbors, &agentpb.ARPNeighbor{ + ToIPAddress: &agentpb.IPAddress{Family: f.family, Address: f.gateway}, + Device: actornet.ActorVethName, + Lladdr: gatewayMAC, + State: 0x80, // NUD_PERMANENT + }) + } if err := ac.UpdateInterface(ctx, &agentpb.Interface{ - Device: actornet.ActorVethName, - Name: actornet.ActorVethName, - HwAddr: actorGuestMAC, - Mtu: mtu, - IPAddresses: []*agentpb.IPAddress{ - {Family: agentpb.IPFamily_v4, Address: actornet.ActorVethIP, Mask: "30"}, - }, + Device: actornet.ActorVethName, + Name: actornet.ActorVethName, + HwAddr: actorGuestMAC, + Mtu: mtu, + IPAddresses: addresses, }); err != nil { return err } - if err := ac.UpdateRoutes(ctx, []*agentpb.Route{ - {Dest: actornet.ActorVethSubnet, Device: actornet.ActorVethName, Scope: uint32(unix.RT_SCOPE_LINK), Family: agentpb.IPFamily_v4}, - {Dest: "", Gateway: actornet.ActorVethGateway, Device: actornet.ActorVethName, Family: agentpb.IPFamily_v4}, - }); err != nil { + if err := ac.UpdateRoutes(ctx, routes); err != nil { return err } - return ac.AddARPNeighbors(ctx, []*agentpb.ARPNeighbor{{ - ToIPAddress: &agentpb.IPAddress{Family: agentpb.IPFamily_v4, Address: actornet.ActorVethGateway}, - Device: actornet.ActorVethName, - Lladdr: gatewayMAC, - State: 0x80, // NUD_PERMANENT - }}) + return ac.AddARPNeighbors(ctx, neighbors) } // waitForFile polls for path to exist, up to d. Used to wait for the kata-agent diff --git a/cmd/ateworker-microvm/run_test.go b/cmd/ateworker-microvm/run_test.go index 5863175d5d..a628172740 100644 --- a/cmd/ateworker-microvm/run_test.go +++ b/cmd/ateworker-microvm/run_test.go @@ -30,6 +30,7 @@ import ( "time" "go.ate.dev/substrate/cmd/ateworker-microvm/internal/kata" + "go.ate.dev/substrate/internal/ateworker/actornet" "go.ate.dev/substrate/internal/proto/ateworkerpb" ) @@ -206,7 +207,7 @@ func TestWorkloadIDs(t *testing.T) { } containers = append(containers, &ateworkerpb.Container{Name: name, ContainerSpec: &ateworkerpb.ContainerSpec{Args: []string{"/app"}}}) } - ctrs, err := (&AteWorkerService{}).buildActorContainers("uid", dirs, containers) + ctrs, err := (&AteWorkerService{families: actornet.Families{IPv4: true, IPv6: true}}).buildActorContainers("uid", dirs, containers) if err != nil { t.Fatal(err) } @@ -232,6 +233,13 @@ func TestKernelParamsDebugConsole(t *testing.T) { } } +func TestBuildVMConfigSkipsIPv6DAD(t *testing.T) { + cfg := buildVMConfig("actor-1", "/vmlinux", "/rootfs.img", "", "/console.log", 256, 1, true, false) + if want := "sysctl.net.ipv6.conf.eth0.accept_dad=0"; !strings.Contains(cfg.Payload.Cmdline, want) { + t.Errorf("cmdline = %q, want %s", cfg.Payload.Cmdline, want) + } +} + func TestBuildVMConfigBalloon(t *testing.T) { cfg := buildVMConfig("actor-1", "/vmlinux", "/rootfs.img", "", "/console.log", 256, 1, true, false) if cfg.Balloon == nil || !cfg.Balloon.FreePageReporting || cfg.Balloon.Size != 0 { diff --git a/docs/guides/network-egress.md b/docs/guides/network-egress.md index db10c29678..866ca48e1a 100644 --- a/docs/guides/network-egress.md +++ b/docs/guides/network-egress.md @@ -16,9 +16,9 @@ Agent Substrate enforces that all outbound traffic from an actor, except traffic ## Transport -At present, actor TCP traffic exits the sandbox through [`atunnel`](../reference/glossary.md#components) and is forwarded on to the PEP. The exception is DNS: TCP and UDP traffic to port 53 on the sandbox's gateway bypasses the PEP and is answered by the sandbox's DNS relay, which forwards a query to the worker pod's resolvers only when the queried hostname matches a host or host wildcard in the actor's egress policy; queries from an actor without a policy, or for a hostname not matched by any rule, are answered `NXDOMAIN`. All other protocols are blocked. `atunnel` is configured with the PEP's network address and port at startup and uses that address to open an mTLS HTTP/1.1 or HTTP/2 CONNECT tunnel to the PEP, as negotiated by ALPN. The CONNECT request target and HTTP/1.1 `Host` header (HTTP/2 `:authority`) are set to the original destination IP and port that `atunnel` derived from the actor's TCP connection. Actor networking is currently IPv4-only. +At present, actor TCP traffic exits the sandbox through [`atunnel`](../reference/glossary.md#components) and is forwarded on to the PEP. The exception is DNS: TCP and UDP traffic to port 53 on the sandbox's gateway bypasses the PEP and is answered by the sandbox's DNS relay, which forwards a query to the worker pod's resolvers only when the queried hostname matches a host or host wildcard in the actor's egress policy; queries from an actor without a policy, or for a hostname not matched by any rule, are answered `NXDOMAIN`. All other protocols are blocked. `atunnel` is configured with the PEP's network address and port at startup and uses that address to open an mTLS HTTP/1.1 or HTTP/2 CONNECT tunnel to the PEP, as negotiated by ALPN. The CONNECT request target and HTTP/1.1 `Host` header (HTTP/2 `:authority`) are set to the original destination IP and port that `atunnel` derived from the actor's TCP connection. A sandbox gets the IP families of its worker pod: IPv4, IPv6, or both on a dual-stack cluster. Egress, the DNS relay, ingress, and wakeup probes work in each, and IPv6 TCP takes the same path as IPv4. Ingress and wakeup probes use the actor's IPv4 address where it has one, so an actor in an IPv6-only sandbox must listen on IPv6. A dual-stack actor prefers IPv6 for names that have both, so the PEP's network needs IPv6 egress too. -Before traffic reaches the egress PEP, ateworker rejects packets destined for the IPv4 link-local range `169.254.0.0/16` or the IPv6 link-local range `fe80::/10`. The internal actor network `169.254.17.0/30` is exempt because it carries traffic for the actor gateway, DNS relay, ingress, and wakeup probes. Localhost traffic remains inside the actor sandbox and does not traverse the PEP. Access to non-link-local destinations remains controlled by substrate egress policy and, at the `WorkerPool` boundary, Kubernetes NetworkPolicy. +Before traffic reaches the egress PEP, ateworker rejects packets destined for the IPv4 link-local range `169.254.0.0/16`, the IPv6 link-local range `fe80::/10`, EC2's IPv6 metadata, DNS, and NTP servers (`fd00:ec2::/64`), Compute Engine's IPv6 metadata server (`fd20:ce::254`), IPv4-mapped addresses (`::ffff:0:0/96`), or link-local space behind NAT64 (`64:ff9b::a9fe:0/112`). The internal actor networks `169.254.17.0/30` and `fd00:a7e:17::/126` are exempt because they carry traffic for the actor gateway, DNS relay, ingress, and wakeup probes. ICMPv6 neighbor solicitations and advertisements are exempt too, for neighbor discovery. Localhost traffic remains inside the actor sandbox and does not traverse the PEP. Access to non-link-local destinations remains controlled by substrate egress policy and, at the `WorkerPool` boundary, Kubernetes NetworkPolicy. ## Refusal responses and policy changes diff --git a/internal/ateworker/actornet/etcfiles.go b/internal/ateworker/actornet/etcfiles.go index f1f4b66e8f..88841aff34 100644 --- a/internal/ateworker/actornet/etcfiles.go +++ b/internal/ateworker/actornet/etcfiles.go @@ -22,18 +22,21 @@ import ( ) // WriteRootfsEtcFiles writes the sandbox's /etc/resolv.conf and /etc/hosts -// into rootfs, pointing the resolver at the actor's gateway. +// into rootfs for families, pointing the resolver at the actor's gateway. // // rootfs must be the base layer under the actor's restored rootfs writes, so // rewriting it on every activation keeps the actor's own edits. Writing these // after restore instead would clobber them. -func WriteRootfsEtcFiles(rootfs, hostname string) error { +func WriteRootfsEtcFiles(rootfs, hostname string, families Families) error { + if err := families.validate(); err != nil { + return fmt.Errorf("actornet: %w", err) + } pod, err := os.ReadFile("/etc/resolv.conf") if err != nil { return fmt.Errorf("reading the worker pod resolv.conf: %w", err) } - if err := WriteRootfsResolvConf(rootfs, SandboxResolvConf(ActorVethGateway, pod)); err != nil { + if err := WriteRootfsResolvConf(rootfs, SandboxResolvConf(families.gatewayIPs(), pod)); err != nil { return err } - return WriteRootfsHosts(rootfs, SandboxHosts(hostname, ActorVethIP)) + return WriteRootfsHosts(rootfs, SandboxHosts(hostname, families.actorIPs())) } diff --git a/internal/ateworker/actornet/net.go b/internal/ateworker/actornet/net.go index 6d794f5a36..b726d8d3cb 100644 --- a/internal/ateworker/actornet/net.go +++ b/internal/ateworker/actornet/net.go @@ -18,11 +18,14 @@ package actornet import ( + "errors" "fmt" "net" + "net/netip" "github.com/google/nftables/expr" "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" ) const ( @@ -30,10 +33,6 @@ const ( ActorVethGateway = "169.254.17.1" ActorVethIP = "169.254.17.2" - // ActorHTTPUpstream is the in-sandbox HTTP endpoint atunnel proxies actor - // ingress to. - ActorHTTPUpstream = "http://" + ActorVethIP + ":80" - // hostVethLocalAddress is the gateway interface's IP address and prefix length. hostVethLocalAddress = "169.254.17.1/30" // actorVethLocalAddress is the actor interface's IP address and prefix length. @@ -41,14 +40,120 @@ const ( // ActorVethSubnet is the point-to-point /30 the actor veth lives on. ActorVethSubnet = "169.254.17.0/30" + + // The IPv6 counterparts, a /126 in a fixed ULA prefix. Link-local alone + // would leave the actor no source address for other destinations. A ULA + // has global scope and 169.254.0.0/16 link-local scope, so RFC 6724 + // address selection prefers IPv6 for names that have both. + ActorVethGatewayV6 = "fd00:a7e:17::1" + ActorVethIPv6 = "fd00:a7e:17::2" + hostVethLocalAddressV6 = "fd00:a7e:17::1/126" + actorVethLocalAddressV6 = "fd00:a7e:17::2/126" + ActorVethSubnetV6 = "fd00:a7e:17::/126" ) var ( HostVethAddr = MustParseAddr(hostVethLocalAddress) ActorVethAddr = MustParseAddr(actorVethLocalAddress) ActorVethGwIP = MustParseIP(ActorVethGateway) + + HostVethAddrV6 = mustParseAddrNoDAD(hostVethLocalAddressV6) + actorVethAddrV6 = mustParseAddrNoDAD(actorVethLocalAddressV6) + actorVethGwIPv6 = MustParseIP(ActorVethGatewayV6) ) +// Families are the IP families a sandbox network carries. At least one is +// set. +type Families struct { + IPv4 bool + IPv6 bool +} + +// PodFamilies returns the families of the worker pod's IPs, so a sandbox +// carries the families its cluster does. +func PodFamilies(podIPs []string) (Families, error) { + var f Families + for _, s := range podIPs { + ip, err := netip.ParseAddr(s) + if err != nil { + return Families{}, fmt.Errorf("actornet: parsing pod IP %q: %w", s, err) + } + if ip.Unmap().Is4() { + f.IPv4 = true + } else { + f.IPv6 = true + } + } + if err := f.validate(); err != nil { + return Families{}, fmt.Errorf("actornet: pod IPs %q: %w", podIPs, err) + } + return f, nil +} + +func (f Families) validate() error { + if !f.IPv4 && !f.IPv6 { + return errors.New("no IP family") + } + return nil +} + +// ActorIP is the actor's address for ingress and wakeup probes: IPv4 where +// the sandbox has it, IPv6 otherwise. +func (f Families) ActorIP() string { + if f.IPv4 { + return ActorVethIP + } + return ActorVethIPv6 +} + +// HTTPUpstream is the in-sandbox HTTP endpoint atunnel proxies actor ingress +// to. +func (f Families) HTTPUpstream() string { + return "http://" + net.JoinHostPort(f.ActorIP(), "80") +} + +// actorIPs are the actor's addresses, IPv4 first. +func (f Families) actorIPs() []string { + return f.pick(ActorVethIP, ActorVethIPv6) +} + +// gatewayIPs are the gateway's addresses, where the DNS relay answers, IPv4 +// first. +func (f Families) gatewayIPs() []string { + return f.pick(ActorVethGateway, ActorVethGatewayV6) +} + +// GatewayAddrs are the gateway interface's addresses. +func (f Families) GatewayAddrs() []*netlink.Addr { + var out []*netlink.Addr + if f.IPv4 { + out = append(out, HostVethAddr) + } + if f.IPv6 { + out = append(out, HostVethAddrV6) + } + return out +} + +func (f Families) pick(v4, v6 string) []string { + var out []string + if f.IPv4 { + out = append(out, v4) + } + if f.IPv6 { + out = append(out, v6) + } + return out +} + +// mustParseAddrNoDAD skips duplicate address detection, which would hold the +// address tentative for a second on a link where nothing else can claim it. +func mustParseAddrNoDAD(cidr string) *netlink.Addr { + a := MustParseAddr(cidr) + a.Flags = unix.IFA_F_NODAD + return a +} + // MustParseAddr parses a CIDR string into a netlink.Addr, panicking on error. func MustParseAddr(cidr string) *netlink.Addr { a, err := netlink.ParseAddr(cidr) @@ -58,11 +163,15 @@ func MustParseAddr(cidr string) *netlink.Addr { return a } -// MustParseIP parses an IPv4 string into a net.IP, panicking on error. +// MustParseIP parses an IP string into a net.IP, panicking on error. IPv4 +// addresses come back in their 4-byte form. func MustParseIP(s string) net.IP { - ip := net.ParseIP(s).To4() + ip := net.ParseIP(s) if ip == nil { - panic(fmt.Sprintf("parsing constant IPv4 %q", s)) + panic(fmt.Sprintf("parsing constant IP %q", s)) + } + if ip4 := ip.To4(); ip4 != nil { + return ip4 } return ip } diff --git a/internal/ateworker/actornet/resolvconf.go b/internal/ateworker/actornet/resolvconf.go index 4eaab2b41c..7432943262 100644 --- a/internal/ateworker/actornet/resolvconf.go +++ b/internal/ateworker/actornet/resolvconf.go @@ -23,12 +23,14 @@ import ( "strings" ) -// SandboxResolvConf replaces the pod's nameservers with nameserver, the -// address the sandbox's DNS is served on, while preserving the pod's search +// SandboxResolvConf replaces the pod's nameservers with nameservers, the +// addresses the sandbox's DNS is served on, while preserving the pod's search // domains and options for Kubernetes DNS. -func SandboxResolvConf(nameserver string, podResolvConf []byte) []byte { +func SandboxResolvConf(nameservers []string, podResolvConf []byte) []byte { var out strings.Builder - out.WriteString("nameserver " + nameserver + "\n") + for _, nameserver := range nameservers { + out.WriteString("nameserver " + nameserver + "\n") + } for line := range strings.SplitSeq(string(podResolvConf), "\n") { if strings.HasPrefix(strings.TrimSpace(line), "nameserver") { continue @@ -41,13 +43,16 @@ func SandboxResolvConf(nameserver string, podResolvConf []byte) []byte { return []byte(out.String()) } -// SandboxHosts maps localhost to loopback and hostname to ip, the way a -// container runtime fills in /etc/hosts. -func SandboxHosts(hostname, ip string) []byte { - return []byte("# Agent Substrate-managed hosts file.\n" + +// SandboxHosts maps localhost to loopback and hostname to each of ips, the +// way a container runtime fills in /etc/hosts. +func SandboxHosts(hostname string, ips []string) []byte { + hosts := "# Agent Substrate-managed hosts file.\n" + "127.0.0.1\tlocalhost\n" + - "::1\tlocalhost ip6-localhost ip6-loopback\n" + - ip + "\t" + hostname + "\n") + "::1\tlocalhost ip6-localhost ip6-loopback\n" + for _, ip := range ips { + hosts += ip + "\t" + hostname + "\n" + } + return []byte(hosts) } // WriteRootfsResolvConf installs content at /etc/resolv.conf inside rootfs. diff --git a/internal/ateworker/actornet/resolvconf_test.go b/internal/ateworker/actornet/resolvconf_test.go index 1842288cc0..bf952a6e18 100644 --- a/internal/ateworker/actornet/resolvconf_test.go +++ b/internal/ateworker/actornet/resolvconf_test.go @@ -28,14 +28,24 @@ func TestSandboxResolvConf(t *testing.T) { pod := "nameserver 10.96.0.10\n" + "search ate-demo.svc.cluster.local svc.cluster.local cluster.local\n" + "options ndots:5\n" - - got := string(SandboxResolvConf("169.254.17.1", []byte(pod))) - - want := "nameserver 169.254.17.1\n" + - "search ate-demo.svc.cluster.local svc.cluster.local cluster.local\n" + + rest := "search ate-demo.svc.cluster.local svc.cluster.local cluster.local\n" + "options ndots:5\n" - if diff := cmp.Diff(want, got); diff != "" { - t.Errorf("actor resolv.conf mismatch (-want +got):\n%s", diff) + + for _, tc := range []struct { + name string + nameservers []string + want string + }{ + {"IPv4", []string{"169.254.17.1"}, "nameserver 169.254.17.1\n" + rest}, + {"IPv6", []string{"fd00:a7e:17::1"}, "nameserver fd00:a7e:17::1\n" + rest}, + {"dual-stack", []string{"169.254.17.1", "fd00:a7e:17::1"}, "nameserver 169.254.17.1\nnameserver fd00:a7e:17::1\n" + rest}, + } { + t.Run(tc.name, func(t *testing.T) { + got := string(SandboxResolvConf(tc.nameservers, []byte(pod))) + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("actor resolv.conf mismatch (-want +got):\n%s", diff) + } + }) } } @@ -43,7 +53,7 @@ func TestSandboxResolvConf(t *testing.T) { // only a nameserver line resolves public names but not cluster ones. func TestSandboxResolvConfKeepsSearchAndOptions(t *testing.T) { pod := "search svc.cluster.local\nnameserver 10.96.0.10\nnameserver 10.96.0.11\noptions ndots:5 timeout:1\n" - got := string(SandboxResolvConf("169.254.17.1", []byte(pod))) + got := string(SandboxResolvConf([]string{"169.254.17.1"}, []byte(pod))) if strings.Contains(got, "10.96.0.10") || strings.Contains(got, "10.96.0.11") { t.Errorf("a pod resolver survived into the actor's file, so its DNS would bypass atunnel:\n%s", got) @@ -118,14 +128,14 @@ func TestWriteRootfsHosts(t *testing.T) { if err := os.WriteFile(filepath.Join(rootfs, "etc", "hosts"), nil, 0o644); err != nil { t.Fatal(err) } - if err := WriteRootfsHosts(rootfs, SandboxHosts("actor", "169.254.17.2")); err != nil { + if err := WriteRootfsHosts(rootfs, SandboxHosts("actor", []string{"169.254.17.2", "fd00:a7e:17::2"})); err != nil { t.Fatalf("WriteRootfsHosts: %v", err) } got, err := os.ReadFile(filepath.Join(rootfs, "etc", "hosts")) if err != nil { t.Fatalf("reading what was written: %v", err) } - want := "# Agent Substrate-managed hosts file.\n127.0.0.1\tlocalhost\n::1\tlocalhost ip6-localhost ip6-loopback\n169.254.17.2\tactor\n" + want := "# Agent Substrate-managed hosts file.\n127.0.0.1\tlocalhost\n::1\tlocalhost ip6-localhost ip6-loopback\n169.254.17.2\tactor\nfd00:a7e:17::2\tactor\n" if string(got) != want { t.Errorf("wrote %q, want %q", got, want) } diff --git a/internal/ateworker/actornet/sandbox.go b/internal/ateworker/actornet/sandbox.go index b7ded2b337..95b7232dbe 100644 --- a/internal/ateworker/actornet/sandbox.go +++ b/internal/ateworker/actornet/sandbox.go @@ -66,6 +66,9 @@ type SandboxNetworkConfig struct { // MicroVMs use a tap in a single namespace instead. Veth bool + // Families are the IP families the actor gets addresses and egress in. + Families Families + // EgressPort is where atunnel serves this actor. Every TCP connection the // actor makes is redirected to it, whatever port it was aimed at. EgressPort uint16 @@ -86,6 +89,9 @@ func SetupSandboxNetwork(ctx context.Context, cfg SandboxNetworkConfig) (_ *Sand if actorUID == "" { return nil, fmt.Errorf("actornet: actor UID is required") } + if err := cfg.Families.validate(); err != nil { + return nil, fmt.Errorf("actornet: %w", err) + } actorNSName := nodepath.ActorNetNSName(actorUID) actorNS, err := netns.CreateNamed(actorNSName) @@ -117,7 +123,7 @@ func SetupSandboxNetwork(ctx context.Context, cfg SandboxNetworkConfig) (_ *Sand }() atunnelNS = outer } - if err := installEgressRules(atunnelNS, cfg.EgressPort); err != nil { + if err := installEgressRules(atunnelNS, cfg.EgressPort, cfg.Families); err != nil { return nil, err } @@ -174,6 +180,11 @@ var sandboxSysctls = []netns.Sysctl{ {Key: "net/ipv4/conf/default/accept_source_route", Value: "0"}, {Key: "net/ipv4/conf/all/rp_filter", Value: "1"}, {Key: "net/ipv4/conf/default/rp_filter", Value: "1"}, + // The node may disable IPv6, and a namespace takes its setting when + // net.core.devconf_inherit_init_net is set. conf/all reaches lo, which + // predates these writes, and conf/default the links added after them. + {Key: "net/ipv6/conf/all/disable_ipv6", Value: "0"}, + {Key: "net/ipv6/conf/default/disable_ipv6", Value: "0"}, // Don't take router advertisements or redirects from the actor. IPv6 // reads both only from the link's own copy, which it takes from // conf/default when the link is created. @@ -217,8 +228,10 @@ func setupVethPair(ctx context.Context, cfg SandboxNetworkConfig, actorNS netns. if err != nil { return err } - if err := netlink.AddrReplace(atSide, HostVethAddr); err != nil { - return fmt.Errorf("while assigning the atunnel-side address: %w", err) + for _, addr := range cfg.Families.GatewayAddrs() { + if err := netlink.AddrReplace(atSide, addr); err != nil { + return fmt.Errorf("while assigning the atunnel-side address %s: %w", addr, err) + } } if err := netlink.LinkSetUp(atSide); err != nil { return err @@ -234,16 +247,28 @@ func setupVethPair(ctx context.Context, cfg SandboxNetworkConfig, actorNS netns. if err != nil { return err } - if err := netlink.AddrReplace(eth0, ActorVethAddr); err != nil { - return fmt.Errorf("while assigning the actor address: %w", err) + var actorAddrs []*netlink.Addr + var gateways []net.IP + if cfg.Families.IPv4 { + actorAddrs, gateways = append(actorAddrs, ActorVethAddr), append(gateways, ActorVethGwIP) + } + if cfg.Families.IPv6 { + actorAddrs, gateways = append(actorAddrs, actorVethAddrV6), append(gateways, actorVethGwIPv6) + } + for _, addr := range actorAddrs { + if err := netlink.AddrReplace(eth0, addr); err != nil { + return fmt.Errorf("while assigning the actor address %s: %w", addr, err) + } } if err := netlink.LinkSetUp(eth0); err != nil { return err } - return netlink.RouteReplace(&netlink.Route{ - LinkIndex: eth0.Attrs().Index, - Gw: ActorVethGwIP, - }) + for _, gw := range gateways { + if err := netlink.RouteReplace(&netlink.Route{LinkIndex: eth0.Attrs().Index, Gw: gw}); err != nil { + return fmt.Errorf("while adding the default route via %s: %w", gw, err) + } + } + return nil }); err != nil { return 0, err } @@ -258,14 +283,16 @@ func linkUp(name string) error { return netlink.LinkSetUp(link) } -// installEgressRules rejects link-local traffic before it reaches the egress PEP, -// then redirects other TCP egress to atunnel. The actor's own /30 is excluded -// from both rules so ingress replies and DNS reach their local sockets. -func installEgressRules(ns netns.Handle, egressPort uint16) error { +// installEgressRules rejects link-local and cloud metadata traffic before it +// reaches the egress PEP, then redirects other TCP egress to atunnel. The +// actor's own subnets are excluded from both rules so traffic to the gateway, +// such as ingress replies and DNS, reaches its local sockets. Only the +// sandbox's families are redirected. The filters cover both, and the gateway +// routes neither. +func installEgressRules(ns netns.Handle, egressPort uint16, families Families) error { const ( - icmpNetUnreachable = 0 - icmpDestinationAdministrativelyProhibited = 13 - icmpv6DestinationAdministrativelyProhibited = 1 + icmpNetUnreachable = 0 + icmpv6NoRoute = 0 ) if egressPort == 0 { @@ -277,22 +304,31 @@ func installEgressRules(ns netns.Handle, egressPort uint16) error { } defer func() { _ = c.CloseLasting() }() - var ipv4Table *nftables.Table for _, family := range []struct { tableFamily nftables.TableFamily name string - addressLen uint32 + subnet netip.Prefix dstOffset uint32 - rejectCode uint8 - isPrefix func(netip.Prefix) bool + noRouteCode uint8 + // neighborDiscovery lets ICMPv6 neighbor solicitations and + // advertisements through, which IPv6 needs to reach the gateway. + neighborDiscovery bool + redirect bool }{ - {nftables.TableFamilyIPv4, "worker-actor", 4, 16, icmpDestinationAdministrativelyProhibited, func(prefix netip.Prefix) bool { return prefix.Addr().Is4() }}, - {nftables.TableFamilyIPv6, "worker-actor-v6", 16, 24, icmpv6DestinationAdministrativelyProhibited, func(prefix netip.Prefix) bool { return prefix.Addr().Is6() }}, + {nftables.TableFamilyIPv4, "worker-actor", actorSubnet, 16, icmpNetUnreachable, false, families.IPv4}, + {nftables.TableFamilyIPv6, "worker-actor-v6", actorSubnetV6, 24, icmpv6NoRoute, true, families.IPv6}, } { - table := c.AddTable(&nftables.Table{Family: family.tableFamily, Name: family.name}) - if family.tableFamily == nftables.TableFamilyIPv4 { - ipv4Table = table + addressLen := uint32(family.subnet.Addr().BitLen() / 8) + // matchDst loads the destination address masked to prefix. + matchDst := func(prefix netip.Prefix, op expr.CmpOp) []expr.Any { + return []expr.Any{ + &expr.Payload{DestRegister: 1, Base: expr.PayloadBaseNetworkHeader, Offset: family.dstOffset, Len: addressLen}, + &expr.Bitwise{SourceRegister: 1, DestRegister: 1, Len: addressLen, Mask: net.CIDRMask(prefix.Bits(), int(addressLen*8)), Xor: make([]byte, addressLen)}, + &expr.Cmp{Op: op, Register: 1, Data: prefix.Masked().Addr().AsSlice()}, + } } + + table := c.AddTable(&nftables.Table{Family: family.tableFamily, Name: family.name}) // Backs up the forwarding sysctls: nothing in this namespace is routed. dropPolicy := nftables.ChainPolicyDrop c.AddChain(&nftables.Chain{ @@ -304,85 +340,78 @@ func installEgressRules(ns netns.Handle, egressPort uint16) error { Name: "disallowed-egress", Table: table, Type: nftables.ChainTypeFilter, Hooknum: nftables.ChainHookPrerouting, Priority: nftables.ChainPriorityRaw, }) - if family.tableFamily == nftables.TableFamilyIPv4 { - c.AddRule(&nftables.Rule{Table: table, Chain: filter, Exprs: []expr.Any{ - &expr.Payload{DestRegister: 1, Base: expr.PayloadBaseNetworkHeader, Offset: family.dstOffset, Len: family.addressLen}, - &expr.Bitwise{SourceRegister: 1, DestRegister: 1, Len: 4, Mask: actorSubnetMask, Xor: []byte{0, 0, 0, 0}}, - &expr.Cmp{Op: expr.CmpOpEq, Register: 1, Data: actorSubnetBase}, + c.AddRule(&nftables.Rule{Table: table, Chain: filter, Exprs: append( + matchDst(family.subnet, expr.CmpOpEq), &expr.Verdict{Kind: expr.VerdictAccept}, + )}) + if family.neighborDiscovery { + const ndNeighborSolicit, ndNeighborAdvert = 135, 136 + exprs := append(l4ProtocolEqual(unix.IPPROTO_ICMPV6), + &expr.Payload{DestRegister: 1, Base: expr.PayloadBaseTransportHeader, Offset: 0, Len: 1}, + &expr.Range{Op: expr.CmpOpEq, Register: 1, FromData: []byte{ndNeighborSolicit}, ToData: []byte{ndNeighborAdvert}}, &expr.Verdict{Kind: expr.VerdictAccept}, - }}) + ) + c.AddRule(&nftables.Rule{Table: table, Chain: filter, Exprs: exprs}) } - for _, prefix := range linkLocalEgressCIDRRanges { - if !family.isPrefix(prefix) { + for _, prefix := range rejectedEgressPrefixes { + if prefix.Addr().BitLen() != family.subnet.Addr().BitLen() { continue } - mask := net.CIDRMask(prefix.Bits(), int(family.addressLen*8)) - address := prefix.Addr().AsSlice() - expressions := []expr.Any{ - &expr.Payload{DestRegister: 1, Base: expr.PayloadBaseNetworkHeader, Offset: family.dstOffset, Len: family.addressLen}, - } - expressions = append(expressions, - &expr.Bitwise{SourceRegister: 1, DestRegister: 1, Len: family.addressLen, Mask: mask, Xor: make([]byte, family.addressLen)}, - &expr.Cmp{Op: expr.CmpOpEq, Register: 1, Data: address}, - &expr.Reject{Type: unix.NFT_REJECT_ICMP_UNREACH, Code: family.rejectCode}, - ) - c.AddRule(&nftables.Rule{Table: table, Chain: filter, Exprs: expressions}) + // Linux TCP ignores an ICMP error that arrives while connect + // still holds the socket, and the actor would wait out a SYN + // retransmit. A reset fails connect at once. The non-TCP rule + // below rejects other protocols. + reject := append(matchDst(prefix, expr.CmpOpEq), l4ProtocolEqual(unix.IPPROTO_TCP)...) + reject = append(reject, &expr.Reject{Type: unix.NFT_REJECT_TCP_RST}) + c.AddRule(&nftables.Rule{Table: table, Chain: filter, Exprs: reject}) } - if family.tableFamily == nftables.TableFamilyIPv4 { - // With forwarding off, the kernel drops unroutable packets silently instead - // of returning ICMP net unreachable. Reject non-TCP egress leaving the /30 - // so UDP or ping fails fast rather than waiting out a timeout. - expressions := append(l4ProtocolNotEqual(unix.IPPROTO_TCP), - &expr.Reject{Type: unix.NFT_REJECT_ICMP_UNREACH, Code: icmpNetUnreachable}, - ) - c.AddRule(&nftables.Rule{Table: table, Chain: filter, Exprs: expressions}) + // With forwarding off, the kernel drops unroutable packets silently instead + // of returning ICMP net unreachable. Reject non-TCP egress leaving the + // subnet so UDP or ping fails fast rather than waiting out a timeout. + c.AddRule(&nftables.Rule{Table: table, Chain: filter, Exprs: append( + l4ProtocolNotEqual(unix.IPPROTO_TCP), + &expr.Reject{Type: unix.NFT_REJECT_ICMP_UNREACH, Code: family.noRouteCode}, + )}) + + if !family.redirect { + continue } + prerouting := c.AddChain(&nftables.Chain{ + Name: "prerouting", Table: table, Type: nftables.ChainTypeNAT, + Hooknum: nftables.ChainHookPrerouting, Priority: nftables.ChainPriorityNATDest, + }) + exprs := matchDst(family.subnet, expr.CmpOpNeq) + exprs = append(exprs, l4ProtocolEqual(unix.IPPROTO_TCP)...) + exprs = append(exprs, + &expr.Immediate{Register: 1, Data: binaryutil.BigEndian.PutUint16(egressPort)}, + &expr.Redir{RegisterProtoMin: 1}, + ) + c.AddRule(&nftables.Rule{Table: table, Chain: prerouting, Exprs: exprs}) } - prerouting := c.AddChain(&nftables.Chain{ - Name: "prerouting", Table: ipv4Table, Type: nftables.ChainTypeNAT, - Hooknum: nftables.ChainHookPrerouting, Priority: nftables.ChainPriorityNATDest, - }) - - // Offset of the destination address in an IPv4 header. - const ipv4HeaderDst = 16 - exprs := []expr.Any{ - &expr.Payload{DestRegister: 1, Base: expr.PayloadBaseNetworkHeader, Offset: ipv4HeaderDst, Len: 4}, - &expr.Bitwise{ - SourceRegister: 1, DestRegister: 1, Len: 4, - Mask: actorSubnetMask, Xor: []byte{0, 0, 0, 0}, - }, - &expr.Cmp{Op: expr.CmpOpNeq, Register: 1, Data: actorSubnetBase}, - } - exprs = append(exprs, l4ProtocolEqual(unix.IPPROTO_TCP)...) - exprs = append(exprs, - &expr.Immediate{Register: 1, Data: binaryutil.BigEndian.PutUint16(egressPort)}, - &expr.Redir{RegisterProtoMin: 1}, - ) - c.AddRule(&nftables.Rule{Table: ipv4Table, Chain: prerouting, Exprs: exprs}) - if err := c.Flush(); err != nil { return fmt.Errorf("while installing the actor egress redirect: %w", err) } return nil } -// linkLocalEgressCIDRRanges cover all IPv4 and IPv6 link-local space. The -// nftables chain accepts the actor's 169.254.17.0/30 first because that network -// carries actor ingress and DNS relay traffic. -var linkLocalEgressCIDRRanges = []netip.Prefix{ +// rejectedEgressPrefixes cover all IPv4 and IPv6 link-local space, which holds +// the IPv4 cloud metadata servers, EC2's IPv6 metadata, DNS and NTP servers, +// and Compute Engine's IPv6 metadata server. IPv4-mapped destinations are rejected because atunnel would +// pass them on as IPv4, and NAT64's well-known prefix because the PEP's network +// may translate it. The nftables chain accepts the actor's own subnets first. +var rejectedEgressPrefixes = []netip.Prefix{ netip.MustParsePrefix("169.254.0.0/16"), netip.MustParsePrefix("fe80::/10"), + netip.MustParsePrefix("fd00:ec2::/64"), + netip.MustParsePrefix("fd20:ce::254/128"), + netip.MustParsePrefix("::ffff:0:0/96"), + netip.MustParsePrefix("64:ff9b::a9fe:0/112"), } -// The actor subnet, in the form the nftables comparison takes. -var actorSubnetBase, actorSubnetMask = func() ([]byte, []byte) { - _, subnet, err := net.ParseCIDR(ActorVethSubnet) - if err != nil { - panic(fmt.Sprintf("parsing constant actor subnet %q: %v", ActorVethSubnet, err)) - } - return subnet.IP.To4(), subnet.Mask -}() +var ( + actorSubnet = netip.MustParsePrefix(ActorVethSubnet) + actorSubnetV6 = netip.MustParsePrefix(ActorVethSubnetV6) +) // gatewayVethName is the veth peer in the gateway namespace. const gatewayVethName = "atside" diff --git a/internal/ateworker/actornet/sandbox_atunnel_linux_test.go b/internal/ateworker/actornet/sandbox_atunnel_linux_test.go index fd4f54f47f..d73199b3f8 100644 --- a/internal/ateworker/actornet/sandbox_atunnel_linux_test.go +++ b/internal/ateworker/actornet/sandbox_atunnel_linux_test.go @@ -20,30 +20,104 @@ package actornet_test import ( "context" + "errors" + "fmt" "io" "net" + "net/netip" + "syscall" "testing" "time" + "github.com/vishvananda/netlink" + "go.ate.dev/substrate/internal/ateworker/actornet" "go.ate.dev/substrate/internal/linuxsys" "go.ate.dev/substrate/internal/netns" "go.ate.dev/substrate/internal/roottest" ) -// Verify redirection preserves the destination, including unconfigured ports. +var testFamilies = []struct { + name string + families actornet.Families +}{ + {"ipv4", actornet.Families{IPv4: true}}, + {"ipv6", actornet.Families{IPv6: true}}, + {"dual", actornet.Families{IPv4: true, IPv6: true}}, +} + +// inFamilies reports whether destination, a host:port, is in one of families. +func inFamilies(t *testing.T, families actornet.Families, destination string) bool { + t.Helper() + ap, err := netip.ParseAddrPort(destination) + if err != nil { + t.Fatal(err) + } + if ap.Addr().Is4() { + return families.IPv4 + } + return families.IPv6 +} + +// waitOperUp waits until the sandbox's veth ends are operationally up. Until +// the kernel's link watch activates a new veth it drops what is sent on it, +// and the dial would wait out a SYN retransmit. +func waitOperUp(t *testing.T, n *actornet.SandboxNetwork) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + for _, end := range []struct { + ns netns.Handle + name string + }{{n.RuntimeNetNS, actornet.ActorVethName}, {n.GatewayNetNS, "atside"}} { + if err := netns.Do(ctx, end.ns, func(ctx context.Context) error { + updates := make(chan netlink.LinkUpdate) + done := make(chan struct{}) + defer close(done) + if err := netlink.LinkSubscribe(updates, done); err != nil { + return err + } + for { + link, err := netlink.LinkByName(end.name) + if err != nil { + return err + } + if link.Attrs().OperState == netlink.OperUp { + return nil + } + select { + case <-updates: + case <-ctx.Done(): + return fmt.Errorf("%s is %s: %w", end.name, link.Attrs().OperState, ctx.Err()) + } + } + }); err != nil { + t.Fatalf("waiting for the veth: %v", err) + } + } +} + +// Verify redirection preserves the destination, including unconfigured ports, +// and that a family the sandbox lacks has no egress at all. func TestSandboxEgressReachesAtunnelOnAnyPort(t *testing.T) { roottest.Require(t, "creates network namespaces") + for _, tc := range testFamilies { + t.Run(tc.name, func(t *testing.T) { testSandboxEgressReachesAtunnel(t, tc.families) }) + } +} + +func testSandboxEgressReachesAtunnel(t *testing.T, families actornet.Families) { ctx := context.Background() const egressPort = 15001 n, err := actornet.SetupSandboxNetwork(ctx, actornet.SandboxNetworkConfig{ - ActorUID: "66666666-6666-6666-6666-666666666666", Veth: true, EgressPort: egressPort, + ActorUID: "66666666-6666-6666-6666-666666666666", Veth: true, Families: families, EgressPort: egressPort, }) if err != nil { t.Fatalf("SetupSandboxNetwork: %v", err) } t.Cleanup(func() { actornet.CleanupSandboxNetwork(n) }) + waitOperUp(t, n) listeners, err := netns.Listen(ctx, n.GatewayNetNS, []uint16{egressPort}) if err != nil { @@ -70,17 +144,24 @@ func TestSandboxEgressReachesAtunnelOnAnyPort(t *testing.T) { } go accept() - for _, want := range []string{"93.184.216.34:443", "93.184.216.34:8080", "93.184.216.34:9999"} { - if err := netns.Do(ctx, n.RuntimeNetNS, func(context.Context) error { - c, err := net.Dial("tcp", want) + for _, want := range []string{"93.184.216.34:443", "93.184.216.34:8080", "93.184.216.34:9999", "[2001:db8::1]:443", "[2001:db8::1]:9999"} { + dialErr := netns.Do(ctx, n.RuntimeNetNS, func(context.Context) error { + c, err := net.DialTimeout("tcp", want, 3*time.Second) if err != nil { return err } defer c.Close() _, err = io.WriteString(c, "hello") return err - }); err != nil { - t.Fatalf("sandbox egress dial to %s: %v", want, err) + }) + if !inFamilies(t, families, want) { + if !errors.Is(dialErr, syscall.ENETUNREACH) { + t.Errorf("dial to %s outside the sandbox's families = %v, want network unreachable", want, dialErr) + } + continue + } + if dialErr != nil { + t.Fatalf("sandbox egress dial to %s: %v", want, dialErr) } select { case c := <-got: @@ -99,18 +180,26 @@ func TestSandboxEgressReachesAtunnelOnAnyPort(t *testing.T) { func TestSandboxLinkLocalDoesNotReachAtunnel(t *testing.T) { roottest.Require(t, "creates network namespaces") + for _, tc := range testFamilies { + t.Run(tc.name, func(t *testing.T) { testSandboxLinkLocalDoesNotReachAtunnel(t, tc.families) }) + } +} + +func testSandboxLinkLocalDoesNotReachAtunnel(t *testing.T, families actornet.Families) { ctx := context.Background() const egressPort = 15001 n, err := actornet.SetupSandboxNetwork(ctx, actornet.SandboxNetworkConfig{ ActorUID: "99999999-9999-9999-9999-999999999999", Veth: true, + Families: families, EgressPort: egressPort, }) if err != nil { t.Fatalf("SetupSandboxNetwork: %v", err) } t.Cleanup(func() { actornet.CleanupSandboxNetwork(n) }) + waitOperUp(t, n) listeners, err := netns.Listen(ctx, n.GatewayNetNS, []uint16{egressPort}) if err != nil { @@ -119,56 +208,67 @@ func TestSandboxLinkLocalDoesNotReachAtunnel(t *testing.T) { defer listeners[0].Close() listener := listeners[0].(*net.TCPListener) - if err := listener.SetDeadline(time.Now().Add(500 * time.Millisecond)); err != nil { - t.Fatal(err) - } - var linkLocalDialErr error - if err := netns.Do(ctx, n.RuntimeNetNS, func(context.Context) error { - conn, err := net.DialTimeout("tcp", "169.254.169.254:80", 250*time.Millisecond) - linkLocalDialErr = err - if conn != nil { + // fe80::/10 is on-link, so the actor never routes it to the gateway. + for _, rejected := range []string{"169.254.169.254:80", "[fd00:ec2::254]:80", "[fd20:ce::254]:80"} { + if !inFamilies(t, families, rejected) { + continue + } + var dialErr error + if err := netns.Do(ctx, n.RuntimeNetNS, func(context.Context) error { + // Under the 1s SYN retransmit, so a dropped SYN times out. + conn, err := net.DialTimeout("tcp", rejected, 750*time.Millisecond) + dialErr = err + if conn != nil { + conn.Close() + } + return nil + }); err != nil { + t.Fatalf("dial to %s: %v", rejected, err) + } + if dialErr == nil { + t.Fatalf("dial to %s succeeded", rejected) + } + if timeout, ok := dialErr.(net.Error); ok && timeout.Timeout() { + t.Fatalf("dial to %s timed out instead of being rejected: %v", rejected, dialErr) + } + if err := listener.SetDeadline(time.Now().Add(250 * time.Millisecond)); err != nil { + t.Fatal(err) + } + if conn, err := listener.Accept(); err == nil { conn.Close() + t.Fatalf("connection to %s reached atunnel", rejected) + } else if timeout, ok := err.(net.Error); !ok || !timeout.Timeout() { + t.Fatalf("Accept after dialing %s: %v", rejected, err) } - return nil - }); err != nil { - t.Fatalf("dial to link-local address: %v", err) - } - if linkLocalDialErr == nil { - t.Fatal("dial to link-local address succeeded") - } - if timeout, ok := linkLocalDialErr.(net.Error); ok && timeout.Timeout() { - t.Fatalf("link-local dial timed out instead of being rejected: %v", linkLocalDialErr) - } - if conn, err := listener.Accept(); err == nil { - conn.Close() - t.Fatal("link-local connection reached atunnel") - } else if timeout, ok := err.(net.Error); !ok || !timeout.Timeout() { - t.Fatalf("Accept after link-local dial: %v", err) } if err := listener.SetDeadline(time.Time{}); err != nil { t.Fatal(err) } - const allowedDestination = "192.0.2.1:443" - if err := netns.Do(ctx, n.RuntimeNetNS, func(context.Context) error { - conn, err := net.Dial("tcp", allowedDestination) + for _, allowed := range []string{"192.0.2.1:443", "[2001:db8::1]:443"} { + if !inFamilies(t, families, allowed) { + continue + } + if err := netns.Do(ctx, n.RuntimeNetNS, func(context.Context) error { + conn, err := net.Dial("tcp", allowed) + if err != nil { + return err + } + return conn.Close() + }); err != nil { + t.Fatalf("dial to allowed CIDR: %v", err) + } + conn, err := listener.Accept() if err != nil { - return err + t.Fatalf("accept allowed connection: %v", err) + } + destination, err := linuxsys.TCPOriginalDestination(conn) + conn.Close() + if err != nil { + t.Fatalf("TCPOriginalDestination: %v", err) + } + if destination != allowed { + t.Errorf("atunnel saw destination %q, want %q", destination, allowed) } - return conn.Close() - }); err != nil { - t.Fatalf("dial to allowed CIDR: %v", err) - } - conn, err := listener.Accept() - if err != nil { - t.Fatalf("accept allowed connection: %v", err) - } - defer conn.Close() - destination, err := linuxsys.TCPOriginalDestination(conn) - if err != nil { - t.Fatalf("TCPOriginalDestination: %v", err) - } - if destination != allowedDestination { - t.Errorf("atunnel saw destination %q, want %q", destination, allowedDestination) } } diff --git a/internal/ateworker/actornet/sandbox_linux_test.go b/internal/ateworker/actornet/sandbox_linux_test.go index 1c5af924d3..b952164cc8 100644 --- a/internal/ateworker/actornet/sandbox_linux_test.go +++ b/internal/ateworker/actornet/sandbox_linux_test.go @@ -33,6 +33,9 @@ import ( "github.com/google/nftables" "github.com/vishvananda/netlink" + "golang.org/x/net/dns/dnsmessage" + + "go.ate.dev/substrate/internal/atunnel/dns" "go.ate.dev/substrate/internal/nodepath" "go.ate.dev/substrate/internal/netns" @@ -41,6 +44,135 @@ import ( const testEgressPort = 15001 +var dualStack = Families{IPv4: true, IPv6: true} + +// testFamilies are the sandbox shapes every family-dependent test covers. +var testFamilies = []struct { + name string + families Families +}{ + {"ipv4", Families{IPv4: true}}, + {"ipv6", Families{IPv6: true}}, + {"dual", dualStack}, +} + +func TestPodFamilies(t *testing.T) { + for _, tc := range []struct { + podIPs []string + want Families + wantErr bool + }{ + {podIPs: []string{"10.0.0.1"}, want: Families{IPv4: true}}, + {podIPs: []string{"fd00::1"}, want: Families{IPv6: true}}, + {podIPs: []string{"10.0.0.1", "fd00::1"}, want: dualStack}, + {podIPs: []string{"::ffff:10.0.0.1"}, want: Families{IPv4: true}}, + {podIPs: nil, wantErr: true}, + {podIPs: []string{"not-an-ip"}, wantErr: true}, + } { + got, err := PodFamilies(tc.podIPs) + if (err != nil) != tc.wantErr || got != tc.want { + t.Errorf("PodFamilies(%q) = %+v, %v; want %+v, error %v", tc.podIPs, got, err, tc.want, tc.wantErr) + } + } +} + +func TestSetupSandboxNetworkNeedsAFamily(t *testing.T) { + if _, err := SetupSandboxNetwork(context.Background(), SandboxNetworkConfig{ActorUID: "no-family", EgressPort: testEgressPort}); err == nil { + t.Fatal("SetupSandboxNetwork with no IP family succeeded") + } +} + +// The actor's resolv.conf names the gateway in each of its families, so the +// relay must answer on every one of them, over UDP and TCP. A nil policy +// refuses every name, so the answer is NXDOMAIN and the upstream sees no +// query. TCP still connects to it for each client. +func TestSandboxDNSAnswersOnEveryGatewayAddress(t *testing.T) { + roottest.Require(t, "creates network namespaces") + upstream, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { upstream.Close() }) + go func() { + for { + c, err := upstream.Accept() + if err != nil { + return + } + t.Cleanup(func() { c.Close() }) + } + }() + relay, err := dns.NewRelayForUpstreams([]string{upstream.Addr().String()}) + if err != nil { + t.Fatal(err) + } + b := dnsmessage.NewBuilder(nil, dnsmessage.Header{ID: 0x5ad, RecursionDesired: true}) + if err := b.StartQuestions(); err != nil { + t.Fatal(err) + } + if err := b.Question(dnsmessage.Question{Name: dnsmessage.MustNewName("example.com."), Type: dnsmessage.TypeAAAA, Class: dnsmessage.ClassINET}); err != nil { + t.Fatal(err) + } + query, err := b.Finish() + if err != nil { + t.Fatal(err) + } + + for _, tc := range testFamilies { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + session, err := ServeSandbox(ctx, SandboxNetworkConfig{ + ActorUID: "dns-" + tc.name, Veth: true, Families: tc.families, EgressPort: testEgressPort, + }, nil, relay) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = session.Close(context.Background()) }) + + for _, nameserver := range tc.families.gatewayIPs() { + for _, network := range []string{"udp", "tcp"} { + var answer []byte + if err := netns.Do(ctx, session.Network.RuntimeNetNS, func(context.Context) error { + c, err := net.DialTimeout(network, net.JoinHostPort(nameserver, "53"), 5*time.Second) + if err != nil { + return err + } + defer c.Close() + _ = c.SetDeadline(time.Now().Add(5 * time.Second)) + msg := query + if network == "tcp" { + msg = append([]byte{byte(len(query) >> 8), byte(len(query))}, query...) + } + if _, err := c.Write(msg); err != nil { + return err + } + buf := make([]byte, 512) + n, err := c.Read(buf) + if err != nil { + return err + } + answer = buf[:n] + if network == "tcp" { + answer = answer[2:] + } + return nil + }); err != nil { + t.Fatalf("querying %s over %s: %v", nameserver, network, err) + } + var p dnsmessage.Parser + h, err := p.Start(answer) + if err != nil { + t.Fatalf("parsing the answer from %s over %s: %v", nameserver, network, err) + } + if h.ID != 0x5ad || h.RCode != dnsmessage.RCodeNameError { + t.Errorf("%s over %s answered id %#x rcode %v, want id 0x5ad NXDOMAIN", nameserver, network, h.ID, h.RCode) + } + } + } + }) + } +} + func TestSandboxSessionDialerAfterClose(t *testing.T) { session := &SandboxSession{} dial := session.Dialer() @@ -55,7 +187,7 @@ func TestSandboxSessionDialerAfterClose(t *testing.T) { func TestSandboxSessionDialerConcurrentClose(t *testing.T) { roottest.Require(t, "creates network namespaces") session, err := ServeSandbox(context.Background(), SandboxNetworkConfig{ - ActorUID: "concurrent-close", EgressPort: testEgressPort, + ActorUID: "concurrent-close", Families: dualStack, EgressPort: testEgressPort, }, nil, nil) if err != nil { t.Fatal(err) @@ -90,7 +222,14 @@ func TestSandboxSessionDialerConcurrentClose(t *testing.T) { func TestSetupSandboxNetwork(t *testing.T) { roottest.Require(t, "creates network namespaces") + for _, tc := range testFamilies { + t.Run(tc.name, func(t *testing.T) { testSetupSandboxNetwork(t, tc.families) }) + } +} + +func testSetupSandboxNetwork(t *testing.T, families Families) { ctx := context.Background() + actorAddr := net.JoinHostPort(families.ActorIP(), "80") type actor struct { net *SandboxNetwork @@ -98,7 +237,7 @@ func TestSetupSandboxNetwork(t *testing.T) { } actors := map[string]*actor{} for _, uid := range []string{"11111111-1111-1111-1111-111111111111", "22222222-2222-2222-2222-222222222222"} { - n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ActorUID: uid, Veth: true, EgressPort: testEgressPort}) + n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ActorUID: uid, Veth: true, Families: families, EgressPort: testEgressPort}) if err != nil { t.Fatalf("SetupSandboxNetwork(%s): %v", uid, err) } @@ -111,7 +250,7 @@ func TestSetupSandboxNetwork(t *testing.T) { // The actor's app, bound where a real one binds, inside its namespace. var lis net.Listener if err := netns.Do(ctx, n.RuntimeNetNS, func(context.Context) error { - l, err := net.Listen("tcp", net.JoinHostPort(ActorVethIP, "80")) + l, err := net.Listen("tcp", actorAddr) lis = l return err }); err != nil { @@ -128,7 +267,7 @@ func TestSetupSandboxNetwork(t *testing.T) { // Reaching each actor is a matter of which namespace the dial is made from. for uid, a := range actors { client := &http.Client{Transport: &http.Transport{DialContext: netns.Dialer(a.net.RuntimeNetNS)}, Timeout: 5 * time.Second} - resp, err := client.Get((&url.URL{Scheme: "http", Host: net.JoinHostPort(ActorVethIP, "80")}).String()) + resp, err := client.Get((&url.URL{Scheme: "http", Host: actorAddr}).String()) if err != nil { t.Fatalf("reaching actor %s: %v", uid, err) } @@ -141,42 +280,103 @@ func TestSetupSandboxNetwork(t *testing.T) { // Sandbox addresses must not be reachable from the worker namespace. direct := &http.Client{Timeout: 2 * time.Second} - if _, err := direct.Get("http://" + net.JoinHostPort(ActorVethIP, "80")); err == nil { + if _, err := direct.Get("http://" + actorAddr); err == nil { t.Error("the worker namespace reached an actor directly; addresses are not isolated") } + + // The actor has addresses and a default route in its families only. + for _, a := range actors { + if err := netns.Do(ctx, a.net.RuntimeNetNS, func(context.Context) error { + eth0, err := netlink.LinkByName(ActorVethName) + if err != nil { + return err + } + for _, f := range []struct { + family int + want bool + addr string + }{ + {netlink.FAMILY_V4, families.IPv4, ActorVethIP}, + {netlink.FAMILY_V6, families.IPv6, ActorVethIPv6}, + } { + addrs, err := netlink.AddrList(eth0, f.family) + if err != nil { + return err + } + var found bool + for _, addr := range addrs { + // The kernel adds an IPv6 link-local address of its own. + if addr.IP.To4() == nil && addr.IP.IsLinkLocalUnicast() { + continue + } + if addr.IP.String() != f.addr { + t.Errorf("unexpected address %s on the actor's %s", addr.IP, ActorVethName) + } + found = true + } + if found != f.want { + t.Errorf("actor address %s present = %v, want %v", f.addr, found, f.want) + } + routes, err := netlink.RouteList(eth0, f.family) + if err != nil { + return err + } + var defaultRoute bool + for _, r := range routes { + defaultRoute = defaultRoute || (r.Gw != nil && (r.Dst == nil || r.Dst.IP.IsUnspecified())) + } + if defaultRoute != f.want { + t.Errorf("family %d default route present = %v, want %v", f.family, defaultRoute, f.want) + } + } + return nil + }); err != nil { + t.Fatalf("inspecting the actor's interface: %v", err) + } + } } func TestActorEgressIsFailClosedWithoutAtunnel(t *testing.T) { roottest.Require(t, "creates network namespaces") ctx := context.Background() - n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ - ActorUID: "33333333-3333-3333-3333-333333333333", Veth: true, EgressPort: testEgressPort, - }) - if err != nil { - t.Fatalf("SetupSandboxNetwork: %v", err) - } - t.Cleanup(func() { CleanupSandboxNetwork(n) }) - - for _, destination := range []string{"93.184.216.34:443", "93.184.216.34:8080"} { - if err := netns.Do(ctx, n.RuntimeNetNS, func(context.Context) error { - c, err := net.DialTimeout("tcp", destination, 3*time.Second) + for _, tc := range testFamilies { + t.Run(tc.name, func(t *testing.T) { + n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ + ActorUID: "33333333-3333-3333-3333-333333333333", Veth: true, Families: tc.families, EgressPort: testEgressPort, + }) if err != nil { - return err + t.Fatalf("SetupSandboxNetwork: %v", err) } - c.Close() - return nil - }); err == nil { - t.Errorf("the actor reached %s with no atunnel listening; egress is not fail-closed", destination) - } + t.Cleanup(func() { CleanupSandboxNetwork(n) }) + + for _, destination := range []string{"93.184.216.34:443", "93.184.216.34:8080", "[2001:db8::1]:443"} { + if err := netns.Do(ctx, n.RuntimeNetNS, func(context.Context) error { + c, err := net.DialTimeout("tcp", destination, 3*time.Second) + if err != nil { + return err + } + c.Close() + return nil + }); err == nil { + t.Errorf("the actor reached %s with no atunnel listening; egress is not fail-closed", destination) + } + } + }) } } func TestIngressCrossesThePairWhileEgressIsCaptured(t *testing.T) { roottest.Require(t, "creates network namespaces") + for _, tc := range testFamilies { + t.Run(tc.name, func(t *testing.T) { testIngressCrossesThePair(t, tc.families) }) + } +} + +func testIngressCrossesThePair(t *testing.T, families Families) { ctx := context.Background() - n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ActorUID: "44444444-4444-4444-4444-444444444444", Veth: true, EgressPort: testEgressPort}) + n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ActorUID: "44444444-4444-4444-4444-444444444444", Veth: true, Families: families, EgressPort: testEgressPort}) if err != nil { t.Fatalf("SetupSandboxNetwork: %v", err) } @@ -184,7 +384,7 @@ func TestIngressCrossesThePairWhileEgressIsCaptured(t *testing.T) { var app net.Listener if err := netns.Do(ctx, n.RuntimeNetNS, func(context.Context) error { - l, e := net.Listen("tcp", net.JoinHostPort(ActorVethIP, "80")) + l, e := net.Listen("tcp", net.JoinHostPort(families.ActorIP(), "80")) app = l return e }); err != nil { @@ -203,7 +403,7 @@ func TestIngressCrossesThePairWhileEgressIsCaptured(t *testing.T) { }() dial := netns.Dialer(n.GatewayNetNS) - c, err := dial(ctx, "tcp", net.JoinHostPort(ActorVethIP, "80")) + c, err := dial(ctx, "tcp", net.JoinHostPort(families.ActorIP(), "80")) if err != nil { t.Fatalf("ingress dial: %v", err) } @@ -216,7 +416,7 @@ func TestIngressCrossesThePairWhileEgressIsCaptured(t *testing.T) { // An unopened port must be refused, not redirected to atunnel. cctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() - if c2, e := dial(cctx, "tcp", net.JoinHostPort(ActorVethIP, "81")); e == nil { + if c2, e := dial(cctx, "tcp", net.JoinHostPort(families.ActorIP(), "81")); e == nil { c2.Close() t.Error("a port with no listener was accepted, so ingress is not reaching the sandbox") } @@ -229,6 +429,7 @@ func TestSetupSandboxNetworkWithoutVeth(t *testing.T) { n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ ActorUID: "77777777-7777-7777-7777-777777777777", + Families: dualStack, EgressPort: testEgressPort, }) if err != nil { @@ -261,7 +462,7 @@ func TestSetupSucceedsOverALeftoverNamespace(t *testing.T) { roottest.Require(t, "creates network namespaces") ctx := context.Background() const uid = "aaaaaaaa-0000-0000-0000-00000000000a" - cfg := SandboxNetworkConfig{ActorUID: uid, Veth: true, EgressPort: testEgressPort} + cfg := SandboxNetworkConfig{ActorUID: uid, Veth: true, Families: dualStack, EgressPort: testEgressPort} first, err := SetupSandboxNetwork(ctx, cfg) if err != nil { @@ -300,14 +501,14 @@ func TestActorUDPHasNowhereToGoBeyondTheNamespacePair(t *testing.T) { ctx := context.Background() n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ - ActorUID: "bbbbbbbb-0000-0000-0000-00000000000b", Veth: true, EgressPort: testEgressPort, + ActorUID: "bbbbbbbb-0000-0000-0000-00000000000b", Veth: true, Families: dualStack, EgressPort: testEgressPort, }) if err != nil { t.Fatalf("SetupSandboxNetwork: %v", err) } t.Cleanup(func() { CleanupSandboxNetwork(n) }) - for _, destination := range []string{"93.184.216.34:443", "93.184.216.34:53"} { + for _, destination := range []string{"93.184.216.34:443", "93.184.216.34:53", "[2001:db8::1]:443", "[2001:db8::1]:53"} { if err := netns.Do(ctx, n.GatewayNetNS, func(context.Context) error { c, err := net.Dial("udp", destination) if err != nil { @@ -326,6 +527,7 @@ func TestCleanupClosesEachDescriptorOnce(t *testing.T) { roottest.Require(t, "creates network namespaces") network, err := SetupSandboxNetwork(context.Background(), SandboxNetworkConfig{ ActorUID: "close-once", + Families: dualStack, EgressPort: 15001, }) if err != nil { @@ -359,7 +561,7 @@ func TestSessionCloseWaitsForServingToStop(t *testing.T) { roottest.Require(t, "creates network namespaces") egress := &slowEgress{release: make(chan struct{})} session, err := ServeSandbox(context.Background(), SandboxNetworkConfig{ - ActorUID: "close-waits", EgressPort: testEgressPort, + ActorUID: "close-waits", Families: dualStack, EgressPort: testEgressPort, }, egress, nil) if err != nil { t.Fatal(err) @@ -392,7 +594,7 @@ func TestSessionCloseReportsAWaitItCouldNotFinish(t *testing.T) { egress := &slowEgress{release: make(chan struct{})} defer close(egress.release) session, err := ServeSandbox(context.Background(), SandboxNetworkConfig{ - ActorUID: "close-deadline", EgressPort: testEgressPort, + ActorUID: "close-deadline", Families: dualStack, EgressPort: testEgressPort, }, egress, nil) if err != nil { t.Fatal(err) @@ -412,9 +614,8 @@ func TestSessionCloseReportsAWaitItCouldNotFinish(t *testing.T) { // the node's own setting is. func TestSandboxNamespacesDoNotForward(t *testing.T) { roottest.Require(t, "creates network namespaces") - ctx := context.Background() - for _, tc := range []struct { + for _, shape := range []struct { name string uid string veth bool @@ -422,68 +623,85 @@ func TestSandboxNamespacesDoNotForward(t *testing.T) { {"veth", "cccccccc-0000-0000-0000-00000000000c", true}, {"tap", "dddddddd-0000-0000-0000-00000000000d", false}, } { - t.Run(tc.name, func(t *testing.T) { - n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ActorUID: tc.uid, Veth: tc.veth, EgressPort: testEgressPort}) - if err != nil { - t.Fatalf("SetupSandboxNetwork: %v", err) - } - t.Cleanup(func() { CleanupSandboxNetwork(n) }) + for _, tc := range testFamilies { + t.Run(shape.name+"/"+tc.name, func(t *testing.T) { testSandboxDoesNotForward(t, shape.uid, shape.veth, tc.families) }) + } + } +} - for _, ns := range []netns.Handle{n.RuntimeNetNS, n.GatewayNetNS} { - if err := netns.Do(ctx, ns, func(context.Context) error { - for _, key := range []string{ - "net/ipv4/conf/all/forwarding", - "net/ipv4/conf/default/forwarding", - } { - b, err := os.ReadFile("/proc/sys/" + key) - if err != nil { - return err - } - if got := strings.TrimSpace(string(b)); got != "0" { - t.Errorf("%s = %s in the sandbox namespace, want 0", key, got) - } - } - return nil - }); err != nil { - t.Fatalf("reading forwarding sysctls: %v", err) - } - } +func testSandboxDoesNotForward(t *testing.T, uid string, veth bool, families Families) { + ctx := context.Background() + n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ActorUID: uid, Veth: veth, Families: families, EgressPort: testEgressPort}) + if err != nil { + t.Fatalf("SetupSandboxNetwork: %v", err) + } + t.Cleanup(func() { CleanupSandboxNetwork(n) }) - c, err := nftables.New(nftables.WithNetNSFd(int(n.GatewayNetNS))) - if err != nil { - t.Fatal(err) - } - chains, err := c.ListChains() - if err != nil { - t.Fatal(err) - } - dropping := map[nftables.TableFamily]bool{} - var foundDisallowedEgress bool - for _, ch := range chains { - if ch.Hooknum != nil && *ch.Hooknum == *nftables.ChainHookForward && - ch.Policy != nil && *ch.Policy == nftables.ChainPolicyDrop { - dropping[ch.Table.Family] = true + for _, ns := range []netns.Handle{n.RuntimeNetNS, n.GatewayNetNS} { + if err := netns.Do(ctx, ns, func(context.Context) error { + for _, key := range []string{ + "net/ipv4/conf/all/forwarding", + "net/ipv4/conf/default/forwarding", + } { + b, err := os.ReadFile("/proc/sys/" + key) + if err != nil { + return err } - if ch.Table.Family == nftables.TableFamilyIPv4 && ch.Name == "disallowed-egress" { - foundDisallowedEgress = true - rules, err := c.GetRules(ch.Table, ch) - if err != nil { - t.Fatalf("getting disallowed-egress rules: %v", err) - } - if len(rules) != 3 { - t.Errorf("disallowed-egress has %d rules, want 3", len(rules)) - } + if got := strings.TrimSpace(string(b)); got != "0" { + t.Errorf("%s = %s in the sandbox namespace, want 0", key, got) } } - for _, family := range []nftables.TableFamily{nftables.TableFamilyIPv4, nftables.TableFamilyIPv6} { - if !dropping[family] { - t.Errorf("no forward-hook chain with a drop policy for family %v", family) - } + return nil + }); err != nil { + t.Fatalf("reading forwarding sysctls: %v", err) + } + } + + c, err := nftables.New(nftables.WithNetNSFd(int(n.GatewayNetNS))) + if err != nil { + t.Fatal(err) + } + chains, err := c.ListChains() + if err != nil { + t.Fatal(err) + } + dropping := map[nftables.TableFamily]bool{} + // The subnet accept, the rejected prefixes and the non-TCP + // reject, plus the ICMPv6 accept for IPv6. + wantDisallowedEgressRules := map[nftables.TableFamily]int{ + nftables.TableFamilyIPv4: 3, + nftables.TableFamilyIPv6: 8, + } + redirecting := map[nftables.TableFamily]bool{} + for _, ch := range chains { + if ch.Hooknum != nil && *ch.Hooknum == *nftables.ChainHookForward && + ch.Policy != nil && *ch.Policy == nftables.ChainPolicyDrop { + dropping[ch.Table.Family] = true + } + if ch.Type == nftables.ChainTypeNAT && ch.Name == "prerouting" { + redirecting[ch.Table.Family] = true + } + if ch.Name == "disallowed-egress" { + rules, err := c.GetRules(ch.Table, ch) + if err != nil { + t.Fatalf("getting disallowed-egress rules: %v", err) } - if !foundDisallowedEgress { - t.Error("no disallowed-egress chain found in IPv4 table") + if want := wantDisallowedEgressRules[ch.Table.Family]; len(rules) != want { + t.Errorf("disallowed-egress in family %v has %d rules, want %d", ch.Table.Family, len(rules), want) } - }) + delete(wantDisallowedEgressRules, ch.Table.Family) + } + } + for _, family := range []nftables.TableFamily{nftables.TableFamilyIPv4, nftables.TableFamilyIPv6} { + if !dropping[family] { + t.Errorf("no forward-hook chain with a drop policy for family %v", family) + } + if want := family == nftables.TableFamilyIPv4 && families.IPv4 || family == nftables.TableFamilyIPv6 && families.IPv6; redirecting[family] != want { + t.Errorf("NAT prerouting chain for family %v present = %v, want %v", family, redirecting[family], want) + } + } + for family := range wantDisallowedEgressRules { + t.Errorf("no disallowed-egress chain found for family %v", family) } } @@ -506,6 +724,7 @@ func TestSandboxNamespacesDoNotInheritNodeSettings(t *testing.T) { } // IPv6 reads these only from the link's own copy. perLinkV6 := map[string]string{ + "disable_ipv6": "0", "forwarding": "0", "accept_ra": "0", "accept_redirects": "0", @@ -519,7 +738,7 @@ func TestSandboxNamespacesDoNotInheritNodeSettings(t *testing.T) { {"tap", "b0b0b0b0-0000-0000-0000-00000000000b", false}, } { t.Run(tc.name, func(t *testing.T) { - n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ActorUID: tc.uid, Veth: tc.veth, EgressPort: testEgressPort}) + n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ActorUID: tc.uid, Veth: tc.veth, Families: dualStack, EgressPort: testEgressPort}) if err != nil { t.Fatalf("SetupSandboxNetwork: %v", err) } @@ -592,7 +811,7 @@ func TestGatewayDoesNotRouteActorTrafficOverAStrayLink(t *testing.T) { ctx := context.Background() n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ - ActorUID: "eeeeeeee-0000-0000-0000-00000000000e", Veth: true, EgressPort: testEgressPort, + ActorUID: "eeeeeeee-0000-0000-0000-00000000000e", Veth: true, Families: dualStack, EgressPort: testEgressPort, }) if err != nil { t.Fatalf("SetupSandboxNetwork: %v", err) diff --git a/internal/atunnel/dns/relay_linux.go b/internal/atunnel/dns/relay_linux.go index fc66f52f81..7d05e1d7d1 100644 --- a/internal/atunnel/dns/relay_linux.go +++ b/internal/atunnel/dns/relay_linux.go @@ -28,6 +28,7 @@ import ( // Serve serves UDP and TCP DNS in the sandbox's local gateway namespace. func (r *Relay) Serve(ctx context.Context, ns netns.Handle, policy PolicySource) (*Server, error) { // Bind the wildcard because the microVM tap's gateway address is added later. + // Go opens it dual-stack, so it answers on both gateway addresses. address := net.JoinHostPort("0.0.0.0", strconv.Itoa(dnsPort)) netC := netConn{ diff --git a/internal/e2e/suites/egressmitm/egressmitm_test.go b/internal/e2e/suites/egressmitm/egressmitm_test.go index 41db17b4bb..7c62b068bc 100644 --- a/internal/e2e/suites/egressmitm/egressmitm_test.go +++ b/internal/e2e/suites/egressmitm/egressmitm_test.go @@ -25,6 +25,7 @@ import ( "encoding/json" "encoding/pem" "io" + "net" "net/http" "net/url" "strings" @@ -146,12 +147,13 @@ func TestActorEgressMITMTrust(t *testing.T) { } // The gateway dials the name the SNI claims. - bySNI := fetchUntilReached(t, ctx, rc, id, passthroughOrigin, "pem", originRoots, "dial="+url.QueryEscape(unreachableAddress)) + unreachable := unreachableAddress(passthrough.ClusterIP) + bySNI := fetchUntilReached(t, ctx, rc, id, passthroughOrigin, "pem", originRoots, "dial="+url.QueryEscape(unreachable)) switch { case bySNI.Error != "": - t.Errorf("TLS passthrough to %s dialed at %s failed: %s — the gateway dialed the actor's address instead of resolving the SNI", passthroughOrigin, unreachableAddress, bySNI.Error) + t.Errorf("TLS passthrough to %s dialed at %s failed: %s — the gateway dialed the actor's address instead of resolving the SNI", passthroughOrigin, unreachable, bySNI.Error) case bySNI.Status != "200": - t.Errorf("passthrough fetch %s dialed at %s: status %s, want 200", passthroughOrigin, unreachableAddress, bySNI.Status) + t.Errorf("passthrough fetch %s dialed at %s: status %s, want 200", passthroughOrigin, unreachable, bySNI.Status) } // Each name is an origin's fully qualified alias: only the wrong-port rule @@ -189,10 +191,18 @@ func originSpec(name string) e2e.ServerPod { }) } +// unreachableAddress returns an address in a reserved block of clusterIP's +// family, which an actor of that family can dial: 240/4 for IPv4 and the +// discard prefix 100::/64 for IPv6. A gateway that dialed it instead of the +// resolved SNI would reach nothing. +func unreachableAddress(clusterIP string) string { + if net.ParseIP(clusterIP).To4() != nil { + return "240.0.0.1:443" + } + return "[100::1]:443" +} + const ( - // unreachableAddress is in the reserved 240/4 block: a gateway that dialed - // it instead of the resolved SNI would reach nothing. - unreachableAddress = "240.0.0.1:443" // systemRoot is the common name of a WebPKI root atelet's image ships. systemRoot = "ISRG Root X1" ) diff --git a/internal/e2e/suites/identity/identity_test.go b/internal/e2e/suites/identity/identity_test.go index 46f73203bd..f8d76db8ee 100644 --- a/internal/e2e/suites/identity/identity_test.go +++ b/internal/e2e/suites/identity/identity_test.go @@ -153,10 +153,12 @@ func TestActorIdentity_AfterRestore_IsOwnID_NotGolden(t *testing.T) { seenUIDs[got.UID] = id // Resolved from the /etc/hosts the runtime writes, not DNS: images - // commonly ship an empty one. - for host, want := range map[string]string{"localhost": "127.0.0.1", got.Hostname: "169.254.17.2"} { - if addrs, err := lookup(ctx, rc, id, host); err != nil || !slices.Contains(addrs, want) { - t.Errorf("actor %q: lookup %q = %v, %v; want %s", id, host, addrs, err, want) + // commonly ship an empty one. The hostname maps to the actor's + // address in each family its sandbox has. + for host, want := range map[string][]string{"localhost": {"127.0.0.1"}, got.Hostname: {"169.254.17.2", "fd00:a7e:17::2"}} { + addrs, err := lookup(ctx, rc, id, host) + if err != nil || !slices.ContainsFunc(want, func(w string) bool { return slices.Contains(addrs, w) }) { + t.Errorf("actor %q: lookup %q = %v, %v; want one of %v", id, host, addrs, err, want) } } } diff --git a/internal/wakeupprobe/wakeupprobe.go b/internal/wakeupprobe/wakeupprobe.go index fc9c805770..16457f6430 100644 --- a/internal/wakeupprobe/wakeupprobe.go +++ b/internal/wakeupprobe/wakeupprobe.go @@ -28,6 +28,7 @@ import ( "log/slog" "net" "net/http" + "strconv" "strings" "time" @@ -185,5 +186,5 @@ func URL(probe *ateworkerpb.WakeupProbe, actorIP string) (string, error) { if !strings.HasPrefix(path, "/") { path = "/" + path } - return fmt.Sprintf("http://%s:%d%s", actorIP, port, path), nil + return "http://" + net.JoinHostPort(actorIP, strconv.Itoa(int(port))) + path, nil } diff --git a/internal/wakeupprobe/wakeupprobe_test.go b/internal/wakeupprobe/wakeupprobe_test.go index 9ecf0798cd..c2a54e6ce3 100644 --- a/internal/wakeupprobe/wakeupprobe_test.go +++ b/internal/wakeupprobe/wakeupprobe_test.go @@ -55,6 +55,12 @@ func TestURL(t *testing.T) { actorIP: "10.0.0.1", want: "http://10.0.0.1:80/ready", }, + { + name: "IPv6 actor", + probe: &ateworkerpb.WakeupProbe{HttpGet: &ateworkerpb.HttpGetAction{Path: "/health", Port: 9000}}, + actorIP: "fd00:a7e:17::2", + want: "http://[fd00:a7e:17::2]:9000/health", + }, { name: "missing httpGet", probe: &ateworkerpb.WakeupProbe{},