carlos / platform Public

host: egress isolation witness: other apps and the probe stay fenced (#328)

TestRootEgressIsolation: on one pre-claim box, app A granted 10.0.5.20
and app B with no policy, both started through POST /start. With A
reaching the address in the same run, B cannot; the real probe unit,
run by Server.RunProbe before and after the grant, reports the same
verdicts; a unit in carlos-instances.slice under the probe template's
deny cannot reach it; carlos-instances.slice holds only the resolver
allow. Then B granted through POST /egress and the stand-in given the
address by hand each reach it, so every refusal was the fence.

The box fixture takes options (target names, more hosts, the probe);
its zero value is Task 13's box. The target fixture here is
carlos-egr2/carlos-egr2n.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 44db9ebdd2834d6d4dcd3fda07f8fc5cd2a9c9ad parent c4d8352
2 files changed, +601 −59
  • internal/host/egress_fixtures_rootrunner_linux_test.go +336 −38
  • internal/host/egress_startpaths_rootrunner_linux_test.go +265 −21
diff --git a/internal/host/egress_fixtures_rootrunner_linux_test.go b/internal/host/egress_fixtures_rootrunner_linux_test.go
index ff381a412..f2c225474 100644
--- a/internal/host/egress_fixtures_rootrunner_linux_test.go
+++ b/internal/host/egress_fixtures_rootrunner_linux_test.go
@@ -18,6 +18,7 @@ import (
"net/url"
"os"
"os/exec"
+ "os/user"
"path/filepath"
"runtime"
"slices"
@@ -25,13 +26,16 @@ import (
"strings"
"sync"
"sync/atomic"
+ "syscall"
"testing"
"time"
"golang.org/x/sys/unix"
"github.com/carlosframework/platform/internal/cgroup"
+ "github.com/carlosframework/platform/internal/controlsock"
"github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/instanceexec"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
@@ -138,7 +142,14 @@ func egressIP(t *testing.T, args ...string) {
// them, which is why the tenants here are unit files, never systemd-run).
func egressTemplateDeny(t *testing.T) string {
t.Helper()
- raw, err := unitsFS.ReadFile("units/carlos-instance@.service")
+ return egressUnitDeny(t, "carlos-instance@.service")
+}
+
+// egressUnitDeny is the IPAddressDeny= list of an embedded unit (one of
+// unitsFS's units/), verbatim.
+func egressUnitDeny(t *testing.T, name string) string {
+ t.Helper()
+ raw, err := unitsFS.ReadFile("units/" + name)
if err != nil {
t.Fatal(err)
}
@@ -146,13 +157,13 @@ func egressTemplateDeny(t *testing.T) string {
for _, line := range strings.Split(string(raw), "\n") {
if v, ok := strings.CutPrefix(line, "IPAddressDeny="); ok {
if deny != "" {
- t.Fatal("template carries more than one IPAddressDeny= line")
+ t.Fatal(name, "carries more than one IPAddressDeny= line")
}
deny = v
}
}
if deny == "" {
- t.Fatal("template carries no IPAddressDeny= line")
+ t.Fatal(name, "carries no IPAddressDeny= line")
}
return deny
}
@@ -187,6 +198,23 @@ func egressTargetNetns(t *testing.T) map[string]string {
// (generationMounts) refuses any nsfs mount on purpose. Calling close, or
// the test's end, tears it down once, last-made first.
func egressTargetNetnsClosable(t *testing.T) (map[string]string, func()) {
+ t.Helper()
+ return egressTargetNetnsAt(t, egressNetnsTask13)
+}
+
+// egressNetnsNames names a target fixture's namespace and veth pair, so
+// two tasks' witnesses never share one: link names are box-wide, and each
+// task removes only what it made.
+type egressNetnsNames struct {
+ ns, hostLink, nsLink string
+}
+
+// egressNetnsTask13 is Task 13's fixture (carlos-egr, carlos-egr1/1n).
+var egressNetnsTask13 = egressNetnsNames{ns: egressNetns, hostLink: egressHostLink, nsLink: egressNsLink}
+
+// egressTargetNetnsAt is egressTargetNetnsClosable with the fixture's
+// names given.
+func egressTargetNetnsAt(t *testing.T, n egressNetnsNames) (map[string]string, func()) {
t.Helper()
var steps []func()
var once sync.Once
@@ -205,64 +233,64 @@ func egressTargetNetnsClosable(t *testing.T) (map[string]string, func()) {
if _, err := exec.LookPath("ip"); err != nil {
t.Fatal("needs ip", err)
}
- nsPath := filepath.Join("/run/netns", egressNetns)
+ nsPath := filepath.Join("/run/netns", n.ns)
if _, err := os.Lstat(nsPath); !errors.Is(err, fs.ErrNotExist) {
t.Fatal("network namespace already exists", nsPath, err)
}
- if _, err := net.InterfaceByName(egressHostLink); err == nil {
- t.Fatal("link already exists", egressHostLink)
+ if _, err := net.InterfaceByName(n.hostLink); err == nil {
+ t.Fatal("link already exists", n.hostLink)
}
- egressIP(t, "netns", "add", egressNetns)
+ egressIP(t, "netns", "add", n.ns)
cleanup(func() {
- if out, err := exec.Command("ip", "netns", "del", egressNetns).CombinedOutput(); err != nil {
- t.Errorf("ip netns del %s: %v: %s", egressNetns, err, out)
+ if out, err := exec.Command("ip", "netns", "del", n.ns).CombinedOutput(); err != nil {
+ t.Errorf("ip netns del %s: %v: %s", n.ns, err, out)
}
if _, err := os.Lstat(nsPath); !errors.Is(err, fs.ErrNotExist) {
t.Errorf("network namespace %s left behind: %v", nsPath, err)
}
})
- egressIP(t, "link", "add", egressHostLink, "type", "veth", "peer", "name", egressNsLink, "netns", egressNetns)
+ egressIP(t, "link", "add", n.hostLink, "type", "veth", "peer", "name", n.nsLink, "netns", n.ns)
cleanup(func() {
// Deleting one end removes the pair. The namespace's own deletion
// would too, but only once nothing holds the namespace, so the
// pair goes first and explicitly.
- if _, err := net.InterfaceByName(egressHostLink); err == nil {
- if out, err := exec.Command("ip", "link", "del", egressHostLink).CombinedOutput(); err != nil {
- t.Errorf("ip link del %s: %v: %s", egressHostLink, err, out)
+ if _, err := net.InterfaceByName(n.hostLink); err == nil {
+ if out, err := exec.Command("ip", "link", "del", n.hostLink).CombinedOutput(); err != nil {
+ t.Errorf("ip link del %s: %v: %s", n.hostLink, err, out)
}
}
for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(100 * time.Millisecond) {
- if _, err := net.InterfaceByName(egressHostLink); err != nil {
+ if _, err := net.InterfaceByName(n.hostLink); err != nil {
break
}
if time.Now().After(deadline) {
- t.Errorf("link %s left behind", egressHostLink)
+ t.Errorf("link %s left behind", n.hostLink)
break
}
}
})
- egressIP(t, "addr", "add", "10.0.5.1/32", "dev", egressHostLink)
- egressIP(t, "-6", "addr", "add", "fd00:5::1/128", "dev", egressHostLink, "nodad")
- egressIP(t, "link", "set", egressHostLink, "up")
- egressIP(t, "route", "add", "10.0.5.20/32", "dev", egressHostLink, "src", "10.0.5.1")
- egressIP(t, "route", "add", "10.0.5.21/32", "dev", egressHostLink, "src", "10.0.5.1")
- egressIP(t, "-6", "route", "add", "fd00:5::20/128", "dev", egressHostLink, "src", "fd00:5::1")
-
- in := func(args ...string) { t.Helper(); egressIP(t, append([]string{"-n", egressNetns}, args...)...) }
+ egressIP(t, "addr", "add", "10.0.5.1/32", "dev", n.hostLink)
+ egressIP(t, "-6", "addr", "add", "fd00:5::1/128", "dev", n.hostLink, "nodad")
+ egressIP(t, "link", "set", n.hostLink, "up")
+ egressIP(t, "route", "add", "10.0.5.20/32", "dev", n.hostLink, "src", "10.0.5.1")
+ egressIP(t, "route", "add", "10.0.5.21/32", "dev", n.hostLink, "src", "10.0.5.1")
+ egressIP(t, "-6", "route", "add", "fd00:5::20/128", "dev", n.hostLink, "src", "fd00:5::1")
+
+ in := func(args ...string) { t.Helper(); egressIP(t, append([]string{"-n", n.ns}, args...)...) }
in("link", "set", "lo", "up")
- in("addr", "add", "10.0.5.20/32", "dev", egressNsLink)
- in("addr", "add", "10.0.5.21/32", "dev", egressNsLink)
- in("-6", "addr", "add", "fd00:5::20/128", "dev", egressNsLink, "nodad")
- in("link", "set", egressNsLink, "up")
- in("route", "add", "10.0.5.1/32", "dev", egressNsLink)
- in("-6", "route", "add", "fd00:5::1/128", "dev", egressNsLink)
+ in("addr", "add", "10.0.5.20/32", "dev", n.nsLink)
+ in("addr", "add", "10.0.5.21/32", "dev", n.nsLink)
+ in("-6", "addr", "add", "fd00:5::20/128", "dev", n.nsLink, "nodad")
+ in("link", "set", n.nsLink, "up")
+ in("route", "add", "10.0.5.1/32", "dev", n.nsLink)
+ in("-6", "route", "add", "fd00:5::1/128", "dev", n.nsLink)
addrs := map[string]string{}
for _, a := range egressTargets {
ln, err := egressListenIn(nsPath, net.JoinHostPort(a, "0"))
if err != nil {
- t.Fatalf("listen on %s in %s: %v", a, egressNetns, err)
+ t.Fatalf("listen on %s in %s: %v", a, n.ns, err)
}
cleanup(func() { ln.Close() })
go func() {
@@ -625,7 +653,12 @@ func egressSliceProperties(t *testing.T, slice string) {
// egressNestedRow is an activator-managed instance row at the nested
// defaults under dataDir: the row the pre-claim rail counts as nested.
func egressNestedRow(dataDir, host string) registry.Route {
- return registry.Route{Host: host, Kind: "instance", Account: "abc", App: "shop", Channel: "stable", Hibernate: true, Status: "ready",
+ return egressNestedAppRow(dataDir, host, "shop")
+}
+
+// egressNestedAppRow is egressNestedRow for the app named.
+func egressNestedAppRow(dataDir, host, app string) registry.Route {
+ return registry.Route{Host: host, Kind: "instance", Account: "abc", App: app, Channel: "stable", Hibernate: true, Status: "ready",
DBPath: provision.NestedDBPath(dataDir, host), Socket: provision.NestedSocket(host)}
}
@@ -678,10 +711,30 @@ type egressBox struct {
reg *registry.Registry
egress *instancectl.EgressAsserter
ctl *egressFailingCtl
+ srv *instancectl.Server
client *instancectl.Client
staged instancectl.StagedExe
}
+// egressBoxOptions widens the pre-claim box for Task 14. The zero value is
+// Task 13's box.
+type egressBoxOptions struct {
+ // netns names the target fixture; zero is Task 13's.
+ netns egressNetnsNames
+ // others are more nested hosts on the box, each another app's (account
+ // abc), with no policy: a registry row, a staged build behind the
+ // host's live link, the run role's launch file and log socket, and the
+ // host slice's cleanup. They are started through POST /start.
+ others []egressOtherHost
+ // probe installs the readiness probe (carlos-instance-probe.service
+ // from unitsFS) and its fixtures, and gives the control service the
+ // probe's production fields, for Server.RunProbe.
+ probe bool
+}
+
+// egressOtherHost is another app's host on the box.
+type egressOtherHost struct{ host, app string }
+
// The templates the pre-claim start paths use.
var egressTemplates = []string{
"carlos-instance@.service",
@@ -694,6 +747,11 @@ var egressTemplates = []string{
const egressGen = 1
func newEgressPreClaimBox(t *testing.T) *egressBox {
+ t.Helper()
+ return newEgressPreClaimBoxWith(t, egressBoxOptions{})
+}
+
+func newEgressPreClaimBoxWith(t *testing.T, o egressBoxOptions) *egressBox {
t.Helper()
egressRootPrereqs(t)
uid, gid := generationRunnerRegistryUser(t)
@@ -708,6 +766,9 @@ func newEgressPreClaimBox(t *testing.T) *egressBox {
instancectl.UnitName(instancectl.RoleCmd, host),
instancectl.GenUnitName(host, egressGen),
}
+ for _, other := range o.others {
+ units = append(units, instancectl.UnitName(instancectl.RoleRun, other.host))
+ }
for _, u := range units {
if state := egressShow(t, u, "LoadState"); state != "not-found" {
t.Fatal("unit already present", u, state)
@@ -732,7 +793,11 @@ func newEgressPreClaimBox(t *testing.T) *egressBox {
}
})
}
- b.targets = egressTargetNetns(t)
+ if o.netns == (egressNetnsNames{}) {
+ b.targets = egressTargetNetns(t)
+ } else {
+ b.targets, _ = egressTargetNetnsAt(t, o.netns)
+ }
// The build: the test binary, as the platform binary the templates
// run (instance-exec, instance-exit) and as the app's staged build,
@@ -763,18 +828,34 @@ func newEgressPreClaimBox(t *testing.T) *egressBox {
if err := os.Symlink(staged, release.LiveLink("/opt/carlos", host)); err != nil {
t.Fatal(err)
}
+ for _, other := range o.others {
+ otherStaged := release.VersionPath("/opt/carlos", "abc", "v1", other.app)
+ if err := os.MkdirAll(filepath.Dir(otherStaged), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(otherStaged, image, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(otherStaged, release.LiveLink("/opt/carlos", other.host)); err != nil {
+ t.Fatal(err)
+ }
+ }
// The instance's two directories, the carlos user's, and the log
// sockets PID 1 connects each unit's output to.
if err := os.Chown("/data", uid, gid); err != nil {
t.Fatal(err)
}
- for _, d := range []string{provision.InstanceDir("/data", host), provision.InstanceRunDir(host), filepath.Join(provision.SocketDir, "logs")} {
+ instanceDirs := []string{provision.InstanceDir("/data", host), provision.InstanceRunDir(host)}
+ for _, other := range o.others {
+ instanceDirs = append(instanceDirs, provision.InstanceDir("/data", other.host), provision.InstanceRunDir(other.host))
+ }
+ for _, d := range append([]string{filepath.Join(provision.SocketDir, "logs")}, instanceDirs...) {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
}
- for _, d := range []string{provision.InstanceDir("/data", host), provision.InstanceRunDir(host)} {
+ for _, d := range instanceDirs {
if err := os.Chown(d, uid, gid); err != nil {
t.Fatal(err)
}
@@ -787,10 +868,14 @@ func newEgressPreClaimBox(t *testing.T) *egressBox {
logs.mu.Unlock()
}
})
- for _, sock := range []string{
+ logSockets := []string{
provision.LogSocket(host, "run"), provision.LogSocket(host, "seed"), provision.LogSocket(host, "sidecar"),
provision.LogSocket(host, "cmd"), provision.LogSocket(host, "cmd-err"), instancectl.GenLogSocket(host, egressGen),
- } {
+ }
+ for _, other := range o.others {
+ logSockets = append(logSockets, provision.LogSocket(other.host, "run"))
+ }
+ for _, sock := range logSockets {
ln, err := net.Listen("unix", sock)
if err != nil {
t.Fatal(err)
@@ -840,8 +925,11 @@ func newEgressPreClaimBox(t *testing.T) *egressBox {
})
}
egressMustCtl(t, "daemon-reload")
- // The slice's drop-ins come off after its units have stopped.
+ // The slices' drop-ins come off after their units have stopped.
egressSliceProperties(t, b.slice)
+ for _, other := range o.others {
+ egressSliceProperties(t, instancectl.SliceName(other.host))
+ }
t.Cleanup(func() {
for _, u := range units {
if out, _ := egressCtl("show", "-p", "LoadState", "--value", u); out != "not-found" {
@@ -869,6 +957,11 @@ func newEgressPreClaimBox(t *testing.T) *egressBox {
if err := reg.SetPolicy(host, "10.0.5.20", "", egressExpiry()); err != nil {
t.Fatal(err)
}
+ for _, other := range o.others {
+ if err := reg.Upsert(egressNestedAppRow("/data", other.host, other.app)); err != nil {
+ t.Fatal(err)
+ }
+ }
b.reg = reg
// The launch files the agent writes before each start. Serving roles
@@ -895,11 +988,24 @@ func newEgressPreClaimBox(t *testing.T) *egressBox {
t.Fatal(err)
}
}
+ // Each other host's run role serves plan14-tenant the same way.
+ for _, other := range o.others {
+ raw, err := json.Marshal(instancectl.Launch{Schema: instancectl.LaunchSchema, Host: other.host,
+ Argv: []string{filepath.Join(instancectl.LiveDir, other.host), "plan14-tenant"},
+ Env: []string{"PLAN14_TENANT_SOCKET=" + filepath.Join(provision.InstanceRunDir(other.host), "run.sock")}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(provision.InstanceDir("/data", other.host), instancectl.LaunchFileName(instancectl.RoleRun)), raw, 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
// The production pre-claim asserter (RunInstanceControl's !claims
// branch), its systemctl behind a pass-through the revoke witness can
// arm, and the control service as runWithClaim builds it, minus the
- // socket activation, the probe and the disk floors.
+ // socket activation, the probe loop and the disk floors (with
+ // o.probe, the probe's fields are runWithClaim's, for RunProbe).
b.egress = newEgressAsserter(registryEgressSource("/data", time.Now), registryEgressHosts("/data"))
b.ctl = &egressFailingCtl{next: b.egress.Systemctl, slice: b.slice}
b.egress.Systemctl = b.ctl.run
@@ -919,6 +1025,14 @@ func newEgressPreClaimBox(t *testing.T) *egressBox {
DataRoot: "/data/instances",
Egress: b.egress,
}
+ if o.probe {
+ egressProbeFixture(t, uid, gid)
+ srv.ProbeOut = egressProbeOut
+ srv.FixtureOK = egressProbeFixturesOK
+ srv.ResolvConf = "/etc/resolv.conf"
+ srv.ResolvedConf = instancectl.ResolvedConf
+ }
+ b.srv = srv
b.client = egressServe(t, srv, filepath.Join(t.TempDir(), "control.sock"))
return b
}
@@ -984,3 +1098,187 @@ func (b *egressBox) startRun(t *testing.T) *http.Client {
}
return c
}
+
+// The readiness probe, for the isolation witness (Task 14): its unit
+// runs this test binary as /opt/carlos/carlos instance-probe, which
+// prints the probe's report (instanceexec.RunProbe) as the real binary
+// does (main.go).
+func init() {
+ if len(os.Args) >= 2 && os.Args[1] == "instance-probe" {
+ instanceexec.RunProbe(os.Args[2:])
+ os.Exit(0)
+ }
+}
+
+// egressProbeUnit is the readiness probe's unit (instancectl's probeUnit).
+const egressProbeUnit = "carlos-instance-probe.service"
+
+// egressProbeOut is where the probe unit's StandardOutput=truncate: lands:
+// runWithClaim's ProbeOut.
+var egressProbeOut = filepath.Join(controlsock.Dir, "probe.out")
+
+// egressProbeFixture installs the probe for Server.RunProbe on the
+// pre-claim box (its fixture roots already made):
+//
+// - the unit from unitsFS into /run/systemd/system, with its mount
+// dependencies (Requires=, After=) dropped as the box drops the
+// templates', everything else verbatim (its IPAddressDeny= and Slice=
+// among it);
+// - the two fixtures tmpfiles stages (bootstrap.go): /etc/carlos/probe-secret
+// root:carlos 0640 and /dev/shm/carlos-probe, root's;
+// - the probe's own instance directories, its bind sources;
+// - carlos-instances.slice's properties, refused if already set and
+// reset on cleanup: RunProbe writes the resolver allow there.
+//
+// Everything is removed on cleanup.
+func egressProbeFixture(t *testing.T, uid, gid int) {
+ t.Helper()
+ if state := egressShow(t, egressProbeUnit, "LoadState"); state != "not-found" {
+ t.Fatal("unit already present", egressProbeUnit, state)
+ }
+ for _, dir := range []string{"/run/systemd/system", "/etc/systemd/system"} {
+ if _, err := os.Lstat(filepath.Join(dir, egressProbeUnit)); !errors.Is(err, fs.ErrNotExist) {
+ t.Fatal("probe unit already installed", dir, err)
+ }
+ }
+ raw, err := unitsFS.ReadFile("units/" + egressProbeUnit)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(raw), "\nStandardOutput=truncate:"+egressProbeOut+"\n") {
+ t.Fatalf("the probe unit does not write its report to %s", egressProbeOut)
+ }
+
+ secret := "/etc/carlos/probe-secret"
+ if err := os.WriteFile(secret, []byte("probe"), 0o640); err != nil {
+ t.Fatal(err)
+ }
+ if err := errors.Join(os.Chown(secret, 0, gid), os.Chmod(secret, 0o640)); err != nil {
+ t.Fatal(err)
+ }
+ shm := "/dev/shm/carlos-probe"
+ f, err := os.OpenFile(shm, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
+ if err != nil {
+ t.Fatal("probe shm fixture:", err)
+ }
+ t.Cleanup(func() {
+ if err := os.Remove(shm); err != nil {
+ t.Error(err)
+ }
+ })
+ _, werr := f.WriteString("probe")
+ if err := errors.Join(werr, f.Close()); err != nil {
+ t.Fatal(err)
+ }
+ for _, d := range []struct {
+ path string
+ mode fs.FileMode
+ }{
+ {filepath.Join("/data/instances", instancectl.ProbeDirName), 0o700},
+ {filepath.Join(provision.SocketDir, "instances", instancectl.ProbeDirName), 0o750 | fs.ModeSetgid},
+ } {
+ if err := os.Mkdir(d.path, 0o700); err != nil {
+ t.Fatal(err)
+ }
+ if err := errors.Join(os.Chown(d.path, uid, gid), os.Chmod(d.path, d.mode)); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ egressParentSliceProperties(t)
+
+ var lines []string
+ for _, line := range strings.Split(string(raw), "\n") {
+ if strings.HasPrefix(line, "Requires=") || strings.HasPrefix(line, "After=") {
+ continue
+ }
+ lines = append(lines, line)
+ }
+ path := filepath.Join("/run/systemd/system", egressProbeUnit)
+ uf, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if out, _ := egressCtl("show", "-p", "LoadState", "--value", egressProbeUnit); out != "not-found" {
+ if out, err := egressCtl("stop", egressProbeUnit); err != nil {
+ t.Errorf("stop %s: %v: %s", egressProbeUnit, err, out)
+ }
+ }
+ egressCtl("reset-failed", egressProbeUnit)
+ if err := os.Remove(path); err != nil {
+ t.Error(err)
+ }
+ if out, err := egressCtl("daemon-reload"); err != nil {
+ t.Errorf("daemon-reload: %v: %s", err, out)
+ }
+ if out, _ := egressCtl("show", "-p", "LoadState", "--value", egressProbeUnit); out != "not-found" {
+ t.Errorf("unit %s left behind: %s", egressProbeUnit, out)
+ }
+ })
+ _, werr = uf.WriteString(strings.Join(lines, "\n"))
+ if err := errors.Join(werr, uf.Close()); err != nil {
+ t.Fatal(err)
+ }
+ egressMustCtl(t, "daemon-reload")
+}
+
+// egressProbeFixturesOK is the control service's FixtureOK, made here as
+// instancectl's probeFixturesOK makes it (unexported there): both probe
+// fixtures present, the secret root:carlos 0640 and the shm file a
+// root-owned regular file. Either one missing would make its probe line
+// pass vacuously.
+func egressProbeFixturesOK() error {
+ shm, err := os.Lstat("/dev/shm/carlos-probe")
+ if err != nil {
+ return fmt.Errorf("probe shm fixture absent: %v", err)
+ }
+ if st, ok := shm.Sys().(*syscall.Stat_t); !ok || st.Uid != 0 || !shm.Mode().IsRegular() {
+ return errors.New("probe shm fixture: not a root-owned regular file")
+ }
+ fi, err := os.Stat("/etc/carlos/probe-secret")
+ if err != nil {
+ return fmt.Errorf("probe fixture absent: %v", err)
+ }
+ st, ok := fi.Sys().(*syscall.Stat_t)
+ if !ok {
+ return errors.New("probe fixture: no stat")
+ }
+ g, err := user.LookupGroup("carlos")
+ if err != nil {
+ return err
+ }
+ gid, _ := strconv.Atoi(g.Gid)
+ if st.Uid != 0 || int(st.Gid) != gid || fi.Mode().Perm() != 0o640 {
+ return fmt.Errorf("probe fixture is uid %d gid %d mode %o, want root:carlos 0640", st.Uid, st.Gid, fi.Mode().Perm())
+ }
+ return nil
+}
+
+// egressParentSliceProperties refuses a carlos-instances.slice that
+// already carries set-property drop-ins or an allow, and on cleanup resets
+// its allow and removes the runtime drop-ins the test's writes leave (the
+// resolver allow RunProbe writes, egressParentAllow's stand-in).
+func egressParentSliceProperties(t *testing.T) {
+ t.Helper()
+ parent := instancectl.InstancesSlice
+ for _, root := range []string{"/run/systemd/system.control", "/etc/systemd/system.control"} {
+ if _, err := os.Lstat(filepath.Join(root, parent+".d")); !errors.Is(err, fs.ErrNotExist) {
+ t.Fatal("parent slice already has set-property drop-ins", root, err)
+ }
+ }
+ if got := egressShow(t, parent, "IPAddressAllow"); got != "" {
+ t.Fatal("parent slice already carries an allow", got)
+ }
+ t.Cleanup(func() {
+ if out, err := egressCtl("set-property", "--runtime", parent, "IPAddressAllow="); err != nil {
+ t.Errorf("reset %s: %v: %s", parent, err, out)
+ }
+ if err := os.RemoveAll(filepath.Join("/run/systemd/system.control", parent+".d")); err != nil {
+ t.Error(err)
+ }
+ if out, err := egressCtl("daemon-reload"); err != nil {
+ t.Errorf("daemon-reload: %v: %s", err, out)
+ }
+ })
+}
diff --git a/internal/host/egress_startpaths_rootrunner_linux_test.go b/internal/host/egress_startpaths_rootrunner_linux_test.go
index e53c3e9ea..2b02253c5 100644
--- a/internal/host/egress_startpaths_rootrunner_linux_test.go
+++ b/internal/host/egress_startpaths_rootrunner_linux_test.go
@@ -6,7 +6,9 @@ import (
"crypto/ed25519"
"errors"
"io/fs"
+ "maps"
"net/http"
+ "net/netip"
"os"
"path/filepath"
"slices"
@@ -149,27 +151,8 @@ func TestRootEgressRevokeWhileRunning(t *testing.T) {
// the probe's resolver allow does in production, and takes it off after.
func egressParentAllow(t *testing.T, prefix string) {
t.Helper()
- parent := instancectl.InstancesSlice
- for _, root := range []string{"/run/systemd/system.control", "/etc/systemd/system.control"} {
- if _, err := os.Lstat(filepath.Join(root, parent+".d")); !errors.Is(err, fs.ErrNotExist) {
- t.Fatal("parent slice already has set-property drop-ins", root, err)
- }
- }
- if got := egressShow(t, parent, "IPAddressAllow"); got != "" {
- t.Fatal("parent slice already carries an allow", got)
- }
- t.Cleanup(func() {
- if out, err := egressCtl("set-property", "--runtime", parent, "IPAddressAllow="); err != nil {
- t.Errorf("reset %s: %v: %s", parent, err, out)
- }
- if err := os.RemoveAll(filepath.Join("/run/systemd/system.control", parent+".d")); err != nil {
- t.Error(err)
- }
- if out, err := egressCtl("daemon-reload"); err != nil {
- t.Errorf("daemon-reload: %v: %s", err, out)
- }
- })
- egressMustCtl(t, "set-property", "--runtime", parent, "IPAddressAllow=", "IPAddressAllow="+prefix)
+ egressParentSliceProperties(t)
+ egressMustCtl(t, "set-property", "--runtime", instancectl.InstancesSlice, "IPAddressAllow=", "IPAddressAllow="+prefix)
}
// runInvocation is the run unit's InvocationID.
@@ -624,3 +607,264 @@ func (w *egressUnderClaimsWitness) check(t *testing.T, egress func(host string)
}
closedBy("POST /egress", before, deadline)
}
+
+// TestRootEgressIsolation is the isolation witness (#328, plan 2 Task 14;
+// spec: "Another app's instance on the same box cannot reach the allowed
+// address; the probe cannot either"). On one pre-claim box, through the
+// real control service and the installed templates, two nested rows:
+// shop-a.example.com (app shop) granted 10.0.5.20 an hour ahead, and
+// shop-b.example.com (app shop-b) with no policy, both started through
+// POST /start. With A's allow in force and A reaching 10.0.5.20 in the
+// same run, before and after:
+//
+// - B's tenant cannot reach it, and B's slice holds nothing;
+// - the real probe unit, run by Server.RunProbe before the grant and
+// again with A granted and both running, gives the same report
+// (Ready and every line's verdict), and its own deny lines hold;
+// - a unit in carlos-instances.slice carrying the probe template's
+// IPAddressDeny= verbatim (the probe's place in the tree and its
+// deny, checked against the loaded probe unit) cannot reach it;
+// - carlos-instances.slice holds the resolver allow RunProbe writes, and
+// nothing else.
+//
+// Then each refusal is shown to be the fence and not a broken dialer: B
+// granted through the production path (column, POST /egress) reaches the
+// address within 2 s, and so does the stand-in given the address on its
+// own unit by hand.
+//
+// The target fixture uses its own names (namespace and veth carlos-egr2,
+// carlos-egr2n), apart from Task 1's carlos-egr0 and Task 13's
+// carlos-egr1.
+func TestRootEgressIsolation(t *testing.T) {
+ other := egressOtherHost{host: "shop-b.example.com", app: "shop-b"}
+ b := newEgressPreClaimBoxWith(t, egressBoxOptions{
+ netns: egressNetnsNames{ns: "carlos-egr2", hostLink: "carlos-egr2", nsLink: "carlos-egr2n"},
+ others: []egressOtherHost{other},
+ probe: true,
+ })
+ ctx := t.Context()
+ target := b.targets["10.0.5.20"]
+ parent := instancectl.InstancesSlice
+ otherSlice := instancectl.SliceName(other.host)
+ otherUnit := instancectl.UnitName(instancectl.RoleRun, other.host)
+ wantParent := egressResolverAllow(t)
+ t.Logf("resolver allow expected on %s: %q", parent, wantParent)
+ if got := b.allow(t); got != "" {
+ t.Fatalf("app A's slice holds %q before any start", got)
+ }
+
+ // The probe, before anything is granted.
+ before := egressRunProbe(t, b.srv, "before the grant")
+ egressWantPrefixes(t, "before the grant: "+parent, egressShow(t, parent, "IPAddressAllow"), wantParent)
+
+ // App A, granted, through POST /start: the slice holds the allow and
+ // the tenant reaches the address (startRun also checks the template's
+ // deny is in force: 10.0.5.21, which nothing grants, is closed).
+ a := b.startRun(t)
+ b.wantAllowed(t, "app A")
+ if !egressReach(t, a, target) {
+ egressFirewallDiag(t, instancectl.UnitName(instancectl.RoleRun, b.host), b.slice, a, target)
+ t.Fatal("app A cannot reach 10.0.5.20 under its own grant: the fixture proves nothing")
+ }
+
+ // App B, no policy, through the same POST /start.
+ if _, err := b.client.Start(ctx, other.host, instancectl.RoleRun, cgroup.TierDefault.MemoryMax); err != nil {
+ t.Fatalf("POST /start run (app B): %v\n%s", err, egressJournal(otherUnit))
+ }
+ bc := egressTenantClient(filepath.Join(provision.InstanceRunDir(other.host), "run.sock"))
+ egressServing(t, otherUnit, bc)
+ if got := egressShow(t, otherSlice, "IPAddressAllow"); got != "" {
+ t.Fatalf("app B's slice holds %q with no policy", got)
+ }
+ if rep := egressHostReport(t, b, other.host); len(rep.Allowed) != 0 || rep.State != "" {
+ t.Fatalf("app B: GET /egress = %+v, want nothing allowed and no state", rep)
+ }
+ if egressReach(t, bc, target) {
+ egressFirewallDiag(t, otherUnit, otherSlice, bc, target)
+ t.Fatal("app B reaches 10.0.5.20, which only app A is granted")
+ }
+
+ // The probe again, with A granted and both instances running: the same
+ // report, and A's grant has not reached the probe's unit or slice.
+ after := egressRunProbe(t, b.srv, "with app A granted")
+ egressSameProbe(t, before, after)
+ if got := egressShow(t, egressProbeUnit, "Slice"); got != parent {
+ t.Fatalf("the probe runs in %q, want %q", got, parent)
+ }
+ if got := egressShow(t, egressProbeUnit, "IPAddressAllow"); got != "" {
+ t.Fatalf("the probe unit holds an allow: %q", got)
+ }
+ egressWantPrefixes(t, "with app A granted: "+parent, egressShow(t, parent, "IPAddressAllow"), wantParent)
+
+ // The probe's stand-in: its slice and its deny, a dialer.
+ scratch, err := os.MkdirTemp("/run", "egr-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { os.RemoveAll(scratch) })
+ const standin = "carlos-egress-probe-standin"
+ standinUnit := standin + ".service"
+ sc := egressUnitTenant(t, standin, parent, egressUnitDeny(t, egressProbeUnit), filepath.Join(scratch, "tenant.sock"))
+ if got, want := egressShow(t, standinUnit, "IPAddressDeny"), egressShow(t, egressProbeUnit, "IPAddressDeny"); got != want || got == "" {
+ t.Fatalf("the stand-in's deny %q is not the loaded probe unit's %q", got, want)
+ }
+ if got := egressShow(t, standinUnit, "IPAddressAllow"); got != "" {
+ t.Fatalf("the stand-in holds an allow: %q", got)
+ }
+ if egressReach(t, sc, target) {
+ egressFirewallDiag(t, standinUnit, parent, sc, target)
+ t.Fatal("a unit in the probe's place, under the probe's deny, reaches 10.0.5.20")
+ }
+
+ // A still reaches it: the target answered throughout.
+ if !egressReach(t, a, target) {
+ t.Fatal("app A lost 10.0.5.20 during the run: the refusals above prove nothing")
+ }
+ b.wantAllowed(t, "app A, at the end")
+
+ // Each refusal was the fence. B, granted through the production path,
+ // reaches the address within 2 s of POST /egress returning.
+ if err := b.reg.SetPolicy(other.host, "10.0.5.20", "", egressExpiry()); err != nil {
+ t.Fatal(err)
+ }
+ if err := b.client.Egress(ctx, other.host); err != nil {
+ t.Fatal("POST /egress (app B):", err)
+ }
+ if !egressWithin(t, time.Now().Add(egressLiveBound), bc, true, target) {
+ egressFirewallDiag(t, otherUnit, otherSlice, bc, target)
+ t.Fatal("app B, granted, cannot reach 10.0.5.20: its refusal above may not have been the fence")
+ }
+ if got := egressShow(t, otherSlice, "IPAddressAllow"); got != "10.0.5.20/32" {
+ t.Fatalf("app B granted: slice holds %q", got)
+ }
+ // The stand-in, given the address on its own unit by hand.
+ dropIns := filepath.Join("/run/systemd/system.control", standinUnit+".d")
+ for _, root := range []string{"/run/systemd/system.control", "/etc/systemd/system.control"} {
+ if _, err := os.Lstat(filepath.Join(root, standinUnit+".d")); !errors.Is(err, fs.ErrNotExist) {
+ t.Fatal("the stand-in already has set-property drop-ins", root, err)
+ }
+ }
+ t.Cleanup(func() {
+ if err := os.RemoveAll(dropIns); err != nil {
+ t.Error(err)
+ }
+ if out, err := egressCtl("daemon-reload"); err != nil {
+ t.Errorf("daemon-reload: %v: %s", err, out)
+ }
+ })
+ egressMustCtl(t, "set-property", "--runtime", standinUnit, "IPAddressAllow=10.0.5.20/32")
+ if !egressWithin(t, time.Now().Add(egressLiveBound), sc, true, target) {
+ egressFirewallDiag(t, standinUnit, parent, sc, target)
+ t.Fatal("the stand-in, given the address, cannot reach 10.0.5.20: its refusal above may not have been the fence")
+ }
+ egressWantPrefixes(t, "at the end: "+parent, egressShow(t, parent, "IPAddressAllow"), wantParent)
+}
+
+// egressHostReport is GET /egress's report for host.
+func egressHostReport(t *testing.T, b *egressBox, host string) instancectl.EgressReport {
+ t.Helper()
+ st, err := b.client.EgressStatus(t.Context())
+ if err != nil {
+ t.Fatal("GET /egress:", err)
+ }
+ return st.Hosts[host]
+}
+
+// egressResolverAllow is the allow RunProbe should leave on
+// carlos-instances.slice, worked out here from what an instance sees
+// (resolved's upstream list when there is one, else /etc/resolv.conf):
+// each nameserver ResolverAllowed admits and that is not one of the box's
+// own addresses, as a single-address prefix, sorted.
+func egressResolverAllow(t *testing.T) []string {
+ t.Helper()
+ file := "/etc/resolv.conf"
+ if _, err := os.Stat(instancectl.ResolvedConf); err == nil {
+ file = instancectl.ResolvedConf
+ }
+ raw, err := os.ReadFile(file)
+ if err != nil {
+ t.Fatal(err)
+ }
+ local, err := instancectl.LocalAddresses()
+ if err != nil {
+ t.Fatal("LocalAddresses:", err)
+ }
+ seen := map[string]bool{}
+ var allow []string
+ for _, a := range instancectl.ParseResolvers(raw) {
+ if ok, _ := instancectl.ResolverAllowed(a); !ok {
+ continue
+ }
+ if slices.ContainsFunc(local, func(p netip.Prefix) bool { return p.Contains(a) }) {
+ continue
+ }
+ if p := netip.PrefixFrom(a, a.BitLen()).String(); !seen[p] {
+ seen[p] = true
+ allow = append(allow, p)
+ }
+ }
+ slices.Sort(allow)
+ return allow
+}
+
+// egressWantPrefixes fails unless systemd's IPAddressAllow value lists
+// exactly want, in any order.
+func egressWantPrefixes(t *testing.T, step, got string, want []string) {
+ t.Helper()
+ fields := strings.Fields(got)
+ slices.Sort(fields)
+ if !slices.Equal(fields, want) {
+ t.Fatalf("%s: IPAddressAllow = %q, want exactly %q", step, got, want)
+ }
+}
+
+// egressRunProbe runs the probe through Server.RunProbe and returns the
+// report it stored. probe.out is removed first, so the report is this
+// run's own. A report that is a refusal before the probe ran (fixtures,
+// exe layout, resolver allow, unit start, output) fails the test, and so
+// does one whose own deny lines are not ok: either would make "unchanged"
+// mean nothing.
+func egressRunProbe(t *testing.T, srv *instancectl.Server, step string) instancectl.ProbeReport {
+ t.Helper()
+ if err := os.Remove(egressProbeOut); err != nil && !errors.Is(err, fs.ErrNotExist) {
+ t.Fatal(err)
+ }
+ srv.RunProbe(t.Context())
+ rep, _ := srv.Ready()
+ verdicts := map[string]string{}
+ for _, l := range rep.Lines {
+ t.Logf("probe %s: %s %s %s", step, l.Check, l.Verdict, l.Detail)
+ verdicts[l.Check] = l.Verdict
+ }
+ t.Logf("probe %s: ready %v", step, rep.Ready)
+ for _, check := range []string{"fixture", "probe-exe", "resolver-allow", "probe-unit", "probe-output", "probe"} {
+ if _, ok := verdicts[check]; ok {
+ t.Fatalf("probe %s: the probe did not run (%s line)\n%s", step, check, egressJournal(egressProbeUnit))
+ }
+ }
+ for _, check := range []string{"imds-v4", "imds-tcp", "loopback-v4", "private-v4"} {
+ if verdicts[check] != "ok" {
+ t.Fatalf("probe %s: %s is %q, want ok: the probe's own deny is not in force", step, check, verdicts[check])
+ }
+ }
+ return rep
+}
+
+// egressSameProbe fails unless two probe reports agree on Ready and on
+// every line's verdict.
+func egressSameProbe(t *testing.T, before, after instancectl.ProbeReport) {
+ t.Helper()
+ verdicts := func(r instancectl.ProbeReport) map[string]string {
+ m := map[string]string{}
+ for _, l := range r.Lines {
+ m[l.Check] = l.Verdict
+ }
+ return m
+ }
+ if before.Ready != after.Ready {
+ t.Fatalf("the probe's Ready went from %v to %v with app A granted", before.Ready, after.Ready)
+ }
+ if b, a := verdicts(before), verdicts(after); !maps.Equal(b, a) {
+ t.Fatalf("the probe's verdicts changed with app A granted:\nbefore %v\nafter %v", b, a)
+ }
+}