From 011c159ef9e8617b1bdb7a3915a22905ff92f186 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Sat, 5 Dec 2026 15:21:09 +0100 Subject: [PATCH 1/2] fix(sandboxpolicy): close the igbackend follow-ups from the NRI gate stack Follow-ups from the reviews of #1160 and #1162, all fail-closed. - HostPIDNamespace requires procRoot to be a procfs (statfs) before the NSpid proof. - A gone container whose entry delete fails no longer matches ErrContainerGone, so start and the move heal fail instead of silently dropping the cleanup (CodeRabbit #1160 4802841890); an entry that is already gone (ErrKeyNotExist) counts as deleted, and a failed bind no longer leaves a binding active with no entry. - Start keeps an ErrCredUnrecorded binding only for the pending slot. - Tests: hadMove with ErrCredUnrecorded, the AdoptedPending fan-out, the holds() exclusion, MarkPod on a record that owes an unbind. - Type-only changes so the node-agent side builds for GOARCH=386 (the IG fork still needs its own patch). - Doc comments. Co-Authored-By: Claude Opus 5.5 Docs-exempt: internal fixes and tests in the unreleased NRI start gate stack Signed-off-by: Matthias Bertschy --- pkg/config/config.go | 2 +- .../gadgets/common/enforcement/bindings.go | 27 +++- .../enforcement/pending_followups_test.go | 146 ++++++++++++++++++ pkg/hostfimsensor/v1/fimsensor_fanotify.go | 2 +- .../igbackend/adoptedpending_test.go | 18 +++ pkg/sandboxpolicy/igbackend/imageevidence.go | 4 +- pkg/sandboxpolicy/igbackend/imageindex.go | 11 +- .../igbackend/markpod_oldpod_test.go | 85 ++++++++++ pkg/sandboxpolicy/integration/nrigate.go | 13 +- .../integration/nrigate_copilot8_test.go | 28 +++- .../integration/podcgroup_linux.go | 25 ++- .../integration/podcgroup_test.go | 2 +- .../sections_adoptedpending_test.go | 78 ++++++++++ 13 files changed, 415 insertions(+), 26 deletions(-) create mode 100644 pkg/ebpf/gadgets/common/enforcement/pending_followups_test.go create mode 100644 pkg/sandboxpolicy/igbackend/markpod_oldpod_test.go create mode 100644 pkg/sandboxpolicy/sections_adoptedpending_test.go diff --git a/pkg/config/config.go b/pkg/config/config.go index 5c4f4d8af7..515024e7d8 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -440,7 +440,7 @@ func LoadConfigOptional(path string, errNotFound bool) (Config, error) { viper.SetDefault("nodeProfileInterval", 10*time.Minute) viper.SetDefault("maxDelaySeconds", 30) viper.SetDefault("maxJitterPercentage", 5) - viper.SetDefault("maxImageSize", 5*1024*1024*1024) + viper.SetDefault("maxImageSize", int64(5*1024*1024*1024)) viper.SetDefault("maxSBOMSize", 20*1024*1024) viper.SetDefault("maxTsProfileSize", 2*1024*1024) viper.SetDefault("maxSniffingTimePerContainer", 24*time.Hour) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index 2a922d639e..10ee44dece 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -660,8 +660,14 @@ func (b *Bindings) bind(c Binding) error { if err := check(); err != nil { if errors.Is(err, ErrContainerGone) { // Gone: nothing to protect; drop it as a failed fresh bind. + // A failed delete of its entry is not a benign + // disappearance: its error does not match + // ErrContainerGone, so start and retryMoves (which skip a + // gone container) report it, and the entry and any + // recorded move stay until a retry removes them + // (CodeRabbit #1160 4802841890). if derr := b.members.Delete(id.CgroupID); derr != nil && !errors.Is(derr, ebpf.ErrKeyNotExist) { - return errors.Join(err, derr) + return fmt.Errorf("removing the binding of a gone container (%v): %w", err, derr) } delete(b.adopted, id.CgroupID) delete(b.active, id.CgroupID) @@ -814,9 +820,17 @@ func (b *Bindings) bind(c Binding) error { // reason: remove the entry it wrote, so the cgroup is as before // the call and the caller sees the error. A container that is // gone needs no protection; a startup replay skips it, and keeps - // an unrecorded Strict pending binding (see start). - if derr := b.members.Delete(id.CgroupID); derr != nil { + // an unrecorded Strict pending binding (see start). A gone + // container whose entry could not be removed is not skipped: + // the error does not match ErrContainerGone (CodeRabbit #1160 + // 4802841890). An entry already absent (ErrKeyNotExist: an + // in-place replacement raced the old instance's unbind of the + // same cgroup) is removed, as in the preflight. + if derr := b.members.Delete(id.CgroupID); derr != nil && !errors.Is(derr, ebpf.ErrKeyNotExist) { b.keepFailed(c, checked) + if errors.Is(err, ErrContainerGone) { + return fmt.Errorf("removing the binding of a gone container (%v): %w", err, derr) + } return errors.Join(err, derr) } delete(b.active, id.CgroupID) @@ -1505,9 +1519,12 @@ func (b *Bindings) start(policy Map, members BindingMap, armed Map, faults, witn // hold). Not a start failure: the pending entry is kept and c // recorded (keepRefusedMove), never c installed. err = b.keepRefusedMove(c, v) - case errors.Is(err, ErrCredUnrecorded): + case errors.Is(err, ErrCredUnrecorded) && c.Slot == PendingSlot: // A Strict pending c whose walk could not record every task - // (only a walk with pending semantics reports it). + // (only a walk with pending semantics reports it). Never a + // real-slot c, whatever the case order: keepUnrecorded would + // install it without its credentials; such an error fails + // the start (copilot-19 review LOW 3). err = b.keepUnrecorded(c) case distrusted && errors.Is(err, ErrIoUringHeld) && c.Slot == PendingSlot && c.Strict: // The take-over found a ring. Not a start failure: a diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_followups_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_followups_test.go new file mode 100644 index 0000000000..1c94495bc6 --- /dev/null +++ b/pkg/ebpf/gadgets/common/enforcement/pending_followups_test.go @@ -0,0 +1,146 @@ +// Copyright 2026 The Kubescape Authors +// SPDX-License-Identifier: Apache-2.0 + +package enforcement + +import ( + "errors" + "fmt" + "testing" + + "github.com/cilium/ebpf" +) + +// A live bind of a cgroup with a refused start move, to another Strict slot, +// whose preflight cannot record every credential (ErrCredUnrecorded, not a +// held ring) records the newer wish (hadMove): the pending entry stays, the +// newer slot is unconfirmed, and a heal moves the cgroup there once the +// record has room, never to the older wish (copilot-19 review LOW 1, M3). +func TestBindAttemptReplacesRefusedMoveOnUnrecordedCreds(t *testing.T) { + c9 := ContainerIdentity{Runtime: "containerd", ID: "c9", CgroupID: 77, CgroupPath: "/workloads.slice/parent-uid-9"} + pendingValue := bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers | bindingRingChecked} + full := true + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.members.data[c9.CgroupID] = pendingValue + f.b.config.InitialPublications = []Publication{f.publication(1, 10, true), f.publication(2, 20, true)} + f.b.desired[selector(c9)] = Binding{Container: c9, Slot: 1} + f.b.recordCreds = func(_ uint64, _ string, flags, slot uint32) (bool, error) { + if full { + return false, fullRecordFor(flags, slot) + } + return false, nil + } + f.armed = &fakeMap{typ: ebpf.TaskStorage} + f.witness = fakeWitness{0: 2} + }) + if f.b.moves[c9.CgroupID] != (Binding{Container: c9, Slot: 1}) { + t.Fatalf("fixture: a refused start move to slot 1: %+v", f.b.moves) + } + kept := f.members.data[c9.CgroupID] + newer := Binding{Container: c9, Slot: 2} + if err := f.b.Bind(newer); !errors.Is(err, ErrCredUnrecorded) { + t.Fatalf("Bind: %v", err) + } + if f.b.moves[c9.CgroupID] != newer || f.b.RingUnconfirmed(1) != 0 || f.b.RingUnconfirmed(2) != 1 { + t.Fatalf("moves %+v, unconfirmed slot 1 %d, slot 2 %d", f.b.moves, f.b.RingUnconfirmed(1), f.b.RingUnconfirmed(2)) + } + if v := f.members.data[c9.CgroupID]; v != kept { + t.Fatalf("the pending entry stays: %+v, was %+v", v, kept) + } + full = false + if err := f.b.HealNode(); err != nil { + t.Fatal(err) + } + if v := f.members.data[c9.CgroupID].(bindingValue); v.Slot != 2 || len(f.b.moves) != 0 { + t.Fatalf("the heal moves the cgroup to the newer wish: %+v, moves %+v", v, f.b.moves) + } +} + +// A heal's retry of a refused move whose cgroup is gone removes its entry; +// a failed delete is not a benign disappearance: the heal fails (the error +// does not match ErrContainerGone) and the entry and the move record stay +// until a retry removes them (CodeRabbit #1160 4802841890). +func TestRetriedMoveOfGoneCgroupFailedDeleteFailsHeal(t *testing.T) { + ring := true + f, c9 := refusedMoveFixture(t, &ring) + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, ErrContainerGone } + f.members.deleteErr = errors.New("busy") + err := f.b.HealNode() + if err == nil || errors.Is(err, ErrContainerGone) { + t.Fatalf("HealNode: %v, want a failure that is not a gone container", err) + } + if _, ok := f.b.moves[c9.CgroupID]; !ok { + t.Fatalf("the move record stays: %+v", f.b.moves) + } + if _, ok := f.members.data[c9.CgroupID]; !ok { + t.Fatal("the entry stays while its delete fails") + } + f.members.deleteErr = nil + if err := f.b.HealNode(); err != nil { + t.Fatalf("HealNode after the delete succeeds: %v", err) + } + if _, ok := f.members.data[c9.CgroupID]; ok || len(f.b.moves) != 0 { + t.Fatalf("entry %v, moves %+v", f.members.data, f.b.moves) + } +} + +// A startup bind of a gone container whose entry cannot be removed fails the +// start: only a gone container that leaves nothing behind is skipped +// (TestStartSkipsGoneContainer; CodeRabbit #1160 4802841890). +func TestStartGoneContainerFailedDeleteFailsStart(t *testing.T) { + b, policy, members, _ := newFixture(t, func(Map) error { return nil }) + b.armExisting = func(Map, string) error { return ErrContainerGone } + members.deleteErr = errors.New("busy") + err := b.start(policy, members, &fakeMap{typ: ebpf.TaskStorage}, nil, nil) + if err == nil || errors.Is(err, ErrContainerGone) { + t.Fatalf("start: %v, want a failure that is not a gone container", err) + } +} + +// start never installs a real-slot binding through keepUnrecorded: a walk +// that reports ErrCredUnrecorded for one (no Strict pending semantics +// produce it today; the fake does) fails the start, and nothing is written +// for it (copilot-19 review LOW 3). +func TestStartNeverKeepsUnrecordedRealSlot(t *testing.T) { + c := ContainerIdentity{Runtime: "containerd", ID: "c71", CgroupID: 71, CgroupPath: "/workloads.slice/c71"} + b, policy, members, _ := newFixture(t, func(Map) error { return nil }) + b.config.StrictSlot = func(uint32) bool { return true } + b.config.InitialBindings = nil + clear(b.desired) + b.desired[selector(c)] = Binding{Container: c, Slot: 1} + b.armExisting = func(Map, string) error { return nil } + b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { + return false, fmt.Errorf("%w: 1 tasks (record full or over quota)", ErrCredUnrecorded) + } + err := b.start(policy, members, &fakeMap{typ: ebpf.TaskStorage}, nil, nil) + if !errors.Is(err, ErrCredUnrecorded) { + t.Fatalf("start: %v, want the unrecorded walk to fail it", err) + } + if v, ok := members.data[c.CgroupID]; ok { + t.Fatalf("a real-slot binding was installed: %+v", v) + } + if _, ok := b.active[c.CgroupID]; ok { + t.Fatal("a real-slot binding is active") + } +} + +// A startup bind of a gone container whose entry is already deleted +// (ErrKeyNotExist: an in-place replacement raced the old instance's unbind +// of the same cgroup) is skipped like any gone container: the start does not +// fail, and nothing of it stays active (rev-c fu1 review MEDIUM). +func TestStartGoneContainerAlreadyDeletedIsSkipped(t *testing.T) { + b, policy, members, _ := newFixture(t, func(Map) error { return nil }) + b.armExisting = func(Map, string) error { + // The old instance unbinds the same cgroup meanwhile: the entry + // this bind wrote is gone, and its delete finds no key. + delete(members.data, identity.CgroupID) + members.deleteErr = fmt.Errorf("delete: %w", ebpf.ErrKeyNotExist) + return ErrContainerGone + } + if err := b.start(policy, members, &fakeMap{typ: ebpf.TaskStorage}, nil, nil); err != nil { + t.Fatalf("start: %v, want the already deleted gone container skipped", err) + } + if len(b.active) != 0 || len(members.data) != 0 { + t.Fatalf("active %+v, entries %v", b.active, members.data) + } +} diff --git a/pkg/hostfimsensor/v1/fimsensor_fanotify.go b/pkg/hostfimsensor/v1/fimsensor_fanotify.go index 566494a8f1..1e24b55cba 100644 --- a/pkg/hostfimsensor/v1/fimsensor_fanotify.go +++ b/pkg/hostfimsensor/v1/fimsensor_fanotify.go @@ -182,7 +182,7 @@ func (h *HostFimSensorFanotify) getFileMetadata(filePath string) (size int64, in uid = stat.Uid gid = stat.Gid mode = uint32(stat.Mode) - ctime = time.Unix(stat.Ctim.Sec, stat.Ctim.Nsec) + ctime = time.Unix(stat.Ctim.Unix()) } } diff --git a/pkg/sandboxpolicy/igbackend/adoptedpending_test.go b/pkg/sandboxpolicy/igbackend/adoptedpending_test.go index 80d8ae9cef..28702e1c54 100644 --- a/pkg/sandboxpolicy/igbackend/adoptedpending_test.go +++ b/pkg/sandboxpolicy/igbackend/adoptedpending_test.go @@ -5,6 +5,7 @@ import ( "time" "github.com/kubescape/node-agent/pkg/ebpf/gadgets/common/enforcement" + "github.com/kubescape/node-agent/pkg/sandboxpolicy" ) // TestAdoptedPending (Copilot #1176 4802130614, part B): the read-back of a @@ -29,6 +30,23 @@ func TestAdoptedPending(t *testing.T) { if _, err := b.AdoptedPending(0, time.Now().Add(time.Minute)); err == nil { t.Fatal("an unresolved cgroup while a Strict mark remains answered") } + // A cgroup this run holds (a pod record) is not an adopted mark this + // run does not hold, even while the instance still lists an adopted + // Strict pending entry on it (the holds exclusion). + held := uint64(podCgroup + 2) + heldMark := strictMark + heldMark.Container.CgroupID = held + i.entries[held], i.adopted[held] = heldMark, true + b.pods["held"] = &podBinding{pod: sandboxpolicy.PodBinding{PodUID: "held", CgroupID: held}} + if strict, err := b.AdoptedPending(held, time.Now().Add(time.Minute)); strict || err != nil { + t.Fatalf("a held cgroup with an adopted Strict pending entry: %v %v", strict, err) + } + delete(b.pods, "held") + if strict, err := b.AdoptedPending(held, time.Now().Add(time.Minute)); !strict || err != nil { + t.Fatalf("fixture: the same entry, not held: %v %v", strict, err) + } + delete(i.entries, held) + delete(i.adopted, held) // Synchronize proves the pod: keepPending drops the mark. b.SetStartGate(true) b.SetNRISynced(1, map[uint64]bool{podCgroup: true}) diff --git a/pkg/sandboxpolicy/igbackend/imageevidence.go b/pkg/sandboxpolicy/igbackend/imageevidence.go index 6a6b95e6d8..6e2df7f553 100644 --- a/pkg/sandboxpolicy/igbackend/imageevidence.go +++ b/pkg/sandboxpolicy/igbackend/imageevidence.go @@ -365,7 +365,7 @@ func validateSandboxShmPins(source, destination *os.File, sourceMounts, destinat } func validateSandboxShmFacts(fs unix.Statfs_t, mode uint32, mountinfo []byte, id uint64) error { requiredFlags := int64(unix.ST_NOSUID | unix.ST_NODEV | unix.ST_NOEXEC) - if mode&unix.S_IFMT != unix.S_IFDIR || fs.Type != unix.TMPFS_MAGIC || fs.Flags&requiredFlags != requiredFlags { + if mode&unix.S_IFMT != unix.S_IFDIR || fs.Type != unix.TMPFS_MAGIC || int64(fs.Flags)&requiredFlags != requiredFlags { return fmt.Errorf("sandbox shm must be a nosuid/nodev/noexec tmpfs directory") } return validateRestrictedMountInfo(mountinfo, id, "tmpfs", true, []string{"nosuid", "nodev", "noexec"}) @@ -495,7 +495,7 @@ func validCgroupMount(m specs.Mount) bool { } func validateCgroupMountFacts(fs unix.Statfs_t, mode uint32, mountinfo []byte, id uint64) error { required := int64(unix.ST_RDONLY | unix.ST_NOSUID | unix.ST_NODEV | unix.ST_NOEXEC) - if mode&unix.S_IFMT != unix.S_IFDIR || fs.Type != unix.CGROUP2_SUPER_MAGIC || fs.Flags&required != required { + if mode&unix.S_IFMT != unix.S_IFDIR || fs.Type != unix.CGROUP2_SUPER_MAGIC || int64(fs.Flags)&required != required { return fmt.Errorf("cgroup mount must be a read-only nosuid/nodev/noexec cgroup2 directory") } return validateRestrictedMountInfo(mountinfo, id, "cgroup2", false, []string{"ro", "nosuid", "nodev", "noexec"}) diff --git a/pkg/sandboxpolicy/igbackend/imageindex.go b/pkg/sandboxpolicy/igbackend/imageindex.go index a5a2e3d842..ea84300abb 100644 --- a/pkg/sandboxpolicy/igbackend/imageindex.go +++ b/pkg/sandboxpolicy/igbackend/imageindex.go @@ -12,6 +12,7 @@ import ( "sort" "strings" "sync" + "unsafe" "golang.org/x/sys/unix" ) @@ -83,11 +84,17 @@ func indexFS(file *os.File) error { if err := unix.Fstatfs(int(file.Fd()), &fs); err != nil { return err } - switch fs.Type { + // The magic as the kernel's unsigned word: a 32-bit Statfs_t (386) + // holds one above MaxInt32 (btrfs) as a negative int32. + magic := uint64(fs.Type) + if unsafe.Sizeof(fs.Type) == 4 { + magic = uint64(uint32(fs.Type)) + } + switch magic { case unix.EXT4_SUPER_MAGIC, unix.XFS_SUPER_MAGIC, unix.BTRFS_SUPER_MAGIC, unix.TMPFS_MAGIC: return nil } - return fmt.Errorf("unsupported lower filesystem %#x (overlay/nested roots are not accepted)", fs.Type) + return fmt.Errorf("unsupported lower filesystem %#x (overlay/nested roots are not accepted)", magic) } // buildLowerIndex does NOT establish that these paths are image layers. The diff --git a/pkg/sandboxpolicy/igbackend/markpod_oldpod_test.go b/pkg/sandboxpolicy/igbackend/markpod_oldpod_test.go new file mode 100644 index 0000000000..c0d3736aca --- /dev/null +++ b/pkg/sandboxpolicy/igbackend/markpod_oldpod_test.go @@ -0,0 +1,85 @@ +package igbackend + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + + "github.com/kubescape/node-agent/pkg/sandboxpolicy" +) + +// TestMarkPodOnARecordThatOwesAnUnbind (#1176 S2 follow-up): after a move +// whose unbind of the old cgroup failed (oldPod), MarkPod refuses both +// cgroups: the old one because the record now holds the new one, the new +// one because the owed unbind goes before any write and still fails. It +// never binds the new cgroup. Once the unbind succeeds, MarkPod retries it +// (oldPod cleared, the old entry gone) and still refuses a mark over the +// failed bind (errEntryNotCovering); EnsurePodBound then binds the target. +func TestMarkPodOnARecordThatOwesAnUnbind(t *testing.T) { + ctx := context.Background() + key, _ := Combination(strictPlan) + moved := testPodBinding("u", podCgroup+1, strictPlan) + for _, before := range []bool{true, false} { + t.Run(fmt.Sprintf("before the delete %v", before), func(t *testing.T) { + b, e := newGate(t) + i := e.last() + mustMark(t, b, strictPlan, seq(5, 5)) + if err := b.EnsurePodBound(ctx, "u"); err != nil { + t.Fatal(err) + } + fail := func(err error) { + if before { + i.unbindBeforeErr = err + } else { + i.unbindErr = err + } + } + fail(errors.New("unbind")) + if err := b.BindPodsAt(ctx, []sandboxpolicy.PodBinding{moved}, seq(9, 9)); err == nil { + t.Fatal("the unbind fails") + } + if p := b.pods["u"]; p == nil || p.oldPod == nil || p.oldPod.CgroupID != podCgroup || p.pod.CgroupID != podCgroup+1 { + t.Fatalf("fixture: a record that owes the old cgroup's unbind: %+v", p) + } + + // The old cgroup: the record holds the new one. + if err := b.MarkPod(ctx, gatePod(strictPlan), seq(10, 10)); err == nil || !strings.Contains(err.Error(), "its record holds cgroup") { + t.Fatalf("MarkPod of the old cgroup: %v", err) + } + // The new cgroup: the owed unbind runs first and fails. + if err := b.MarkPod(ctx, moved, seq(10, 10)); err == nil || !strings.Contains(err.Error(), "unbinding its previous cgroup") { + t.Fatalf("MarkPod of the new cgroup while the unbind fails: %v", err) + } + if i.binds[podCgroup+1] != 0 || b.pods["u"].oldPod == nil { + t.Fatalf("nothing binds the new cgroup while the old one's unbind fails: %+v", b.pods["u"]) + } + if c := b.ConfirmPod("u", podCgroup+1, strictPlan); c.State == sandboxpolicy.PodSectionConfirmed { + t.Fatalf("ConfirmPod %+v", c) + } + + // The unbind succeeds: MarkPod retries it, and still writes + // no mark over the failed bind. + fail(nil) + if err := b.MarkPod(ctx, moved, seq(10, 10)); !errors.Is(err, errEntryNotCovering) { + t.Fatalf("MarkPod after the unbind succeeds: %v", err) + } + if _, ok := i.entries[podCgroup]; ok || b.pods["u"].oldPod != nil { + t.Fatalf("MarkPod retried the owed unbind: entries %v, record %+v", i.entries, b.pods["u"]) + } + if i.binds[podCgroup+1] != 0 { + t.Fatal("MarkPod bound the new cgroup") + } + if err := b.EnsurePodBound(ctx, "u"); err != nil { + t.Fatal(err) + } + if i.entries[podCgroup+1].Slot != b.slots[key] { + t.Fatalf("the target is bound: %+v", i.entries[podCgroup+1]) + } + if c := b.ConfirmPod("u", podCgroup+1, strictPlan); c.State != sandboxpolicy.PodSectionConfirmed { + t.Fatalf("ConfirmPod %+v", c) + } + }) + } +} diff --git a/pkg/sandboxpolicy/integration/nrigate.go b/pkg/sandboxpolicy/integration/nrigate.go index a1a520a862..9f1bddd697 100644 --- a/pkg/sandboxpolicy/integration/nrigate.go +++ b/pkg/sandboxpolicy/integration/nrigate.go @@ -343,10 +343,10 @@ var _ startgate.Gate = (*nriGate)(nil) // EnableNRIStartGate turns the NRI start gate on. While the build constant // is false (startgate.Buildable), it returns startgate.ErrNotBuildable and // changes nothing: no gate, no goroutine, no socket. Otherwise it checks -// that node-agent shares the host PID namespace (HostPIDNamespace, by PID -// namespace inode), enables the pod gate (enableStartGate, which refuses -// once Start ran) and creates the plugin; Start runs it after the informers -// synced. Call it once, before Start, from the goroutine that calls Start +// that host.HostRoot/proc (a hostPath mount of the node's /proc) is a procfs +// of node-agent's own PID namespace (HostPIDNamespace: statfs, then NSpid), +// enables the pod gate (enableStartGate, which refuses once Start ran) and +// creates the plugin; Start runs it after the informers synced. Call it once, before Start, from the goroutine that calls Start // (S3 review v3 R2). func (s *Service) EnableNRIStartGate(ctx context.Context) error { if !startgate.Buildable() { @@ -744,8 +744,9 @@ func (n *nriGate) ClassificationSeq(ctx context.Context) sandboxpolicy.Seq { // Registration is the node-level registration gate (design ยง6, v5): the // pod gate is enabled (enableStartGate, with its cgroup-gone self-test), -// node-agent shares the host PID namespace, restart survival is on (a mark -// must outlive node-agent), and the informers synced once. The lifetime +// procRoot is a procfs of node-agent's own PID namespace +// (HostPIDNamespace), restart survival is on (a mark must outlive +// node-agent), and the informers synced once. The lifetime // lock (L2) and the lift marker belong to S6, which adds them here; the // build constant keeps the gate off until S9, after S6. func (n *nriGate) Registration() error { diff --git a/pkg/sandboxpolicy/integration/nrigate_copilot8_test.go b/pkg/sandboxpolicy/integration/nrigate_copilot8_test.go index 641a3e3aaa..d375009cdf 100644 --- a/pkg/sandboxpolicy/integration/nrigate_copilot8_test.go +++ b/pkg/sandboxpolicy/integration/nrigate_copilot8_test.go @@ -80,13 +80,15 @@ func c8Proc(t *testing.T, nspid string) string { // the procfs's namespace down to this process's): exactly one level, equal // to this process's PID. A procfs of an ancestor namespace where the // numbers coincide lists two levels and is refused; an unprovable one -// (no NSpid) is refused. +// (no NSpid) is refused. The fake trees are not a procfs, so they go +// through samePIDNamespace, the file proof HostPIDNamespace runs once its +// statfs passed (TestHostPIDNamespaceNeedsAProcfs). func TestCopilot8PIDNamespaceOfTheProcfs(t *testing.T) { pid := strconv.Itoa(os.Getpid()) if err := HostPIDNamespace("/proc"); err != nil { t.Fatalf("this process's own procfs: %v", err) } - if err := HostPIDNamespace(c8Proc(t, pid)); err != nil { + if err := samePIDNamespace(c8Proc(t, pid)); err != nil { t.Fatalf("one level, this PID: %v", err) } for name, nspid := range map[string]string{ @@ -95,8 +97,28 @@ func TestCopilot8PIDNamespaceOfTheProcfs(t *testing.T) { "no NSpid line": "", "another PID at one level": "1", } { - if err := HostPIDNamespace(c8Proc(t, nspid)); err == nil || !strings.Contains(err.Error(), "not node-agent's PID namespace") && !strings.Contains(err.Error(), "NSpid") { + if err := samePIDNamespace(c8Proc(t, nspid)); err == nil || !strings.Contains(err.Error(), "not node-agent's PID namespace") && !strings.Contains(err.Error(), "NSpid") { t.Errorf("%s: %v, want refused", name, err) } } } + +// TestHostPIDNamespaceNeedsAProcfs (rev-a, Copilot #1176 round 8 LOW 1): a +// directory that is not a procfs is refused even when its files pass the +// NSpid proof (a crafted self link and self/status): HostPIDNamespace +// requires PROC_SUPER_MAGIC on procRoot first. +func TestHostPIDNamespaceNeedsAProcfs(t *testing.T) { + crafted := c8Proc(t, strconv.Itoa(os.Getpid())) + if err := samePIDNamespace(crafted); err != nil { + t.Fatalf("fixture: the crafted files pass the file proof: %v", err) + } + if err := HostPIDNamespace(crafted); err == nil || !strings.Contains(err.Error(), "is not a procfs") { + t.Fatalf("a crafted non-procfs directory: %v, want refused as not a procfs", err) + } + if err := HostPIDNamespace(filepath.Join(t.TempDir(), "missing")); err == nil || !strings.Contains(err.Error(), "statfs") { + t.Fatalf("a missing procRoot: %v, want the statfs error", err) + } + if err := HostPIDNamespace("/proc"); err != nil { + t.Fatalf("this process's procfs: %v", err) + } +} diff --git a/pkg/sandboxpolicy/integration/podcgroup_linux.go b/pkg/sandboxpolicy/integration/podcgroup_linux.go index 86ad324e53..b05c7d6446 100644 --- a/pkg/sandboxpolicy/integration/podcgroup_linux.go +++ b/pkg/sandboxpolicy/integration/podcgroup_linux.go @@ -41,7 +41,8 @@ func cgroupID(root, rel string) (uint64, error) { // readPauseCgroup runs read (the pause process's /proc//cgroup) under a // pidfd taken before it, and refuses the result when the process exited // meanwhile: its PID may then name another process. The pidfd is taken in -// node-agent's PID namespace, which is the host's (hostPID). +// node-agent's PID namespace, which HostPIDNamespace proves is the one of +// the procfs at procRoot. func readPauseCgroup(pid uint32, read func() ([]byte, error)) (data []byte, err error) { if pid == 0 { return nil, fmt.Errorf("no PID") @@ -66,7 +67,10 @@ func readPauseCgroup(pid uint32, read func() ([]byte, error)) (data []byte, err } // HostPIDNamespace checks that procRoot is a procfs of node-agent's own PID -// namespace: procRoot/self resolves to os.Getpid(), and the NSpid line of +// namespace. procRoot itself must be a procfs (statfs PROC_SUPER_MAGIC): a +// plain directory with a crafted self link and self/status would pass the +// file checks below (rev-a, Copilot #1176 round 8 LOW 1). Then +// procRoot/self resolves to os.Getpid(), and the NSpid line of // procRoot/self/status, which lists this process's PIDs from the procfs's // own PID namespace down to the process's, has exactly one level, that // PID. A procfs of an ancestor namespace lists more levels even when the @@ -75,14 +79,25 @@ func readPauseCgroup(pid uint32, read func() ([]byte, error)) (data []byte, err // #1176 4800270766). NSpid needs no access to another process (unlike // procRoot/1/ns/pid). A procfs that cannot prove it (no NSpid) is refused. // readPauseCgroup takes its pidfd in node-agent's PID namespace and reads -// through procRoot, so both must name the same processes (hostPID). S5 -// calls it before it wires the pod cgroup resolver, and again at every NRI +// through procRoot, so both must name the same processes. It proves "the +// procfs at procRoot is of node-agent's own namespace"; that this is the +// node's (containerd's, whose PIDs NRI reports) rests on procRoot being +// host.HostRoot/proc, a hostPath mount of the node's /proc. S5 calls it +// before it wires the pod cgroup resolver, and again at every NRI // registration. func HostPIDNamespace(procRoot string) error { + var fs unix.Statfs_t + if err := unix.Statfs(procRoot, &fs); err != nil { + return fmt.Errorf("statfs %s: %w", procRoot, err) + } + if fs.Type != unix.PROC_SUPER_MAGIC { + return fmt.Errorf("%s is not a procfs (filesystem type %#x): cannot prove it is node-agent's PID namespace", procRoot, fs.Type) + } return samePIDNamespace(procRoot) } -// samePIDNamespace is HostPIDNamespace. +// samePIDNamespace is HostPIDNamespace's proof from procRoot's files, once +// procRoot is known to be a procfs. func samePIDNamespace(procRoot string) error { pid := strconv.Itoa(os.Getpid()) self, err := os.Readlink(filepath.Join(procRoot, "self")) diff --git a/pkg/sandboxpolicy/integration/podcgroup_test.go b/pkg/sandboxpolicy/integration/podcgroup_test.go index e8667edf47..16bb17f573 100644 --- a/pkg/sandboxpolicy/integration/podcgroup_test.go +++ b/pkg/sandboxpolicy/integration/podcgroup_test.go @@ -329,7 +329,7 @@ func TestHostPIDNamespace(t *testing.T) { if err := os.Symlink("1", filepath.Join(other, "self")); err != nil { t.Fatal(err) } - if err := HostPIDNamespace(other); err == nil || !strings.Contains(err.Error(), "not node-agent's PID namespace") { + if err := samePIDNamespace(other); err == nil || !strings.Contains(err.Error(), "not node-agent's PID namespace") { t.Fatalf("another PID namespace: %v", err) } if err := HostPIDNamespace(t.TempDir()); err == nil { diff --git a/pkg/sandboxpolicy/sections_adoptedpending_test.go b/pkg/sandboxpolicy/sections_adoptedpending_test.go new file mode 100644 index 0000000000..f12a2fd88f --- /dev/null +++ b/pkg/sandboxpolicy/sections_adoptedpending_test.go @@ -0,0 +1,78 @@ +package sandboxpolicy + +import ( + "errors" + "strings" + "testing" + "time" +) + +// adoptedPendingFake is a section backend that reads back a previous run's +// pending marks (AdoptedPendingReader): strict lists the cgroups with a +// Strict one; err fails every read. +type adoptedPendingFake struct { + *fakeBackend + strict map[uint64]bool + err error + asked []uint64 + when []time.Time +} + +func (f *adoptedPendingFake) AdoptedPending(cgroupID uint64, deadline time.Time) (bool, error) { + f.asked, f.when = append(f.asked, cgroupID), append(f.when, deadline) + return f.strict[cgroupID], f.err +} + +// TestAdoptedPendingFansOutToEverySection (#1162 S2 follow-up): the +// SectionBackend asks every section whose backend reads its marks back, +// with the caller's cgroup and deadline, and skips one that cannot +// (a plain backend). A Strict mark in any section is true, whichever +// section answers after it; any section's error is the fan-out's error, +// naming the section, also when another section found a mark. +func TestAdoptedPendingFansOutToEverySection(t *testing.T) { + deadline := time.Now().Add(time.Minute) + privilege := &adoptedPendingFake{fakeBackend: &fakeBackend{plans: map[string]Plan{}}, strict: map[uint64]bool{1: true}} + network := &adoptedPendingFake{fakeBackend: &fakeBackend{plans: map[string]Plan{}}, strict: map[uint64]bool{2: true}} + s, err := NewSectionBackend(&fakeBackend{plans: map[string]Plan{}}, privilege, nil) + if err != nil { + t.Fatal(err) + } + s.WithNetwork(network, nil).WithFile(&fakeBackend{plans: map[string]Plan{}}, nil) + + for _, tc := range []struct { + cgroup uint64 + strict bool + }{ + {cgroup: 1, strict: true}, // the first section's mark, the next one has none + {cgroup: 2, strict: true}, // the last reader's mark + {cgroup: 3}, + } { + strict, err := s.AdoptedPending(tc.cgroup, deadline) + if strict != tc.strict || err != nil { + t.Errorf("cgroup %d: %v %v, want %v", tc.cgroup, strict, err, tc.strict) + } + } + for name, f := range map[string]*adoptedPendingFake{"privilege": privilege, "network": network} { + if len(f.asked) != 3 || f.asked[0] != 1 || f.asked[1] != 2 || f.asked[2] != 3 { + t.Errorf("%s asked %v, want every cgroup", name, f.asked) + } + for _, d := range f.when { + if !d.Equal(deadline) { + t.Errorf("%s got deadline %v, want %v", name, d, deadline) + } + } + } + + network.err = errors.New("pinned set unreadable") + strict, err := s.AdoptedPending(1, deadline) + if !strict || err == nil || !strings.Contains(err.Error(), SectionNetwork) || !strings.Contains(err.Error(), "pinned set unreadable") { + t.Fatalf("one section failing: %v %v, want its error (named) and the other's mark", strict, err) + } + if strict, err := s.AdoptedPending(3, deadline); strict || err == nil { + t.Fatalf("one section failing, no mark: %v %v, want an error", strict, err) + } + privilege.err = errors.New("busy") + if _, err := s.AdoptedPending(3, deadline); err == nil || !strings.Contains(err.Error(), SectionPrivilege) || !strings.Contains(err.Error(), SectionNetwork) { + t.Fatalf("both failing: %v, want both errors", err) + } +} From 66971b07eba4d89ccca5f70217c95708bacf9d8a Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Sat, 5 Dec 2026 16:30:45 +0100 Subject: [PATCH 2/2] revert(sandboxpolicy): drop the GOARCH=386 type changes node-agent ships only linux/amd64 and linux/arm64 (Makefile, release workflows), and the IG fork does not build for 386, so the 32-bit type changes add nothing. Restore the four files to their previous form. Co-Authored-By: Claude Opus 5.5 Docs-exempt: reverts type-only changes, no behavior change on shipped platforms Signed-off-by: Matthias Bertschy --- pkg/config/config.go | 2 +- pkg/hostfimsensor/v1/fimsensor_fanotify.go | 2 +- pkg/sandboxpolicy/igbackend/imageevidence.go | 4 ++-- pkg/sandboxpolicy/igbackend/imageindex.go | 11 ++--------- 4 files changed, 6 insertions(+), 13 deletions(-) diff --git a/pkg/config/config.go b/pkg/config/config.go index 515024e7d8..5c4f4d8af7 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -440,7 +440,7 @@ func LoadConfigOptional(path string, errNotFound bool) (Config, error) { viper.SetDefault("nodeProfileInterval", 10*time.Minute) viper.SetDefault("maxDelaySeconds", 30) viper.SetDefault("maxJitterPercentage", 5) - viper.SetDefault("maxImageSize", int64(5*1024*1024*1024)) + viper.SetDefault("maxImageSize", 5*1024*1024*1024) viper.SetDefault("maxSBOMSize", 20*1024*1024) viper.SetDefault("maxTsProfileSize", 2*1024*1024) viper.SetDefault("maxSniffingTimePerContainer", 24*time.Hour) diff --git a/pkg/hostfimsensor/v1/fimsensor_fanotify.go b/pkg/hostfimsensor/v1/fimsensor_fanotify.go index 1e24b55cba..566494a8f1 100644 --- a/pkg/hostfimsensor/v1/fimsensor_fanotify.go +++ b/pkg/hostfimsensor/v1/fimsensor_fanotify.go @@ -182,7 +182,7 @@ func (h *HostFimSensorFanotify) getFileMetadata(filePath string) (size int64, in uid = stat.Uid gid = stat.Gid mode = uint32(stat.Mode) - ctime = time.Unix(stat.Ctim.Unix()) + ctime = time.Unix(stat.Ctim.Sec, stat.Ctim.Nsec) } } diff --git a/pkg/sandboxpolicy/igbackend/imageevidence.go b/pkg/sandboxpolicy/igbackend/imageevidence.go index 6e2df7f553..6a6b95e6d8 100644 --- a/pkg/sandboxpolicy/igbackend/imageevidence.go +++ b/pkg/sandboxpolicy/igbackend/imageevidence.go @@ -365,7 +365,7 @@ func validateSandboxShmPins(source, destination *os.File, sourceMounts, destinat } func validateSandboxShmFacts(fs unix.Statfs_t, mode uint32, mountinfo []byte, id uint64) error { requiredFlags := int64(unix.ST_NOSUID | unix.ST_NODEV | unix.ST_NOEXEC) - if mode&unix.S_IFMT != unix.S_IFDIR || fs.Type != unix.TMPFS_MAGIC || int64(fs.Flags)&requiredFlags != requiredFlags { + if mode&unix.S_IFMT != unix.S_IFDIR || fs.Type != unix.TMPFS_MAGIC || fs.Flags&requiredFlags != requiredFlags { return fmt.Errorf("sandbox shm must be a nosuid/nodev/noexec tmpfs directory") } return validateRestrictedMountInfo(mountinfo, id, "tmpfs", true, []string{"nosuid", "nodev", "noexec"}) @@ -495,7 +495,7 @@ func validCgroupMount(m specs.Mount) bool { } func validateCgroupMountFacts(fs unix.Statfs_t, mode uint32, mountinfo []byte, id uint64) error { required := int64(unix.ST_RDONLY | unix.ST_NOSUID | unix.ST_NODEV | unix.ST_NOEXEC) - if mode&unix.S_IFMT != unix.S_IFDIR || fs.Type != unix.CGROUP2_SUPER_MAGIC || int64(fs.Flags)&required != required { + if mode&unix.S_IFMT != unix.S_IFDIR || fs.Type != unix.CGROUP2_SUPER_MAGIC || fs.Flags&required != required { return fmt.Errorf("cgroup mount must be a read-only nosuid/nodev/noexec cgroup2 directory") } return validateRestrictedMountInfo(mountinfo, id, "cgroup2", false, []string{"ro", "nosuid", "nodev", "noexec"}) diff --git a/pkg/sandboxpolicy/igbackend/imageindex.go b/pkg/sandboxpolicy/igbackend/imageindex.go index ea84300abb..a5a2e3d842 100644 --- a/pkg/sandboxpolicy/igbackend/imageindex.go +++ b/pkg/sandboxpolicy/igbackend/imageindex.go @@ -12,7 +12,6 @@ import ( "sort" "strings" "sync" - "unsafe" "golang.org/x/sys/unix" ) @@ -84,17 +83,11 @@ func indexFS(file *os.File) error { if err := unix.Fstatfs(int(file.Fd()), &fs); err != nil { return err } - // The magic as the kernel's unsigned word: a 32-bit Statfs_t (386) - // holds one above MaxInt32 (btrfs) as a negative int32. - magic := uint64(fs.Type) - if unsafe.Sizeof(fs.Type) == 4 { - magic = uint64(uint32(fs.Type)) - } - switch magic { + switch fs.Type { case unix.EXT4_SUPER_MAGIC, unix.XFS_SUPER_MAGIC, unix.BTRFS_SUPER_MAGIC, unix.TMPFS_MAGIC: return nil } - return fmt.Errorf("unsupported lower filesystem %#x (overlay/nested roots are not accepted)", magic) + return fmt.Errorf("unsupported lower filesystem %#x (overlay/nested roots are not accepted)", fs.Type) } // buildLowerIndex does NOT establish that these paths are image layers. The