instancectl: exempt the box's global addresses only behind a verified edge fence (#990)
Task 3 of the edge-fence plan. denyLocalAddrs takes an address out of the slice deny only after edgefence.Verify passes for it; every failure applies the whole deny. guardStarts wraps the service's systemctl so every start checks the fence first (a recreated slice gets a fresh fence or the whole deny before the unit starts), and the egress asserter's restarts check it through RestartAllowed. denyLoop re-reads the fence every tick while it exempts, without setting an unchanged deny again. Control checks the fence before it serves. Off on group boxes (the hairpin applies), in claims mode (claim units start outside the check), with CARLOS_EDGE_FENCE=off, and with no public address. The units do not grant AF_NETLINK yet (Task 4), so on a box nft fails and the whole deny stays: this commit changes no box's behaviour.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+678
−3
internal/instancectl/edgefence.go+223 −0internal/instancectl/edgefence_test.go+390 −0internal/instancectl/hardening.go+37 −3internal/instancectl/server.go+28 −0
diff --git a/internal/instancectl/edgefence.go b/internal/instancectl/edgefence.go| new file mode 100644 |
| index 000000000..72bbc84cf |
| --- /dev/null |
| +++ b/internal/instancectl/edgefence.go |
| @@ -0,0 +1,223 @@ |
| +package instancectl |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/netip" |
| + "slices" |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/edgefence" |
| +) |
| + |
| +// The edge fence (#990, plan 2026-11-13-same-box-calls-edge-fence): a |
| +// nested instance reaches the box's own global addresses on TCP 80 and |
| +// 443, the edge, and on nothing else, so an app can call another app on |
| +// its own box by hostname as it can call one on any other box. |
| +// |
| +// The invariant, kept here and nowhere else: |
| +// |
| +// An instance reaches an address of its own box only on TCP 80 or 443, |
| +// or the full #367 deny is in place. |
| +// |
| +// An address leaves the slice's IPAddressDeny= only while |
| +// edgefence.Verify passes for it, checked under denyMu after the fence |
| +// was (re)loaded. Every failure applies the full deny. Because nft names |
| +// the slice by the cgroup id it had when the table loaded, a recreated |
| +// slice leaves the rules matching nothing; guardStarts therefore runs the |
| +// readback before every unit start the service asks for, and the slice |
| +// is recreated only by a start (every instance template is Restart=no). |
| +// denyLoop re-reads the fence every tick while it exempts, which bounds |
| +// the one gap left, an nft flush while instances run, to one tick while |
| +// this service is up; Run checks the fence before it serves, because the |
| +// runtime deny drop-in outlives this process. |
| +// |
| +// Group-mode boxes never load the fence: the region HA hairpin owns their |
| +// box-address exemption (internal/hairpin). |
| + |
| +// EdgeFenceEnv is the host.env switch: "off" keeps the full #367 deny on |
| +// this box (the operator's rollback without a release). |
| +const EdgeFenceEnv = "CARLOS_EDGE_FENCE" |
| + |
| +// edgeFenceGroupBox reports a group-mode box; a var so tests can say. |
| +var edgeFenceGroupBox = groupHairpinMarker |
| + |
| +// fenceInternalKey marks the fence's own systemctl calls, which |
| +// guardStarts lets through: checking the fence before the slice start the |
| +// fence itself asks for would wait on denyMu, which the caller holds. |
| +type fenceInternalKey struct{} |
| + |
| +// Reasons the fence is not exempting, as the box reports them. |
| +const ( |
| + fenceOffSwitch = "off on this box (" + EdgeFenceEnv + "=off)" |
| + fenceOffGroup = "group box: the region HA hairpin applies" |
| + fenceOffNoAddr = "this box has no public address of its own" |
| + fenceOffUnwired = "not wired" |
| + fenceOffClaims = "host claims mode: claim units start outside the fence check" |
| +) |
| + |
| +// EdgeFenceState is what the box reports: whether same-box calls are on, |
| +// for which addresses, and why not when they are off. |
| +type EdgeFenceState struct { |
| + On bool |
| + Addresses []netip.Addr |
| + Reason string |
| +} |
| + |
| +// EdgeFence is the fence's state as last applied. |
| +func (s *Server) EdgeFence() EdgeFenceState { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return EdgeFenceState{On: len(s.fenceAddrs) > 0, Addresses: slices.Clone(s.fenceAddrs), Reason: s.fenceReason} |
| +} |
| + |
| +// edgeFenceDeny is the deny for local and the addresses it exempts. The |
| +// exemption is non-empty only when the fence for exactly those addresses |
| +// has just read back as loaded; otherwise deny is local, whole, and |
| +// reason says why. The caller holds denyMu. |
| +func (s *Server) edgeFenceDeny(ctx context.Context, local []netip.Prefix) (deny []netip.Prefix, exempt []netip.Addr, reason string) { |
| + switch { |
| + case edgeFenceGroupBox(): |
| + return local, nil, fenceOffGroup |
| + case s.EdgeFenceOff: |
| + return local, nil, fenceOffSwitch |
| + case s.NFT == nil: |
| + return local, nil, fenceOffUnwired |
| + case s.ClaimStop != nil: |
| + // Claim launches start their units with their own systemctl |
| + // (ClaimUnits), which guardStarts does not see. Host claims are |
| + // shelved (2026-10-25); until a claim start checks the fence, a |
| + // claims-mode box keeps the whole deny. |
| + return local, nil, fenceOffClaims |
| + } |
| + addrs := edgefence.Addresses(local) |
| + if len(addrs) == 0 { |
| + return local, nil, fenceOffNoAddr |
| + } |
| + // nft resolves the slice's path when the table loads, and an empty |
| + // slice may not exist: start it (a no-op when it runs) so the path |
| + // names the cgroup the next instance will join. |
| + internal := context.WithValue(ctx, fenceInternalKey{}, true) |
| + if out, err := s.Systemctl(internal, "start", InstancesSlice); err != nil { |
| + return local, nil, fmt.Sprintf("start %s: %s", InstancesSlice, strings.TrimSpace(out+" "+err.Error())) |
| + } |
| + if err := edgefence.Verify(ctx, s.NFT, addrs); err != nil { |
| + if !s.fenceWasLoaded(addrs) { |
| + err = nil // the first load, or a new address set: nothing to report |
| + } |
| + if ierr := edgefence.Install(ctx, s.NFT, addrs); ierr != nil { |
| + return local, nil, ierr.Error() |
| + } |
| + if verr := edgefence.Verify(ctx, s.NFT, addrs); verr != nil { |
| + return local, nil, verr.Error() |
| + } |
| + if err != nil { |
| + s.logf("instance-control: edge fence: %v; reloaded", err) |
| + } |
| + } |
| + deny = make([]netip.Prefix, 0, len(local)) |
| + for _, p := range local { |
| + if p.IsSingleIP() && slices.Contains(addrs, p.Addr()) { |
| + continue |
| + } |
| + deny = append(deny, p) |
| + } |
| + return deny, addrs, "" |
| +} |
| + |
| +// fenceWasLoaded reports whether the fence last applied was for addrs, so |
| +// a readback failure means it went away rather than was never there. |
| +func (s *Server) fenceWasLoaded(addrs []netip.Addr) bool { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return slices.Equal(s.fenceAddrs, addrs) |
| +} |
| + |
| +// recordFence remembers what the deny just applied exempts. The caller |
| +// holds denyMu and has applied the deny. |
| +func (s *Server) recordFence(exempt []netip.Addr, reason string) { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + if len(s.fenceAddrs) > 0 && len(exempt) == 0 { |
| + s.logf("instance-control: edge fence: off, the full box-address deny applies: %s", reason) |
| + } |
| + if len(s.fenceAddrs) == 0 && len(exempt) > 0 { |
| + s.logf("instance-control: edge fence: on for %v", exempt) |
| + } |
| + s.fenceAddrs = slices.Clone(exempt) |
| + s.fenceReason = reason |
| + s.denyApplied = true |
| +} |
| + |
| +// errFenceUnknown refuses a start before this service has applied any |
| +// deny: a deny drop-in left by an earlier process may exempt an address |
| +// whose fence nobody has checked. |
| +var errFenceUnknown = errors.New("edge fence: the box-address deny has not been applied since this service started; refusing the start") |
| + |
| +// fenceBeforeStart is guardStarts' check: when the applied deny exempts |
| +// an address, the fence must still read back as loaded, or the deny is |
| +// worked out again (reloading the fence, or the full deny) before the |
| +// start goes ahead. A service with no NFT, and a group box, never exempt |
| +// here and check nothing; a group box's starts stay off the hairpin lock. |
| +// Elsewhere hairpinLocked takes no lock (no group config), so denyMu is |
| +// what serialises this with the deny refresh. |
| +func (s *Server) fenceBeforeStart(ctx context.Context) error { |
| + if s.NFT == nil || edgeFenceGroupBox() { |
| + return nil |
| + } |
| + s.denyMu.Lock() |
| + defer s.denyMu.Unlock() |
| + s.mu.Lock() |
| + addrs, applied := slices.Clone(s.fenceAddrs), s.denyApplied |
| + s.mu.Unlock() |
| + if !applied { |
| + return errFenceUnknown |
| + } |
| + if len(addrs) == 0 { |
| + return nil |
| + } |
| + err := edgefence.Verify(ctx, s.NFT, addrs) |
| + if err == nil { |
| + return nil |
| + } |
| + s.logf("instance-control: edge fence before a start: %v", err) |
| + return s.denyLocalAddrsLocked(ctx, false) |
| +} |
| + |
| +// startVerbs are the systemctl verbs that can start a unit. |
| +var startVerbs = map[string]bool{"start": true, "restart": true, "try-restart": true, "reload-or-restart": true, "try-reload-or-restart": true} |
| + |
| +// guardStarts wraps systemctl so that every start the service asks for |
| +// runs fenceBeforeStart first, whatever the unit: one choke point rather |
| +// than a check at each start site, so a new start site is covered too. |
| +// The fence's own calls (fenceInternalKey) pass straight through. |
| +func (s *Server) guardStarts(raw func(context.Context, ...string) (string, error)) func(context.Context, ...string) (string, error) { |
| + return func(ctx context.Context, args ...string) (string, error) { |
| + if len(args) > 0 && startVerbs[args[0]] && ctx.Value(fenceInternalKey{}) == nil { |
| + if err := s.fenceBeforeStart(ctx); err != nil { |
| + return "", err |
| + } |
| + } |
| + return raw(ctx, args...) |
| + } |
| +} |
| + |
| +// bindEgressFence puts fenceBeforeStart in front of the egress asserter's |
| +// restarts (#328): it restarts instance units with a systemctl of its own, |
| +// which guardStarts does not wrap, after asking RestartAllowed. |
| +func (s *Server) bindEgressFence() { |
| + if s.Egress == nil { |
| + return |
| + } |
| + previous := s.Egress.RestartAllowed |
| + s.Egress.RestartAllowed = func(ctx context.Context) error { |
| + if err := s.fenceBeforeStart(ctx); err != nil { |
| + return err |
| + } |
| + if previous != nil { |
| + return previous(ctx) |
| + } |
| + return nil |
| + } |
| +} |
diff --git a/internal/instancectl/edgefence_test.go b/internal/instancectl/edgefence_test.go| new file mode 100644 |
| index 000000000..8f80c6a05 |
| --- /dev/null |
| +++ b/internal/instancectl/edgefence_test.go |
| @@ -0,0 +1,390 @@ |
| +package instancectl |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/netip" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/edgefence" |
| +) |
| + |
| +// fakeNFT models the one table the fence owns: loaded or not, and, once |
| +// the slice is recreated (stale), printed with a bare cgroup id as nft |
| +// does (plan evidence 4). |
| +type fakeNFT struct { |
| + mu sync.Mutex |
| + loaded string // the table's text as nft would print it; "" when not loaded |
| + stale bool |
| + failLoad error |
| + loads int |
| + readbacks int |
| + log []string |
| +} |
| + |
| +var tableBody = regexp.MustCompile(`(?s)table inet ` + edgefence.Table + ` \{.*`) |
| + |
| +func (f *fakeNFT) run(_ context.Context, input string, args ...string) ([]byte, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + line := strings.Join(args, " ") |
| + f.log = append(f.log, line) |
| + switch line { |
| + case "nft -f -": |
| + f.loads++ |
| + if f.failLoad != nil { |
| + return []byte("Error: Could not process rule"), f.failLoad |
| + } |
| + f.loaded, f.stale = tableBody.FindString(input), false |
| + return nil, nil |
| + case "nft -s -nn -y list table inet " + edgefence.Table: |
| + f.readbacks++ |
| + if f.loaded == "" { |
| + return []byte("Error: No such file or directory"), errors.New("exit status 1") |
| + } |
| + if f.stale { |
| + return []byte(strings.ReplaceAll(f.loaded, fmt.Sprintf("%q", edgefence.Cgroup), "803329")), nil |
| + } |
| + return []byte(f.loaded), nil |
| + } |
| + return nil, fmt.Errorf("unexpected nft call %q", line) |
| +} |
| + |
| +func (f *fakeNFT) set(fn func(*fakeNFT)) { f.mu.Lock(); defer f.mu.Unlock(); fn(f) } |
| +func (f *fakeNFT) counts() (loads, readbacks int) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return f.loads, f.readbacks |
| +} |
| + |
| +// A box like leo-bookbinding: one public IPv4 on its interface, plus a |
| +// private one and a global IPv6 for coverage. |
| +var fenceLocal = func() ([]netip.Prefix, error) { |
| + return parsePrefixes("127.0.0.0/8", "172.31.7.19/32", "203.0.113.7/32", "2001:db8::7/128", "fe80::1/128"), nil |
| +} |
| + |
| +const ( |
| + wholeDeny = "IPAddressDeny=127.0.0.0/8 172.31.7.19/32 2001:db8::7/128 203.0.113.7/32 fe80::1/128" |
| + fencedDeny = "IPAddressDeny=127.0.0.0/8 172.31.7.19/32 fe80::1/128" |
| +) |
| + |
| +func notGroup(t *testing.T) { |
| + t.Helper() |
| + old := edgeFenceGroupBox |
| + edgeFenceGroupBox = func() bool { return false } |
| + t.Cleanup(func() { edgeFenceGroupBox = old }) |
| +} |
| + |
| +func fenceServer(t *testing.T) (*Server, *fakeCtl, *fakeNFT) { |
| + t.Helper() |
| + notGroup(t) |
| + ctl, nft := &fakeCtl{}, &fakeNFT{} |
| + s := &Server{Systemctl: ctl.run, Logf: t.Logf, LocalAddrs: fenceLocal, NFT: nft.run} |
| + return s, ctl, nft |
| +} |
| + |
| +// #990: the box's global addresses leave the deny only after the fence for |
| +// exactly those addresses reads back as loaded, and the slice is started |
| +// before the load so the rules name the cgroup instances will join. |
| +func TestEdgeFenceExemptsOnlyAfterTheReadback(t *testing.T) { |
| + s, ctl, nft := fenceServer(t) |
| + if err := s.denyLocalAddrs(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctl.mustHaveCallsInOrder(t, "start "+InstancesSlice, "set-property --runtime "+InstancesSlice+" IPAddressDeny= "+fencedDeny) |
| + if got := strings.Join(nft.log, "; "); got != "nft -s -nn -y list table inet carlos_edge_fence; nft -f -; nft -s -nn -y list table inet carlos_edge_fence" { |
| + t.Fatalf("nft calls: %s", got) |
| + } |
| + want, _ := edgefence.Rules([]netip.Addr{netip.MustParseAddr("203.0.113.7"), netip.MustParseAddr("2001:db8::7")}) |
| + if nft.loaded != want { |
| + t.Fatalf("loaded %q, want %q", nft.loaded, want) |
| + } |
| + st := s.EdgeFence() |
| + if !st.On || len(st.Addresses) != 2 || st.Reason != "" { |
| + t.Fatalf("state = %+v", st) |
| + } |
| +} |
| + |
| +// Every way the fence can fail leaves the deny whole and says why. |
| +func TestEdgeFenceFailuresKeepTheWholeDeny(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + setup func(*fakeCtl, *fakeNFT) |
| + reason string |
| + }{ |
| + {"the load fails", func(_ *fakeCtl, n *fakeNFT) { n.failLoad = errors.New("exit status 1") }, "load"}, |
| + {"the slice cannot start", func(c *fakeCtl, _ *fakeNFT) { |
| + c.fail = map[string]error{"start": errors.New("exit status 5")} |
| + }, "start " + InstancesSlice}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + s, ctl, nft := fenceServer(t) |
| + tc.setup(ctl, nft) |
| + if err := s.denyLocalAddrs(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := ctl.count(wholeDeny); n != 1 { |
| + t.Fatalf("whole deny applied %d times; calls %q", n, ctl.joined()) |
| + } |
| + st := s.EdgeFence() |
| + if st.On || !strings.Contains(st.Reason, tc.reason) { |
| + t.Fatalf("state = %+v, want off naming %q", st, tc.reason) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// A readback that differs after a load (here: the slice recreated between |
| +// the load and the readback) is a failure too. |
| +func TestEdgeFenceRefusesAReadbackThatDiffersAfterTheLoad(t *testing.T) { |
| + s, ctl, _ := fenceServer(t) |
| + stale := &fakeNFT{} |
| + s.NFT = func(ctx context.Context, input string, args ...string) ([]byte, error) { |
| + out, err := stale.run(ctx, input, args...) |
| + if args[1] == "-f" { |
| + stale.set(func(f *fakeNFT) { f.stale = true }) |
| + } |
| + return out, err |
| + } |
| + if err := s.denyLocalAddrs(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if n := ctl.count(wholeDeny); n != 1 { |
| + t.Fatalf("whole deny applied %d times; calls %q", n, ctl.joined()) |
| + } |
| + if st := s.EdgeFence(); st.On || !strings.Contains(st.Reason, "recreated") { |
| + t.Fatalf("state = %+v", st) |
| + } |
| +} |
| + |
| +// The off switch, a group box, a claims-mode box, a box with no public |
| +// address and a service with no NFT never touch nft or the slice, and |
| +// keep the deny whole. |
| +func TestEdgeFenceOffCases(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + setup func(*Server) |
| + reason string |
| + }{ |
| + {"off switch", func(s *Server) { s.EdgeFenceOff = true }, fenceOffSwitch}, |
| + {"group box", func(*Server) { edgeFenceGroupBox = func() bool { return true } }, fenceOffGroup}, |
| + {"claims mode", func(s *Server) { s.ClaimStop = http.NotFoundHandler() }, fenceOffClaims}, |
| + {"no public address", func(s *Server) { |
| + s.LocalAddrs = func() ([]netip.Prefix, error) { return parsePrefixes("127.0.0.0/8", "172.31.7.19/32"), nil } |
| + }, fenceOffNoAddr}, |
| + {"no nft", func(s *Server) { s.NFT = nil }, fenceOffUnwired}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + s, ctl, nft := fenceServer(t) |
| + tc.setup(s) |
| + if err := s.denyLocalAddrs(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(nft.log) != 0 { |
| + t.Fatalf("nft ran: %v", nft.log) |
| + } |
| + if ctl.count("start") != 0 { |
| + t.Fatalf("the slice was started: %q", ctl.joined()) |
| + } |
| + if ctl.count("set-property") != 1 || ctl.count(fencedDeny) != 0 { |
| + t.Fatalf("calls %q", ctl.joined()) |
| + } |
| + if st := s.EdgeFence(); st.On || st.Reason != tc.reason { |
| + t.Fatalf("state = %+v, want reason %q", st, tc.reason) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// While the fence exempts, every tick reads it back, addresses changed or |
| +// not, without setting an unchanged deny again. A flushed table is |
| +// reloaded on the next tick; one that cannot be reloaded puts the whole |
| +// deny back. |
| +func TestDenyLoopRereadsTheFenceEveryTick(t *testing.T) { |
| + s, ctl, nft := fenceServer(t) |
| + ticks, handled := make(chan time.Time), make(chan struct{}) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + defer cancel() |
| + go s.denyLoopWith(ctx, ticks, func() { handled <- struct{}{} }) |
| + tick := func() { ticks <- time.Time{}; <-handled } |
| + |
| + tick() |
| + if n := ctl.count(fencedDeny); n != 1 { |
| + t.Fatalf("first tick: fenced deny applied %d times; %q", n, ctl.joined()) |
| + } |
| + _, before := nft.counts() |
| + for i := 0; i < 3; i++ { |
| + tick() |
| + } |
| + if _, after := nft.counts(); after != before+3 { |
| + t.Fatalf("3 ticks with unchanged addresses read the fence back %d times, want 3", after-before) |
| + } |
| + if n := ctl.count("set-property"); n != 1 { |
| + t.Fatalf("an unchanged deny was set again: %d set-property calls", n) |
| + } |
| + |
| + // `systemctl reload nftables` flushed the ruleset. |
| + nft.set(func(f *fakeNFT) { f.loaded = "" }) |
| + loads, _ := nft.counts() |
| + tick() |
| + if l, _ := nft.counts(); l != loads+1 { |
| + t.Fatalf("a flushed fence was not reloaded on the next tick") |
| + } |
| + if !s.EdgeFence().On || ctl.count("set-property") != 1 { |
| + t.Fatalf("a reloaded fence changed the deny: %q", ctl.joined()) |
| + } |
| + |
| + // Flushed again, and now it cannot load: the whole deny returns. |
| + nft.set(func(f *fakeNFT) { f.loaded, f.failLoad = "", errors.New("exit status 1") }) |
| + tick() |
| + if n := ctl.count(wholeDeny); n != 1 { |
| + t.Fatalf("whole deny applied %d times after a failed reload; %q", n, ctl.joined()) |
| + } |
| + if s.EdgeFence().On { |
| + t.Fatal("the fence still reads as on") |
| + } |
| +} |
| + |
| +// guardStarts refuses a start before this service has applied a deny, and |
| +// otherwise checks the fence before every start: a slice recreated under a |
| +// loaded fence (bare cgroup id) gets a fresh fence, or the whole deny, |
| +// before the unit starts. |
| +func TestGuardStartsChecksTheFenceBeforeEveryStart(t *testing.T) { |
| + s, ctl, nft := fenceServer(t) |
| + s.Systemctl = s.guardStarts(ctl.run) |
| + ctx := context.Background() |
| + |
| + if _, err := s.Systemctl(ctx, "start", "carlos-instance@a.service"); !errors.Is(err, errFenceUnknown) { |
| + t.Fatalf("start before any deny: %v", err) |
| + } |
| + if ctl.count("carlos-instance@a.service") != 0 { |
| + t.Fatal("the unit started") |
| + } |
| + if err := s.denyLocalAddrs(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + _, before := nft.counts() |
| + if _, err := s.Systemctl(ctx, "start", "carlos-instance@a.service"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, after := nft.counts(); after != before+1 { |
| + t.Fatalf("the start read the fence back %d times, want 1", after-before) |
| + } |
| + // Verbs that start nothing are not checked. |
| + if _, err := s.Systemctl(ctx, "stop", "carlos-instance@a.service"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, after := nft.counts(); after != before+1 { |
| + t.Fatal("a stop read the fence back") |
| + } |
| + |
| + // The slice was stopped and is about to be recreated by this start. |
| + nft.set(func(f *fakeNFT) { f.stale = true }) |
| + loads, _ := nft.counts() |
| + if _, err := s.Systemctl(ctx, "restart", "carlos-instance@a.service"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if l, _ := nft.counts(); l != loads+1 { |
| + t.Fatal("a stale fence was not reloaded before the restart") |
| + } |
| + ctl.mustHaveCallsInOrder(t, "start "+InstancesSlice, "restart carlos-instance@a.service") |
| + |
| + // Stale again, and the reload fails: the whole deny is set before the |
| + // unit starts. |
| + nft.set(func(f *fakeNFT) { f.stale, f.failLoad = true, errors.New("exit status 1") }) |
| + if _, err := s.Systemctl(ctx, "start", "carlos-instance@b.service"); err != nil { |
| + t.Fatal(err) |
| + } |
| + ctl.mustHaveCallsInOrder(t, "set-property --runtime "+InstancesSlice+" IPAddressDeny= "+wholeDeny, "start carlos-instance@b.service") |
| +} |
| + |
| +// A whole deny that cannot be set when the fence fails before a start |
| +// refuses the start: the last deny may exempt an address nothing fences. |
| +func TestGuardStartsRefusesWhenTheWholeDenyCannotBeSet(t *testing.T) { |
| + s, ctl, nft := fenceServer(t) |
| + s.Systemctl = s.guardStarts(ctl.run) |
| + ctx := context.Background() |
| + if err := s.denyLocalAddrs(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + nft.set(func(f *fakeNFT) { f.loaded, f.failLoad = "", errors.New("exit status 1") }) |
| + ctl.mu.Lock() |
| + ctl.fail = map[string]error{"set-property": errors.New("exit status 1")} |
| + ctl.mu.Unlock() |
| + if _, err := s.Systemctl(ctx, "start", "carlos-instance@a.service"); err == nil { |
| + t.Fatal("the start went ahead") |
| + } |
| + if ctl.count("start carlos-instance@a.service") != 0 { |
| + t.Fatal("the unit started") |
| + } |
| +} |
| + |
| +// The egress asserter restarts instance units with a systemctl of its own; |
| +// its RestartAllowed runs the fence check first. |
| +func TestEgressRestartsCheckTheFence(t *testing.T) { |
| + s, _, _ := fenceServer(t) |
| + called := false |
| + s.Egress = &EgressAsserter{RestartAllowed: func(context.Context) error { called = true; return nil }} |
| + s.bindEgressFence() |
| + if err := s.Egress.RestartAllowed(context.Background()); !errors.Is(err, errFenceUnknown) { |
| + t.Fatalf("restart before any deny: %v", err) |
| + } |
| + if called { |
| + t.Fatal("the earlier hook ran after the fence refused") |
| + } |
| + if err := s.denyLocalAddrs(context.Background()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := s.Egress.RestartAllowed(context.Background()); err != nil || !called { |
| + t.Fatalf("after the deny: %v, earlier hook ran %v", err, called) |
| + } |
| +} |
| + |
| +// Every start the package asks systemd for goes through a systemctl the |
| +// fence check sees: the Server's (guardStarts), the egress asserter's |
| +// (RestartAllowed, bindEgressFence), or a claim unit's (the fence stays |
| +// off in claims mode). A start site on any other systemctl, or on exec |
| +// directly, would start a unit behind the fence check; this test names |
| +// it. |
| +func TestEveryStartIsSeenByTheFenceCheck(t *testing.T) { |
| + paths, err := filepath.Glob("*.go") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + call := regexp.MustCompile(`([\w.]+)\.Systemctl\(\w+, "(start|restart|try-restart|reload-or-restart|try-reload-or-restart)"`) |
| + direct := regexp.MustCompile(`"systemctl", "(start|restart|try-restart)"`) |
| + allowed := map[string]bool{"s": true, "p.s": true, "e": true, "u": true} |
| + seen := 0 |
| + for _, path := range paths { |
| + if strings.HasSuffix(path, "_test.go") { |
| + continue |
| + } |
| + b, err := os.ReadFile(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for i, line := range strings.Split(string(b), "\n") { |
| + if m := call.FindStringSubmatch(line); m != nil { |
| + seen++ |
| + if !allowed[m[1]] { |
| + t.Errorf("%s:%d: %s starts a unit through %s.Systemctl, which the fence check does not see", path, i+1, m[2], m[1]) |
| + } |
| + } |
| + if direct.MatchString(line) { |
| + t.Errorf("%s:%d: a unit started by exec, not through a fenced systemctl", path, i+1) |
| + } |
| + } |
| + } |
| + if seen < 10 { |
| + t.Fatalf("found %d start sites; the pattern has stopped matching them", seen) |
| + } |
| +} |
diff --git a/internal/instancectl/hardening.go b/internal/instancectl/hardening.go| index 2e4eb43dd..6f37c6a36 100644 |
| --- a/internal/instancectl/hardening.go |
| +++ b/internal/instancectl/hardening.go |
| @@ -290,7 +290,18 @@ func (s *Server) allowResolvers(ctx context.Context) (refused []string, err erro |
| // (the last deny stands) and returns the error. What it applied is |
| // remembered in lastDeny, for denyLoop. denyMu runs one call at a time, so |
| // an older read can never be applied over a newer one. |
| +// |
| +// The edge fence (#990, edgefence.go) may exempt the box's global |
| +// addresses from the deny, and only after its table reads back as loaded |
| +// for exactly those addresses; every failure leaves the deny whole. |
| func (s *Server) denyLocalAddrs(ctx context.Context) error { |
| + return s.denyLocalAddrsWith(ctx, false) |
| +} |
| + |
| +// denyLocalAddrsWith is denyLocalAddrs; refresh is denyLoop's tick, which |
| +// re-checks the fence but does not set an unchanged deny again (setting |
| +// it re-attaches the slice's address filters under every instance). |
| +func (s *Server) denyLocalAddrsWith(ctx context.Context, refresh bool) error { |
| ctx, unlock, lockErr := hairpinLocked(ctx) |
| if lockErr != nil { |
| return lockErr |
| @@ -298,6 +309,12 @@ func (s *Server) denyLocalAddrs(ctx context.Context) error { |
| defer unlock() |
| s.denyMu.Lock() |
| defer s.denyMu.Unlock() |
| + return s.denyLocalAddrsLocked(ctx, refresh) |
| +} |
| + |
| +// denyLocalAddrsLocked is denyLocalAddrsWith under denyMu (and the hairpin |
| +// lock, where there is one). |
| +func (s *Server) denyLocalAddrsLocked(ctx context.Context, refresh bool) error { |
| local, err := s.localPrefixes() |
| if err != nil { |
| return fmt.Errorf("this box's addresses: %v; the last deny stands", err) |
| @@ -306,7 +323,21 @@ func (s *Server) denyLocalAddrs(ctx context.Context) error { |
| if hairpinErr != nil { |
| return hairpinErr |
| } |
| - return s.applyLocalDeny(ctx, local, false) |
| + deny, exempt, reason := s.edgeFenceDeny(ctx, local) |
| + if refresh && len(exempt) > 0 { |
| + s.mu.Lock() |
| + unchanged := slices.Equal(denySet(deny), s.lastDeny) |
| + s.mu.Unlock() |
| + if unchanged { |
| + s.recordFence(exempt, reason) |
| + return nil |
| + } |
| + } |
| + if err := s.applyLocalDeny(ctx, deny, false); err != nil { |
| + return err |
| + } |
| + s.recordFence(exempt, reason) |
| + return nil |
| } |
| // The caller holds denyMu. A failed hairpin readback forces a full deny even |
| @@ -400,9 +431,12 @@ func (s *Server) denyLoopWith(ctx context.Context, ticks <-chan time.Time, done |
| previous := slices.Clone(s.lastDeny) |
| unchanged := slices.Equal(denySet(local), previous) |
| active := s.hairpinActive |
| + // #990: while the edge fence exempts, every tick re-reads it, |
| + // addresses changed or not. |
| + fence := len(s.fenceAddrs) > 0 |
| s.mu.Unlock() |
| - if !unchanged || active { |
| - err := s.denyLocalAddrs(ctx) |
| + if !unchanged || active || fence { |
| + err := s.denyLocalAddrsWith(ctx, fence) |
| logErr(err) |
| if err == nil { |
| s.mu.Lock() |
diff --git a/internal/instancectl/server.go b/internal/instancectl/server.go| index 29353c073..07f3f6d50 100644 |
| --- a/internal/instancectl/server.go |
| +++ b/internal/instancectl/server.go |
| @@ -27,6 +27,7 @@ import ( |
| "github.com/carlosframework/platform/internal/controlsock" |
| "github.com/carlosframework/platform/internal/demo" |
| "github.com/carlosframework/platform/internal/demobuild" |
| + "github.com/carlosframework/platform/internal/edgefence" |
| "github.com/carlosframework/platform/internal/execsandbox" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -140,6 +141,12 @@ type Server struct { |
| // inside it is never opened (#126). Production reads procfs |
| // (localPrefixes); nil closes every resolver. |
| LocalAddrs func() ([]netip.Prefix, error) |
| + // NFT runs nft for the edge fence (#990); nil never loads it and keeps |
| + // the full #367 deny (tests of other verbs, the hairpin reset server). |
| + NFT edgefence.Runner |
| + // EdgeFenceOff is host.env's CARLOS_EDGE_FENCE=off: the full deny, |
| + // whatever the box's addresses. |
| + EdgeFenceOff bool |
| // DenyEvery is denyLoop's cadence: how often the box's addresses are |
| // re-read for a change, so a new one is denied to every nested unit |
| // (#367; 10 s in production). Zero runs no loop. |
| @@ -235,6 +242,14 @@ type Server struct { |
| lastDeny []netip.Prefix |
| hairpinActive bool |
| hairpinWatch groupHairpinWatch |
| + // fenceAddrs is what the deny denyLocalAddrs last applied exempts for |
| + // the edge fence (#990, edgefence.go), sorted; empty when the deny is |
| + // whole. fenceReason says why it is whole. denyApplied is whether any |
| + // deny has been applied since this service started (guardStarts |
| + // refuses starts until one has). |
| + fenceAddrs []netip.Addr |
| + fenceReason string |
| + denyApplied bool |
| // denyMu runs one denyLocalAddrs at a time (RunProbe's and denyLoop's), |
| // so an older read of the addresses is never applied over a newer one. |
| denyMu sync.Mutex |
| @@ -345,6 +360,8 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV |
| ResolvConf: "/etc/resolv.conf", |
| ResolvedConf: ResolvedConf, |
| LocalAddrs: func() ([]netip.Prefix, error) { return localPrefixes(fibTriePath, ifInet6Path) }, |
| + NFT: edgefence.Exec, |
| + EdgeFenceOff: os.Getenv(EdgeFenceEnv) == "off", |
| DenyEvery: 10 * time.Second, |
| DataRoot: "/data/instances", |
| Statfs: statfsBytes, |
| @@ -353,7 +370,11 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV |
| ExeCurrent: installedBinaryCurrent, |
| Egress: egress, |
| } |
| + // #990: every start this service asks for checks the edge fence first |
| + // (guardStarts, edgefence.go). |
| + s.Systemctl = s.guardStarts(s.Systemctl) |
| s.bindSandboxEgress() |
| + s.bindEgressFence() |
| ln, activated, err := activatedListener() |
| if err != nil { |
| log.Fatalf("instance-control: %v", err) |
| @@ -371,6 +392,13 @@ func runWithClaim(args []string, claim, heldRelease http.Handler, view RegistryV |
| if err := s.resumeGroupHairpin(ctx); err != nil { |
| log.Fatal(err) |
| } |
| + // #990: the deny is a runtime drop-in that outlives this process, and |
| + // may exempt an address whose fence an nft flush removed while it was |
| + // down. Check the fence, or put the whole deny back, before serving. |
| + // On a failure starts are refused (guardStarts) until a deny applies. |
| + if err := s.denyLocalAddrs(ctx); err != nil { |
| + log.Printf("instance-control: box-address deny at start: %v", err) |
| + } |
| s.InspectMountpoints(ctx) |
| firstProbe := make(chan struct{}) |
| builderEnv := os.Getenv |