carlos / platform Public

egress: kernel proof that a slice allow opens, closes and combines live (#328)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 2295ec6f1a48f01509d661fe34eb68adb14a2913 parent 4317d89
1 file changed, +443 −0
  • internal/host/egress_kernel_rootrunner_linux_test.go +443 −0
diff --git a/internal/host/egress_kernel_rootrunner_linux_test.go b/internal/host/egress_kernel_rootrunner_linux_test.go
new file mode 100644
index 000000000..0175078bf
--- /dev/null
+++ b/internal/host/egress_kernel_rootrunner_linux_test.go
@@ -0,0 +1,443 @@
+//go:build linux && rootrunner
+
+package host
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io/fs"
+ "net"
+ "net/http"
+ "net/netip"
+ "net/url"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "golang.org/x/sys/unix"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+)
+
+// egressProofLink is this test's dummy link (C16: Task 13 uses carlos-egr1).
+const egressProofLink = "carlos-egr0"
+
+// TestRootEgressKernelProof is the kernel proof of spec §4.3 (#328): a
+// per-host slice's IPAddressAllow=, written with `systemctl set-property
+// --runtime`, opens and closes a private address for a process already
+// running in a child unit that carries the template's IPAddressDeny=, and
+// combines with the allow on carlos-instances.slice rather than replacing it.
+//
+// Network: the test reaches no network beyond its own dummy link
+// carlos-egr0. Its three TCP listeners sit on that link's addresses inside
+// this process; its tenants are this binary (plan14-tenant) behind Unix
+// sockets in a scratch directory, and they dial only those listeners.
+//
+// It logs one "verdict:" line per question (revoke live, open live,
+// combines with parent, slice show is own entries only) so a failed run
+// still answers every question it reached. It fails, never skips, without
+// root, systemd as PID 1 or cgroup v2, and removes every unit, slice
+// drop-in, link, listener and file it made.
+func TestRootEgressKernelProof(t *testing.T) {
+ verdicts := map[string]string{}
+ order := []string{"revoke live", "open live", "combines with parent", "slice show is own entries only"}
+ t.Cleanup(func() {
+ for _, k := range order {
+ v := verdicts[k]
+ if v == "" {
+ v = "not reached"
+ }
+ t.Logf("verdict: %s: %s", k, v)
+ }
+ })
+ verdict := func(k string, ok bool) {
+ switch {
+ case !ok:
+ verdicts[k] = "no"
+ case verdicts[k] != "no": // a "no" anywhere stands
+ verdicts[k] = "yes"
+ }
+ }
+
+ // Prerequisites: fail, never skip.
+ if os.Geteuid() != 0 {
+ t.Fatal("needs real root")
+ }
+ if pid1, err := os.ReadFile("/proc/1/comm"); err != nil || strings.TrimSpace(string(pid1)) != "systemd" {
+ t.Fatalf("needs systemd as PID 1: %q %v", pid1, err)
+ }
+ var st unix.Statfs_t
+ if err := unix.Statfs("/sys/fs/cgroup", &st); err != nil || st.Type != unix.CGROUP2_SUPER_MAGIC {
+ t.Fatalf("needs cgroup v2 at /sys/fs/cgroup: type %#x %v", st.Type, err)
+ }
+ for _, tool := range []string{"ip", "systemctl", "systemd-run"} {
+ if _, err := exec.LookPath(tool); err != nil {
+ t.Fatal("needs", tool, err)
+ }
+ }
+ exe, err := os.Executable()
+ if err != nil || !filepath.IsAbs(exe) {
+ t.Fatal("test binary path", exe, err)
+ }
+
+ ctl := func(args ...string) (string, error) {
+ out, err := exec.Command("systemctl", args...).CombinedOutput()
+ return strings.TrimSpace(string(out)), err
+ }
+ mustCtl := func(args ...string) string {
+ t.Helper()
+ out, err := ctl(args...)
+ if err != nil {
+ t.Fatalf("systemctl %s: %v: %s", strings.Join(args, " "), err, out)
+ }
+ return out
+ }
+ show := func(unit, prop string) string {
+ t.Helper()
+ return mustCtl("show", "-p", prop, "--value", unit)
+ }
+
+ host := "egress-proof.example.com"
+ slice := instancectl.SliceName(host)
+ otherSlice := instancectl.SliceName("other-app.example.com")
+ parent := instancectl.InstancesSlice
+ units := []string{"carlos-egress-proof-a", "carlos-egress-proof-b", "carlos-egress-proof-c"}
+
+ // The deny line, read from the embedded template.
+ template, err := unitsFS.ReadFile("units/carlos-instance@.service")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var deny string
+ for _, line := range strings.Split(string(template), "\n") {
+ if strings.HasPrefix(line, "IPAddressDeny=") {
+ if deny != "" {
+ t.Fatal("template carries more than one IPAddressDeny= line")
+ }
+ deny = strings.TrimPrefix(line, "IPAddressDeny=")
+ }
+ }
+ if deny == "" {
+ t.Fatal("template carries no IPAddressDeny= line")
+ }
+
+ // Refuse anything this test would otherwise overwrite or remove.
+ if _, err := net.InterfaceByName(egressProofLink); err == nil {
+ t.Fatal("link already exists", egressProofLink)
+ }
+ for _, u := range units {
+ if state := show(u, "LoadState"); state != "not-found" {
+ t.Fatal("unit already present", u, state)
+ }
+ }
+ slices := []string{slice, otherSlice, parent}
+ for _, s := range slices {
+ for _, root := range []string{"/run/systemd/system.control", "/etc/systemd/system.control"} {
+ if _, err := os.Lstat(filepath.Join(root, s+".d")); !errors.Is(err, fs.ErrNotExist) {
+ t.Fatal("slice already has set-property drop-ins", s, root, err)
+ }
+ }
+ if allow := show(s, "IPAddressAllow"); allow != "" {
+ t.Fatal("slice already carries an allow", s, allow)
+ }
+ }
+ // Starting a unit in a per-host slice starts its ancestors too; stop
+ // on cleanup only the ones this test found inactive.
+ stopAfter := []string{slice, otherSlice}
+ for _, s := range []string{parent, "carlos.slice"} {
+ if show(s, "ActiveState") == "inactive" {
+ stopAfter = append(stopAfter, s)
+ }
+ }
+
+ scratch, err := os.MkdirTemp("", "egr")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := os.RemoveAll(scratch); err != nil {
+ t.Error(err)
+ }
+ })
+
+ // The dummy link and its listeners.
+ ip := func(args ...string) {
+ t.Helper()
+ if out, err := exec.Command("ip", args...).CombinedOutput(); err != nil {
+ t.Fatalf("ip %s: %v: %s", strings.Join(args, " "), err, out)
+ }
+ }
+ ip("link", "add", egressProofLink, "type", "dummy")
+ t.Cleanup(func() {
+ if out, err := exec.Command("ip", "link", "del", egressProofLink).CombinedOutput(); err != nil {
+ t.Errorf("ip link del %s: %v: %s", egressProofLink, err, out)
+ }
+ })
+ ip("link", "set", egressProofLink, "up")
+ ip("addr", "add", "10.0.5.20/32", "dev", egressProofLink)
+ ip("addr", "add", "10.0.5.21/32", "dev", egressProofLink)
+ ip("-6", "addr", "add", "fd00:5::20/128", "dev", egressProofLink, "nodad")
+ listen := func(addr string) string {
+ t.Helper()
+ ln, err := net.Listen("tcp", addr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { ln.Close() })
+ go func() {
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ c.Close()
+ }
+ }()
+ return ln.Addr().String() // an explicit port: the tenant dials host:port (C15)
+ }
+ open20 := listen("10.0.5.20:0")
+ open21 := listen("10.0.5.21:0")
+ open6 := listen("[fd00:5::20]:0")
+ for _, addr := range []string{open20, open21, open6} {
+ c, err := net.DialTimeout("tcp", addr, time.Second)
+ if err != nil {
+ t.Fatal("listener unreachable from the test itself", addr, err)
+ }
+ c.Close()
+ }
+
+ // Slice drop-ins come off after every unit has stopped (cleanups run
+ // last-registered first, and the units register theirs later).
+ t.Cleanup(func() {
+ for _, s := range slices {
+ if out, err := ctl("show", "-p", "LoadState", "--value", s); err == nil && out == "loaded" {
+ if out, err := ctl("set-property", "--runtime", s, "IPAddressAllow="); err != nil {
+ t.Errorf("reset %s: %v: %s", s, err, out)
+ }
+ }
+ if err := os.RemoveAll(filepath.Join("/run/systemd/system.control", s+".d")); err != nil {
+ t.Error(err)
+ }
+ }
+ if out, err := ctl("daemon-reload"); err != nil {
+ t.Errorf("daemon-reload: %v: %s", err, out)
+ }
+ for _, s := range stopAfter {
+ if out, _ := ctl("show", "-p", "ActiveState", "--value", s); out != "inactive" {
+ if out, err := ctl("stop", s); err != nil {
+ t.Errorf("stop %s: %v: %s", s, err, out)
+ }
+ }
+ }
+ })
+
+ // The resolver allow's stand-in on the parent.
+ mustCtl("set-property", "--runtime", parent, "IPAddressAllow=10.0.5.21/32")
+
+ // serving waits for a tenant to answer on its socket.
+ serving := func(unit string, c *http.Client) {
+ t.Helper()
+ deadline := time.Now().Add(10 * time.Second)
+ for {
+ resp, err := c.Get("http://tenant/")
+ if err == nil {
+ resp.Body.Close()
+ if resp.StatusCode == http.StatusOK {
+ return
+ }
+ err = errors.New(resp.Status)
+ }
+ if time.Now().After(deadline) {
+ logs, _ := exec.Command("journalctl", "-u", unit, "--no-pager", "-n", "40").CombinedOutput()
+ t.Fatalf("%s did not serve: %v\n%s", unit, err, logs)
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ }
+ // start runs this binary's plan14-tenant in a transient unit carrying
+ // the template's deny, and returns a client for its socket.
+ start := func(unit, inSlice, sock string) *http.Client {
+ t.Helper()
+ t.Cleanup(func() {
+ if out, _ := ctl("show", "-p", "LoadState", "--value", unit); out != "not-found" {
+ if out, err := ctl("stop", unit); err != nil {
+ t.Errorf("stop %s: %v: %s", unit, err, out)
+ }
+ ctl("reset-failed", unit)
+ }
+ for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(100 * time.Millisecond) {
+ out, _ := ctl("show", "-p", "LoadState", "--value", unit)
+ if out == "not-found" {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Errorf("unit %s left behind: %s", unit, out)
+ break
+ }
+ }
+ })
+ socket := filepath.Join(scratch, sock)
+ out, err := exec.Command("systemd-run", "--unit="+unit, "--slice="+inSlice,
+ "-p", "IPAddressDeny="+deny,
+ "-E", "PLAN14_TENANT_SOCKET="+socket,
+ exe, "plan14-tenant").CombinedOutput()
+ if err != nil {
+ t.Fatalf("systemd-run %s: %v: %s", unit, err, out)
+ }
+ transport := &http.Transport{DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
+ return (&net.Dialer{}).DialContext(ctx, "unix", socket)
+ }, DisableKeepAlives: true}
+ client := &http.Client{Transport: transport, Timeout: 3 * time.Second}
+ serving(unit, client)
+ if got := show(unit, "Slice"); got != inSlice {
+ t.Fatalf("%s runs in %q, want %q", unit, got, inSlice)
+ }
+ return client
+ }
+ // reach asks a tenant to dial addr (host:port): 204 reachable, 403 not.
+ reach := func(c *http.Client, addr string) bool {
+ t.Helper()
+ resp, err := c.Get("http://tenant/?dial=" + url.QueryEscape(addr))
+ if err != nil {
+ t.Fatal("tenant probe", addr, err)
+ }
+ resp.Body.Close()
+ switch resp.StatusCode {
+ case http.StatusNoContent:
+ return true
+ case http.StatusForbidden:
+ return false
+ }
+ t.Fatal("tenant probe", addr, resp.Status)
+ return false
+ }
+ // within polls every 100 ms for up to 2 s until reach(addr) == want.
+ within := func(c *http.Client, addr string, want bool) bool {
+ t.Helper()
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ if reach(c, addr) == want {
+ return true
+ }
+ if time.Now().After(deadline) {
+ return false
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+ }
+
+ // Step 1: the slice's allow is written before the child exists (the
+ // start-path order), then the child starts under it.
+ mustCtl("set-property", "--runtime", slice, "IPAddressAllow=", "IPAddressAllow=10.0.5.20/32 fd00:5::20/128")
+ a := start(units[0], slice, "a.sock")
+ if got := show(units[0], "ExecStart"); !strings.Contains(got, "path="+exe+" ;") {
+ t.Fatalf("ExecStart does not name the test binary %s: %s", exe, got)
+ }
+ ownAllow := show(units[0], "IPAddressAllow")
+ t.Logf("unit's own IPAddressAllow after start: %q", ownAllow)
+ t.Logf("unit's IPAddressDeny: %q", show(units[0], "IPAddressDeny"))
+ if !reach(a, open20) || !reach(a, open6) {
+ t.Fatal("step 1: the slice's allow, written before start, did not open 10.0.5.20 and fd00:5::20")
+ }
+ if !reach(a, open21) {
+ t.Error("step 1: the parent's allow (10.0.5.21) is not reachable beside the slice's own")
+ verdict("combines with parent", false)
+ }
+
+ // Step 2: reset the slice's allow while the child runs.
+ mustCtl("set-property", "--runtime", slice, "IPAddressAllow=")
+ revoked := within(a, open20, false) && within(a, open6, false)
+ verdict("revoke live", revoked)
+ if !revoked {
+ t.Error("step 2: 10.0.5.20 or fd00:5::20 still reachable 2 s after the slice's allow was reset")
+ }
+ if reach(a, open21) {
+ verdict("combines with parent", true)
+ } else {
+ t.Error("step 2: the parent's allow (10.0.5.21) closed with the slice's")
+ verdict("combines with parent", false)
+ }
+ if !revoked {
+ // Close it by restarting, so step 3 still measures "open live".
+ mustCtl("restart", units[0])
+ serving(units[0], a)
+ if !within(a, open20, false) {
+ t.Fatal("step 2: 10.0.5.20 still reachable after a restart under an empty slice allow")
+ }
+ }
+
+ // Step 3: re-open 10.0.5.20 while the child runs.
+ mustCtl("set-property", "--runtime", slice, "IPAddressAllow=", "IPAddressAllow=10.0.5.20/32")
+ opened := within(a, open20, true)
+ verdict("open live", opened)
+ if !opened {
+ t.Error("step 3: 10.0.5.20 not reachable 2 s after the slice's allow named it")
+ }
+ if reach(a, open6) {
+ t.Error("step 3: fd00:5::20 reachable though the slice's allow no longer names it")
+ }
+
+ // Step 4: the unit's own list is untouched (claimEffectiveUnit reads it).
+ if got := show(units[0], "IPAddressAllow"); got != ownAllow {
+ t.Errorf("step 4: unit's own IPAddressAllow changed from %q to %q", ownAllow, got)
+ }
+
+ // Step 5: the slice's show lists its own entries only.
+ raw := show(slice, "IPAddressAllow")
+ t.Logf("slice IPAddressAllow raw: %q", raw)
+ got, err := egressProofPrefixes(raw)
+ if err != nil {
+ t.Fatal("step 5:", err)
+ }
+ own := len(got) == 1 && got[0] == netip.MustParsePrefix("10.0.5.20/32")
+ verdict("slice show is own entries only", own)
+ if !own {
+ t.Errorf("step 5: slice IPAddressAllow is %v, want exactly [10.0.5.20/32]", got)
+ }
+
+ // Step 6: isolation at the kernel, while step 3's allow is in force.
+ others := map[string]*http.Client{
+ units[1] + " in " + otherSlice: start(units[1], otherSlice, "b.sock"),
+ units[2] + " in " + parent: start(units[2], parent, "c.sock"),
+ }
+ for name, c := range others {
+ if reach(c, open20) {
+ t.Errorf("step 6: %s reached 10.0.5.20, which only %s allows", name, slice)
+ }
+ if reach(c, open6) {
+ t.Errorf("step 6: %s reached fd00:5::20", name)
+ }
+ if !reach(c, open21) {
+ t.Errorf("step 6: %s cannot reach the parent's allow 10.0.5.21", name)
+ }
+ }
+ if opened && !reach(a, open20) {
+ t.Error("step 6: 10.0.5.20 closed for the allowed unit while its siblings ran")
+ }
+}
+
+// egressProofPrefixes parses systemd's space-separated IPAddressAllow
+// value; a bare address is its full-length prefix.
+func egressProofPrefixes(raw string) ([]netip.Prefix, error) {
+ var out []netip.Prefix
+ for _, f := range strings.Fields(raw) {
+ if strings.Contains(f, "/") {
+ p, err := netip.ParsePrefix(f)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, p)
+ continue
+ }
+ a, err := netip.ParseAddr(f)
+ if err != nil {
+ return nil, fmt.Errorf("allow entry %q: %w", f, err)
+ }
+ out = append(out, netip.PrefixFrom(a, a.BitLen()))
+ }
+ return out, nil
+}