From 1defff6db39cb14b59e5b2d5dce110e42f67ad48 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Tue, 24 Nov 2026 10:32:02 +0100 Subject: [PATCH 01/21] feat(sandboxpolicy): pending-slot bindings and EPERM for Strict tracking faults Add the enforcement-library groundwork for the NRI start gate: a binding can point at PendingSlot, a slot that is never published. The file, network and privilege programs already treat an unpublished slot as a structural fault, so a pending pod mark denies a Strict task (EPERM) and lets an Audit one run, counted in the node-wide section error counter. No BPF map or layout changes, and nothing writes a pending binding yet. - Binding.Strict and PendingSlot. classOf takes the class of a pending binding from the binding and of a real slot from the slot only, so an in-place Strict to Audit flip never keeps BINDING_STRICT. validate refuses Strict on a real slot. - Rebind swaps the identity of a cgroup's binding in one map write. - HealNode, Kept, rewriteClass, the adoption reconcile and slotGate handle pending entries. Per-slot counters of a pending slot return an error, never zero. - Strict tracking faults in the file and privilege programs return EPERM instead of ENOMEM. A refused credential preparation still surfaces as ENOMEM: the kernel's prepare_creds() and cred_alloc_blank() turn the hook's refusal into NULL. Tested with unit tests (including the class-flip test) and kernel tests for pending marks in all three sections, the move to a real slot, a replacement on a full bindings map, a subtree mark, and the fork, exec and credential errnos. The privilege, file and network kernel suites pass on AL2023 6.18.56 and Debian 13 6.12.117 in local VMs. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- docs/features/sandbox-policy.md | 8 + pkg/ebpf/gadgets/common/README.md | 4 +- pkg/ebpf/gadgets/common/arming.h | 2 +- .../gadgets/common/enforcement/bindings.go | 116 ++++- .../gadgets/common/enforcement/counters.go | 4 + .../gadgets/common/enforcement/creds_linux.go | 3 +- .../common/enforcement/pending_test.go | 442 ++++++++++++++++++ pkg/ebpf/gadgets/common/enforcement/slots.go | 18 +- pkg/ebpf/gadgets/enforce_file/README.md | 2 +- pkg/ebpf/gadgets/enforce_file/program.bpf.c | 11 +- .../runtime/pending_kernel_test.go | 335 +++++++++++++ .../gadgets/enforce_file/runtime/runtime.go | 2 +- .../runtime/runtime_kernel_test.go | 14 +- .../runtime/pending_kernel_test.go | 203 ++++++++ pkg/ebpf/gadgets/enforce_privilege/README.md | 11 +- .../gadgets/enforce_privilege/program.bpf.c | 17 +- .../runtime/exec_coexist_kernel_test.go | 42 +- .../runtime/pending_kernel_test.go | 156 +++++++ .../runtime/runtime_kernel_test.go | 23 +- pkg/sandboxpolicy/igbackend/file_native.go | 4 +- .../igbackend/privilege_native.go | 11 +- pkg/sandboxpolicy/igbackend/slotgate_test.go | 44 +- 22 files changed, 1400 insertions(+), 72 deletions(-) create mode 100644 pkg/ebpf/gadgets/common/enforcement/pending_test.go create mode 100644 pkg/ebpf/gadgets/enforce_file/runtime/pending_kernel_test.go create mode 100644 pkg/ebpf/gadgets/enforce_network/runtime/pending_kernel_test.go create mode 100644 pkg/ebpf/gadgets/enforce_privilege/runtime/pending_kernel_test.go diff --git a/docs/features/sandbox-policy.md b/docs/features/sandbox-policy.md index 32011382f5..c0894b53bb 100644 --- a/docs/features/sandbox-policy.md +++ b/docs/features/sandbox-policy.md @@ -144,6 +144,14 @@ reports `ProtectionUnconfirmed`, also when the cause is an unreadable counter. The privilege instance is not ready while its credential record (the overridden credentials it judges, see the gadget README) is at least 90% full: a Strict binding would soon be refused new credentials. +A Strict binding refuses an operation it cannot track (a fork whose child +mark fails, an exec whose mark cannot be prepared, or credentials the record +cannot hold) with `EPERM`, as every Strict deny; an Audit binding allows it +and counts it. A refused credential preparation is the one exception user +space sees: the kernel's `prepare_creds()` and `cred_alloc_blank()` turn the +hook's refusal into a NULL credential, so the syscall (including a fork) +fails with `ENOMEM`; an io_uring request under a personality still fails with +`EPERM`. A new Strict binding (privilege or file section) whose container holds io_uring rings opened before it is refused: the policy reports `NotReady` with reason `IoUringHeld`, and the refresh binds it once the rings are closed (an io_uring diff --git a/pkg/ebpf/gadgets/common/README.md b/pkg/ebpf/gadgets/common/README.md index 339fdf5558..b66ebdca24 100644 --- a/pkg/ebpf/gadgets/common/README.md +++ b/pkg/ebpf/gadgets/common/README.md @@ -17,7 +17,7 @@ and keeps its path rules in an array that `policy.h` does not describe. | File | Content | |---|---| -| `bindings.h` | `
bindings` map (version 1, gadget annotation `sandbox-bindings-version`, which the controller checks at instance start): cgroup id → the container's policy slot and flags. Exact scope by default; `BINDING_SUBTREE` covers descendant cgroups, `BINDING_STRICT` carries the slot's class (a fault denies), `BINDING_RUNTIME_HELPERS` admits the arming exemption | +| `bindings.h` | `
bindings` map (version 1, gadget annotation `sandbox-bindings-version`, which the controller checks at instance start): cgroup id → the container's policy slot and flags. Exact scope by default; `BINDING_SUBTREE` covers descendant cgroups, `BINDING_STRICT` carries the slot's class (a fault denies), `BINDING_RUNTIME_HELPERS` admits the arming exemption. `enforcement.PendingSlot` (0xFFFFFFFF) is a slot that is never published: the program finds no policy there, so for a judged task a Strict pending binding fails closed (a structural fault, EPERM) and an Audit one allows; both count only in the node-wide section error counter, with no per-slot counter (`SlotFaults`/`Counters(PendingSlot)` return an error); its class is the binding's own (`Binding.Strict`, refused on a real slot), and a class flip of a real slot never rewrites it | | `policy.h` | policy modes (0 off, 1 audit, 2 enforce), rank resolution (explicit deny > allow > default, one mode per rule), shared policy value | | `verdict.h` | first verdict fields (`generation`, `cgroup`, `deny`, `mode`), per-CPU `counters` (denied, submitted, dropped, allowed, section error, rate limited), 100 reports per CPU per second | | `root_barrier.h` | root barrier: always deny chroot, pivot_root, new user namespaces, new or joined mount namespaces and mount-tree changes for the tasks a gadget-defined predicate covers | @@ -27,7 +27,7 @@ and keeps its path rules in an array that `policy.h` does not describe. | `pin.h` | the section's state maps are pinned by name with its prefix (`SANDBOX_SECTION`, for example `sbx1_priv_`): a new load of the gadget re-opens them, so a restart keeps bindings, slot state, policy, task marks and fault counts. `enforcement.RemovePinnedMaps` starts from empty state | | `merge/` | the merge contract for several policies on one container, and its shared test vectors | | `rootbarrier/` | Go: attestation (each barrier program has a live LSM link, BPF LSM is active) and a self-test, for the Ready step of a gadget that includes `root_barrier.h` | -| `enforcement/` | Go: the binding controller of one long-lived node-wide instance: live `Bind`/`Unbind` of a container to a slot; `Publish` of a slot's policy into its inactive buffer and one flip write (a failed publish keeps the last-good policy); `Free` and a quarantine (default 2 s) before a buffer is deleted or a slot reused; `Heal`/`HealNode` arm the bound tasks again without a reload; readiness, `SlotFaults`, `ArmingWitness` (a counter below its base or unreadable is an error, never zero); `Counters`/`NodeCounters` read the raw pinned counters, and `RateWindow`/`FailRate` (failrate.go) apply the reporting rule: Degraded on any failure within 60 s, NotReady above 0.1 % over 5 min, unknown when a counter is unreadable or moved backwards. A section instance with a test-only switch set is refused unless `FaultInjection` admits it. A frozen mode (policy written and frozen before any binding) stays for sections not moved yet | +| `enforcement/` | Go: the binding controller of one long-lived node-wide instance: live `Bind`/`Unbind` of a container to a slot; `Rebind` hands a bound cgroup to another identity with one map write; `Publish` of a slot's policy into its inactive buffer and one flip write (a failed publish keeps the last-good policy); `Free` and a quarantine (default 2 s) before a buffer is deleted or a slot reused; `Heal`/`HealNode` arm the bound tasks again without a reload; readiness, `SlotFaults`, `ArmingWitness` (a counter below its base or unreadable is an error, never zero); `Counters`/`NodeCounters` read the raw pinned counters, and `RateWindow`/`FailRate` (failrate.go) apply the reporting rule: Degraded on any failure within 60 s, NotReady above 0.1 % over 5 min, unknown when a counter is unreadable or moved backwards. A section instance with a test-only switch set is refused unless `FaultInjection` admits it. A frozen mode (policy written and frozen before any binding) stays for sections not moved yet | Section-specific parts (the policy key layout, hooks, compiler) stay in each gadget. diff --git a/pkg/ebpf/gadgets/common/arming.h b/pkg/ebpf/gadgets/common/arming.h index ab73bb5126..ee2ef57a85 100644 --- a/pkg/ebpf/gadgets/common/arming.h +++ b/pkg/ebpf/gadgets/common/arming.h @@ -293,7 +293,7 @@ static __always_inline bool arming_exec_needs_prepare(void) // arming_prepare_exec runs in bprm_check_security, where the exec can still // fail: it creates the task's mark storage (unarmed) when the exec may need a // mark. It returns false when the storage could not be allocated; the -// caller then refuses the exec under a Strict binding (-ENOMEM), so a +// caller then refuses the exec under a Strict binding (-EPERM), so a // committed exec never needs an allocation. static __always_inline bool arming_prepare_exec(__u32 binding_flags) { diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index 1597f0b08a..a896427f3d 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -56,8 +56,20 @@ type Binding struct { // the tasks this binding covers (OCI hooks that runc init forks before the // workload starts). Set it only with Subtree on such a parent cgroup. RuntimeHelpers bool + // Strict is the class of a PendingSlot binding, which has no slot to + // take it from. It is refused on a real slot: there the class is the + // slot's (see classOf). + Strict bool } +// PendingSlot is a slot index that is never published: a binding to it marks +// a cgroup before its policy slot is ready. The kernel finds no policy there, +// so a Strict pending binding fails closed (EPERM) and an Audit one allows. +// Its faults and lost judgements count only in the node-wide section error +// counter: there is no per-slot counter (SlotFaults and Counters return an +// error for it). Its class is Binding.Strict. +const PendingSlot uint32 = 0xFFFFFFFF + // Flags of struct sandbox_binding in ../bindings.h. const ( bindingSubtree uint32 = 1 << 0 @@ -322,6 +334,58 @@ func (b *Bindings) Unbind(c ContainerIdentity) error { return b.recordError(b.unbind(c)) } +// Rebind hands the cgroup of an active binding over to another identity: the +// binding of old (a parent cgroup binding, for example) becomes next, a +// binding of the same cgroup under the next identity, with one map write. No +// moment leaves the cgroup without an entry, and none holds both identities. +// A failed bind that keeps the previous entry keeps old as its identity. +func (b *Bindings) Rebind(old ContainerIdentity, next Binding) error { + b.mu.Lock() + defer b.mu.Unlock() + if !b.ready || b.stopped { + return b.recordError(fmt.Errorf("binding controller is not running")) + } + return b.recordError(b.rebind(old, next)) +} + +func (b *Bindings) rebind(old ContainerIdentity, next Binding) error { + id := next.Container + if old.CgroupID != id.CgroupID || old.CgroupPath != id.CgroupPath { + // The same cgroup, by ID and path: arming walks the path, and the + // old binding was validated with it. + return fmt.Errorf("rebind needs the same cgroup (%d %s, not %d %s)", id.CgroupID, id.CgroupPath, old.CgroupID, old.CgroupPath) + } + previous, bound := b.active[id.CgroupID] + if !bound || previous.Container != old { + return fmt.Errorf("rebind: the cgroup has no active binding of the old identity") + } + if err := b.validate(next); err != nil { + return err + } + for cgroup, other := range b.active { + if cgroup != id.CgroupID && selector(other.Container) == selector(id) { + return fmt.Errorf("container identity already bound to a different cgroup") + } + } + // The identity swap: bind then sees a bound cgroup of the next identity + // and moves it with one write. + swapped := previous + swapped.Container = id + b.active[id.CgroupID] = swapped + err := b.bind(next) + c, ok := b.active[id.CgroupID] + switch { + case ok && c == swapped && err != nil: + // The undo put the previous entry back: it is old's again. + b.active[id.CgroupID] = previous + case ok && c == swapped: + // The kernel value did not change (bind returned early): record + // next itself, so its other fields (SkipArming) are current. + b.active[id.CgroupID] = next + } + return err +} + // Ready is the final startup boundary. func (b *Bindings) Ready(operators.GadgetContext) error { b.mu.Lock() @@ -350,9 +414,14 @@ func selector(c ContainerIdentity) execpolicy.Container { } func (b *Bindings) validate(c Binding) error { - if c.Slot >= b.config.Slots { + if c.Slot != PendingSlot && c.Slot >= b.config.Slots { return fmt.Errorf("policy slot %d out of range", c.Slot) } + if c.Slot != PendingSlot && c.Strict { + // A real slot's class is its publication's: a Strict field there + // would outlive a flip of the slot to Audit. + return fmt.Errorf("a Strict class on policy slot %d: only a pending binding carries its own class", c.Slot) + } if c.RuntimeHelpers && !c.Subtree { return fmt.Errorf("the runtime helper exemption needs a subtree binding") } @@ -360,7 +429,7 @@ func (b *Bindings) validate(c Binding) error { // The program would not see the binding from its descendants. return fmt.Errorf("subtree binding deeper than cgroup level %d", b.config.SubtreeLevels) } - if b.config.SubtreeLevels > 0 && b.strict(c.Slot) && + if b.config.SubtreeLevels > 0 && b.classOf(c) && cgroupLevel(c.Container.CgroupPath) > b.config.SubtreeLevels { // A task that moves into a child cgroup would not be seen as // outside the Strict binding's scope, so it would not be judged. @@ -380,7 +449,7 @@ func (b *Bindings) value(c Binding) bindingValue { if c.Subtree { v.Flags |= bindingSubtree } - if b.strict(c.Slot) { + if b.classOf(c) { v.Flags |= bindingStrict } if c.RuntimeHelpers { @@ -389,6 +458,23 @@ func (b *Bindings) value(c Binding) bindingValue { return v } +// classOf is the class of a binding: its own for a PendingSlot binding, else +// its slot's. Called with mu held. +func (b *Bindings) classOf(c Binding) bool { + if c.Slot == PendingSlot { + return c.Strict + } + return b.strict(c.Slot) +} + +// ClassOf reports whether a binding is Strict: Binding.Strict for a +// PendingSlot binding, else the class of its slot (Strict). +func (b *Bindings) ClassOf(c Binding) bool { + b.mu.Lock() + defer b.mu.Unlock() + return b.classOf(c) +} + func validate(c ContainerIdentity) error { if strings.TrimSpace(c.Runtime) == "" || strings.TrimSpace(c.ID) == "" || c.CgroupID == 0 || c.CgroupPath == "/" || !strings.HasPrefix(c.CgroupPath, "/") { return fmt.Errorf("binding requires runtime, full container ID and non-root cgroup v2 identity") @@ -400,7 +486,9 @@ func (b *Bindings) bind(c Binding) error { if err := b.validate(c); err != nil { return err } - if b.slotState != nil { + if b.slotState != nil && c.Slot != PendingSlot { + // A pending binding has its own class, and its slot is never + // published: the program finds no policy and decides by the class. if r := b.slots[c.Slot]; r == nil || !r.published { // The class is unknown and the program would see a slot // with no policy. @@ -415,7 +503,7 @@ func (b *Bindings) bind(c Binding) error { // A Strict binding that is unconfirmed binds again, so the walk can // confirm it (a refresh re-binds the same value). if bound && b.value(previous) == b.value(c) && !b.unarmed[id.CgroupID] && - !(b.ringUnconfirmed[id.CgroupID] && b.strict(c.Slot) && b.checkable(c)) { + !(b.ringUnconfirmed[id.CgroupID] && b.classOf(c) && b.checkable(c)) { return nil } if !bound { @@ -438,9 +526,9 @@ func (b *Bindings) bind(c Binding) error { // or an adopted Strict entry with bindingRingChecked when the record kept // its credentials (no purge at start). Any other binding that becomes // Strict here is checked by the walk (newStrict). - wasChecked := (bound && b.strict(previous.Slot) && b.ringChecked[id.CgroupID]) || + wasChecked := (bound && b.classOf(previous) && b.ringChecked[id.CgroupID]) || (wasAdopted && adopted.Flags&bindingStrict != 0 && adopted.Flags&bindingRingChecked != 0 && !b.credsPurged) - strict := b.strict(c.Slot) + strict := b.classOf(c) checked := wasChecked && strict if err := b.members.Put(id.CgroupID, b.kernelValue(c, checked)); err != nil { return fmt.Errorf("writing container binding: %w", err) @@ -460,7 +548,7 @@ func (b *Bindings) bind(c Binding) error { // armed (arm armed the tasks before the ring check) and // unconfirmed, as a heal keeps it (healArm). Not a failure: // the caller commits and reports ProtectionUnconfirmed. - b.markUnchecked(id.CgroupID, previous, b.strict(previous.Slot), false) + b.markUnchecked(id.CgroupID, previous, b.classOf(previous), false) delete(b.unarmed, id.CgroupID) delete(b.ioUringAudit, id.CgroupID) // a Strict entry return nil @@ -471,7 +559,7 @@ func (b *Bindings) bind(c Binding) error { b.keepFailed(c, checked) return errors.Join(err, perr) } - b.markUnchecked(id.CgroupID, previous, b.strict(previous.Slot), b.ringChecked[id.CgroupID]) + b.markUnchecked(id.CgroupID, previous, b.classOf(previous), b.ringChecked[id.CgroupID]) return err } if wasAdopted && !errors.Is(err, ErrContainerGone) { @@ -546,7 +634,7 @@ func (b *Bindings) keepFailed(c Binding, checked bool) { b.active[id] = c b.unarmed[id] = true b.setRingChecked(id, checked) - b.markUnchecked(id, c, b.strict(c.Slot), checked) + b.markUnchecked(id, c, b.classOf(c), checked) } // checkable reports whether a bind of c walks its tasks for io_uring rings: @@ -711,7 +799,7 @@ func (b *Bindings) arm(c Binding, newStrict bool) error { switch { case ring && newStrict: return fmt.Errorf("%w (container %s, cgroup %d)", ErrIoUringHeld, c.Container.ID, c.Container.CgroupID) - case ring && !b.strict(c.Slot): + case ring && !b.classOf(c): b.ioUringAudit[c.Container.CgroupID] = true default: delete(b.ioUringAudit, c.Container.CgroupID) @@ -727,7 +815,7 @@ func (b *Bindings) Kept(cgroup uint64) (kept, strict bool) { b.mu.Lock() defer b.mu.Unlock() if c, ok := b.active[cgroup]; ok { - return true, b.strict(c.Slot) + return true, b.classOf(c) } if v, ok := b.adopted[cgroup]; ok { return true, v.Flags&bindingStrict != 0 @@ -930,6 +1018,10 @@ func (b *Bindings) SlotFaults(slot uint32) (uint64, error) { if b.faults == nil { return 0, fmt.Errorf("no fault map configured") } + if slot == PendingSlot { + // Not a slot: the kernel counts nothing there. Unknown, never zero. + return 0, fmt.Errorf("the pending slot has no fault counter") + } var count uint64 if err := b.faults.Lookup(slot, &count); err != nil { return 0, fmt.Errorf("reading tracking faults: %w", err) diff --git a/pkg/ebpf/gadgets/common/enforcement/counters.go b/pkg/ebpf/gadgets/common/enforcement/counters.go index e285bbfa2c..a0a1c99c0e 100644 --- a/pkg/ebpf/gadgets/common/enforcement/counters.go +++ b/pkg/ebpf/gadgets/common/enforcement/counters.go @@ -37,6 +37,10 @@ func (b *Bindings) Counters(slot uint32) (SlotCounters, error) { if b.faults == nil || b.attempts == nil || b.unevaluated == nil { return SlotCounters{}, fmt.Errorf("%s: reporting counters are not configured", b.config.Name) } + if slot == PendingSlot { + // Not a slot: the kernel counts nothing there. Unknown, never zero. + return SlotCounters{}, fmt.Errorf("%s: the pending slot has no counters", b.config.Name) + } var c SlotCounters if err := b.faults.Lookup(slot, &c.Faults); err != nil { return SlotCounters{}, fmt.Errorf("reading slot %d faults: %w", slot, err) diff --git a/pkg/ebpf/gadgets/common/enforcement/creds_linux.go b/pkg/ebpf/gadgets/common/enforcement/creds_linux.go index 204dc06805..890a2b520f 100644 --- a/pkg/ebpf/gadgets/common/enforcement/creds_linux.go +++ b/pkg/ebpf/gadgets/common/enforcement/creds_linux.go @@ -517,7 +517,8 @@ func (b *Bindings) CredRecordFill() (used, size uint64, err error) { } // CredRecordHealth fails when the credential record is at least 90% full: -// then a Strict binding may soon be refused new credentials (ENOMEM). It also +// then a Strict binding may soon be refused new credentials (user space sees +// ENOMEM from prepare_creds; an io_uring personality request EPERM). It also // fails while the active binding count cannot be written (the share check // reads a stale count); it retries the write first. func (b *Bindings) CredRecordHealth() error { diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go new file mode 100644 index 0000000000..d72609bf3f --- /dev/null +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -0,0 +1,442 @@ +// Copyright 2026 The Kubescape Authors +// SPDX-License-Identifier: Apache-2.0 + +package enforcement + +import ( + "errors" + "strings" + "testing" + + "github.com/cilium/ebpf" +) + +// parentIdentity is a parent cgroup marked before its containers start; +// containerInParent is a container that runs in that same cgroup (it shares +// the cgroup ID). +var ( + parentIdentity = ContainerIdentity{Runtime: "parent", ID: "uid-1", CgroupID: 42, CgroupPath: "/workloads.slice/parent-uid-1"} + containerInParent = ContainerIdentity{Runtime: "containerd", ID: "c1", CgroupID: 42, CgroupPath: "/workloads.slice/parent-uid-1"} +) + +// pendingMark is the parent cgroup mark of a start gate: PendingSlot, Subtree and +// RuntimeHelpers, with its own class. +func pendingMark(strict bool) Binding { + return Binding{Container: parentIdentity, Slot: PendingSlot, Strict: strict, Subtree: true, RuntimeHelpers: true} +} + +// puts counts the binding map writes in the fixture's log. +func puts(log []string) int { + n := 0 + for _, l := range log { + if l == "put bindings" { + n++ + } + } + return n +} + +// validate takes the class of a real slot from the slot only, and exempts +// PendingSlot from the range check. +func TestValidatePendingSlot(t *testing.T) { + f := newPublishFixture(t) + tests := []struct { + name string + binding Binding + wantErr string + }{ + {name: "Strict pending", binding: pendingMark(true)}, + {name: "Audit pending", binding: pendingMark(false)}, + {name: "exact Audit pending", binding: Binding{Container: parentIdentity, Slot: PendingSlot}}, + {name: "real slot", binding: Binding{Container: parentIdentity, Slot: 1}}, + {name: "Strict on a real slot", binding: Binding{Container: parentIdentity, Slot: 1, Strict: true}, wantErr: "only a pending binding carries its own class"}, + {name: "Strict on slot 0", binding: Binding{Container: parentIdentity, Slot: 0, Strict: true}, wantErr: "only a pending binding carries its own class"}, + {name: "out of range", binding: Binding{Container: parentIdentity, Slot: 4}, wantErr: "out of range"}, + {name: "one below PendingSlot", binding: Binding{Container: parentIdentity, Slot: PendingSlot - 1}, wantErr: "out of range"}, + {name: "pending runtime helpers without subtree", binding: Binding{Container: parentIdentity, Slot: PendingSlot, RuntimeHelpers: true}, wantErr: "subtree"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f.b.mu.Lock() + err := f.b.validate(tt.binding) + f.b.mu.Unlock() + switch { + case tt.wantErr == "" && err != nil: + t.Fatalf("validate: %v", err) + case tt.wantErr != "" && (err == nil || !strings.Contains(err.Error(), tt.wantErr)): + t.Fatalf("validate: %v, want %q", err, tt.wantErr) + } + }) + } +} + +// A pending binding needs no published slot (there is none); a real slot +// still does. +func TestBindPendingSlotNeedsNoPublication(t *testing.T) { + f := newPublishFixture(t) + if err := f.b.Bind(Binding{Container: parentIdentity, Slot: 2}); err == nil || !strings.Contains(err.Error(), "not published") { + t.Fatalf("a bind to an unpublished real slot: %v", err) + } + if err := f.b.Bind(pendingMark(true)); err != nil { + t.Fatalf("a pending bind: %v", err) + } + if v := f.members.data[parentIdentity.CgroupID].(bindingValue); v.Slot != PendingSlot { + t.Fatalf("pending entry: %+v", v) + } +} + +// The kernel value of a pending binding carries its own class, whatever the +// configured class of the (missing) slot is: the fixture's StrictSlot says +// Audit for every slot. +func TestPendingSlotFlags(t *testing.T) { + tests := []struct { + name string + binding Binding + checked bool + want bindingValue + }{ + {name: "Strict mark", binding: pendingMark(true), want: bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers}}, + {name: "Strict mark, checked", binding: pendingMark(true), checked: true, want: bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers | bindingRingChecked}}, + {name: "Audit mark", binding: pendingMark(false), want: bindingValue{Slot: PendingSlot, Flags: bindingSubtree | bindingRuntimeHelpers}}, + {name: "Audit mark, checked", binding: pendingMark(false), checked: true, want: bindingValue{Slot: PendingSlot, Flags: bindingSubtree | bindingRuntimeHelpers}}, + {name: "exact Strict", binding: Binding{Container: parentIdentity, Slot: PendingSlot, Strict: true}, want: bindingValue{Slot: PendingSlot, Flags: bindingStrict}}, + {name: "exact Audit", binding: Binding{Container: parentIdentity, Slot: PendingSlot}, want: bindingValue{Slot: PendingSlot}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := newPublishFixture(t) + f.b.mu.Lock() + value, kernel := f.b.value(tt.binding), f.b.kernelValue(tt.binding, tt.checked) + f.b.mu.Unlock() + if kernel != tt.want { + t.Fatalf("kernelValue %+v, want %+v", kernel, tt.want) + } + if want := (bindingValue{Slot: tt.want.Slot, Flags: tt.want.Flags &^ bindingRingChecked}); value != want { + t.Fatalf("value %+v, want %+v", value, want) + } + if got := f.b.ClassOf(tt.binding); got != tt.binding.Strict { + t.Fatalf("ClassOf %v, want %v", got, tt.binding.Strict) + } + // Bind writes the same value (no walk in this fixture). + if err := f.b.Bind(tt.binding); err != nil { + t.Fatal(err) + } + if got := f.members.data[parentIdentity.CgroupID].(bindingValue); got != value { + t.Fatalf("bound entry %+v, want %+v", got, value) + } + }) + } +} + +// THE FLIP TEST: a parent cgroup bound from a Strict pending mark to a real Strict slot +// takes the slot's class there; a later in-place Strict->Audit flip of that +// slot leaves no BINDING_STRICT on it. +func TestPendingToSlotThenAuditFlipDropsStrict(t *testing.T) { + f := newPublishFixture(t) + if err := f.b.Publish(f.publication(2, 10, true)); err != nil { + t.Fatal(err) + } + if err := f.b.Bind(pendingMark(true)); err != nil { + t.Fatal(err) + } + if v := f.members.data[parentIdentity.CgroupID].(bindingValue); v != (bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers}) { + t.Fatalf("Strict pending mark: %+v", v) + } + // The class of a real slot is the slot's: a bound binding never carries + // Strict itself. + if err := f.b.Bind(Binding{Container: parentIdentity, Slot: 2, Strict: true, Subtree: true, RuntimeHelpers: true}); err == nil { + t.Fatal("a Strict class on a real slot must be refused") + } + before := puts(*f.members.log) + bound := Binding{Container: parentIdentity, Slot: 2, Subtree: true, RuntimeHelpers: true} + if err := f.b.Bind(bound); err != nil { + t.Fatal(err) + } + if n := puts(*f.members.log) - before; n != 1 { + t.Fatalf("pending -> bound must be one map write, got %d", n) + } + if v := f.members.data[parentIdentity.CgroupID].(bindingValue); v != (bindingValue{Slot: 2, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers}) { + t.Fatalf("bound to a Strict slot: %+v", v) + } + // Strict -> Audit in place (slots.go publishSlot -> rewriteClass). + f.clock = f.clock.Add(DefaultQuarantine) + if err := f.b.Publish(f.publication(2, 11, false)); err != nil { + t.Fatal(err) + } + if v := f.members.data[parentIdentity.CgroupID].(bindingValue); v.Flags&bindingStrict != 0 || v != (bindingValue{Slot: 2, Flags: bindingSubtree | bindingRuntimeHelpers}) { + t.Fatalf("after the Audit flip the binding must not be Strict: %+v", v) + } + if f.b.ClassOf(bound) { + t.Fatal("ClassOf must follow the slot after the flip") + } + if kept, strict := f.b.Kept(parentIdentity.CgroupID); !kept || strict { + t.Fatalf("Kept after the flip: %v %v", kept, strict) + } + // A refresh re-bind writes nothing new and stays Audit. + if err := f.b.Bind(bound); err != nil { + t.Fatal(err) + } + if v := f.members.data[parentIdentity.CgroupID].(bindingValue); v.Flags&bindingStrict != 0 { + t.Fatalf("re-bind after the flip: %+v", v) + } +} + +// rewriteClass (a class flip of a slot) and the adoption reconcile never +// touch a PendingSlot entry: its class is its own. +func TestRewriteClassSkipsPendingSlot(t *testing.T) { + adoptedStrict := bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRingChecked} + adoptedAudit := bindingValue{Slot: PendingSlot, Flags: bindingSubtree} + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.state.data[uint32(1)] = slotState(0, 4) + f.strictAt[Storage(1, 0)] = true + f.members.data[uint64(98)] = adoptedAudit + f.members.data[uint64(99)] = adoptedStrict + }) + // The adoption reconcile left both as they were. This holds without + // adopt's PendingSlot guard too (no slot record exists for PendingSlot), + // so it does not prove the guard; it pins the outcome. + if f.members.data[uint64(98)] != adoptedAudit || f.members.data[uint64(99)] != adoptedStrict || + f.b.adopted[98] != adoptedAudit || f.b.adopted[99] != adoptedStrict { + t.Fatalf("adoption must keep pending entries: kernel %v adopted %v", f.members.data, f.b.adopted) + } + if err := f.b.Bind(pendingMark(true)); err != nil { + t.Fatal(err) + } + other := ContainerIdentity{Runtime: "docker", ID: "d1", CgroupID: 43, CgroupPath: "/system.slice/docker-d1.scope"} + if err := f.b.Bind(Binding{Container: other, Slot: 1}); err != nil { + t.Fatal(err) + } + pending := f.members.data[parentIdentity.CgroupID] + for _, step := range []struct { + generation uint64 + strict bool + }{{5, false}, {6, true}, {7, false}} { + f.clock = f.clock.Add(DefaultQuarantine) + if err := f.b.Publish(f.publication(1, step.generation, step.strict)); err != nil { + t.Fatal(err) + } + if v := f.members.data[other.CgroupID].(bindingValue); (v.Flags&bindingStrict != 0) != step.strict { + t.Fatalf("generation %d: the slot's binding follows the class: %+v", step.generation, v) + } + if f.members.data[parentIdentity.CgroupID] != pending || f.members.data[uint64(98)] != adoptedAudit || f.members.data[uint64(99)] != adoptedStrict { + t.Fatalf("generation %d: a flip touched a pending entry: %v", step.generation, f.members.data) + } + } + // Called with PendingSlot itself, it writes nothing. + before := puts(*f.members.log) + f.b.mu.Lock() + err := f.b.rewriteClass(PendingSlot, false) + f.b.mu.Unlock() + if err != nil || puts(*f.members.log) != before { + t.Fatalf("rewriteClass(PendingSlot): %v, %d writes", err, puts(*f.members.log)-before) + } +} + +// HealNode refuses while a Strict adopted entry has no bind: for a PendingSlot +// entry the class is its own flag, not the configured class of the slot (the +// fixture's StrictSlot says Audit for every slot). +func TestHealNodeAdoptedPendingSlot(t *testing.T) { + tests := []struct { + name string + adopted bindingValue + wantErr bool + }{ + {name: "Strict pending", adopted: bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree}, wantErr: true}, + {name: "Audit pending", adopted: bindingValue{Slot: PendingSlot, Flags: bindingSubtree}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.members.data[parentIdentity.CgroupID] = tt.adopted + }) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.witness = fakeWitness{0: 2} + err := f.b.HealNode() + if tt.wantErr { + if err == nil || errors.Is(err, ErrNotHealable) || f.b.nodeFaultBase != 0 { + t.Fatalf("a Strict pending adopted entry must keep the node faults: %v (base %d)", err, f.b.nodeFaultBase) + } + return + } + if err != nil || f.b.nodeFaultBase != 2 { + t.Fatalf("an Audit pending adopted entry does not block the heal: %v (base %d)", err, f.b.nodeFaultBase) + } + }) + } +} + +// A Strict pending binding that does not arm keeps the node faults counted: +// HealNode takes its class from the binding. +func TestHealNodeActivePendingSlotNotArmable(t *testing.T) { + f := newPublishFixture(t) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.witness = fakeWitness{0: 2} + mark := pendingMark(true) + mark.SkipArming = true + if err := f.b.Bind(mark); err != nil { + t.Fatal(err) + } + if err := f.b.HealNode(); !errors.Is(err, ErrNotHealable) { + t.Fatalf("a Strict pending binding that does not arm: %v", err) + } +} + +// Kept reports the class of the entry the kernel holds for the cgroup. +func TestKeptPendingSlot(t *testing.T) { + tests := []struct { + name string + bind *Binding + adopted *bindingValue + wantStrict bool + }{ + {name: "active Strict pending", bind: &Binding{Container: parentIdentity, Slot: PendingSlot, Strict: true, Subtree: true}, wantStrict: true}, + {name: "active Audit pending", bind: &Binding{Container: parentIdentity, Slot: PendingSlot, Subtree: true}}, + {name: "adopted Strict pending", adopted: &bindingValue{Slot: PendingSlot, Flags: bindingStrict}, wantStrict: true}, + {name: "adopted Audit pending", adopted: &bindingValue{Slot: PendingSlot}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + f := newPublishFixtureWith(t, func(f *publishFixture) { + if tt.adopted != nil { + f.members.data[parentIdentity.CgroupID] = *tt.adopted + } + }) + if tt.bind != nil { + if err := f.b.Bind(*tt.bind); err != nil { + t.Fatal(err) + } + } + if kept, strict := f.b.Kept(parentIdentity.CgroupID); !kept || strict != tt.wantStrict { + t.Fatalf("Kept: %v %v, want true %v", kept, strict, tt.wantStrict) + } + }) + } +} + +// Rebind hands a parent cgroup over to the container that runs in it: one +// identity swap and one map write; the old identity no longer owns it. +func TestRebind(t *testing.T) { + setup := func(t *testing.T) *publishFixture { + f := newPublishFixture(t) + if err := f.b.Publish(f.publication(1, 10, true)); err != nil { + t.Fatal(err) + } + if err := f.b.Bind(pendingMark(true)); err != nil { + t.Fatal(err) + } + return f + } + t.Run("hand-over", func(t *testing.T) { + f := setup(t) + before := puts(*f.members.log) + if err := f.b.Rebind(parentIdentity, Binding{Container: containerInParent, Slot: 1}); err != nil { + t.Fatal(err) + } + if n := puts(*f.members.log) - before; n != 1 { + t.Fatalf("a rebind is one map write, got %d", n) + } + if v := f.members.data[parentIdentity.CgroupID].(bindingValue); v != (bindingValue{Slot: 1, Flags: bindingStrict}) { + t.Fatalf("rebound entry %+v", v) + } + if c := f.b.active[parentIdentity.CgroupID]; c.Container != containerInParent { + t.Fatalf("active identity %+v", c.Container) + } + // The old identity no longer owns the cgroup: its removal is stale. + if err := f.b.Unbind(parentIdentity); err != nil { + t.Fatal(err) + } + if _, ok := f.members.data[parentIdentity.CgroupID]; !ok { + t.Fatal("an unbind of the old identity must not remove the new binding") + } + if err := f.b.Unbind(containerInParent); err != nil { + t.Fatal(err) + } + if _, ok := f.members.data[parentIdentity.CgroupID]; ok { + t.Fatal("an unbind of the new identity removes it") + } + }) + // An identity-only hand-over (the same kernel value): no write, and the + // active binding is next itself, with its own SkipArming. + t.Run("pending to pending, same value", func(t *testing.T) { + f := setup(t) + next := pendingMark(true) + next.Container, next.SkipArming = containerInParent, true + before := puts(*f.members.log) + if err := f.b.Rebind(parentIdentity, next); err != nil { + t.Fatal(err) + } + if n := puts(*f.members.log) - before; n != 0 { + t.Fatalf("an unchanged kernel value needs no write, got %d", n) + } + if c := f.b.active[parentIdentity.CgroupID]; c != next { + t.Fatalf("active binding %+v, want %+v", c, next) + } + }) + refusals := []struct { + name string + old ContainerIdentity + next Binding + prep func(*publishFixture) + want string + }{ + {name: "old identity not bound", old: ContainerIdentity{Runtime: "parent", ID: "uid-2", CgroupID: 42, CgroupPath: parentIdentity.CgroupPath}, + next: Binding{Container: containerInParent, Slot: 1}, want: "no active binding of the old identity"}, + {name: "another cgroup", old: parentIdentity, + next: Binding{Container: ContainerIdentity{Runtime: "containerd", ID: "c1", CgroupID: 43, CgroupPath: "/workloads.slice/other"}, Slot: 1}, want: "same cgroup"}, + {name: "same cgroup ID, another path", old: parentIdentity, + next: Binding{Container: ContainerIdentity{Runtime: "containerd", ID: "c1", CgroupID: 42, CgroupPath: "/workloads.slice/moved"}, Slot: 1}, want: "same cgroup"}, + {name: "Strict on a real slot", old: parentIdentity, next: Binding{Container: containerInParent, Slot: 1, Strict: true}, want: "only a pending binding"}, + {name: "unpublished slot", old: parentIdentity, next: Binding{Container: containerInParent, Slot: 3}, want: "not published"}, + {name: "new identity bound elsewhere", old: parentIdentity, next: Binding{Container: containerInParent, Slot: 1}, + prep: func(f *publishFixture) { + elsewhere := containerInParent + elsewhere.CgroupID, elsewhere.CgroupPath = 44, "/workloads.slice/elsewhere" + if err := f.b.Bind(Binding{Container: elsewhere, Slot: 1}); err != nil { + t.Fatal(err) + } + }, want: "already bound to a different cgroup"}, + {name: "failed arming undoes the move", old: parentIdentity, next: Binding{Container: containerInParent, Slot: 1}, + prep: func(f *publishFixture) { + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.armExisting = func(Map, string) error { return errors.New("arming failed") } + }, want: "arming failed"}, + } + for _, tt := range refusals { + t.Run(tt.name, func(t *testing.T) { + f := setup(t) + if tt.prep != nil { + tt.prep(f) + } + mark := f.members.data[parentIdentity.CgroupID] + err := f.b.Rebind(tt.old, tt.next) + if err == nil || !strings.Contains(err.Error(), tt.want) { + t.Fatalf("Rebind: %v, want %q", err, tt.want) + } + // The parent cgroup keeps its mark and its identity. + if got := f.members.data[parentIdentity.CgroupID]; got != mark { + t.Fatalf("the pending mark must stay: %+v, want %+v", got, mark) + } + if c := f.b.active[parentIdentity.CgroupID]; c != pendingMark(true) { + t.Fatalf("the old identity must keep the binding: %+v", c) + } + if err := f.b.Unbind(parentIdentity); err != nil { + t.Fatal(err) + } + if _, ok := f.members.data[parentIdentity.CgroupID]; ok { + t.Fatal("the old identity still removes its mark") + } + }) + } +} + +// The per-slot counters never read PendingSlot: unknown, never zero. +func TestPendingSlotHasNoCounters(t *testing.T) { + f := newPublishFixture(t) + if _, err := f.b.SlotFaults(PendingSlot); err == nil { + t.Fatal("SlotFaults(PendingSlot) must be an error, not zero faults") + } + f.b.attempts, f.b.unevaluated = fakeFaults{}, fakeFaults{} + if _, err := f.b.Counters(PendingSlot); err == nil { + t.Fatal("Counters(PendingSlot) must be an error, not zero counts") + } +} diff --git a/pkg/ebpf/gadgets/common/enforcement/slots.go b/pkg/ebpf/gadgets/common/enforcement/slots.go index 9c6cdc1f0c..b4d1f732ea 100644 --- a/pkg/ebpf/gadgets/common/enforcement/slots.go +++ b/pkg/ebpf/gadgets/common/enforcement/slots.go @@ -210,7 +210,11 @@ func (b *Bindings) discard(p Publication, storage uint32) error { // rewriteClass writes the bindings of slot with the class strict, the // adopted ones too (a bind has not taken them over yet, but they enforce the // slot's policy). Called with mu held, around a flip that changes the class. +// A PendingSlot binding is never rewritten: its class is its own. func (b *Bindings) rewriteClass(slot uint32, strict bool) error { + if slot == PendingSlot { + return nil + } r := b.slots[slot] saved := r.strict r.strict = strict @@ -416,7 +420,12 @@ func (b *Bindings) HealNode() error { return fmt.Errorf("%w: no arming map", ErrNotHealable) } for _, v := range b.adopted { - if b.strict(v.Slot) { + // An adopted PendingSlot entry has no slot to take the class from: + // its own flag is its class. + if v.Slot == PendingSlot && v.Flags&bindingStrict != 0 { + return fmt.Errorf("Strict pending adopted bindings that no bind took over") + } + if v.Slot != PendingSlot && b.strict(v.Slot) { return fmt.Errorf("slot %d has Strict adopted bindings that no bind took over", v.Slot) } } @@ -424,7 +433,7 @@ func (b *Bindings) HealNode() error { for _, c := range b.active { if !armable(c) { // Node faults concern Strict slots only. - skipped = skipped || b.strict(c.Slot) + skipped = skipped || b.classOf(c) continue } if err := b.healArm(c); err != nil && !errors.Is(err, ErrContainerGone) { @@ -445,7 +454,7 @@ func (b *Bindings) HealNode() error { // slot health reports it; the heal goes on). Called with mu held. func (b *Bindings) healArm(c Binding) error { id := c.Container.CgroupID - check := b.ringUnconfirmed[id] && b.strict(c.Slot) && b.checkable(c) + check := b.ringUnconfirmed[id] && b.classOf(c) && b.checkable(c) err := b.arm(c, check) switch { case check && err == nil: @@ -532,6 +541,9 @@ func (b *Bindings) adopt() error { } var errs []error for cgroup, v := range adopted { + if v.Slot == PendingSlot { + continue // its class is its own flag; no slot to reconcile with + } r := b.slots[v.Slot] if r == nil || !r.published || (v.Flags&bindingStrict != 0) == r.strict { continue diff --git a/pkg/ebpf/gadgets/enforce_file/README.md b/pkg/ebpf/gadgets/enforce_file/README.md index 94943f1bfe..b79cc74683 100644 --- a/pkg/ebpf/gadgets/enforce_file/README.md +++ b/pkg/ebpf/gadgets/enforce_file/README.md @@ -248,7 +248,7 @@ reported and allowed. `bprm_check_security` (`ig_file_exec_check`), where the exec can still fail; `bprm_committed_creds` (`ig_file_exec`) only sets it. In a Strict binding a fork whose child mark fails, and an exec whose mark storage cannot - be allocated, are refused (`-ENOMEM`); both count a slot fault and send a + be allocated, are refused (`-EPERM`); both count a slot fault and send a `fault` verdict with `access` `tracking`. Audit never blocks: outside a Strict binding the fork and the exec are allowed (an Audit binding counts an unevaluated judgement), and a `CLONE_INTO_CGROUP` fork counts a node fault diff --git a/pkg/ebpf/gadgets/enforce_file/program.bpf.c b/pkg/ebpf/gadgets/enforce_file/program.bpf.c index ff87df1301..70a310dfdb 100644 --- a/pkg/ebpf/gadgets/enforce_file/program.bpf.c +++ b/pkg/ebpf/gadgets/enforce_file/program.bpf.c @@ -90,7 +90,6 @@ GADGET_PARAM(cred_record_fail); GADGET_PARAM(cred_forget_fail); #define EPERM 1 -#define ENOMEM 12 #define EINVAL 22 #define FILE_FMODE_READ 0x1 #define FILE_FMODE_WRITE 0x2 @@ -1164,7 +1163,7 @@ static __always_inline __u64 file_slot_generation(__u32 slot) // file_record_cred records credentials a task of a binding prepares or // applies (common/creds.h). Over the binding's quota or with a full record, a -// Strict binding refuses (-ENOMEM) and counts a slot fault; Audit counts it +// Strict binding refuses (-EPERM) and counts a slot fault; Audit counts it // as unevaluated. static __always_inline int file_record_cred(const struct cred *cred) { @@ -1180,7 +1179,7 @@ static __always_inline int file_record_cred(const struct cred *cred) arming_slot_fault(slot); file_fault_report(cgid, slot, file_slot_generation(slot), true, FILE_FAULT_TRACKING); - return -ENOMEM; + return -EPERM; } arming_slot_unevaluated(slot); return 0; @@ -1228,7 +1227,7 @@ int BPF_PROG(ig_file_cred_free, struct cred *cred) CRED_WALK_PROGRAM(ig_file_cred_walk) // The mark of an exec is prepared where the exec can still fail: a Strict -// binding refuses an exec whose mark storage cannot be allocated (-ENOMEM, a +// binding refuses an exec whose mark storage cannot be allocated (-EPERM, a // slot fault), so a committed exec in a Strict binding is never left unarmed. // An Audit binding lets the exec run; it is counted as unevaluated. SEC("lsm/bprm_check_security") @@ -1254,7 +1253,7 @@ int BPF_PROG(ig_file_exec_check, struct linux_binprm *bprm, int ret) arming_slot_fault(slot); file_fault_report(cgid, slot, file_slot_generation(slot), true, FILE_FAULT_TRACKING); - return -ENOMEM; + return -EPERM; } if (bound) arming_slot_unevaluated(slot); @@ -1408,7 +1407,7 @@ int BPF_PROG(ig_file_alloc, struct task_struct *task, arming_slot_fault(slot); file_fault_report(cgid, slot, file_slot_generation(slot), true, FILE_FAULT_TRACKING); - return -ENOMEM; + return -EPERM; } if (binding_lookup(&cgid, &slot, &flags)) arming_slot_unevaluated(slot); diff --git a/pkg/ebpf/gadgets/enforce_file/runtime/pending_kernel_test.go b/pkg/ebpf/gadgets/enforce_file/runtime/pending_kernel_test.go new file mode 100644 index 0000000000..a2d0fc75cc --- /dev/null +++ b/pkg/ebpf/gadgets/enforce_file/runtime/pending_kernel_test.go @@ -0,0 +1,335 @@ +//go:build linux && file_kernel + +// Copyright 2026 The Kubescape Authors +// SPDX-License-Identifier: Apache-2.0 + +package runtime + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/cilium/ebpf" + "golang.org/x/sys/unix" + + "github.com/kubescape/node-agent/pkg/ebpf/gadgets/common/enforcement" + filepolicy "github.com/kubescape/node-agent/pkg/ebpf/gadgets/enforce_file/policy" +) + +// Same fixture and environment as runtime_kernel_test.go. +// TestForkMarkFaultErrno needs FILE_HELPER_BINARY with a `fork -` command +// (one fork, the child exits; on failure "fork -: ", exit 1). + +// pinnedBinding reads the kernel entry of a cgroup in the section's pinned +// binding map: its slot and flags (struct sandbox_binding, ../../common/bindings.h). +func pinnedBinding(t *testing.T, cgroup uint64) (slot, flags uint32) { + t.Helper() + m, err := ebpf.LoadPinnedMap(filepath.Join(enforcement.PinRoot, MapPrefix+enforcement.BindingsMap), nil) + if err != nil { + t.Fatal(err) + } + defer m.Close() + var v struct{ Slot, Flags uint32 } + if err := m.Lookup(cgroup, &v); err != nil { + t.Fatalf("binding of cgroup %d: %v", cgroup, err) + } + return v.Slot, v.Flags +} + +// bindingStrictFlag is BINDING_STRICT of ../../common/bindings.h. +const bindingStrictFlag = 1 << 1 + +// waitFaultSince waits for a fault verdict (hook "fault", sent only for an +// armed task) with mode (1 Audit, 2 Strict) among the verdicts after from. +func (f *kernelFixture) waitFaultSince(t *testing.T, from int, mode uint32) { + t.Helper() + for i := 0; i < 30; i++ { + f.mu.Lock() + for j := from; j < len(f.verdicts); j++ { + // The hook enum is exported by name (as FILE_HOOK_ROOT_BARRIER in the suite). + if f.hooks[j] == "FILE_HOOK_FAULT" && f.verdicts[j].mode == mode { + f.mu.Unlock() + return + } + } + f.mu.Unlock() + time.Sleep(100 * time.Millisecond) + } + f.mu.Lock() + defer f.mu.Unlock() + t.Errorf("no fault verdict with mode %d after %d; hooks %v", mode, from, f.hooks[from:]) +} + +// sectionErrors reads the node-wide SECTION_ERROR verdict counter. +func (f *kernelFixture) sectionErrors(t *testing.T) uint64 { + t.Helper() + c, err := f.bindings.VerdictCounters() + if err != nil { + t.Fatal(err) + } + return c.SectionErrors +} + +// TestPendingSlotKernel binds the fixture container to PendingSlot, a slot +// that is never published (the start gate's mark). Strict: every judged file +// access of an armed task is a structural fault, denied with EPERM (the shell +// itself cannot load its libraries, so the command fails with that errno). +// Audit: allowed. Both send a fault verdict of their class and count only in +// the node-wide SECTION_ERROR counter. Then one bind moves the entry to the +// published slot 0 (the lab policy), whose rules decide from then on. +func TestPendingSlotKernel(t *testing.T) { + f := newKernelFixture(t) + compiled, err := filepolicy.CompileSlots([][]filepolicy.Document{{labDocument("pending", "enforce")}}, 1) + if err != nil { + t.Fatal(err) + } + f.start(t, compiled) + read := "cat /etc/hostname >/dev/null" + f.ok(t, f.id, read) // unbound: not judged + t.Cleanup(func() { f.bindings.Unbind(f.container) }) + + // Strict pending: EPERM, a Strict fault verdict, a section error. + if err := f.bindings.Bind(enforcement.Binding{Container: f.container, Slot: enforcement.PendingSlot, Strict: true}); err != nil { + t.Fatal(err) + } + if slot, flags := pinnedBinding(t, f.container.CgroupID); slot != enforcement.PendingSlot || flags&bindingStrictFlag == 0 { + t.Fatalf("Strict pending entry: slot %#x flags %#x", slot, flags) + } + before, from := f.sectionErrors(t), f.mark() + f.denied(t, f.id, read) + f.waitFaultSince(t, from, 2) + after := f.sectionErrors(t) + t.Logf("Strict pending: section errors %d -> %d", before, after) + if after <= before { + t.Fatalf("the structural fault counts a section error: %d -> %d", before, after) + } + if _, err := f.bindings.SlotFaults(enforcement.PendingSlot); err == nil { + t.Fatal("SlotFaults(PendingSlot) must be an error, never zero") + } + if _, err := f.bindings.Counters(enforcement.PendingSlot); err == nil { + t.Fatal("Counters(PendingSlot) must be an error, never zero") + } + + // Audit pending: allowed (the lab policy would deny /etc/shadow; with + // no policy the Audit mark allows it), an Audit fault verdict, a + // section error. + if err := f.bindings.Bind(enforcement.Binding{Container: f.container, Slot: enforcement.PendingSlot}); err != nil { + t.Fatal(err) + } + if slot, flags := pinnedBinding(t, f.container.CgroupID); slot != enforcement.PendingSlot || flags&bindingStrictFlag != 0 { + t.Fatalf("Audit pending entry: slot %#x flags %#x", slot, flags) + } + before, from = f.sectionErrors(t), f.mark() + f.ok(t, f.id, read) + f.ok(t, f.id, "cat /etc/shadow >/dev/null") + f.waitFaultSince(t, from, 1) + after = f.sectionErrors(t) + t.Logf("Audit pending: section errors %d -> %d", before, after) + if after <= before { + t.Fatalf("the Audit structural fault counts a section error: %d -> %d", before, after) + } + + // Pending -> slot 0 in one bind: the lab policy decides (a rule deny, + // not a fault). + if err := f.bindings.Bind(enforcement.Binding{Container: f.container, Slot: 0}); err != nil { + t.Fatal(err) + } + if slot, flags := pinnedBinding(t, f.container.CgroupID); slot != 0 || flags&bindingStrictFlag == 0 { + t.Fatalf("bound entry: slot %d flags %#x", slot, flags) + } + slotBefore, err := f.bindings.Counters(0) + if err != nil { + t.Fatal(err) + } + from = f.mark() + f.ok(t, f.id, read) + f.denied(t, f.id, "cat /etc/shadow >/dev/null") + f.waitVerdictSince(t, from, verdict{rule: "pending/secret-read", deny: 1, mode: 2, access: accessRead, path: "/etc/shadow"}) + slotAfter, err := f.bindings.Counters(0) + if err != nil { + t.Fatal(err) + } + t.Logf("slot 0: counters %+v -> %+v", slotBefore, slotAfter) + if slotAfter.Faults != slotBefore.Faults || slotAfter.Attempts <= slotBefore.Attempts { + t.Fatalf("slot 0 judges with no fault: %+v -> %+v", slotBefore, slotAfter) + } +} + +// TestPendingSlotSubtreeKernel binds a parent cgroup outside the container +// with the start gate's mark shape (PendingSlot, Subtree, RuntimeHelpers) +// and moves the worker, an armed task and the only task there, into its +// child cgroup: the subtree lookup must find the pending entry. Audit: the +// worker runs and sends Audit fault verdicts. Strict: its accesses send +// Strict fault verdicts (it can no longer answer: every file access fails). +func TestPendingSlotSubtreeKernel(t *testing.T) { + f := newKernelFixture(t) + compiled, err := filepolicy.CompileSlots([][]filepolicy.Document{{labDocument("pending-subtree", "enforce")}}, 1) + if err != nil { + t.Fatal(err) + } + f.start(t, compiled) + parentPath := "/file-test-pending-parent" + child := filepath.Join(parentPath, "child") + for _, p := range []string{parentPath, child} { + if err := os.Mkdir(cgroupDir(p), 0o755); err != nil && !os.IsExist(err) { + t.Fatal(err) + } + } + parent := identity(t, "parent", "file-test-pending-parent", parentPath) + w := startWorker(t, f) + t.Cleanup(func() { + f.bindings.Unbind(parent) + unix.Kill(w.pid, unix.SIGKILL) + for _, p := range []string{child, parentPath} { + var err error + for i := 0; i < 50; i++ { + if err = os.Remove(cgroupDir(p)); err == nil || os.IsNotExist(err) { + err = nil + break + } + time.Sleep(100 * time.Millisecond) + } + if err != nil { + t.Logf("cleanup: cgroup %s left behind: %v", p, err) + } + } + }) + w.moveTo(t, child) + const readSecret = "read x < /etc/shadow" + w.ok(t, readSecret) // unbound: not judged + mark := enforcement.Binding{Container: parent, Slot: enforcement.PendingSlot, Subtree: true, RuntimeHelpers: true} + + // Audit pending subtree: allowed, an Audit fault verdict. + if err := f.bindings.Bind(mark); err != nil { + t.Fatal(err) + } + if slot, flags := pinnedBinding(t, parent.CgroupID); slot != enforcement.PendingSlot || flags&bindingStrictFlag != 0 { + t.Fatalf("Audit pending subtree entry: slot %#x flags %#x", slot, flags) + } + before, from := f.sectionErrors(t), f.mark() + w.ok(t, readSecret) + f.waitFaultSince(t, from, 1) + after := f.sectionErrors(t) + t.Logf("Audit pending subtree: section errors %d -> %d", before, after) + if after <= before { + t.Fatalf("the Audit structural fault counts a section error: %d -> %d", before, after) + } + + // Strict pending subtree (last: the worker cannot answer after it). + mark.Strict = true + before, from = f.sectionErrors(t), f.mark() + if err := f.bindings.Bind(mark); err != nil { + t.Fatal(err) + } + if slot, flags := pinnedBinding(t, parent.CgroupID); slot != enforcement.PendingSlot || flags&bindingStrictFlag == 0 { + t.Fatalf("Strict pending subtree entry: slot %#x flags %#x", slot, flags) + } + f.waitFaultSince(t, from, 2) // the worker's own loop (sleep, /tmp/w.cmd) + after = f.sectionErrors(t) + t.Logf("Strict pending subtree: section errors %d -> %d", before, after) + if after <= before { + t.Fatalf("the Strict structural fault counts a section error: %d -> %d", before, after) + } +} + +// TestForkMarkFaultErrno: with every child mark failing, a Strict binding +// refuses the fork with EPERM (N1; the shell prints no errno, so the static +// helper forks). Audit allows it. +func TestForkMarkFaultErrno(t *testing.T) { + helper := os.Getenv("FILE_HELPER_BINARY") + for _, mode := range []string{"enforce", "audit"} { + t.Run(mode, func(t *testing.T) { + f := newKernelFixture(t) + if helper == "" { + t.Skip("FILE_HELPER_BINARY is not set") + } + compiled, err := filepolicy.CompileSlots([][]filepolicy.Document{{labDocument("fork-errno-"+mode, mode)}}, 1) + if err != nil { + t.Fatal(err) + } + f.startExtra(t, compiled, map[string]string{"arming-fail-fork-marks": "1"}) + // exec: the shell must not fork itself (its fork would fail first). + fork := "exec " + helper + " fork -" + f.ok(t, f.id, fork) // unbound: not judged + if err := f.bindings.Bind(enforcement.Binding{Container: f.container}); err != nil { + t.Fatal(err) + } + defer f.bindings.Unbind(f.container) + before, err := f.bindings.Counters(0) + if err != nil { + t.Fatal(err) + } + code, out := f.sh(t, f.id, fork) + after, err := f.bindings.Counters(0) + if err != nil { + t.Fatal(err) + } + t.Logf("%s: rc %d %s; counters %+v -> %+v", fork, code, out, before, after) + switch mode { + case "enforce": + if code == 0 || !strings.Contains(out, "fork -: Operation not permitted") || after.Faults <= before.Faults { + t.Fatalf("Strict must refuse the fork with EPERM and count a fault: rc %d %s", code, out) + } + case "audit": + if code != 0 || after.Faults != before.Faults || after.Unevaluated <= before.Unevaluated { + t.Fatalf("audit mode must allow the fork, count no fault and count an unevaluated judgement: rc %d %s", code, out) + } + } + }) + } +} + +// TestCredRecordFailureErrno: with every credential record failing, a Strict +// binding refuses the exec (runc init's own credential changes, recorded at +// file_record_cred via cred_prepare) and counts a slot fault; Audit runs it. +// The hook returns EPERM, but prepare_creds() turns a security_prepare_creds +// failure into NULL and its callers return ENOMEM: the errno user space sees +// here is the kernel's. The match is case-insensitive on runc's (or nsexec's) +// "cannot allocate memory" for the refused credential change. +func TestCredRecordFailureErrno(t *testing.T) { + for _, mode := range []string{"enforce", "audit"} { + t.Run(mode, func(t *testing.T) { + f := newKernelFixture(t) + compiled, err := filepolicy.CompileSlots([][]filepolicy.Document{{labDocument("cred-errno-"+mode, mode)}}, 1) + if err != nil { + t.Fatal(err) + } + f.startExtra(t, compiled, map[string]string{"cred-record-fail": "1"}) + run := func() (string, error) { + out, err := exec.CommandContext(f.ctx, "docker", "exec", f.id, "true").CombinedOutput() + return strings.TrimSpace(string(out)), err + } + if out, err := run(); err != nil { + t.Fatalf("an unbound container must not be judged: %v %s", err, out) + } + if err := f.bindings.Bind(enforcement.Binding{Container: f.container}); err != nil { + t.Fatal(err) + } + defer f.bindings.Unbind(f.container) + before, err := f.bindings.Counters(0) + if err != nil { + t.Fatal(err) + } + out, runErr := run() + after, err := f.bindings.Counters(0) + if err != nil { + t.Fatal(err) + } + t.Logf("docker exec true: %v %s; counters %+v -> %+v", runErr, out, before, after) + switch mode { + case "enforce": + if runErr == nil || !strings.Contains(strings.ToLower(out), "cannot allocate memory") || after.Faults <= before.Faults { + t.Fatalf("Strict must refuse unrecordable credentials (the kernel's ENOMEM from prepare_creds) and count a fault: %v %s", runErr, out) + } + case "audit": + if runErr != nil || after.Faults != before.Faults || after.Unevaluated <= before.Unevaluated { + t.Fatalf("audit mode must run the exec, count no fault and count an unevaluated judgement: %v %s", runErr, out) + } + } + }) + } +} diff --git a/pkg/ebpf/gadgets/enforce_file/runtime/runtime.go b/pkg/ebpf/gadgets/enforce_file/runtime/runtime.go index 2ae0f27e8b..483470b100 100644 --- a/pkg/ebpf/gadgets/enforce_file/runtime/runtime.go +++ b/pkg/ebpf/gadgets/enforce_file/runtime/runtime.go @@ -369,7 +369,7 @@ func GetPublisher(gc operators.GadgetContext) (func(slot uint32, p filepolicy.Co // Enforcing reports whether a slot can enforce. The root barrier covers the // tasks of such a slot (see "Root barrier" in ../program.bpf.c). func Enforcing(p filepolicy.Compiled, slot uint32) bool { - return int(slot) < len(p.Slots) && p.Slots[slot].Mode == filepolicy.KernelModeEnforce + return uint64(slot) < uint64(len(p.Slots)) && p.Slots[slot].Mode == filepolicy.KernelModeEnforce } // Barrier is the root barrier attestation of one instance. diff --git a/pkg/ebpf/gadgets/enforce_file/runtime/runtime_kernel_test.go b/pkg/ebpf/gadgets/enforce_file/runtime/runtime_kernel_test.go index a4711b7e62..97cff9504f 100644 --- a/pkg/ebpf/gadgets/enforce_file/runtime/runtime_kernel_test.go +++ b/pkg/ebpf/gadgets/enforce_file/runtime/runtime_kernel_test.go @@ -1401,11 +1401,14 @@ func TestExecMarkFaultInjection(t *testing.T) { t.Fatal(err) } f.startExtra(t, compiled, map[string]string{"arming-fail-exec-marks": "1"}) + var out []byte run := func() error { - return exec.CommandContext(f.ctx, "docker", "exec", f.id, "true").Run() + var err error + out, err = exec.CommandContext(f.ctx, "docker", "exec", f.id, "true").CombinedOutput() + return err } if err := run(); err != nil { - t.Fatalf("an unbound container must not be judged: %v", err) + t.Fatalf("an unbound container must not be judged: %v %s", err, out) } if err := f.bindings.Bind(enforcement.Binding{Container: f.container}); err != nil { t.Fatal(err) @@ -1420,14 +1423,15 @@ func TestExecMarkFaultInjection(t *testing.T) { if cerr != nil { t.Fatal(cerr) } - t.Logf("docker exec true: %v; counters %+v -> %+v", err, before, after) + t.Logf("docker exec true: %v %s; counters %+v -> %+v", err, out, before, after) if after.Attempts <= before.Attempts { t.Fatalf("the exec counts an attempt: %+v -> %+v", before, after) } switch mode { case "enforce": - if err == nil { - t.Fatal("an exec whose mark cannot be allocated must be refused under Strict") + // N1: EPERM (runc reports the exec errno in lower case). + if err == nil || !strings.Contains(strings.ToLower(string(out)), "operation not permitted") { + t.Fatalf("an exec whose mark cannot be allocated must be refused under Strict with EPERM: %v %s", err, out) } if after.Faults <= before.Faults { t.Fatalf("the refused exec counts a fault: %+v -> %+v", before, after) diff --git a/pkg/ebpf/gadgets/enforce_network/runtime/pending_kernel_test.go b/pkg/ebpf/gadgets/enforce_network/runtime/pending_kernel_test.go new file mode 100644 index 0000000000..3ca4ea17e2 --- /dev/null +++ b/pkg/ebpf/gadgets/enforce_network/runtime/pending_kernel_test.go @@ -0,0 +1,203 @@ +//go:build linux && network_kernel + +// Copyright 2026 The Kubescape Authors +// SPDX-License-Identifier: Apache-2.0 + +package runtime + +import ( + "path/filepath" + "testing" + + "github.com/cilium/ebpf" + + "github.com/kubescape/node-agent/pkg/ebpf/gadgets/common/enforcement" +) + +// Same fixture and environment as runtime_kernel_test.go. + +// bindingEntry is struct sandbox_binding of ../../common/bindings.h. +type bindingEntry struct{ Slot, Flags uint32 } + +// bindingStrictFlag is BINDING_STRICT of ../../common/bindings.h. +const bindingStrictFlag = 1 << 1 + +func pinnedBindings(t *testing.T) *ebpf.Map { + t.Helper() + m, err := ebpf.LoadPinnedMap(filepath.Join(enforcement.PinRoot, MapPrefix+enforcement.BindingsMap), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { m.Close() }) + return m +} + +func pinnedBinding(t *testing.T, m *ebpf.Map, cgroup uint64) bindingEntry { + t.Helper() + var v bindingEntry + if err := m.Lookup(cgroup, &v); err != nil { + t.Fatalf("binding of cgroup %d: %v", cgroup, err) + } + return v +} + +// TestPendingSlotKernel binds the fixture container to PendingSlot, a slot +// that is never published (the start gate's mark). Strict: a connect is a +// structural fault, denied with EPERM. Audit: the kernel alone decides. +// Both count only in the node-wide SECTION_ERROR counter. Then one bind moves +// the entry to the published slot 1 (default deny, loopback allowed), whose +// rules decide from then on. +func TestPendingSlotKernel(t *testing.T) { + f := newKernelFixture(t) + if err := f.start(t, matrixPolicy(t)); err != nil { + t.Fatal(err) + } + m := pinnedBindings(t) + loopback := f.call(t, f.id, "tcp4", "127.0.0.1", 9) // the kernel alone, unbound + if loopback == "EPERM" { + t.Fatalf("unbound loopback connect = %s", loopback) + } + sectionErrors := func() uint64 { + t.Helper() + c, err := f.bindings.VerdictCounters() + if err != nil { + t.Fatal(err) + } + return c.SectionErrors + } + t.Cleanup(func() { f.bindings.Unbind(f.container) }) + + // Strict pending: EPERM, a section error. + if err := f.bindings.Bind(enforcement.Binding{Container: f.container, Slot: enforcement.PendingSlot, Strict: true}); err != nil { + t.Fatal(err) + } + if v := pinnedBinding(t, m, f.container.CgroupID); v.Slot != enforcement.PendingSlot || v.Flags&bindingStrictFlag == 0 { + t.Fatalf("Strict pending entry: %+v", v) + } + before := sectionErrors() + f.expect(t, f.id, "tcp4", "127.0.0.1", 9, "EPERM") + after := sectionErrors() + t.Logf("Strict pending: section errors %d -> %d", before, after) + if after <= before { + t.Fatalf("the structural fault counts a section error: %d -> %d", before, after) + } + f.waitFault(t) + if _, err := f.bindings.SlotFaults(enforcement.PendingSlot); err == nil { + t.Fatal("SlotFaults(PendingSlot) must be an error, never zero") + } + if _, err := f.bindings.Counters(enforcement.PendingSlot); err == nil { + t.Fatal("Counters(PendingSlot) must be an error, never zero") + } + + // Audit pending: the kernel decides, still a section error. + if err := f.bindings.Bind(enforcement.Binding{Container: f.container, Slot: enforcement.PendingSlot}); err != nil { + t.Fatal(err) + } + if v := pinnedBinding(t, m, f.container.CgroupID); v.Slot != enforcement.PendingSlot || v.Flags&bindingStrictFlag != 0 { + t.Fatalf("Audit pending entry: %+v", v) + } + before = sectionErrors() + f.expect(t, f.id, "tcp4", "127.0.0.1", 9, loopback) + after = sectionErrors() + t.Logf("Audit pending: section errors %d -> %d", before, after) + if after <= before { + t.Fatalf("the Audit structural fault counts a section error: %d -> %d", before, after) + } + + // Pending -> slot 1 in one bind: the default deny decides. + if err := f.bindings.Bind(enforcement.Binding{Container: f.container, Slot: 1}); err != nil { + t.Fatal(err) + } + if v := pinnedBinding(t, m, f.container.CgroupID); v.Slot != 1 || v.Flags&bindingStrictFlag == 0 { + t.Fatalf("bound entry: %+v", v) + } + slotBefore, err := f.bindings.Counters(1) + if err != nil { + t.Fatal(err) + } + f.expect(t, f.id, "tcp4", "127.0.0.1", 9, loopback) + f.expect(t, f.id, "tcp4", "192.0.2.7", 80, "EPERM") + slotAfter, err := f.bindings.Counters(1) + if err != nil { + t.Fatal(err) + } + t.Logf("slot 1: counters %+v -> %+v", slotBefore, slotAfter) + if slotAfter.Faults != slotBefore.Faults || slotAfter.Attempts <= slotBefore.Attempts { + t.Fatalf("slot 1 judges with no fault: %+v -> %+v", slotBefore, slotAfter) + } +} + +// TestPendingSlotFullMapReplace fills the gadget's own pinned binding map to +// capacity (dummy keys: cgroup IDs no task has), then moves the fixture +// container's entry from PendingSlot to slot 1 with one bind: replacing an +// existing key of a full HASH map must succeed, while a new key is refused. +func TestPendingSlotFullMapReplace(t *testing.T) { + f := newKernelFixture(t) + if err := f.start(t, matrixPolicy(t)); err != nil { + t.Fatal(err) + } + m := pinnedBindings(t) + // The kernel alone, unbound: after the replacement slot 1 allows + // loopback, where the Strict pending mark denied it. + loopback := f.call(t, f.id, "tcp4", "127.0.0.1", 9) + if loopback == "EPERM" { + t.Fatalf("unbound loopback connect = %s", loopback) + } + if m.MaxEntries() != enforcement.MaxBindings { + t.Fatalf("binding map has %d entries, want %d", m.MaxEntries(), enforcement.MaxBindings) + } + t.Cleanup(func() { f.bindings.Unbind(f.container) }) + if err := f.bindings.Bind(enforcement.Binding{Container: f.container, Slot: enforcement.PendingSlot, Strict: true}); err != nil { + t.Fatal(err) + } + f.expect(t, f.id, "tcp4", "127.0.0.1", 9, "EPERM") + + const dummyBase = uint64(0xFFFF) << 48 + var dummies []uint64 + t.Cleanup(func() { + for _, k := range dummies { + _ = m.Delete(k) + } + }) + for i := uint64(0); ; i++ { + k := dummyBase + i + err := m.Update(k, bindingEntry{Slot: 0}, ebpf.UpdateNoExist) + if err != nil { + t.Logf("binding map full after %d dummy keys: %v", len(dummies), err) + break + } + dummies = append(dummies, k) + if i > enforcement.MaxBindings { + t.Fatal("the binding map took more keys than its capacity") + } + } + var ( + key uint64 + value bindingEntry + entries int + ) + for it := m.Iterate(); it.Next(&key, &value); { + entries++ + } + t.Logf("binding map: %d entries (%d dummy keys), capacity %d", entries, len(dummies), enforcement.MaxBindings) + if entries != enforcement.MaxBindings { + t.Fatalf("the binding map holds %d entries, want it full at %d", entries, enforcement.MaxBindings) + } + err := m.Update(dummyBase+uint64(len(dummies))+1, bindingEntry{}, ebpf.UpdateAny) + t.Logf("a new key on the full map: %v", err) + if err == nil { + t.Fatal("a new key must be refused by the full map") + } + + // The replacement: PendingSlot -> slot 1, one bind. + if err := f.bindings.Bind(enforcement.Binding{Container: f.container, Slot: 1}); err != nil { + t.Fatalf("replacing an existing key of a full binding map: %v", err) + } + if v := pinnedBinding(t, m, f.container.CgroupID); v.Slot != 1 || v.Flags&bindingStrictFlag == 0 { + t.Fatalf("replaced entry: %+v", v) + } + // The kernel judges with slot 1 now: loopback is back to the kernel's + // own result (EPERM under the pending mark), other destinations denied. + f.expect(t, f.id, "tcp4", "127.0.0.1", 9, loopback) + f.expect(t, f.id, "tcp4", "192.0.2.7", 80, "EPERM") +} diff --git a/pkg/ebpf/gadgets/enforce_privilege/README.md b/pkg/ebpf/gadgets/enforce_privilege/README.md index ab5e83fe1d..d07a5b51a6 100644 --- a/pkg/ebpf/gadgets/enforce_privilege/README.md +++ b/pkg/ebpf/gadgets/enforce_privilege/README.md @@ -104,7 +104,7 @@ policy: program uses the global init task's. - **Lost arming.** The kernel can fail to allocate a task's mark (memory pressure). When an armed task forks and the child's mark fails, a Strict - binding (its slot has any enforce entry) refuses the fork (`-ENOMEM`): an + binding (its slot has any enforce entry) refuses the fork (`-EPERM`): an unmarked child would escape every rule. Audit never blocks, even on a fault: an Audit binding, or an unbound cgroup, allows the fork. When that fork is a clone into another cgroup (`CLONE_INTO_CGROUP`), the child can start in a @@ -192,8 +192,11 @@ policy: bindings): the bindings under that share together fit in the last quarter, so bindings that fill their quotas cannot take every entry. Over its quota or its share, or when the record is full, a Strict binding refuses - the preparation (the syscall fails with `ENOMEM`; an io_uring request - fails with `ENOMEM`) and counts a slot fault; Audit counts it as + the preparation (the hook returns `EPERM`; `prepare_creds()` and + `cred_alloc_blank()` turn the failure into NULL, so the syscall, a fork + and a keyctl session-to-parent fail with the kernel's `ENOMEM`; an + io_uring request under a personality, refused at `uring_override_creds`, + fails with `EPERM`) and counts a slot fault; Audit counts it as unevaluated. A task outside every binding records nothing. `CredRecordHealth` fails from 90% full. A freed credential leaves the record after an RCU grace period, so a burst counts until then: on 8-CPU @@ -284,7 +287,7 @@ policy: a process a hook leaves behind) is not judged, and neither are its children. A workload task whose exec mark failed (memory pressure) is also an unarmed parent. The mark is prepared in `bprm_check_security`, where the exec can - still fail: a Strict binding refuses the exec (`-ENOMEM`, a slot fault); an + still fail: a Strict binding refuses the exec (`-EPERM`, a slot fault); an Audit binding runs it and counts an unevaluated judgement, and its exec'd children are then exempt too. `ExemptExecs` makes every exemption visible. Only the runtime or a host root process can create such a task. This was verified with runc, which execs the workload diff --git a/pkg/ebpf/gadgets/enforce_privilege/program.bpf.c b/pkg/ebpf/gadgets/enforce_privilege/program.bpf.c index d4bd593b6e..1a351c8256 100644 --- a/pkg/ebpf/gadgets/enforce_privilege/program.bpf.c +++ b/pkg/ebpf/gadgets/enforce_privilege/program.bpf.c @@ -44,7 +44,6 @@ GADGET_PARAM(cred_record_fail); GADGET_PARAM(cred_forget_fail); #define EPERM 1 -#define ENOMEM 12 #define CAP_SYS_ADMIN 21 #define CAP_OPT_NOAUDIT (1UL << 1) #define PTRACE_MODE_ATTACH 0x02 @@ -573,7 +572,7 @@ static __always_inline bool priv_strict_binding(__u64 *cgid, __u32 *slot, } // The mark of an exec is prepared where the exec can still fail: a Strict -// binding refuses an exec whose mark storage cannot be allocated (-ENOMEM), so +// binding refuses an exec whose mark storage cannot be allocated (-EPERM), so // a committed exec in a Strict binding is never left unarmed. An Audit binding // lets the exec run; it is counted as unevaluated. SEC("lsm/bprm_check_security") @@ -600,7 +599,7 @@ int BPF_PROG(ig_priv_exec_check, struct linux_binprm *bprm, int ret) arming_slot_fault(slot); priv_fault_report(cgid, slot, priv_slot_generation(slot), true, PRIV_FAULT_TRACKING); - return -ENOMEM; + return -EPERM; } if (bound) arming_slot_unevaluated(slot); @@ -646,7 +645,7 @@ static __always_inline int priv_lost_child(unsigned long clone_flags) arming_slot_fault(slot); priv_fault_report(cgid, slot, priv_slot_generation(slot), true, PRIV_FAULT_TRACKING); - return -ENOMEM; + return -EPERM; } if (binding_lookup(&cgid, &slot, &flags)) arming_slot_unevaluated(slot); @@ -715,7 +714,7 @@ static __always_inline int do_task_alloc(void *ctx, struct task_struct *task, priv_count_fork(); if (!arming_on_fork(task, clone_flags) && priv_lost_child(clone_flags)) - return -ENOMEM; + return -EPERM; // userns_create judges CLONE_NEWUSER. flags = clone_flags & CLONE_NS_MASK & ~CLONE_NEWUSER; @@ -789,7 +788,9 @@ static __always_inline enum priv_syscall capable_syscall(__u64 *flags) // priv_record_cred records credentials a task of a binding prepares or // applies (common/creds.h). Over the binding's quota or with a full record, a -// Strict binding refuses the preparation (the syscall fails with -ENOMEM) and +// Strict binding refuses the preparation (the hook returns -EPERM; through +// prepare_creds or cred_alloc_blank user space sees ENOMEM, through +// uring_override_creds EPERM) and // counts a slot fault: unrecorded credentials would escape every capability // rule once overridden. Audit lets it run; it is counted as unevaluated. static __always_inline int priv_record_cred(const struct cred *cred) @@ -806,7 +807,7 @@ static __always_inline int priv_record_cred(const struct cred *cred) arming_slot_fault(slot); priv_fault_report(cgid, slot, priv_slot_generation(slot), true, PRIV_FAULT_TRACKING); - return -ENOMEM; + return -EPERM; } arming_slot_unevaluated(slot); return 0; @@ -887,7 +888,7 @@ int BPF_PROG(ig_priv_cred_alloc_blank, struct cred *cred, gfp_t gfp, int ret) // 6.12 and 6.18 the hook runs only for a personality, when the request is // prepared): recorded there, so a personality registered before the bind is // judged too. A Strict binding whose record fails refuses the request -// (-ENOMEM). +// (-EPERM). SEC("lsm/uring_override_creds") int BPF_PROG(ig_priv_uring_creds, const struct cred *new, int ret) { diff --git a/pkg/ebpf/gadgets/enforce_privilege/runtime/exec_coexist_kernel_test.go b/pkg/ebpf/gadgets/enforce_privilege/runtime/exec_coexist_kernel_test.go index 64793b8da1..2187868448 100644 --- a/pkg/ebpf/gadgets/enforce_privilege/runtime/exec_coexist_kernel_test.go +++ b/pkg/ebpf/gadgets/enforce_privilege/runtime/exec_coexist_kernel_test.go @@ -397,6 +397,25 @@ func (n *sharedExec) settle(t *testing.T, label string, tasks, works uint32) { } } +// entryRefusals reads the live ENTRY cell of the shared node's fail-closed +// witness (opaque_real_fail_closed_rates[FailClosedRateEntry]): an exec on an +// owned route by a task with no TASK, which enforce_exec refuses before its +// policy is evaluated. A map read, not FailClosedHealth (a poller sample). +func (n *sharedExec) entryRefusals(t *testing.T) uint64 { + t.Helper() + return n.failClosedCell(t, fullruntime.FailClosedRateEntry) +} + +// failClosedCell reads one live cell of the shared node's fail-closed witness. +func (n *sharedExec) failClosedCell(t *testing.T, cell int) uint64 { + t.Helper() + var v uint64 + if err := n.mapOf(t, "opaque_real_fail_closed_rates").Lookup(uint32(cell), &v); err != nil { + t.Fatalf("fail-closed witness cell %d: %v", cell, err) + } + return v +} + func (n *sharedExec) park(t *testing.T) fullruntime.SharedBirthParkHealth { t.Helper() h, err := n.node.BirthParkHealth() @@ -459,7 +478,7 @@ func (n *sharedExec) round(t *testing.T, label string, tasks, works uint32, acti // TestExecRefusalWithSharedExec runs this gadget next to enforce_exec's real // shared node, where this gadget refuses an exec in bprm_check_security -// (-ENOMEM: every exec mark fails, Strict) after enforce_exec may have built +// (-EPERM: every exec mark fails, Strict) after enforce_exec may have built // its exec state, in both attach orders; and where enforce_exec itself denies // an exec. Every round keeps the shared node's invariants (TASK/WORK credits, // birth park, capsule faults, fail-closed witness). Requirements as in @@ -563,6 +582,8 @@ func execRefusalRound(t *testing.T, object, cgroup, helper string, privilegeFirs if err != nil { t.Fatal(err) } + execBefore := n.entryRefusals(t) + admBefore := n.failClosedCell(t, fullruntime.FailClosedRateAdmission) var startErr error code, _ := n.round(t, "unarmed exec", tasks, works, func() int { dir, err := os.Open(cgroup) @@ -585,9 +606,22 @@ func execRefusalRound(t *testing.T, object, cgroup, helper string, privilegeFirs if err != nil { t.Fatal(err) } - t.Logf("unarmed exec refused: %v; privilege faults %d -> %d", startErr, before.Faults, after.Faults) - if errors.Is(startErr, syscall.ENOMEM) && after.Faults <= before.Faults { - t.Fatalf("this gadget refused the exec (ENOMEM) but counted no fault: %+v -> %+v", before, after) + execAfter := n.entryRefusals(t) + admAfter := n.failClosedCell(t, fullruntime.FailClosedRateAdmission) + t.Logf("unarmed exec refused: %v; privilege faults %d -> %d; enforce_exec ENTRY refusals %d -> %d, ADMISSION %d -> %d", startErr, before.Faults, after.Faults, execBefore, execAfter, admBefore, admAfter) + // Both gadgets refuse with EPERM, so the errno does not tell which one + // decided: the attach order does. The newest link runs first and the + // kernel stops at the first nonzero return. + if !privilegeFirst { + // This gadget is the newest link: it refuses the exec itself. + if !errors.Is(startErr, syscall.EPERM) || after.Faults <= before.Faults { + t.Fatalf("attached last, this gadget must refuse the exec (EPERM) and count a fault: %v, %+v -> %+v", startErr, before, after) + } + } else if !errors.Is(startErr, syscall.EPERM) || (after.Faults <= before.Faults && execAfter <= execBefore) { + // enforce_exec runs first: either it refused the exec (EPERM, + // counted in its live ENTRY cell), or it allowed it and this gadget + // refused it (EPERM, a fault). + t.Fatalf("the refused exec must fail with EPERM and be counted by one gadget: %v; privilege %+v -> %+v, enforce_exec ENTRY %d -> %d", startErr, before, after, execBefore, execAfter) } // enforce_exec denies an exec of uid 1000 (EPERM; a missing permission // would be EACCES); this gadget does not judge it (the armed init's child diff --git a/pkg/ebpf/gadgets/enforce_privilege/runtime/pending_kernel_test.go b/pkg/ebpf/gadgets/enforce_privilege/runtime/pending_kernel_test.go new file mode 100644 index 0000000000..a25d133097 --- /dev/null +++ b/pkg/ebpf/gadgets/enforce_privilege/runtime/pending_kernel_test.go @@ -0,0 +1,156 @@ +//go:build linux && privilege_kernel + +// Copyright 2026 The Kubescape Authors +// SPDX-License-Identifier: Apache-2.0 + +package runtime + +import ( + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/cilium/ebpf" + + "github.com/kubescape/node-agent/pkg/ebpf/gadgets/common/enforcement" + privpolicy "github.com/kubescape/node-agent/pkg/ebpf/gadgets/enforce_privilege/policy" +) + +// Same fixture and environment as runtime_kernel_test.go (the container needs +// util-linux unshare, as TestGadgetWithInspektorGadgetAlone). Run the fixture +// container without a healthcheck and nothing else exec'd into it during the +// test: the slot-0 step asserts the node-wide SECTION_ERROR counter does not +// move, and any other judged task in the cgroup could move it. + +// pinnedBinding reads the kernel entry of a cgroup in the section's pinned +// binding map: its slot and flags (struct sandbox_binding, ../../common/bindings.h). +func pinnedBinding(t *testing.T, cgroup uint64) (slot, flags uint32) { + t.Helper() + m, err := ebpf.LoadPinnedMap(filepath.Join(enforcement.PinRoot, MapPrefix+enforcement.BindingsMap), nil) + if err != nil { + t.Fatal(err) + } + defer m.Close() + var v struct{ Slot, Flags uint32 } + if err := m.Lookup(cgroup, &v); err != nil { + t.Fatalf("binding of cgroup %d: %v", cgroup, err) + } + return v.Slot, v.Flags +} + +// bindingStrictFlag is BINDING_STRICT of ../../common/bindings.h. +const bindingStrictFlag = 1 << 1 + +// TestPendingSlotKernel binds the fixture container to PendingSlot, a slot +// that is never published (the start gate's mark). Strict: a judged call is +// a structural fault, denied with EPERM. Audit: it is allowed. Both count +// only in the node-wide SECTION_ERROR counter; there is no per-slot counter. +// Then one bind moves the entry to the published slot 0, whose policy +// decides from then on. +func TestPendingSlotKernel(t *testing.T) { + f := newKernelFixture(t) + rule := privpolicy.Rule{Name: "no-newns", Action: "deny", Target: privpolicy.Target{Syscall: []string{"unshare"}, Flags: []string{"CLONE_NEWNS"}}} + doc := privpolicy.Document{Version: 1, Name: "pending", Policy: privpolicy.Policy{Mode: "enforce", Privilege: privpolicy.Section{Default: "allow", Rules: []privpolicy.Rule{rule}}}} + compiled, err := privpolicy.CompileKernel(doc, 1) + if err != nil { + t.Fatal(err) + } + f.start(t, "privilege-pending", compiled, nil) + unshare := func() (string, error) { + out, err := exec.CommandContext(f.ctx, "docker", "exec", f.id, "unshare", "-m", "true").CombinedOutput() + return strings.TrimSpace(string(out)), err + } + if out, err := unshare(); err != nil { + t.Fatalf("an unbound container must not be judged: %v %s", err, out) + } + sectionErrors := func() uint64 { + t.Helper() + c, err := f.bindings.VerdictCounters() + if err != nil { + t.Fatal(err) + } + return c.SectionErrors + } + t.Cleanup(func() { f.bindings.Unbind(f.container) }) + + // Strict pending: EPERM, a section error. + if err := f.bindings.Bind(enforcement.Binding{Container: f.container, Slot: enforcement.PendingSlot, Strict: true}); err != nil { + t.Fatal(err) + } + if slot, flags := pinnedBinding(t, f.container.CgroupID); slot != enforcement.PendingSlot || flags&bindingStrictFlag == 0 { + t.Fatalf("Strict pending entry: slot %#x flags %#x", slot, flags) + } + before := sectionErrors() + out, err := unshare() + after := sectionErrors() + t.Logf("Strict pending: unshare %v %s; section errors %d -> %d", err, out, before, after) + if err == nil || !strings.Contains(out, "Operation not permitted") { + t.Fatalf("a Strict pending binding must deny with EPERM: %v %s", err, out) + } + if after <= before { + t.Fatalf("the structural fault counts a section error: %d -> %d", before, after) + } + if _, err := f.bindings.SlotFaults(enforcement.PendingSlot); err == nil { + t.Fatal("SlotFaults(PendingSlot) must be an error, never zero") + } + if _, err := f.bindings.Counters(enforcement.PendingSlot); err == nil { + t.Fatal("Counters(PendingSlot) must be an error, never zero") + } + + // Audit pending: allowed, still a section error. + if err := f.bindings.Bind(enforcement.Binding{Container: f.container, Slot: enforcement.PendingSlot}); err != nil { + t.Fatal(err) + } + if slot, flags := pinnedBinding(t, f.container.CgroupID); slot != enforcement.PendingSlot || flags&bindingStrictFlag != 0 { + t.Fatalf("Audit pending entry: slot %#x flags %#x", slot, flags) + } + before = sectionErrors() + out, err = unshare() + after = sectionErrors() + t.Logf("Audit pending: unshare %v %s; section errors %d -> %d", err, out, before, after) + if err != nil { + t.Fatalf("an Audit pending binding must allow: %v %s", err, out) + } + if after <= before { + t.Fatalf("the Audit structural fault counts a section error: %d -> %d", before, after) + } + + // Pending -> slot 0 in one bind: the published policy decides (a + // policy deny, not a fault). + if err := f.bindings.Bind(enforcement.Binding{Container: f.container, Slot: 0}); err != nil { + t.Fatal(err) + } + if slot, flags := pinnedBinding(t, f.container.CgroupID); slot != 0 || flags&bindingStrictFlag == 0 { + t.Fatalf("bound entry: slot %d flags %#x", slot, flags) + } + counters, err := f.bindings.VerdictCounters() + if err != nil { + t.Fatal(err) + } + slotBefore, err := f.bindings.Counters(0) + if err != nil { + t.Fatal(err) + } + out, unshareErr := unshare() + verdictsAfter, err := f.bindings.VerdictCounters() + if err != nil { + t.Fatal(err) + } + slotAfter, err := f.bindings.Counters(0) + if err != nil { + t.Fatal(err) + } + t.Logf("slot 0: unshare %v %s; verdicts %+v -> %+v; slot %+v -> %+v", unshareErr, out, counters, verdictsAfter, slotBefore, slotAfter) + if unshareErr == nil || !strings.Contains(out, "Operation not permitted") { + t.Fatalf("slot 0 denies unshare(CLONE_NEWNS) with EPERM: %v %s", unshareErr, out) + } + if verdictsAfter.SectionErrors != counters.SectionErrors { + // A healthcheck or another exec in the cgroup moves this + // node-wide counter too (see the header). + t.Fatalf("slot 0's policy deny is not a fault: section errors moved by %d", verdictsAfter.SectionErrors-counters.SectionErrors) + } + if verdictsAfter.Denied <= counters.Denied || slotAfter.Faults != slotBefore.Faults || slotAfter.Attempts <= slotBefore.Attempts { + t.Fatalf("slot 0's policy deny, not a fault: verdicts %+v -> %+v, slot %+v -> %+v", counters, verdictsAfter, slotBefore, slotAfter) + } +} diff --git a/pkg/ebpf/gadgets/enforce_privilege/runtime/runtime_kernel_test.go b/pkg/ebpf/gadgets/enforce_privilege/runtime/runtime_kernel_test.go index 205fadc57d..1fe2df99ec 100644 --- a/pkg/ebpf/gadgets/enforce_privilege/runtime/runtime_kernel_test.go +++ b/pkg/ebpf/gadgets/enforce_privilege/runtime/runtime_kernel_test.go @@ -19,7 +19,7 @@ package runtime // TestForkMarkFaultInjection uses the same fixture. The container needs a // POSIX sh, and perl for TestSetnsVerdictsPerCheck (busybox has none; for // example debian:13-slim with perl). TestTaskAllocCoexistence reads busybox -// sh's fork errors ("Out of memory", "Permission denied"; dash prints only +// sh's fork errors ("Operation not permitted", "Permission denied"; dash prints only // "Cannot fork"): run it alone in a busybox container (it skips in another). On an AppArmor host, also start it with // --security-opt apparmor=unconfined: docker-default blocks the unbound // unshare, setns and raw socket baselines. Run the tests from this directory @@ -1484,7 +1484,7 @@ func hostCgroup(t *testing.T, name string) ContainerIdentity { } // TestCredRecordQuotaPerBinding: a binding that fills its quota of the -// credential record is refused new credentials (ENOMEM) and counts a slot +// credential record is refused new credentials and counts a slot // fault; another Strict binding on the node keeps working. When the filler // exits, its credentials leave the record. func TestCredRecordQuotaPerBinding(t *testing.T) { @@ -1533,8 +1533,11 @@ func TestCredRecordQuotaPerBinding(t *testing.T) { if _, err := fmt.Sscan(string(data), &n, &errno); err != nil { t.Fatal(err) } + // The hook returns EPERM, but prepare_creds() turns any security_prepare_creds + // failure into NULL and its callers (setresuid here) return ENOMEM: the + // errno user space sees at a credential-record refusal is the kernel's. if errno != int(unix.ENOMEM) || n > quota { - t.Fatalf("binding a: %d credentials, then errno %d; want ENOMEM at its quota of %d", n, errno, quota) + t.Fatalf("binding a: %d credentials, then errno %d; want the kernel's ENOMEM (prepare_creds) at its quota of %d", n, errno, quota) } if faults, err := f.bindings.SlotFaults(0); err != nil || faults == 0 { t.Fatalf("the refusal must count a slot fault: %d %v", faults, err) @@ -1852,7 +1855,7 @@ func standInTaskAlloc(t *testing.T, cgid uint64, errno int32) *ebpf.Program { // - the other program's fork deny is never overridden: in Audit the fork // fails with its errno; in Strict it fails with the errno of the program // that runs first (the kernel runs the newest link first and stops at the -// first nonzero return): EACCES when the other program is newer, ENOMEM +// first nonzero return): EACCES when the other program is newer, EPERM // (the gadget's lost child) when it is older. // // The stand-in has no task state. The state check that Matthias's review asks @@ -1877,8 +1880,8 @@ func TestTaskAllocCoexistence(t *testing.T) { return "ok" case strings.Contains(string(out), "Permission denied"): return "EACCES" - case strings.Contains(string(out), "Out of memory"), strings.Contains(string(out), "Cannot allocate memory"): - return "ENOMEM" + case strings.Contains(string(out), "Operation not permitted"): + return "EPERM" } return "failed: " + strings.TrimSpace(string(out)) } @@ -1913,7 +1916,7 @@ func TestTaskAllocCoexistence(t *testing.T) { if mode == "audit" && got != "ok" { t.Fatalf("an Audit binding must never deny a fork: %s", got) } - if mode == "enforce" && got != "ENOMEM" { + if mode == "enforce" && got != "EPERM" { t.Fatalf("a Strict binding must refuse a fork whose child cannot be armed: %s", got) } @@ -1945,7 +1948,7 @@ func TestTaskAllocCoexistence(t *testing.T) { case "enforce": want := "EACCES" if order == "other-older" { - want = "ENOMEM" + want = "EPERM" } if got != want { t.Fatalf("the newest program decides and no deny becomes an allow: got %s, want %s", got, want) @@ -2364,8 +2367,8 @@ func TestCredRecordShareUnderPressure(t *testing.T) { n, errno, stop := fillIn(t, filler, dir, id) defer stop() switch { - case errno != int(unix.ENOMEM): - t.Fatalf("binding %d: errno %d after %d credentials, want ENOMEM", i, errno, n) + case errno != int(unix.ENOMEM): // prepare_creds() maps the hook's EPERM to ENOMEM + t.Fatalf("binding %d: errno %d after %d credentials, want the kernel's ENOMEM (prepare_creds)", i, errno, n) case i < full && (n > quota || n < quota-5): t.Fatalf("binding %d: %d credentials, want its quota %d (the record is under the pressure level)", i, n, quota) case i >= full && n > share: diff --git a/pkg/sandboxpolicy/igbackend/file_native.go b/pkg/sandboxpolicy/igbackend/file_native.go index 841c7d827b..e750617d3c 100644 --- a/pkg/sandboxpolicy/igbackend/file_native.go +++ b/pkg/sandboxpolicy/igbackend/file_native.go @@ -83,8 +83,8 @@ func (e *nativeFileEngine) Start(ctx context.Context, id string, config FileConf } return n, nil } - instance.slotGate = func(slot uint32) error { - if !instance.bindings.Strict(slot) { + instance.slotGate = func(_ uint32, strict bool) error { + if !strict { return nil } return barrier.Err() diff --git a/pkg/sandboxpolicy/igbackend/privilege_native.go b/pkg/sandboxpolicy/igbackend/privilege_native.go index 7b130bad94..2e71a66b01 100644 --- a/pkg/sandboxpolicy/igbackend/privilege_native.go +++ b/pkg/sandboxpolicy/igbackend/privilege_native.go @@ -88,8 +88,9 @@ type nativeNodeInstance struct { faults bool // slotGate, when set, refuses a slot that cannot protect now (for file: // an enforcing slot without an attested root barrier). Bind refuses the - // slot and SlotHealth reports it. - slotGate func(slot uint32) error + // slot and SlotHealth reports it. strict is the class of the binding or + // slot: a PendingSlot binding carries its own (enforcement.ClassOf). + slotGate func(slot uint32, strict bool) error // strict reports a Strict slot (nil: none): a node tracking fault also // fails its health. strict func(slot uint32) bool @@ -332,7 +333,7 @@ func (i *nativeNodeInstance) Ready() error { return fmt.Errorf("%s instance not ready: %w", i.section, err) } // A nearly full credential record will soon refuse new credentials of - // Strict bindings (ENOMEM). + // Strict bindings (EPERM). if err := i.bindings.CredRecordHealth(); err != nil { return fmt.Errorf("%s instance not ready: %w", i.section, err) } @@ -356,7 +357,7 @@ func (i *nativeNodeInstance) VerdictCounters() (enforcement.VerdictCounters, err // Degraded notice (rates.go), and a lost Audit judgement never blocks. func (i *nativeNodeInstance) SlotHealth(slot uint32) error { if i.slotGate != nil { - if err := i.slotGate(slot); err != nil { + if err := i.slotGate(slot, i.bindings.Strict(slot)); err != nil { return err } } @@ -401,7 +402,7 @@ func (i *nativeNodeInstance) IoUringHeld(cgroup uint64) bool { func (i *nativeNodeInstance) Bind(b enforcement.Binding) error { if i.slotGate != nil { - if err := i.slotGate(b.Slot); err != nil { + if err := i.slotGate(b.Slot, i.bindings.ClassOf(b)); err != nil { return fmt.Errorf("%s slot %d refused: %w", i.section, b.Slot, err) } } diff --git a/pkg/sandboxpolicy/igbackend/slotgate_test.go b/pkg/sandboxpolicy/igbackend/slotgate_test.go index 993c97886e..752ba444f1 100644 --- a/pkg/sandboxpolicy/igbackend/slotgate_test.go +++ b/pkg/sandboxpolicy/igbackend/slotgate_test.go @@ -10,18 +10,48 @@ import ( // A gated slot (for file: an enforcing slot without an attested root // barrier) is refused at Bind and reported by SlotHealth; other slots are not -// affected. +// affected. The gate gets the class of the binding: a PendingSlot binding +// carries its own (Binding.Strict), since Strict(PendingSlot) is the +// configured class of a slot that does not exist. func TestNodeInstanceSlotGate(t *testing.T) { - i := &nativeNodeInstance{section: "file", slotGate: func(slot uint32) error { - if slot == 1 { + // Not started: Bind past the gate fails with "not running", which is + // not a gate refusal. Slot 1 is Strict. + bindings, err := enforcement.New(enforcement.Config{Name: "gate", Generation: 1, Slots: 2, PolicyMap: "policy", + WritePolicy: func(enforcement.Map) error { return nil }, StrictSlot: func(slot uint32) bool { return slot == 1 }}) + if err != nil { + t.Fatal(err) + } + var gotStrict []bool + i := &nativeNodeInstance{section: "file", bindings: bindings, slotGate: func(_ uint32, strict bool) error { + gotStrict = append(gotStrict, strict) + if strict { return fmt.Errorf("root barrier: no live LSM link") } return nil }} - // bindings is nil: a refused Bind must return before it is used. - err := i.Bind(enforcement.Binding{Slot: 1}) - if err == nil || !strings.Contains(err.Error(), "file slot 1 refused: root barrier") { - t.Fatalf("Bind of a gated slot: %v", err) + pod := enforcement.ContainerIdentity{Runtime: "kubernetes-pod", ID: "uid-1", CgroupID: 7, CgroupPath: "/kubepods.slice/pod-uid-1"} + tests := []struct { + name string + binding enforcement.Binding + strict bool + }{ + {name: "Strict slot", binding: enforcement.Binding{Container: pod, Slot: 1}, strict: true}, + {name: "Audit slot", binding: enforcement.Binding{Container: pod, Slot: 0}, strict: false}, + {name: "Strict pending", binding: enforcement.Binding{Container: pod, Slot: enforcement.PendingSlot, Strict: true}, strict: true}, + {name: "Audit pending", binding: enforcement.Binding{Container: pod, Slot: enforcement.PendingSlot}, strict: false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gotStrict = nil + err := i.Bind(tt.binding) + if len(gotStrict) != 1 || gotStrict[0] != tt.strict { + t.Fatalf("the gate got class %v, want [%v]", gotStrict, tt.strict) + } + refused := err != nil && strings.Contains(err.Error(), fmt.Sprintf("file slot %d refused: root barrier", tt.binding.Slot)) + if refused != tt.strict { + t.Fatalf("Bind: refused %v, want %v (%v)", refused, tt.strict, err) + } + }) } if err := i.SlotHealth(1); err == nil { t.Fatal("SlotHealth of a gated slot is nil") From 29704a31a5578e7b7ff43d3e47e32b0a2621f0b3 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Thu, 3 Dec 2026 18:13:15 +0100 Subject: [PATCH 02/21] fix(sandboxpolicy): rotate the privilege and file section image pins This slice returns EPERM instead of ENOMEM for a Strict tracking fault in the privilege and file gadgets, so their manifests changed. Rebuilt with IG v0.57.0, SOURCE_DATE_EPOCH=0 and the section Makefiles' build line; a build of main 39414b7e with the same setup reproduces main's six pins. Network is unchanged. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- pkg/sandboxpolicy/igbackend/section_images.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pkg/sandboxpolicy/igbackend/section_images.go b/pkg/sandboxpolicy/igbackend/section_images.go index 00bf2b3ca1..4bd209adab 100644 --- a/pkg/sandboxpolicy/igbackend/section_images.go +++ b/pkg/sandboxpolicy/igbackend/section_images.go @@ -24,16 +24,16 @@ import ( // when its gadget changes. An architecture without a pin is refused. var sectionManifests = map[string]map[string]string{ sandboxpolicy.SectionPrivilege: { - "amd64": "sha256:a22d4922017cd95556b222cabc6de9838db957683a24019c3a7f3b9cefb6fc6c", - "arm64": "sha256:d6cabc5dd71398c21d71f6d6bd306785a15918ed37b38278e031f39d1308e111", + "amd64": "sha256:1f224f0a75bfc5f2c8e1fcbd40c22f1bc66cf4296a1be6cd12581a43017afc5c", + "arm64": "sha256:5ea7c8b6b6fc7235b7a151eaa2d35a558eb4dbc0fd5304db75fdbd145391696e", }, sandboxpolicy.SectionNetwork: { "amd64": "sha256:0104faebaa04f7ff8ecf5279c5119ccc8a731d5bd689596861bd937db91b15c2", "arm64": "sha256:cb0e59a89ce473bbaab69368280efa10fbaa49cc85c861510fabf92e3f4873c6", }, sandboxpolicy.SectionFile: { - "amd64": "sha256:710b9c35fd19a43e3752353e84c7d2928f100182d87ff7a59f0f5612e4835823", - "arm64": "sha256:ceeb06df226c83cb72f29a23121ef37e500a02f6ed552f95d256d056f78d95f0", + "amd64": "sha256:b4456c427769eceb0f942591a17edb3e3f4e290ce40db59f3f09dd00ebae1cd5", + "arm64": "sha256:7211aa274d9717a2aca828005dcc2808ffd0852a4ab8edf262e3f4fe37efa295", }, } From e30b1eb1210c9abc22e1b1d9646a824a3b3e5ea6 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Thu, 3 Dec 2026 21:17:09 +0100 Subject: [PATCH 03/21] fix(enforcement): arm on a SkipArming hand-over; refuse a Strict pending start on a failed barrier - Bindings.bind: a same-value bind that goes from SkipArming to an arming binding no longer takes the fast path, so its tasks are armed and checked for io_uring rings; a ring found on that hand-over marks the new binding unconfirmed (the SkipArming previous one is not checkable). - enforce_file instance.Ready: a failed root-barrier attestation refuses activation for a Strict PendingSlot initial binding too. Addresses Copilot review on #1160 (r4790452518, r4790452606). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 8 +++- .../common/enforcement/pending_test.go | 43 +++++++++++++++++++ .../gadgets/enforce_file/runtime/runtime.go | 5 ++- .../enforce_file/runtime/runtime_test.go | 16 +++++++ 4 files changed, 68 insertions(+), 4 deletions(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index 7e8de64ea2..b732bb8303 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -509,8 +509,10 @@ func (b *Bindings) bind(c Binding) error { return fmt.Errorf("cgroup identity conflicts with active binding") } // A Strict binding that is unconfirmed binds again, so the walk can - // confirm it (a refresh re-binds the same value). + // confirm it (a refresh re-binds the same value). A SkipArming binding + // that becomes one that arms binds again too: its tasks were never armed. if bound && b.value(previous) == b.value(c) && !b.unarmed[id.CgroupID] && + (!previous.SkipArming || c.SkipArming) && !(b.ringUnconfirmed[id.CgroupID] && b.classOf(c) && b.checkable(c)) { return nil } @@ -556,7 +558,9 @@ func (b *Bindings) bind(c Binding) error { // armed (arm armed the tasks before the ring check) and // unconfirmed, as a heal keeps it (healArm). Not a failure: // the caller commits and reports ProtectionUnconfirmed. - b.markUnchecked(id.CgroupID, previous, b.classOf(previous), false) + // c, not previous: a SkipArming previous binding is not + // checkable, yet c armed and found the ring. + b.markUnchecked(id.CgroupID, c, b.classOf(previous), false) delete(b.unarmed, id.CgroupID) delete(b.ioUringAudit, id.CgroupID) // a Strict entry return nil diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index d72609bf3f..b6d7254fa6 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -5,6 +5,7 @@ package enforcement import ( "errors" + "fmt" "strings" "testing" @@ -440,3 +441,45 @@ func TestPendingSlotHasNoCounters(t *testing.T) { t.Fatal("Counters(PendingSlot) must be an error, not zero counts") } } + +// A same-value hand-over from a SkipArming binding to one that arms walks the +// cgroup: the tasks the mark left unarmed are armed and their io_uring rings +// checked. A held ring leaves the Strict binding unconfirmed, never confirmed. +func TestRebindFromSkipArmingArms(t *testing.T) { + for _, ring := range []bool{false, true} { + t.Run(fmt.Sprintf("ring held %v", ring), func(t *testing.T) { + f := newPublishFixture(t) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + var armedPaths []string + f.b.armExisting = func(_ Map, path string) error { armedPaths = append(armedPaths, path); return nil } + walks := 0 + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { walks++; return ring, nil } + mark := pendingMark(true) + mark.SkipArming = true + if err := f.b.Bind(mark); err != nil || len(armedPaths) != 0 || walks != 0 { + t.Fatalf("a SkipArming mark arms nothing: %v %v %d", err, armedPaths, walks) + } + next := pendingMark(true) + next.Container = containerInParent + if err := f.b.Rebind(parentIdentity, next); err != nil { + t.Fatal(err) + } + if len(armedPaths) != 1 || armedPaths[0] != parentIdentity.CgroupPath || walks != 1 { + t.Fatalf("the hand-over must arm and walk the cgroup: %v %d", armedPaths, walks) + } + if c := f.b.active[parentIdentity.CgroupID]; c != next { + t.Fatalf("active binding %+v, want %+v", c, next) + } + if got := f.b.RingUnconfirmed(PendingSlot); got != map[bool]int{false: 0, true: 1}[ring] { + t.Fatalf("RingUnconfirmed = %d with ring held %v", got, ring) + } + // A further identical bind walks only while the ring keeps it unconfirmed. + if err := f.b.Bind(next); err != nil { + t.Fatal(err) + } + if want := map[bool]int{false: 1, true: 2}[ring]; walks != want { + t.Fatalf("walks after a refresh = %d, want %d", walks, want) + } + }) + } +} diff --git a/pkg/ebpf/gadgets/enforce_file/runtime/runtime.go b/pkg/ebpf/gadgets/enforce_file/runtime/runtime.go index 483470b100..55795ee5a1 100644 --- a/pkg/ebpf/gadgets/enforce_file/runtime/runtime.go +++ b/pkg/ebpf/gadgets/enforce_file/runtime/runtime.go @@ -442,7 +442,7 @@ type instance struct { // Ready attests the root barrier, then completes the binding controller. A // failed attestation refuses activation when an initial binding is on an -// enforcing slot. Otherwise the instance starts, and Barrier.Err reports the +// enforcing slot or is a Strict pending binding. Otherwise the instance starts, and Barrier.Err reports the // failure: the owner then refuses bindings to enforcing slots. func (i *instance) Ready(gc operators.GadgetContext) error { var value any @@ -460,7 +460,8 @@ func (i *instance) Ready(gc operators.GadgetContext) error { if err != nil { err = fmt.Errorf("root barrier: %w", err) for _, b := range i.initial { - if Enforcing(i.policy, b.Slot) { + // A pending binding has no slot: its class is its own. + if (b.Slot == enforcement.PendingSlot && b.Strict) || Enforcing(i.policy, b.Slot) { return err } } diff --git a/pkg/ebpf/gadgets/enforce_file/runtime/runtime_test.go b/pkg/ebpf/gadgets/enforce_file/runtime/runtime_test.go index 8df0090bca..73d16c61b8 100644 --- a/pkg/ebpf/gadgets/enforce_file/runtime/runtime_test.go +++ b/pkg/ebpf/gadgets/enforce_file/runtime/runtime_test.go @@ -260,6 +260,22 @@ func TestReadyRootBarrier(t *testing.T) { t.Fatalf("audit-only initial binding: want the barrier error kept, got %v", err) } + // A pending initial binding has no slot to take its class from: a + // Strict one refuses activation like an enforcing slot, an Audit one + // does not. + for _, strict := range []bool{true, false} { + i = newInstance(t, 1) + i.initial = []enforcement.Binding{{Slot: enforcement.PendingSlot, Strict: strict, Container: enforcement.ContainerIdentity{ + Runtime: "docker", ID: "pending", CgroupID: 200, CgroupPath: "/pending"}}} + err := i.Ready(nil) + if strict && (err == nil || !strings.Contains(err.Error(), "no live LSM link")) { + t.Fatalf("Strict pending initial binding: want the barrier error, got %v", err) + } + if !strict && (err == nil || err.Error() != notRunning) { + t.Fatalf("Audit pending initial binding: Ready must go on to the controller, got %v", err) + } + } + verifyBarrier = func(operators.GadgetContext, []rootbarrier.Hook) error { return nil } i = newInstance(t, 0) if err := i.Ready(nil); err == nil || err.Error() != notRunning { From 8b606842ab76b9ae431daec1650d7bc4b8065cfc Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Thu, 3 Dec 2026 23:21:17 +0100 Subject: [PATCH 04/21] test(enforce_privilege): enter the cgroup after unsharing, as runc exec does IG's root barrier (inspektor-gadget 42f1d9b6, in the pinned c5f01340) covers tasks in a cgroup with an active Strict exec route and refuses unshare(CLONE_NEWNS) and CLONE_NEWNS clones there, counted in root_barrier_counters. The unarmed-exec fixture cloned straight into the bound cgroup and unshared there, so it never reached execve and no gadget counted the refusal. - cloneHelper "enter" unshares the mount namespace in the host cgroup, moves itself into the bound cgroup and execs; the unarmed-exec round uses it. Both attach orders still require the refusing gadget to count the refusal; a moved OpUnshareNS counter or a setup failure is a fixture error. - A new round pins the barrier: the old start fails with EPERM, counted in OpUnshareNS, with no privilege or enforce_exec exec counter moving. - TestTaskAllocWithSharedExec: under an exec Enforce route the barrier refuses the CLONE_NEWNS clone (EPERM, OpCloneNS, no TASK); a barrier denial must park one birth fewer than the plain round. VM: privilege-exec-refusal 16/16 on al2023-k618, al2023-k612, debian13. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../runtime/exec_coexist_kernel_test.go | 161 ++++++++++++++---- 1 file changed, 129 insertions(+), 32 deletions(-) diff --git a/pkg/ebpf/gadgets/enforce_privilege/runtime/exec_coexist_kernel_test.go b/pkg/ebpf/gadgets/enforce_privilege/runtime/exec_coexist_kernel_test.go index 2187868448..390e64d10a 100644 --- a/pkg/ebpf/gadgets/enforce_privilege/runtime/exec_coexist_kernel_test.go +++ b/pkg/ebpf/gadgets/enforce_privilege/runtime/exec_coexist_kernel_test.go @@ -40,6 +40,7 @@ import ( "github.com/cilium/ebpf" "github.com/cilium/ebpf/rlimit" + igrootbarrier "github.com/inspektor-gadget/inspektor-gadget/gadgets/common/rootbarrier" "github.com/inspektor-gadget/inspektor-gadget/gadgets/enforce_exec/fullpolicy" "github.com/inspektor-gadget/inspektor-gadget/gadgets/enforce_exec/fullruntime" gadgetcontext "github.com/inspektor-gadget/inspektor-gadget/pkg/gadget-context" @@ -68,8 +69,16 @@ var execProfile = fullruntime.SharedProfile{ // cloneHelper forks once with raw clone(2), with CLONE_NEWNS when its // argument is "newns". It exits with the clone errno, 0 when the child ran. +// +// "enter " enters a cgroup the way a runtime exec does +// (runc exec joins the mount namespace, then the cgroup): it unshares its +// mount namespace while still outside the cgroup (where the root barrier of +// a Strict route does not cover it), moves itself into the cgroup, and +// execs path ("plain"). It exits 200 or 201 when the unshare or the move +// fails, else with the exec errno (0 when the exec ran and path exited 0). const cloneHelper = `#define _GNU_SOURCE #include +#include #include #include #include @@ -77,6 +86,16 @@ const cloneHelper = `#define _GNU_SOURCE #include #include int main(int argc, char **argv) { + if (argc > 3 && !strcmp(argv[1], "enter")) { + if (unshare(CLONE_NEWNS)) + return 200; + int fd = open(argv[2], O_WRONLY | O_CLOEXEC); + if (fd < 0 || write(fd, "0", 1) != 1) + return 201; + close(fd); + execl(argv[3], argv[3], "plain", (char *)0); + return errno; + } unsigned long flags = SIGCHLD; if (argc > 1 && !strcmp(argv[1], "newns")) flags |= CLONE_NEWNS; @@ -135,6 +154,14 @@ func TestTaskAllocWithSharedExec(t *testing.T) { return } t.Logf("the shared node built a TASK for the denied fork before the privilege deny: privilege first %v, privilege last %v", ran[true], ran[false]) + // A Strict exec route: the root barrier refuses the clone + // before the shared node claims a birth, in both orders. + if execMode == fullpolicy.Enforce { + if ran[true] || ran[false] { + t.Fatalf("the shared node built a TASK for a clone its root barrier refuses: privilege first %v, privilege last %v", ran[true], ran[false]) + } + return + } if ran[true] == ran[false] { t.Fatalf("the shared node built a TASK for the denied fork in %v of both orders; want exactly one order", ran[true]) } @@ -216,35 +243,61 @@ func (c coexistCase) run(t *testing.T) bool { if v := f.cloneVerdicts(0); len(v) != 0 { t.Fatalf("plain fork: privilege verdicts %v, want none", v) } + // A Strict exec route covers the init with enforce_exec's root barrier, + // which refuses a CLONE_NEWNS clone (EPERM, counted in + // root_barrier_counters) in the shared node's task_alloc program, before + // it claims a birth. The barrier runs only when that program runs before + // this gadget's (privilege attached first), or after this gadget allowed + // the clone (Audit). + barrier := c.execMode == fullpolicy.Enforce + barrierBefore := n.barrierDenials(t, igrootbarrier.OpCloneNS) code, denied := round("CLONE_NEWNS fork", "newns") - want := 0 + barrierAfter := n.barrierDenials(t, igrootbarrier.OpCloneNS) + want, wantBarrier, wantVerdicts := 0, false, 1 if c.privMode == "enforce" { want = int(unix.EPERM) } + if barrier && (c.privilegeFirst || c.privMode != "enforce") { + want, wantBarrier = int(unix.EPERM), true + } + if barrier && c.privilegeFirst { + // The barrier refused the clone first: this gadget never judged it. + wantVerdicts = 0 + } + t.Logf("CLONE_NEWNS fork: exit %d, root barrier clone denials %d -> %d", code, barrierBefore, barrierAfter) if code != want { - t.Fatalf("CLONE_NEWNS fork: exit %d, want %d (privilege %s)", code, want, c.privMode) + t.Fatalf("CLONE_NEWNS fork: exit %d, want %d (exec %s, privilege %s)", code, want, c.execMode, c.privMode) + } + if (barrierAfter > barrierBefore) != wantBarrier { + t.Fatalf("CLONE_NEWNS fork: root barrier clone denials %d -> %d, want a denial %v", barrierBefore, barrierAfter, wantBarrier) } // The verdict shows that this gadget judged the fork, in both modes: - // an EPERM alone could also come from the shared node. - if v := f.cloneVerdicts(1); len(v) != 1 { - t.Fatalf("CLONE_NEWNS fork: privilege task_alloc verdicts %v, want exactly one", v) + // an EPERM alone could also come from the shared node. Wait for one + // even when none is wanted, so that a late verdict is seen. + if v := f.cloneVerdicts(max(wantVerdicts, 1)); len(v) != wantVerdicts { + t.Fatalf("CLONE_NEWNS fork: privilege task_alloc verdicts %v, want exactly %d", v, wantVerdicts) } if code, _ := round("next plain fork", "plain"); code != 0 { t.Fatalf("next plain fork: exit %d, want 0", code) } - if v := f.cloneVerdicts(1); len(v) != 1 { - t.Fatalf("after the next plain fork: privilege task_alloc verdicts %v, want still one", v) + if v := f.cloneVerdicts(max(wantVerdicts, 1)); len(v) != wantVerdicts { + t.Fatalf("after the next plain fork: privilege task_alloc verdicts %v, want still %d", v, wantVerdicts) } // The plain and the denied round differ only in the clone flag: the // denied round parks as many births when the shared node ran for the // denied fork, one fewer when this gadget denied it first. switch { case denied.Parked == control.Parked: + if wantBarrier { + // The barrier refuses the clone before the shared node parks + // its birth: an equal count means a birth was parked first. + t.Fatalf("the root barrier denied the fork, but the denied round parked as many births as the plain one: %+v vs %+v", denied, control) + } if c.privMode == "enforce" && (denied.Taken != denied.Parked || denied.Abandoned != 0) { t.Fatalf("the shared node ran for the denied fork but did not build its TASK: %+v", denied) } return c.privMode == "enforce" - case denied.Parked+1 == control.Parked && c.privMode == "enforce": + case denied.Parked+1 == control.Parked && (c.privMode == "enforce" || barrier): return false } t.Fatalf("the denied fork parked %d births, the plain fork %d", denied.Parked, control.Parked) @@ -416,6 +469,21 @@ func (n *sharedExec) failClosedCell(t *testing.T, cell int) uint64 { return v } +// barrierDenials reads the denials of one root barrier operation in the +// shared node's root_barrier_counters (a per-CPU array: summed). +func (n *sharedExec) barrierDenials(t *testing.T, op igrootbarrier.Op) uint64 { + t.Helper() + var perCPU []uint64 + if err := n.mapOf(t, igrootbarrier.CountersMap).Lookup(uint32(op), &perCPU); err != nil { + t.Fatalf("root barrier counter %s: %v", op, err) + } + var sum uint64 + for _, v := range perCPU { + sum += v + } + return sum +} + func (n *sharedExec) park(t *testing.T) fullruntime.SharedBirthParkHealth { t.Helper() h, err := n.node.BirthParkHealth() @@ -480,9 +548,10 @@ func (n *sharedExec) round(t *testing.T, label string, tasks, works uint32, acti // shared node, where this gadget refuses an exec in bprm_check_security // (-EPERM: every exec mark fails, Strict) after enforce_exec may have built // its exec state, in both attach orders; and where enforce_exec itself denies -// an exec. Every round keeps the shared node's invariants (TASK/WORK credits, -// birth park, capsule faults, fail-closed witness). Requirements as in -// TestTaskAllocWithSharedExec. +// an exec; and where enforce_exec's root barrier refuses a new mount +// namespace inside the Strict route before any exec. Every round keeps the +// shared node's invariants (TASK/WORK credits, birth park, capsule faults, +// fail-closed witness). Requirements as in TestTaskAllocWithSharedExec. func TestExecRefusalWithSharedExec(t *testing.T) { if os.Getenv("PRIVILEGE_KERNEL_TEST") != "1" { t.Skip("explicit disposable kernel fixture opt-in required") @@ -577,51 +646,79 @@ func execRefusalRound(t *testing.T, object, cgroup, helper string, privilegeFirs // A task that enters the cgroup unarmed (its own mount namespace, like a // runtime exec) needs an exec mark: this gadget refuses its exec under // Strict. enforce_exec may refuse it first in one attach order; either - // way the exec fails and nothing leaks. + // way the exec fails and nothing leaks. The helper unshares its mount + // namespace before it moves into the cgroup, as runc exec does: inside a + // Strict route, enforce_exec's root barrier refuses the unshare itself, + // and the exec would never run (the barrier round below). before, err := f.bindings.Counters(0) if err != nil { t.Fatal(err) } execBefore := n.entryRefusals(t) admBefore := n.failClosedCell(t, fullruntime.FailClosedRateAdmission) - var startErr error + unshareBefore := n.barrierDenials(t, igrootbarrier.OpUnshareNS) code, _ := n.round(t, "unarmed exec", tasks, works, func() int { - dir, err := os.Open(cgroup) - if err != nil { - t.Fatal(err) - } - defer dir.Close() - cmd := exec.Command(helper, "plain") - cmd.SysProcAttr = &syscall.SysProcAttr{Unshareflags: syscall.CLONE_NEWNS, UseCgroupFD: true, CgroupFD: int(dir.Fd())} - if startErr = cmd.Start(); startErr != nil { - return 1 - } - _ = cmd.Wait() + cmd := exec.Command(helper, "enter", filepath.Join(cgroup, "cgroup.procs"), helper) + _ = cmd.Run() return cmd.ProcessState.ExitCode() }) - if code == 0 || startErr == nil { - t.Fatalf("unarmed exec under a Strict slot whose exec marks fail: exit %d (%v), want a refused exec", code, startErr) - } after, err := f.bindings.Counters(0) if err != nil { t.Fatal(err) } execAfter := n.entryRefusals(t) admAfter := n.failClosedCell(t, fullruntime.FailClosedRateAdmission) - t.Logf("unarmed exec refused: %v; privilege faults %d -> %d; enforce_exec ENTRY refusals %d -> %d, ADMISSION %d -> %d", startErr, before.Faults, after.Faults, execBefore, execAfter, admBefore, admAfter) + unshareAfter := n.barrierDenials(t, igrootbarrier.OpUnshareNS) + t.Logf("unarmed exec: exit %d; privilege faults %d -> %d; enforce_exec ENTRY refusals %d -> %d, ADMISSION %d -> %d; root barrier unshare denials %d -> %d", + code, before.Faults, after.Faults, execBefore, execAfter, admBefore, admAfter, unshareBefore, unshareAfter) + if code == 200 || code == 201 || unshareAfter != unshareBefore { + t.Fatalf("fixture error: the unarmed task did not reach its exec (exit %d, root barrier unshare denials %d -> %d)", code, unshareBefore, unshareAfter) + } // Both gadgets refuse with EPERM, so the errno does not tell which one // decided: the attach order does. The newest link runs first and the // kernel stops at the first nonzero return. if !privilegeFirst { // This gadget is the newest link: it refuses the exec itself. - if !errors.Is(startErr, syscall.EPERM) || after.Faults <= before.Faults { - t.Fatalf("attached last, this gadget must refuse the exec (EPERM) and count a fault: %v, %+v -> %+v", startErr, before, after) + if code != int(syscall.EPERM) || after.Faults <= before.Faults { + t.Fatalf("attached last, this gadget must refuse the exec (EPERM) and count a fault: exit %d, %+v -> %+v", code, before, after) } - } else if !errors.Is(startErr, syscall.EPERM) || (after.Faults <= before.Faults && execAfter <= execBefore) { + } else if code != int(syscall.EPERM) || (after.Faults <= before.Faults && execAfter <= execBefore) { // enforce_exec runs first: either it refused the exec (EPERM, // counted in its live ENTRY cell), or it allowed it and this gadget // refused it (EPERM, a fault). - t.Fatalf("the refused exec must fail with EPERM and be counted by one gadget: %v; privilege %+v -> %+v, enforce_exec ENTRY %d -> %d", startErr, before, after, execBefore, execAfter) + t.Fatalf("the refused exec must fail with EPERM and be counted by one gadget: exit %d; privilege %+v -> %+v, enforce_exec ENTRY %d -> %d", code, before, after, execBefore, execAfter) + } + // Inside the Strict route, a new mount namespace is refused before any + // exec: enforce_exec's root barrier denies the unshare(CLONE_NEWNS) of a + // task started in the cgroup (clone3 CLONE_INTO_CGROUP; Go unshares in + // the child) and counts it in root_barrier_counters. No exec hook runs, + // so neither this gadget nor enforce_exec's exec verdict counts it. + before, execBefore, unshareBefore = after, execAfter, unshareAfter + var startErr error + n.round(t, "unshare in the Strict route", tasks, works, func() int { + dir, err := os.Open(cgroup) + if err != nil { + t.Fatal(err) + } + defer dir.Close() + cmd := exec.Command(helper, "plain") + cmd.SysProcAttr = &syscall.SysProcAttr{Unshareflags: syscall.CLONE_NEWNS, UseCgroupFD: true, CgroupFD: int(dir.Fd())} + if startErr = cmd.Start(); startErr != nil { + return 1 + } + _ = cmd.Wait() + return cmd.ProcessState.ExitCode() + }) + if after, err = f.bindings.Counters(0); err != nil { + t.Fatal(err) + } + execAfter = n.entryRefusals(t) + unshareAfter = n.barrierDenials(t, igrootbarrier.OpUnshareNS) + t.Logf("unshare in the Strict route: %v; root barrier unshare denials %d -> %d; privilege %+v -> %+v; enforce_exec ENTRY %d -> %d", + startErr, unshareBefore, unshareAfter, before, after, execBefore, execAfter) + if !errors.Is(startErr, syscall.EPERM) || unshareAfter <= unshareBefore || after.Faults != before.Faults || after.Attempts != before.Attempts || execAfter != execBefore { + t.Fatalf("the root barrier must refuse the unshare (EPERM) and count it, with no exec verdict: %v; root barrier unshare denials %d -> %d; privilege %+v -> %+v; enforce_exec ENTRY %d -> %d", + startErr, unshareBefore, unshareAfter, before, after, execBefore, execAfter) } // enforce_exec denies an exec of uid 1000 (EPERM; a missing permission // would be EACCES); this gadget does not judge it (the armed init's child From d96378d2719d8bcd773056caf7297a922cc214d8 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Thu, 3 Dec 2026 23:33:28 +0100 Subject: [PATCH 05/21] feat(sandboxpolicy): Plan.GateStrict carries a section's Strict pending class An Audit policy with an enforce rule or default override is Strict for the start gate (S4), but the backend derived a pod mark's pending class only from the policy mode. GateStrict names the sections whose pending class is Strict; it is excluded from JSON, the revision and the combination keys, and policy slots keep the policy mode. Callers follow in S2 (backend), S4 (PodPlansAt) and S3 (gate plans). For Copilot review on #1165 (r4792384813). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- pkg/sandboxpolicy/types.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pkg/sandboxpolicy/types.go b/pkg/sandboxpolicy/types.go index f17497b0ed..9e7b5fbc80 100644 --- a/pkg/sandboxpolicy/types.go +++ b/pkg/sandboxpolicy/types.go @@ -141,6 +141,12 @@ type CompiledPolicy struct { type Plan struct { Revision string `json:"revision"` Policies []CompiledPolicy `json:"policies"` + // GateStrict names the sections whose start-gate pending class is + // Strict although no policy of the plan is in enforce mode (an Audit + // policy with an enforce rule or default override). A pod mark or pod + // binding uses it for its pending class only; policy slots and rates + // keep the policy mode. Not part of the revision or combination keys. + GateStrict map[string]bool `json:"-"` } // ReplaceResult distinguishes a failed candidate from a committed candidate whose From a0ca2db24a6289679324f92745df802bc8156378 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 07:17:46 +0100 Subject: [PATCH 06/21] fix(enforcement): a held-ring Bind records the new binding as active A direct Bind that turned a same-value Strict binding from SkipArming to armed and then found a held io_uring ring returned success but kept the old SkipArming binding in active, so every later heal returned ErrNotHealable even after the ring closed. Record the new binding before returning; it stays unconfirmed until a later walk finds no ring. Addresses Copilot review on #1160 (comment 4792446677). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 2 + .../common/enforcement/pending_test.go | 39 +++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index b732bb8303..e452757756 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -563,6 +563,8 @@ func (b *Bindings) bind(c Binding) error { b.markUnchecked(id.CgroupID, c, b.classOf(previous), false) delete(b.unarmed, id.CgroupID) delete(b.ioUringAudit, id.CgroupID) // a Strict entry + // c armed: a heal arms it and checks the ring again. + b.active[id.CgroupID] = c return nil } if bound && !errors.Is(err, ErrContainerGone) { diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index b6d7254fa6..7af6a6acde 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -483,3 +483,42 @@ func TestRebindFromSkipArmingArms(t *testing.T) { }) } } + +// A direct Bind that turns a same-value Strict SkipArming binding into one +// that arms, and finds a held ring, records the new binding: a heal then +// arms it and, once the ring is closed, confirms it. +func TestBindFromSkipArmingRingHeldHeals(t *testing.T) { + f := newPublishFixture(t) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.witness = fakeWitness{0: 2} + walks, ring := 0, true + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { walks++; return ring, nil } + mark := pendingMark(true) + mark.SkipArming = true + if err := f.b.Bind(mark); err != nil { + t.Fatal(err) + } + next := pendingMark(true) + if err := f.b.Bind(next); err != nil { + t.Fatal(err) + } + if walks != 1 || f.b.RingUnconfirmed(PendingSlot) != 1 { + t.Fatalf("the bind must walk and stay unconfirmed: walks %d, unconfirmed %d", walks, f.b.RingUnconfirmed(PendingSlot)) + } + if c := f.b.active[parentIdentity.CgroupID]; c != next { + t.Fatalf("active binding %+v, want %+v", c, next) + } + if v := f.members.data[parentIdentity.CgroupID].(bindingValue); v != f.b.value(next) { + t.Fatalf("the Strict entry must stay unchanged and unchecked: %+v", v) + } + ring = false + if err := f.b.HealNode(); err != nil { + t.Fatalf("a heal after the ring closed: %v", err) + } + if walks != 2 || f.b.RingUnconfirmed(PendingSlot) != 0 || f.b.nodeFaultBase != 2 { + t.Fatalf("the heal must check and confirm: walks %d, unconfirmed %d, base %d", walks, f.b.RingUnconfirmed(PendingSlot), f.b.nodeFaultBase) + } + if v := f.members.data[parentIdentity.CgroupID].(bindingValue); v.Flags&bindingRingChecked == 0 { + t.Fatalf("a confirmed entry carries bindingRingChecked: %+v", v) + } +} From a9520481d9c86f7e64daf5b820106aa13ddb5864 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 07:33:35 +0100 Subject: [PATCH 07/21] test(enforce_file): fail TestForkMarkFaultErrno in CI without its helper A CI run without FILE_HELPER_BINARY skipped both subtests and passed without checking the fork errno. Fail when CI is set; keep the local skip. Addresses Copilot review on #1160. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/enforce_file/runtime/pending_kernel_test.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pkg/ebpf/gadgets/enforce_file/runtime/pending_kernel_test.go b/pkg/ebpf/gadgets/enforce_file/runtime/pending_kernel_test.go index a2d0fc75cc..76606ae572 100644 --- a/pkg/ebpf/gadgets/enforce_file/runtime/pending_kernel_test.go +++ b/pkg/ebpf/gadgets/enforce_file/runtime/pending_kernel_test.go @@ -22,7 +22,8 @@ import ( // Same fixture and environment as runtime_kernel_test.go. // TestForkMarkFaultErrno needs FILE_HELPER_BINARY with a `fork -` command -// (one fork, the child exits; on failure "fork -: ", exit 1). +// (one fork, the child exits; on failure "fork -: ", exit 1). It +// skips without one, but fails when CI is set. // pinnedBinding reads the kernel entry of a cgroup in the section's pinned // binding map: its slot and flags (struct sandbox_binding, ../../common/bindings.h). @@ -245,6 +246,10 @@ func TestForkMarkFaultErrno(t *testing.T) { t.Run(mode, func(t *testing.T) { f := newKernelFixture(t) if helper == "" { + // A CI run must not pass without checking the errno. + if os.Getenv("CI") != "" { + t.Fatal("FILE_HELPER_BINARY is not set: CI must check the fork errno") + } t.Skip("FILE_HELPER_BINARY is not set") } compiled, err := filepolicy.CompileSlots([][]filepolicy.Document{{labDocument("fork-errno-"+mode, mode)}}, 1) From c6e618d0b2bd15e445c298e975d9b222d38bc431 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 08:11:00 +0100 Subject: [PATCH 08/21] fix(enforcement): a Strict pending binding with unrecorded credentials stays unconfirmed When the credential walk could not record a task of a Strict PendingSlot binding (record full or over quota), the BPF fault counter missed the pending slot (0xFFFFFFFF has no counter) and record ignored the per-task result, so Bind and HealNode returned nil and marked the binding ring-checked with the failure unrecorded. - record returns an error after the full walk when a task of a Strict pending binding was not recorded; Audit pending bindings are unchanged. - Heal and HealNode re-arm every binding, join the errors and skip the fault-base rebase when any binding fails; a confirmed binding with unrecorded credentials becomes unconfirmed again. - An instance start (and recordAdopted) keeps such a binding's Strict entry, unconfirmed and not ring-checked, for a later heal, instead of failing the whole section; other errors still fail the start. Addresses the Copilot review summary on #1160. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 44 ++++++- .../gadgets/common/enforcement/creds_linux.go | 36 +++++- .../common/enforcement/creds_linux_test.go | 23 ++++ .../common/enforcement/pending_test.go | 121 ++++++++++++++++++ pkg/ebpf/gadgets/common/enforcement/slots.go | 27 +++- .../runtime/pending_kernel_test.go | 23 ++++ 6 files changed, 264 insertions(+), 10 deletions(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index e452757756..b23ef6bd0a 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -588,8 +588,11 @@ func (b *Bindings) bind(c Binding) error { adopted.Flags&bindingRingChecked != 0 && !b.credsPurged) return err } - // A container that is gone needs no protection; a startup - // replay skips it (see start). + // A fresh bind (not bound, not adopted) that failed, for any + // 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 { b.keepFailed(c, checked) return errors.Join(err, derr) @@ -730,7 +733,9 @@ func countBindings(m Map) (int, error) { // RingUnconfirmed returns how many Strict bindings of a slot (adopted or // active) may run io_uring requests under credentials the record lacks // (ringUnconfirmed): their protection is unconfirmed until a bind walk finds -// no ring. +// no ring. It also counts a Strict pending binding kept at start or after a +// purge whose walk could not record every task (ErrCredUnrecorded) until a +// walk records them all. func (b *Bindings) RingUnconfirmed(slot uint32) int { b.mu.Lock() defer b.mu.Unlock() @@ -1068,6 +1073,33 @@ func (b *Bindings) SlotFaults(slot uint32) (uint64, error) { return count, nil } +// keepUnrecorded installs a startup binding whose walk armed its tasks but +// could not record all their credentials (ErrCredUnrecorded, a Strict pending +// binding): one binding must not stop the start of the whole section, and +// dropping it would leave its cgroup unprotected. Its kernel entry is +// written without bindingRingChecked (a Strict pending entry denies what it +// judges), it is active, and it is unconfirmed (RingUnconfirmed), so a heal +// walks it again and confirms it once the record has room. A failed write +// fails the start. Called with mu held. +func (b *Bindings) keepUnrecorded(c Binding) error { + id := c.Container.CgroupID + if err := b.members.Put(id, b.kernelValue(c, false)); err != nil { + return fmt.Errorf("keeping an unrecorded Strict pending binding: %w", err) + } + delete(b.adopted, id) + if b.creds != nil { + // A fresh bind's failure path forgot its counter: it counts again. + delete(b.creds.draining, id) + } + b.active[id] = c + delete(b.unarmed, id) + delete(b.ioUringAudit, id) + b.setRingChecked(id, false) + b.ringUnconfirmed[id] = true + b.setCredActive() + return nil +} + // start writes and freezes the policy before any binding is written. func (b *Bindings) start(policy Map, members BindingMap, armed Map, faults, witness FaultMap) error { b.mu.Lock() @@ -1122,7 +1154,11 @@ func (b *Bindings) start(policy Map, members BindingMap, armed Map, faults, witn } } for _, c := range b.desired { - if err := b.bind(c); err != nil && !errors.Is(err, ErrContainerGone) { + err := b.bind(c) + if errors.Is(err, ErrCredUnrecorded) { + err = b.keepUnrecorded(c) + } + if err != nil && !errors.Is(err, ErrContainerGone) { return b.recordError(err) } } diff --git a/pkg/ebpf/gadgets/common/enforcement/creds_linux.go b/pkg/ebpf/gadgets/common/enforcement/creds_linux.go index 890a2b520f..e85a5a56df 100644 --- a/pkg/ebpf/gadgets/common/enforcement/creds_linux.go +++ b/pkg/ebpf/gadgets/common/enforcement/creds_linux.go @@ -68,6 +68,12 @@ type credWalkArgs struct { // retried once the rings are closed. var ErrIoUringHeld = errors.New("the container holds io_uring rings opened before its Strict binding") +// ErrCredUnrecorded: the walk of a Strict PendingSlot binding could not +// record the credentials of some tasks (record full or over quota), and the +// program counted nothing (see pendingRecordFault). The tasks are armed; the +// binding stays unconfirmed until a walk records them all. +var ErrCredUnrecorded = errors.New("credentials of a Strict pending binding not recorded") + // CredConstants returns the native constants of the credential record: // quota, pressure and size (0 keeps the program's defaults), and the number of // possible CPUs for the per-CPU total. The pressure level must be below the @@ -409,8 +415,10 @@ func (r *credRecord) fill() (uint64, error) { // cgroup.threads files of its cgroup and child cgroups, except tasks in the // runtime's mount namespace (as ArmExisting). A record over the binding's // quota or into a full record counts a slot fault (Strict) or an unevaluated -// judgement (Audit) in the program; it is not an error here. +// judgement (Audit) in the program; it is not an error here, except for a +// Strict PendingSlot binding (see pendingRecordFault). func (r *credRecord) record(cgroupID uint64, cgroupPath string, flags, slot uint32) (ring bool, err error) { + unrecorded := 0 delete(r.draining, cgroupID) // bound again: its counter stays hostMntns, err := mntnsOf("1") if err != nil { @@ -460,12 +468,28 @@ func (r *credRecord) record(cgroupID uint64, cgroupPath string, flags, slot uint return fmt.Errorf("recording the credentials of task %d: %w", tid, err) } ring = ring || res&credIoUring != 0 + if pendingRecordFault(res, flags, slot) { + unrecorded++ + } } return scanner.Err() }) + if err == nil && unrecorded > 0 { + // After the whole walk, so the other tasks are recorded. + err = fmt.Errorf("%w: %d tasks (record full or over quota)", ErrCredUnrecorded, unrecorded) + } return ring, err } +// pendingRecordFault reports a walk result whose failed record nothing +// counts: the program counts a Strict binding's failed record as a fault of +// its slot, and PendingSlot has no slot counter. The bind or heal then fails, +// so it never reports a binding whose tasks' credentials are not recorded. +func pendingRecordFault(res, flags, slot uint32) bool { + failed := res&^credIoUring == credFull || res&^credIoUring == credOverQuota + return failed && slot == PendingSlot && flags&bindingStrict != 0 +} + // forget marks the counter of an unbound cgroup for deletion. It stays // until the cgroup's entries are freed (drain), so a rebind before that keeps // counting them. @@ -576,14 +600,18 @@ func (b *Bindings) recordAdopted() error { continue // the cgroup is gone } ring, err := b.creds.record(id, path, v.Flags, v.Slot) - if err != nil && !errors.Is(err, ErrContainerGone) { + unrecorded := errors.Is(err, ErrCredUnrecorded) + if err != nil && !unrecorded && !errors.Is(err, ErrContainerGone) { errs = append(errs, err) } // The purge lost the credentials of requests queued before it: a // Strict adopted binding with rings is unconfirmed until a bind walk // finds no ring. Its entry loses bindingRingChecked, so an instance - // that adopts it next to this one (no purge) checks it again. - if ring && v.Flags&bindingStrict != 0 { + // that adopts it next to this one (no purge) checks it again. An + // adopted Strict pending binding whose tasks the walk could not all + // record stays too (not a start failure: its entry keeps denying), + // unconfirmed the same way. + if (ring || unrecorded) && v.Flags&bindingStrict != 0 { b.ringUnconfirmed[id] = true if v.Flags&bindingRingChecked != 0 { v.Flags &^= bindingRingChecked diff --git a/pkg/ebpf/gadgets/common/enforcement/creds_linux_test.go b/pkg/ebpf/gadgets/common/enforcement/creds_linux_test.go index 242d2cf6fd..6c9fabafb9 100644 --- a/pkg/ebpf/gadgets/common/enforcement/creds_linux_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/creds_linux_test.go @@ -25,3 +25,26 @@ func TestCredConstantsChecksPressureBelowSize(t *testing.T) { } } } + +// A failed walk record of a Strict PendingSlot binding counts nothing in the +// program (no slot counter), so the walk reports it; a real slot counts a +// fault, and an Audit binding never fails. +func TestPendingRecordFault(t *testing.T) { + for _, c := range []struct { + res, flags, slot uint32 + want bool + }{ + {credFull, bindingStrict, PendingSlot, true}, + {credOverQuota, bindingStrict, PendingSlot, true}, + {credFull | credIoUring, bindingStrict | bindingSubtree, PendingSlot, true}, + {credOK, bindingStrict, PendingSlot, false}, + {credGone, bindingStrict, PendingSlot, false}, + {credOK | credIoUring, bindingStrict, PendingSlot, false}, + {credFull, 0, PendingSlot, false}, + {credFull, bindingStrict, 0, false}, + } { + if got := pendingRecordFault(c.res, c.flags, c.slot); got != c.want { + t.Errorf("pendingRecordFault(%#x, %#x, %#x) = %v, want %v", c.res, c.flags, c.slot, got, c.want) + } + } +} diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index 7af6a6acde..62dc27becc 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -522,3 +522,124 @@ func TestBindFromSkipArmingRingHeldHeals(t *testing.T) { t.Fatalf("a confirmed entry carries bindingRingChecked: %+v", v) } } + +// unrecordedAt makes the credential walk of the given cgroups fail as a +// Strict pending walk that cannot record every task does; other walks pass. +func unrecordedAt(b *Bindings, cgroups map[uint64]bool) *int { + walks := 0 + b.recordCreds = func(cgroup uint64, _ string, _, _ uint32) (bool, error) { + walks++ + if cgroups[cgroup] { + return false, fmt.Errorf("%w: 1 tasks", ErrCredUnrecorded) + } + return false, nil + } + return &walks +} + +// A live Bind whose walk leaves credentials unrecorded fails and never marks +// the entry checked: a fresh bind leaves no entry, a move from Audit keeps +// the Audit entry. +func TestBindUnrecordedCredentials(t *testing.T) { + f := newPublishFixture(t) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + unrecordedAt(f.b, map[uint64]bool{parentIdentity.CgroupID: true}) + if err := f.b.Bind(pendingMark(true)); !errors.Is(err, ErrCredUnrecorded) { + t.Fatalf("fresh Strict pending bind: %v", err) + } + if _, ok := f.members.data[parentIdentity.CgroupID]; ok { + t.Fatal("a failed fresh bind leaves no entry") + } + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + if err := f.b.Bind(pendingMark(false)); err != nil { + t.Fatal(err) + } + unrecordedAt(f.b, map[uint64]bool{parentIdentity.CgroupID: true}) + if err := f.b.Bind(pendingMark(true)); !errors.Is(err, ErrCredUnrecorded) { + t.Fatalf("Audit to Strict pending bind: %v", err) + } + if v := f.members.data[parentIdentity.CgroupID].(bindingValue); v.Flags&(bindingStrict|bindingRingChecked) != 0 { + t.Fatalf("the Audit entry stays, never checked: %+v", v) + } +} + +// HealNode arms every binding even when one walk leaves credentials +// unrecorded; it then fails without moving the base, and that binding becomes +// unconfirmed (its entry loses bindingRingChecked). Once the record has room, +// a heal confirms it. +func TestHealNodeUnrecordedCredentials(t *testing.T) { + other := ContainerIdentity{Runtime: "parent", ID: "uid-2", CgroupID: 43, CgroupPath: "/workloads.slice/parent-uid-2"} + for range 8 { // map order varies: the failing binding must not stop the others + f := newPublishFixture(t) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.witness = fakeWitness{0: 2} + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + second := pendingMark(true) + second.Container = other + for _, c := range []Binding{pendingMark(true), second} { + if err := f.b.Bind(c); err != nil { + t.Fatal(err) + } + } + if v := f.members.data[parentIdentity.CgroupID].(bindingValue); v.Flags&bindingRingChecked == 0 { + t.Fatalf("a bind with every credential recorded is checked: %+v", v) + } + armed := map[string]int{} + f.b.armExisting = func(_ Map, path string) error { armed[path]++; return nil } + unrecordedAt(f.b, map[uint64]bool{parentIdentity.CgroupID: true}) + if err := f.b.HealNode(); !errors.Is(err, ErrCredUnrecorded) { + t.Fatalf("HealNode: %v", err) + } + if armed[parentIdentity.CgroupPath] != 1 || armed[other.CgroupPath] != 1 { + t.Fatalf("every binding is armed again: %v", armed) + } + if f.b.nodeFaultBase != 0 || f.b.RingUnconfirmed(PendingSlot) != 1 { + t.Fatalf("no rebase, still unconfirmed: base %d, unconfirmed %d", f.b.nodeFaultBase, f.b.RingUnconfirmed(PendingSlot)) + } + if v := f.members.data[parentIdentity.CgroupID].(bindingValue); v.Flags&bindingRingChecked != 0 { + t.Fatalf("an unrecorded binding is never checked: %+v", v) + } + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + if err := f.b.HealNode(); err != nil || f.b.nodeFaultBase != 2 || f.b.RingUnconfirmed(PendingSlot) != 0 { + t.Fatalf("a heal with room confirms: %v, base %d, unconfirmed %d", err, f.b.nodeFaultBase, f.b.RingUnconfirmed(PendingSlot)) + } + } +} + +// A startup binding whose walk leaves credentials unrecorded does not stop +// the start: its Strict pending entry is written (it keeps denying), without +// bindingRingChecked, active and unconfirmed, so a heal walks it again. +// Another error still fails the start. +func TestStartKeepsUnrecordedPendingBinding(t *testing.T) { + pending := ContainerIdentity{Runtime: "parent", ID: "uid-9", CgroupID: 77, CgroupPath: "/workloads.slice/parent-uid-9"} + mark := Binding{Container: pending, Slot: PendingSlot, Strict: true, Subtree: true, RuntimeHelpers: true} + b, policy, members, _ := newFixture(t, func(Map) error { return nil }) + b.desired[selector(pending)] = mark + b.armExisting = func(Map, string) error { return nil } + unrecordedAt(b, map[uint64]bool{pending.CgroupID: true}) + if err := b.start(policy, members, &fakeMap{typ: ebpf.TaskStorage}, nil, nil); err != nil { + t.Fatalf("start: %v", err) + } + if err := b.Ready(nil); err != nil { + t.Fatalf("Ready: %v", err) + } + if v := members.data[pending.CgroupID].(bindingValue); v != (bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers}) { + t.Fatalf("the Strict pending entry, unchecked: %+v", v) + } + if c := b.active[pending.CgroupID]; c != mark || b.RingUnconfirmed(PendingSlot) != 1 { + t.Fatalf("active %+v, unconfirmed %d", c, b.RingUnconfirmed(PendingSlot)) + } + + b, policy, members, _ = newFixture(t, func(Map) error { return nil }) + b.desired[selector(pending)] = mark + b.armExisting = func(Map, string) error { return nil } + b.recordCreds = func(cgroup uint64, _ string, _, _ uint32) (bool, error) { + if cgroup == pending.CgroupID { + return false, errors.New("listing container tasks: permission denied") + } + return false, nil + } + if err := b.start(policy, members, &fakeMap{typ: ebpf.TaskStorage}, nil, nil); err == nil { + t.Fatal("another walk error still fails the start") + } +} diff --git a/pkg/ebpf/gadgets/common/enforcement/slots.go b/pkg/ebpf/gadgets/common/enforcement/slots.go index b4d1f732ea..58b130b33c 100644 --- a/pkg/ebpf/gadgets/common/enforcement/slots.go +++ b/pkg/ebpf/gadgets/common/enforcement/slots.go @@ -381,6 +381,7 @@ func (b *Bindings) Heal(slot uint32) error { } } skipped := false + var errs []error for _, c := range b.active { if c.Slot != slot { continue @@ -389,10 +390,16 @@ func (b *Bindings) Heal(slot uint32) error { skipped = true continue } + // Every binding is armed again, even after one fails: a failure + // (a pending binding whose credentials stay unrecorded) must not + // leave the others unarmed. The faults then stay counted. if err := b.healArm(c); err != nil && !errors.Is(err, ErrContainerGone) { - return err + errs = append(errs, err) } } + if len(errs) > 0 { + return errors.Join(errs...) + } if skipped { // A binding that never arms covers tasks this heal did not mark: // the faults stay counted. @@ -430,16 +437,21 @@ func (b *Bindings) HealNode() error { } } skipped := false + var errs []error for _, c := range b.active { if !armable(c) { // Node faults concern Strict slots only. skipped = skipped || b.classOf(c) continue } + // As Heal: arm every binding, then report the failures. if err := b.healArm(c); err != nil && !errors.Is(err, ErrContainerGone) { - return err + errs = append(errs, err) } } + if len(errs) > 0 { + return errors.Join(errs...) + } if skipped { return fmt.Errorf("%w: Strict bindings that do not arm", ErrNotHealable) } @@ -463,6 +475,17 @@ func (b *Bindings) healArm(c Binding) error { _ = b.members.Put(id, b.kernelValue(c, true)) // not retried: an adopter checks again case errors.Is(err, ErrIoUringHeld): return nil + case errors.Is(err, ErrCredUnrecorded): + // Tasks whose credentials the record lacks: unconfirmed, and the + // entry loses bindingRingChecked, until a heal walk records them + // all (check above). The heal fails. + b.ringUnconfirmed[id] = true + if b.ringChecked[id] { + b.setRingChecked(id, false) + if perr := b.members.Put(id, b.kernelValue(c, false)); perr != nil { + return errors.Join(err, perr) + } + } } return err } diff --git a/pkg/ebpf/gadgets/enforce_file/runtime/pending_kernel_test.go b/pkg/ebpf/gadgets/enforce_file/runtime/pending_kernel_test.go index 76606ae572..19d49f3477 100644 --- a/pkg/ebpf/gadgets/enforce_file/runtime/pending_kernel_test.go +++ b/pkg/ebpf/gadgets/enforce_file/runtime/pending_kernel_test.go @@ -338,3 +338,26 @@ func TestCredRecordFailureErrno(t *testing.T) { }) } } + +// TestPendingCredRecordFailureBind: the program counts nothing for a failed +// walk record of a PendingSlot binding (no slot counter), so a Strict pending +// Bind whose walk cannot record a task's credentials fails; an Audit one binds. +func TestPendingCredRecordFailureBind(t *testing.T) { + f := newKernelFixture(t) + compiled, err := filepolicy.CompileSlots([][]filepolicy.Document{{labDocument("pending-cred", "enforce")}}, 1) + if err != nil { + t.Fatal(err) + } + f.startExtra(t, compiled, map[string]string{"cred-record-fail": "1"}) + err = f.bindings.Bind(enforcement.Binding{Container: f.container, Slot: enforcement.PendingSlot, Strict: true}) + if err == nil || !strings.Contains(err.Error(), "Strict pending binding") { + f.bindings.Unbind(f.container) + t.Fatalf("a Strict pending bind with unrecorded credentials must fail: %v", err) + } + if err := f.bindings.Bind(enforcement.Binding{Container: f.container, Slot: enforcement.PendingSlot}); err != nil { + t.Fatalf("an Audit pending bind never fails on a record: %v", err) + } + if err := f.bindings.Unbind(f.container); err != nil { + t.Fatal(err) + } +} From 609b68d5d608c33fd6f24bc17a857ddd428a1337 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 08:23:41 +0100 Subject: [PATCH 09/21] fix(enforcement): retry a failed write of a binding's unchecked entry A heal that found unrecorded credentials cleared the local ring-checked state before writing the unchecked value to the pinned map. If that write failed, later heals did not retry it, a held-ring heal reported success, and the pinned entry kept bindingRingChecked for a replacement instance to trust. A per-binding flag now records the owed write; every heal retries it, Heal and HealNode fail and skip the fault-base rebase while it is owed (including on a held ring), and it clears only after a successful write of that binding's entry or its removal. Addresses Copilot review on #1160 (comment 4796700966). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 11 ++++- .../common/enforcement/pending_test.go | 39 ++++++++++++++++++ pkg/ebpf/gadgets/common/enforcement/slots.go | 41 ++++++++++++++++--- 3 files changed, 83 insertions(+), 8 deletions(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index b23ef6bd0a..cfb2cdb7ed 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -256,6 +256,10 @@ type Bindings struct { // change to Strict. // The slot's health fails until a bind walk finds no ring, or an unbind. ringChecked, ringUnconfirmed map[uint64]bool + // uncheckPending: active bindings whose local check was cleared but + // whose kernel entry may still carry bindingRingChecked (the write of + // the unchecked value failed). Every heal writes it again (healArm). + uncheckPending map[uint64]bool // Long-lived instance (WritePolicy nil): see slots.go. slotState Map publish map[string]Map @@ -300,7 +304,7 @@ func New(config Config) (*Bindings, error) { return nil, fmt.Errorf("enforcement controller with a fault map requires the slot class") } b := &Bindings{config: config, desired: map[execpolicy.Container]Binding{}, active: map[uint64]Binding{}, unarmed: map[uint64]bool{}, armExisting: ArmExisting, - slots: map[uint32]*slotRecord{}, now: time.Now, classRetry: map[uint32]bool{}, adopted: map[uint64]bindingValue{}, listBindings: listPinnedBindings, ioUringAudit: map[uint64]bool{}, ringChecked: map[uint64]bool{}, ringUnconfirmed: map[uint64]bool{}} + slots: map[uint32]*slotRecord{}, now: time.Now, classRetry: map[uint32]bool{}, adopted: map[uint64]bindingValue{}, listBindings: listPinnedBindings, ioUringAudit: map[uint64]bool{}, ringChecked: map[uint64]bool{}, ringUnconfirmed: map[uint64]bool{}, uncheckPending: map[uint64]bool{}} for _, c := range config.InitialBindings { if err := b.validate(c); err != nil { return nil, err @@ -543,7 +547,8 @@ func (b *Bindings) bind(c Binding) error { if err := b.members.Put(id.CgroupID, b.kernelValue(c, checked)); err != nil { return fmt.Errorf("writing container binding: %w", err) } - delete(b.adopted, id.CgroupID) // this run owns the entry now + delete(b.uncheckPending, id.CgroupID) // the entry is written as the state holds it + delete(b.adopted, id.CgroupID) // this run owns the entry now walked := false // A slot move arms again too: a task that the old slot left unarmed (an // audit slot allows a fork whose child mark failed) must not escape the @@ -778,6 +783,7 @@ func (b *Bindings) unbind(c ContainerIdentity) error { // forgetCreds drops the io_uring state of a cgroup that is no longer bound and // deletes its credential counter (when the section keeps a record). func (b *Bindings) forgetCreds(cgroup uint64) error { + delete(b.uncheckPending, cgroup) delete(b.ioUringAudit, cgroup) delete(b.ringChecked, cgroup) delete(b.ringUnconfirmed, cgroup) @@ -1086,6 +1092,7 @@ func (b *Bindings) keepUnrecorded(c Binding) error { if err := b.members.Put(id, b.kernelValue(c, false)); err != nil { return fmt.Errorf("keeping an unrecorded Strict pending binding: %w", err) } + delete(b.uncheckPending, id) delete(b.adopted, id) if b.creds != nil { // A fresh bind's failure path forgot its counter: it counts again. diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index 62dc27becc..559f6b676d 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -643,3 +643,42 @@ func TestStartKeepsUnrecordedPendingBinding(t *testing.T) { t.Fatal("another walk error still fails the start") } } + +// A failed write of the unchecked entry stays pending: the pinned entry may +// still carry bindingRingChecked, which a replacement instance would trust. +// Every heal writes it again and fails until the write succeeds, also when +// the walk finds a held ring (a heal that otherwise succeeds). +func TestHealRetriesUncheckedEntryWrite(t *testing.T) { + f := newPublishFixture(t) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.witness = fakeWitness{0: 2} + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + if err := f.b.Bind(pendingMark(true)); err != nil { + t.Fatal(err) + } + entry := func() bindingValue { return f.members.data[parentIdentity.CgroupID].(bindingValue) } + if entry().Flags&bindingRingChecked == 0 { + t.Fatalf("a bind with every credential recorded is checked: %+v", entry()) + } + // The walk leaves credentials unrecorded and the unchecked write fails. + unrecordedAt(f.b, map[uint64]bool{parentIdentity.CgroupID: true}) + f.members.putErr = errors.New("map busy") + if err := f.b.HealNode(); !errors.Is(err, ErrCredUnrecorded) || !strings.Contains(err.Error(), "map busy") { + t.Fatalf("first heal: %v", err) + } + // The ring is now held: the walk alone would let the heal succeed. + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return true, nil } + if err := f.b.HealNode(); err == nil || !strings.Contains(err.Error(), "map busy") || f.b.nodeFaultBase != 0 { + t.Fatalf("a heal with the unchecked write still pending must fail: %v (base %d)", err, f.b.nodeFaultBase) + } + if entry().Flags&bindingRingChecked == 0 { + t.Fatal("fixture: the failed writes must leave the stale flag") + } + f.members.putErr = nil + if err := f.b.HealNode(); err != nil || f.b.nodeFaultBase != 2 { + t.Fatalf("the write succeeds, the held ring keeps the binding unconfirmed: %v (base %d)", err, f.b.nodeFaultBase) + } + if entry().Flags&bindingRingChecked != 0 || f.b.RingUnconfirmed(PendingSlot) != 1 || f.b.uncheckPending[parentIdentity.CgroupID] { + t.Fatalf("entry %+v, unconfirmed %d, pending %v", entry(), f.b.RingUnconfirmed(PendingSlot), f.b.uncheckPending[parentIdentity.CgroupID]) + } +} diff --git a/pkg/ebpf/gadgets/common/enforcement/slots.go b/pkg/ebpf/gadgets/common/enforcement/slots.go index 58b130b33c..c9eadbea9c 100644 --- a/pkg/ebpf/gadgets/common/enforcement/slots.go +++ b/pkg/ebpf/gadgets/common/enforcement/slots.go @@ -230,6 +230,7 @@ func (b *Bindings) rewriteClass(slot uint32, strict bool) error { errs = append(errs, fmt.Errorf("rewriting binding class: %w", err)) continue } + delete(b.uncheckPending, id) // the entry is written as the state holds it // Made Strict without a walk: unconfirmed until a bind walks // it (an Audit binding may hold rings it opened after its own // walk, under credentials the record lacks). @@ -466,15 +467,26 @@ func (b *Bindings) HealNode() error { // slot health reports it; the heal goes on). Called with mu held. func (b *Bindings) healArm(c Binding) error { id := c.Container.CgroupID + // An entry that still carries a stale bindingRingChecked (an earlier + // write of the unchecked value failed) is written again first; the heal + // fails until that write succeeds, whatever the walk finds. + var perr error + if b.uncheckPending[id] { + perr = b.putUnchecked(id, c) + } check := b.ringUnconfirmed[id] && b.classOf(c) && b.checkable(c) err := b.arm(c, check) switch { case check && err == nil: delete(b.ringUnconfirmed, id) b.setRingChecked(id, true) - _ = b.members.Put(id, b.kernelValue(c, true)) // not retried: an adopter checks again + // Not retried: an adopter checks again. + if b.members.Put(id, b.kernelValue(c, true)) == nil { + delete(b.uncheckPending, id) + perr = nil + } case errors.Is(err, ErrIoUringHeld): - return nil + err = nil case errors.Is(err, ErrCredUnrecorded): // Tasks whose credentials the record lacks: unconfirmed, and the // entry loses bindingRingChecked, until a heal walk records them @@ -482,12 +494,29 @@ func (b *Bindings) healArm(c Binding) error { b.ringUnconfirmed[id] = true if b.ringChecked[id] { b.setRingChecked(id, false) - if perr := b.members.Put(id, b.kernelValue(c, false)); perr != nil { - return errors.Join(err, perr) - } + b.uncheckPending[id] = true + perr = b.putUnchecked(id, c) } } - return err + if perr != nil && (err == nil || errors.Is(err, ErrContainerGone)) { + // Never hidden behind a success or a gone container: the entry + // may still claim a check. + return perr + } + return errors.Join(err, perr) +} + +// putUnchecked writes the entry of an active binding without +// bindingRingChecked. On a failure it stays pending (uncheckPending): every +// heal of the binding writes it again and fails until it succeeds, so a +// replacement instance never adopts a check that no longer holds. Called +// with mu held. +func (b *Bindings) putUnchecked(id uint64, c Binding) error { + if err := b.members.Put(id, b.kernelValue(c, false)); err != nil { + return fmt.Errorf("clearing the io_uring check of a binding: %w", err) + } + delete(b.uncheckPending, id) + return nil } // armable reports whether a heal can arm the tasks a binding covers: a From 19e6bc864cd56bc0a7e1fc2d773ebcbf576b9503 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 08:44:36 +0100 Subject: [PATCH 10/21] fix(enforcement): a rollback after unrecorded credentials leaves the binding unchecked bind writes the new entry with the old checked bit before the walk. When a Strict pending walk left credentials unrecorded: - a failed undo (keepFailed) kept the new entry checked and confirmed; the binding is now unchecked and unconfirmed, and the next heal writes the unchecked entry (uncheckPending) and fails until it succeeds; - a successful undo of the previous binding, or restore of an adopted entry, kept the old checked bit although the same cgroup's walk just found unrecorded credentials (e.g. a SkipArming binding that took over the check without walking); the restored entry is now written without bindingRingChecked and a Strict binding is marked unconfirmed, so a replacement re-checks it and the next arming Bind confirms it. Addresses the Copilot review summary on #1160. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 40 ++++- .../common/enforcement/pending_test.go | 141 ++++++++++++++++++ 2 files changed, 179 insertions(+), 2 deletions(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index cfb2cdb7ed..b2e87501d3 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -556,6 +556,25 @@ func (b *Bindings) bind(c Binding) error { if b.armed != nil && !c.SkipArming { newStrict := strict && !wasChecked if err := b.arm(c, newStrict); err != nil { + // The walk of this cgroup found tasks whose credentials the + // record lacks (the program counted nothing: PendingSlot). No + // pending or adopted entry restored or kept below claims a + // check (bindingRingChecked); a Strict one is unconfirmed. A + // previous binding on a real slot keeps its check: its own + // failed records are counted as faults of its slot. + unrecorded := errors.Is(err, ErrCredUnrecorded) + uncheckPrevious := unrecorded && previous.Slot == PendingSlot && b.classOf(previous) + if checked && unrecorded { + // The entry written for c carries bindingRingChecked (the + // previous check), but c's walk found tasks whose + // credentials the record lacks. If that entry stays (a + // failed undo, keepFailed), it is unchecked and + // unconfirmed, and a heal writes the unchecked value + // (uncheckPending). A successful undo or restore writes + // the entry it restores and clears uncheckPending. + checked = false + b.uncheckPending[id.CgroupID] = true + } if bound && errors.Is(err, ErrIoUringHeld) && b.value(previous) == b.value(c) { // A re-bind of the same value (a refresh of an unconfirmed // binding): the entry already holds that value, so there is @@ -574,20 +593,37 @@ func (b *Bindings) bind(c Binding) error { } if bound && !errors.Is(err, ErrContainerGone) { // Undo the move, so a retry moves and arms again. - if perr := b.members.Put(id.CgroupID, b.kernelValue(previous, b.ringChecked[id.CgroupID])); perr != nil { + prevChecked := b.ringChecked[id.CgroupID] && !uncheckPrevious + if perr := b.members.Put(id.CgroupID, b.kernelValue(previous, prevChecked)); perr != nil { b.keepFailed(c, checked) return errors.Join(err, perr) } + // The previous entry is back as the state holds it. + delete(b.uncheckPending, id.CgroupID) + if uncheckPrevious { + // A Strict pending previous binding is restored + // unchecked and unconfirmed, also when it does not arm + // (SkipArming): a re-bind that arms walks it again; a + // heal cannot (ErrNotHealable). + b.setRingChecked(id.CgroupID, false) + b.ringUnconfirmed[id.CgroupID] = true + return err + } b.markUnchecked(id.CgroupID, previous, b.classOf(previous), b.ringChecked[id.CgroupID]) return err } if wasAdopted && !errors.Is(err, ErrContainerGone) { // Keep the entry the state had, so the container stays - // protected until a retry binds it. + // protected until a retry binds it; without the check after + // an unrecorded walk (unconfirmed by markUnchecked below). + if unrecorded { + adopted.Flags &^= bindingRingChecked + } if perr := b.members.Put(id.CgroupID, adopted); perr != nil { b.keepFailed(c, checked) return errors.Join(err, perr) } + delete(b.uncheckPending, id.CgroupID) // the adopted entry is back b.adopted[id.CgroupID] = adopted b.markUnchecked(id.CgroupID, c, adopted.Flags&bindingStrict != 0, adopted.Flags&bindingRingChecked != 0 && !b.credsPurged) diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index 559f6b676d..b3de0be7ca 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -682,3 +682,144 @@ func TestHealRetriesUncheckedEntryWrite(t *testing.T) { t.Fatalf("entry %+v, unconfirmed %d, pending %v", entry(), f.b.RingUnconfirmed(PendingSlot), f.b.uncheckPending[parentIdentity.CgroupID]) } } + +// failNthPut fails the nth write of a binding map (1-based) once. +type failNthPut struct { + *fakeMap + n, puts int +} + +func (m *failNthPut) Put(k, v interface{}) error { + m.puts++ + if m.puts == m.n { + return errors.New("map busy") + } + return m.fakeMap.Put(k, v) +} + +// A checked Strict binding moved to a Strict pending value whose walk leaves +// credentials unrecorded, and whose undo write fails: the entry written for +// the new value (with bindingRingChecked, from the old check) stays. The +// binding must then be unchecked and unconfirmed, and the unchecked entry +// written by the next heal (uncheckPending), never kept as checked. +func TestBindUnrecordedFailedUndoIsUnchecked(t *testing.T) { + f := newPublishFixture(t) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.witness = fakeWitness{0: 2} + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + exact := Binding{Container: parentIdentity, Slot: PendingSlot, Strict: true} + if err := f.b.Bind(exact); err != nil { + t.Fatal(err) + } + if !f.b.ringChecked[parentIdentity.CgroupID] { + t.Fatal("fixture: the first bind is checked") + } + f.b.members = &failNthPut{fakeMap: f.members, n: 2} // the move succeeds, its undo fails + unrecordedAt(f.b, map[uint64]bool{parentIdentity.CgroupID: true}) + if err := f.b.Bind(pendingMark(true)); !errors.Is(err, ErrCredUnrecorded) { + t.Fatalf("Bind: %v", err) + } + id := parentIdentity.CgroupID + if c := f.b.active[id]; c != pendingMark(true) { + t.Fatalf("the kept entry is the new binding's: %+v", c) + } + if f.b.ringChecked[id] || f.b.RingUnconfirmed(PendingSlot) != 1 || !f.b.uncheckPending[id] { + t.Fatalf("checked %v, unconfirmed %d, pending %v", f.b.ringChecked[id], f.b.RingUnconfirmed(PendingSlot), f.b.uncheckPending[id]) + } + // The next heal writes the unchecked entry; the walk still fails. + if err := f.b.HealNode(); !errors.Is(err, ErrCredUnrecorded) || f.b.nodeFaultBase != 0 { + t.Fatalf("HealNode: %v (base %d)", err, f.b.nodeFaultBase) + } + if v := f.members.data[id].(bindingValue); v.Flags&bindingRingChecked != 0 || f.b.uncheckPending[id] { + t.Fatalf("entry %+v, pending %v", v, f.b.uncheckPending[id]) + } +} + +// After a walk that leaves credentials unrecorded, a successful undo never +// restores a check: a checked SkipArming Strict pending binding (it took the +// check over without a walk) is restored unchecked and unconfirmed. It does +// not arm, so a heal cannot confirm it (ErrNotHealable); a bind that arms +// walks it again. +func TestUnrecordedUndoRestoresUnchecked(t *testing.T) { + f := newPublishFixture(t) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.witness = fakeWitness{0: 2} + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + id := parentIdentity.CgroupID + entry := func() bindingValue { return f.members.data[id].(bindingValue) } + if err := f.b.Bind(Binding{Container: parentIdentity, Slot: PendingSlot, Strict: true}); err != nil { + t.Fatal(err) + } + skip := pendingMark(true) + skip.SkipArming = true + if err := f.b.Bind(skip); err != nil { + t.Fatal(err) + } + if !f.b.ringChecked[id] || entry().Flags&bindingRingChecked == 0 { + t.Fatalf("fixture: the SkipArming binding keeps the check: %+v", entry()) + } + unrecordedAt(f.b, map[uint64]bool{id: true}) + if err := f.b.Bind(pendingMark(true)); !errors.Is(err, ErrCredUnrecorded) { + t.Fatalf("Bind: %v", err) + } + if c := f.b.active[id]; c != skip { + t.Fatalf("the undo restores the SkipArming binding: %+v", c) + } + if entry().Flags&bindingRingChecked != 0 || f.b.ringChecked[id] || f.b.RingUnconfirmed(PendingSlot) != 1 || f.b.uncheckPending[id] { + t.Fatalf("entry %+v, checked %v, unconfirmed %d, pending %v", entry(), f.b.ringChecked[id], f.b.RingUnconfirmed(PendingSlot), f.b.uncheckPending[id]) + } + if err := f.b.HealNode(); !errors.Is(err, ErrNotHealable) || f.b.nodeFaultBase != 0 { + t.Fatalf("a Strict binding that does not arm is not healable: %v (base %d)", err, f.b.nodeFaultBase) + } + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + if err := f.b.Bind(pendingMark(true)); err != nil { + t.Fatal(err) + } + if entry().Flags&bindingRingChecked == 0 || f.b.RingUnconfirmed(PendingSlot) != 0 { + t.Fatalf("a bind that arms and records every task confirms: %+v, unconfirmed %d", entry(), f.b.RingUnconfirmed(PendingSlot)) + } +} + +// The same for an adopted checked Strict pending entry: its restore after an +// unrecorded walk drops bindingRingChecked and the binding is unconfirmed. +func TestUnrecordedRestoreOfAdoptedIsUnchecked(t *testing.T) { + id := parentIdentity.CgroupID + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.members.data[id] = bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingRingChecked} + }) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + unrecordedAt(f.b, map[uint64]bool{id: true}) + if err := f.b.Bind(pendingMark(true)); !errors.Is(err, ErrCredUnrecorded) { + t.Fatalf("Bind: %v", err) + } + want := bindingValue{Slot: PendingSlot, Flags: bindingStrict} + if v := f.members.data[id].(bindingValue); v != want || f.b.adopted[id] != want { + t.Fatalf("restored entry %+v, adopted %+v, want %+v", v, f.b.adopted[id], want) + } + if f.b.RingUnconfirmed(PendingSlot) != 1 || f.b.uncheckPending[id] { + t.Fatalf("unconfirmed %d, pending %v", f.b.RingUnconfirmed(PendingSlot), f.b.uncheckPending[id]) + } +} + +// A previous binding on a real Strict slot keeps its check after an +// unrecorded walk of a move to PendingSlot: its own failed records are counted +// as faults of its slot. +func TestUnrecordedUndoKeepsRealSlotCheck(t *testing.T) { + f := newPublishFixture(t) + if err := f.b.Publish(f.publication(1, 10, true)); err != nil { + t.Fatal(err) + } + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + id := parentIdentity.CgroupID + if err := f.b.Bind(Binding{Container: parentIdentity, Slot: 1}); err != nil { + t.Fatal(err) + } + unrecordedAt(f.b, map[uint64]bool{id: true}) + if err := f.b.Bind(pendingMark(true)); !errors.Is(err, ErrCredUnrecorded) { + t.Fatalf("Bind: %v", err) + } + if v := f.members.data[id].(bindingValue); v != (bindingValue{Slot: 1, Flags: bindingStrict | bindingRingChecked}) || !f.b.ringChecked[id] || f.b.RingUnconfirmed(1) != 0 { + t.Fatalf("entry %+v, checked %v, unconfirmed %d", v, f.b.ringChecked[id], f.b.RingUnconfirmed(1)) + } +} From 95434db658d8a910dc205d7d67bd80f961a676e5 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 09:21:39 +0100 Subject: [PATCH 11/21] fix(enforcement): no bind fast path or reload while an unchecked write is owed - bind's same-value fast path no longer applies while a binding's unchecked entry write is owed (uncheckPending): Bind and Rebind in every direction write it first and fail while it fails, so a SkipArming hand-over cannot leave a stale pinned check that later heals skip. - Heal and HealNode also write an owed entry of a binding that does not arm (a safeguard; they still return ErrNotHealable for it). - A failed owed write carries ErrUncheckedWriteOwed through the error joins, and the node owner does not reload on ErrNotHealable while it is present, so a replacement instance never adopts the stale bit; the heal is retried at the rate-limited interval. Addresses Copilot review on #1160 (comment 4796990285). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 3 + .../common/enforcement/pending_test.go | 63 ++++++++++++++++++- pkg/ebpf/gadgets/common/enforcement/slots.go | 25 +++++++- pkg/sandboxpolicy/igbackend/nodeowner.go | 5 +- pkg/sandboxpolicy/igbackend/privilege_test.go | 26 ++++++++ 5 files changed, 119 insertions(+), 3 deletions(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index b2e87501d3..de23587699 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -515,7 +515,10 @@ func (b *Bindings) bind(c Binding) error { // A Strict binding that is unconfirmed binds again, so the walk can // confirm it (a refresh re-binds the same value). A SkipArming binding // that becomes one that arms binds again too: its tasks were never armed. + // So does a binding whose unchecked entry is owed (uncheckPending): the + // write below publishes it, and the bind fails while it fails. if bound && b.value(previous) == b.value(c) && !b.unarmed[id.CgroupID] && + !b.uncheckPending[id.CgroupID] && (!previous.SkipArming || c.SkipArming) && !(b.ringUnconfirmed[id.CgroupID] && b.classOf(c) && b.checkable(c)) { return nil diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index b3de0be7ca..645cdb72f1 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -668,7 +668,7 @@ func TestHealRetriesUncheckedEntryWrite(t *testing.T) { } // The ring is now held: the walk alone would let the heal succeed. f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return true, nil } - if err := f.b.HealNode(); err == nil || !strings.Contains(err.Error(), "map busy") || f.b.nodeFaultBase != 0 { + if err := f.b.HealNode(); !errors.Is(err, ErrUncheckedWriteOwed) || !strings.Contains(err.Error(), "map busy") || f.b.nodeFaultBase != 0 { t.Fatalf("a heal with the unchecked write still pending must fail: %v (base %d)", err, f.b.nodeFaultBase) } if entry().Flags&bindingRingChecked == 0 { @@ -823,3 +823,64 @@ func TestUnrecordedUndoKeepsRealSlotCheck(t *testing.T) { t.Fatalf("entry %+v, checked %v, unconfirmed %d", v, f.b.ringChecked[id], f.b.RingUnconfirmed(1)) } } + +// A same-value hand-over never skips an owed unchecked write (uncheckPending): +// a SkipArming next binding is skipped by heals, so the hand-over writes the +// unchecked entry, and fails while that write fails. +func TestRebindWritesOwedUncheckedEntry(t *testing.T) { + f := newPublishFixture(t) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.witness = fakeWitness{0: 2} + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + id := parentIdentity.CgroupID + entry := func() bindingValue { return f.members.data[id].(bindingValue) } + if err := f.b.Bind(pendingMark(true)); err != nil { + t.Fatal(err) + } + unrecordedAt(f.b, map[uint64]bool{id: true}) + f.members.putErr = errors.New("map busy") + if err := f.b.HealNode(); err == nil || !f.b.uncheckPending[id] || entry().Flags&bindingRingChecked == 0 { + t.Fatalf("fixture: the unchecked write is owed: %v, pending %v, entry %+v", err, f.b.uncheckPending[id], entry()) + } + next := pendingMark(true) + next.Container, next.SkipArming = containerInParent, true + // Still failing: the hand-over fails and the old identity keeps the cgroup. + if err := f.b.Rebind(parentIdentity, next); err == nil { + t.Fatal("a hand-over whose owed write fails must fail") + } + if c := f.b.active[id]; c != pendingMark(true) || !f.b.uncheckPending[id] { + t.Fatalf("active %+v, pending %v", c, f.b.uncheckPending[id]) + } + f.members.putErr = nil + if err := f.b.Rebind(parentIdentity, next); err != nil { + t.Fatal(err) + } + if c := f.b.active[id]; c != next || f.b.uncheckPending[id] || entry().Flags&bindingRingChecked != 0 || entry().Flags&bindingStrict == 0 { + t.Fatalf("active %+v, pending %v, entry %+v", c, f.b.uncheckPending[id], entry()) + } + if f.b.RingUnconfirmed(PendingSlot) != 1 { + t.Fatalf("still unconfirmed: %d", f.b.RingUnconfirmed(PendingSlot)) + } +} + +// A heal skips a binding that does not arm, but still writes its owed +// unchecked entry (defensive: no bind path leaves one now). +func TestHealWritesOwedEntryOfUnarmableBinding(t *testing.T) { + f := newPublishFixture(t) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.witness = fakeWitness{0: 2} + skip := pendingMark(true) + skip.SkipArming = true + if err := f.b.Bind(skip); err != nil { + t.Fatal(err) + } + id := parentIdentity.CgroupID + f.members.data[id] = bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers | bindingRingChecked} + f.b.uncheckPending[id] = true + if err := f.b.HealNode(); !errors.Is(err, ErrNotHealable) { + t.Fatalf("HealNode: %v", err) + } + if v := f.members.data[id].(bindingValue); v.Flags&bindingRingChecked != 0 || f.b.uncheckPending[id] { + t.Fatalf("entry %+v, pending %v", v, f.b.uncheckPending[id]) + } +} diff --git a/pkg/ebpf/gadgets/common/enforcement/slots.go b/pkg/ebpf/gadgets/common/enforcement/slots.go index c9eadbea9c..5b0a0ed8b7 100644 --- a/pkg/ebpf/gadgets/common/enforcement/slots.go +++ b/pkg/ebpf/gadgets/common/enforcement/slots.go @@ -37,6 +37,13 @@ var ErrSlotBusy = errors.New("policy slot in quarantine") // map, or a binding that never arms). The faults stay counted. var ErrNotHealable = errors.New("faults cannot heal in place") +// ErrUncheckedWriteOwed: a heal could not write a binding's unchecked entry, +// so the pinned entry may still carry a check (bindingRingChecked) that no +// longer holds. A new instance would adopt it: the owner must not replace +// the instance (ErrNotHealable) while this error is returned, and retries +// the heal instead. +var ErrUncheckedWriteOwed = errors.New("an unchecked binding entry is still owed") + // SlotState matches struct slot_state in ../slots.h: generation << 1 | // active buffer, one 8-byte value that a hook reads with one load. type SlotState struct { @@ -389,6 +396,14 @@ func (b *Bindings) Heal(slot uint32) error { } if !armable(c) { skipped = true + if b.uncheckPending[c.Container.CgroupID] { + // Not armed, but its owed unchecked entry is written. A + // safeguard: no bind leaves a binding that does not arm + // with a write owed (the fast path in bind writes it). + if err := b.putUnchecked(c.Container.CgroupID, c); err != nil { + errs = append(errs, err) + } + } continue } // Every binding is armed again, even after one fails: a failure @@ -443,6 +458,14 @@ func (b *Bindings) HealNode() error { if !armable(c) { // Node faults concern Strict slots only. skipped = skipped || b.classOf(c) + if b.uncheckPending[c.Container.CgroupID] { + // Not armed, but its owed unchecked entry is written. A + // safeguard: no bind leaves a binding that does not arm + // with a write owed (the fast path in bind writes it). + if err := b.putUnchecked(c.Container.CgroupID, c); err != nil { + errs = append(errs, err) + } + } continue } // As Heal: arm every binding, then report the failures. @@ -513,7 +536,7 @@ func (b *Bindings) healArm(c Binding) error { // with mu held. func (b *Bindings) putUnchecked(id uint64, c Binding) error { if err := b.members.Put(id, b.kernelValue(c, false)); err != nil { - return fmt.Errorf("clearing the io_uring check of a binding: %w", err) + return fmt.Errorf("%w: clearing the io_uring check of a binding: %w", ErrUncheckedWriteOwed, err) } delete(b.uncheckPending, id) return nil diff --git a/pkg/sandboxpolicy/igbackend/nodeowner.go b/pkg/sandboxpolicy/igbackend/nodeowner.go index 021adbef91..4627b81db7 100644 --- a/pkg/sandboxpolicy/igbackend/nodeowner.go +++ b/pkg/sandboxpolicy/igbackend/nodeowner.go @@ -438,9 +438,12 @@ func (b *nodeOwner[C]) Replace(ctx context.Context, binding sandboxpolicy.Bindin if b.section.inPlace { err := b.instance.Heal(slot) switch { - case errors.Is(err, enforcement.ErrNotHealable): + case errors.Is(err, enforcement.ErrNotHealable) && !errors.Is(err, enforcement.ErrUncheckedWriteOwed): // Tasks a heal cannot arm (a pod binding never arms): // a new instance heals, as without in-place publishing. + // Not while an unchecked entry is owed: the new instance + // would adopt its stale check (the error is returned, and + // the next heal retries the write). reload = true case err != nil: return result, errors.Join(health, err) diff --git a/pkg/sandboxpolicy/igbackend/privilege_test.go b/pkg/sandboxpolicy/igbackend/privilege_test.go index 91a6de4a48..da57b85a6c 100644 --- a/pkg/sandboxpolicy/igbackend/privilege_test.go +++ b/pkg/sandboxpolicy/igbackend/privilege_test.go @@ -1113,6 +1113,32 @@ func TestPrivilegeHealFallsBackToReload(t *testing.T) { } } +// No reload while a heal owes an unchecked entry write: the new instance +// would adopt the stale check. The error is returned and the next heal +// retries; once the write is no longer owed, ErrNotHealable reloads. +func TestPrivilegeHealOwedWriteDoesNotReload(t *testing.T) { + e := &fakePrivilegeEngine{} + b, _ := NewPrivilege(e, nil, "n") + ctx := context.Background() + plan := privPlan("r1", privPolicy("p1", api.ActionAllow, denyMount)) + if _, err := b.Replace(ctx, privBinding(1), plan); err != nil { + t.Fatal(err) + } + i := e.instances[0] + i.faults = map[uint32]uint64{i.bound[1]: 1} + i.healErr = errors.Join(fmt.Errorf("%w: map busy", enforcement.ErrUncheckedWriteOwed), + fmt.Errorf("%w: Strict bindings that do not arm", enforcement.ErrNotHealable)) + r, err := b.Replace(ctx, privBinding(1), plan) + if !errors.Is(err, enforcement.ErrUncheckedWriteOwed) || r.Committed || len(e.instances) != 1 || i.stops != 0 { + t.Fatalf("an owed write must not reload: %+v %v instances=%d", r, err, len(e.instances)) + } + i.healErr = fmt.Errorf("%w: Strict bindings that do not arm", enforcement.ErrNotHealable) + b.lastHeal = time.Time{} // past healRetry + if r, err := b.Replace(ctx, privBinding(1), plan); err != nil || !r.Committed || len(e.instances) != 2 || i.stops != 1 { + t.Fatalf("reload once nothing is owed: %+v %v instances=%d", r, err, len(e.instances)) + } +} + // A bind into a slot with faults does not heal it: the result stays // unconfirmed. func TestPrivilegeBindOnFaultedSlotStaysUnconfirmed(t *testing.T) { From 4fb6a2fe0a7afa6850c588046de1493c0f06aa17 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 09:32:01 +0100 Subject: [PATCH 12/21] fix(enforcement): never trust an adopted Strict pending entry's ring check A replacement instance (or a restart) could adopt a pinned Strict pending entry whose bindingRingChecked was stale because the old instance never managed to write the unchecked value. A new instance now never trusts an adopted Strict PendingSlot entry's checked bit: bind clears it, so a take-over walks the entry like a new Strict binding; a held ring refuses a live take-over (the entry stays Strict pending, unchecked and unconfirmed), and at start the binding is kept unconfirmed so a replacement is never blocked. Adopted real-slot checks are still trusted, since their failed records count as slot faults. The heal reload is back to plain ErrNotHealable; ErrUncheckedWriteOwed is kept for heal reporting. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 23 +++++- .../common/enforcement/pending_test.go | 70 +++++++++++++++++++ pkg/ebpf/gadgets/common/enforcement/slots.go | 7 +- pkg/sandboxpolicy/igbackend/nodeowner.go | 8 +-- pkg/sandboxpolicy/igbackend/privilege_test.go | 18 ++--- 5 files changed, 105 insertions(+), 21 deletions(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index de23587699..714a98d1f0 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -538,6 +538,15 @@ func (b *Bindings) bind(c Binding) error { // The entry as the kernel holds it now: an instance next to this // one may have rewritten it since the start. adopted = b.currentEntry(id.CgroupID, adopted) + if adopted.Slot == PendingSlot { + // Never trusted: the instance that wrote it may have owed + // the write of its unchecked value (uncheckPending) when it + // was replaced or stopped, since only a Strict pending + // binding's walk leaves credentials unrecorded. The take-over + // walks it as a new Strict binding, and a restore below writes + // it without the check. + adopted.Flags &^= bindingRingChecked + } } // Already checked: an active Strict binding whose io_uring check passed, // or an adopted Strict entry with bindingRingChecked when the record kept @@ -1120,11 +1129,13 @@ func (b *Bindings) SlotFaults(slot uint32) (uint64, error) { // keepUnrecorded installs a startup binding whose walk armed its tasks but // could not record all their credentials (ErrCredUnrecorded, a Strict pending -// binding): one binding must not stop the start of the whole section, and +// binding), or found a ring while taking over an adopted Strict pending entry +// (ErrIoUringHeld): one binding must not stop the start of the whole section, and // dropping it would leave its cgroup unprotected. Its kernel entry is // written without bindingRingChecked (a Strict pending entry denies what it // judges), it is active, and it is unconfirmed (RingUnconfirmed), so a heal -// walks it again and confirms it once the record has room. A failed write +// walks it again and confirms it once the record has room and no ring is +// held. A failed write // fails the start. Called with mu held. func (b *Bindings) keepUnrecorded(c Binding) error { id := c.Container.CgroupID @@ -1200,8 +1211,14 @@ func (b *Bindings) start(policy Map, members BindingMap, armed Map, faults, witn } } for _, c := range b.desired { + v, adopted := b.adopted[c.Container.CgroupID] + distrusted := adopted && v.Slot == PendingSlot && v.Flags&bindingStrict != 0 err := b.bind(c) - if errors.Is(err, ErrCredUnrecorded) { + if errors.Is(err, ErrCredUnrecorded) || (distrusted && errors.Is(err, ErrIoUringHeld)) { + // A take-over of a Strict pending entry whose check is not + // trusted (see bind) that finds a ring is kept too: a + // replacement must not be blocked (the instance it replaces + // may enforce nothing). err = b.keepUnrecorded(c) } if err != nil && !errors.Is(err, ErrContainerGone) { diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index 645cdb72f1..6531b94b15 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -884,3 +884,73 @@ func TestHealWritesOwedEntryOfUnarmableBinding(t *testing.T) { t.Fatalf("entry %+v, pending %v", v, f.b.uncheckPending[id]) } } + +// An adopted Strict pending entry's bindingRingChecked is never trusted: an +// earlier instance may have owed its unchecked write (uncheckPending) when it +// was replaced or stopped. A take-over walks it as a new Strict binding: a held +// ring refuses it, and the entry restored is unchecked and unconfirmed. +func TestAdoptedPendingCheckIsNotTrusted(t *testing.T) { + id := parentIdentity.CgroupID + stale := bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers | bindingRingChecked} + for _, ring := range []bool{true, false} { + t.Run(fmt.Sprintf("ring held %v", ring), func(t *testing.T) { + f := newPublishFixtureWith(t, func(f *publishFixture) { f.members.data[id] = stale }) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return ring, nil } + err := f.b.Bind(pendingMark(true)) + v := f.members.data[id].(bindingValue) + if ring { + if !errors.Is(err, ErrIoUringHeld) || v.Flags&bindingRingChecked != 0 || v.Flags&bindingStrict == 0 || f.b.RingUnconfirmed(PendingSlot) != 1 { + t.Fatalf("a held ring refuses the take-over: %v, entry %+v, unconfirmed %d", err, v, f.b.RingUnconfirmed(PendingSlot)) + } + return + } + if err != nil || v.Flags&bindingRingChecked == 0 || f.b.RingUnconfirmed(PendingSlot) != 0 { + t.Fatalf("a walk with no ring confirms it: %v, entry %+v", err, v) + } + }) + } +} + +// A startup take-over of an adopted Strict pending entry whose tasks hold a +// ring does not stop the start (a replacement of an instance that enforces +// nothing must not be blocked): the binding is kept, its entry unchecked, +// and it is unconfirmed until a walk finds no ring. +func TestStartKeepsDistrustedPendingTakeOverWithRing(t *testing.T) { + pending := ContainerIdentity{Runtime: "parent", ID: "uid-9", CgroupID: 77, CgroupPath: "/workloads.slice/parent-uid-9"} + mark := Binding{Container: pending, Slot: PendingSlot, Strict: true, Subtree: true, RuntimeHelpers: true} + b, policy, members, _ := newFixture(t, func(Map) error { return nil }) + b.desired[selector(pending)] = mark + b.armExisting = func(Map, string) error { return nil } + b.recordCreds = func(cgroup uint64, _ string, _, _ uint32) (bool, error) { return cgroup == pending.CgroupID, nil } + stale := bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers | bindingRingChecked} + members.data[pending.CgroupID] = stale + b.adopted[pending.CgroupID] = stale + if err := b.start(policy, members, &fakeMap{typ: ebpf.TaskStorage}, nil, nil); err != nil { + t.Fatalf("start: %v", err) + } + if v := members.data[pending.CgroupID].(bindingValue); v.Flags&bindingRingChecked != 0 || v.Flags&bindingStrict == 0 { + t.Fatalf("entry %+v", v) + } + if c := b.active[pending.CgroupID]; c != mark || b.RingUnconfirmed(PendingSlot) != 1 || b.ringChecked[pending.CgroupID] { + t.Fatalf("active %+v, unconfirmed %d", c, b.RingUnconfirmed(PendingSlot)) + } +} + +// An adopted entry on a real slot keeps its trusted check (its owed writes +// never exist: only a Strict pending binding's walk leaves credentials +// unrecorded). +func TestAdoptedRealSlotCheckIsTrusted(t *testing.T) { + id := parentIdentity.CgroupID + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.members.data[id] = bindingValue{Slot: 1, Flags: bindingStrict | bindingRingChecked} + }) + if err := f.b.Publish(f.publication(1, 10, true)); err != nil { + t.Fatal(err) + } + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return true, nil } + if err := f.b.Bind(Binding{Container: parentIdentity, Slot: 1}); err != nil { + t.Fatalf("a checked real-slot entry is trusted: %v", err) + } +} diff --git a/pkg/ebpf/gadgets/common/enforcement/slots.go b/pkg/ebpf/gadgets/common/enforcement/slots.go index 5b0a0ed8b7..7bb79209a5 100644 --- a/pkg/ebpf/gadgets/common/enforcement/slots.go +++ b/pkg/ebpf/gadgets/common/enforcement/slots.go @@ -39,9 +39,10 @@ var ErrNotHealable = errors.New("faults cannot heal in place") // ErrUncheckedWriteOwed: a heal could not write a binding's unchecked entry, // so the pinned entry may still carry a check (bindingRingChecked) that no -// longer holds. A new instance would adopt it: the owner must not replace -// the instance (ErrNotHealable) while this error is returned, and retries -// the heal instead. +// longer holds. The heal fails (no rebase) and the next one retries. A new +// instance never trusts that check (only a Strict pending entry can owe one, +// and bind never trusts an adopted Strict pending entry's check), so a +// replacement is safe. var ErrUncheckedWriteOwed = errors.New("an unchecked binding entry is still owed") // SlotState matches struct slot_state in ../slots.h: generation << 1 | diff --git a/pkg/sandboxpolicy/igbackend/nodeowner.go b/pkg/sandboxpolicy/igbackend/nodeowner.go index 4627b81db7..4d174b8a19 100644 --- a/pkg/sandboxpolicy/igbackend/nodeowner.go +++ b/pkg/sandboxpolicy/igbackend/nodeowner.go @@ -438,12 +438,12 @@ func (b *nodeOwner[C]) Replace(ctx context.Context, binding sandboxpolicy.Bindin if b.section.inPlace { err := b.instance.Heal(slot) switch { - case errors.Is(err, enforcement.ErrNotHealable) && !errors.Is(err, enforcement.ErrUncheckedWriteOwed): + case errors.Is(err, enforcement.ErrNotHealable): // Tasks a heal cannot arm (a pod binding never arms): // a new instance heals, as without in-place publishing. - // Not while an unchecked entry is owed: the new instance - // would adopt its stale check (the error is returned, and - // the next heal retries the write). + // Also while an unchecked entry is owed + // (ErrUncheckedWriteOwed): a new instance never trusts + // the check of an adopted Strict pending entry. reload = true case err != nil: return result, errors.Join(health, err) diff --git a/pkg/sandboxpolicy/igbackend/privilege_test.go b/pkg/sandboxpolicy/igbackend/privilege_test.go index da57b85a6c..e1a6f54f61 100644 --- a/pkg/sandboxpolicy/igbackend/privilege_test.go +++ b/pkg/sandboxpolicy/igbackend/privilege_test.go @@ -1113,10 +1113,12 @@ func TestPrivilegeHealFallsBackToReload(t *testing.T) { } } -// No reload while a heal owes an unchecked entry write: the new instance -// would adopt the stale check. The error is returned and the next heal -// retries; once the write is no longer owed, ErrNotHealable reloads. -func TestPrivilegeHealOwedWriteDoesNotReload(t *testing.T) { +// A heal that owes an unchecked entry write (ErrUncheckedWriteOwed) and +// cannot arm every task still reloads: the new instance never trusts an +// adopted Strict pending entry's check (enforcement bind), so a replacement +// is never blocked by an owed write, even when the running instance enforces +// nothing. +func TestPrivilegeHealOwedWriteStillReloads(t *testing.T) { e := &fakePrivilegeEngine{} b, _ := NewPrivilege(e, nil, "n") ctx := context.Background() @@ -1128,14 +1130,8 @@ func TestPrivilegeHealOwedWriteDoesNotReload(t *testing.T) { i.faults = map[uint32]uint64{i.bound[1]: 1} i.healErr = errors.Join(fmt.Errorf("%w: map busy", enforcement.ErrUncheckedWriteOwed), fmt.Errorf("%w: Strict bindings that do not arm", enforcement.ErrNotHealable)) - r, err := b.Replace(ctx, privBinding(1), plan) - if !errors.Is(err, enforcement.ErrUncheckedWriteOwed) || r.Committed || len(e.instances) != 1 || i.stops != 0 { - t.Fatalf("an owed write must not reload: %+v %v instances=%d", r, err, len(e.instances)) - } - i.healErr = fmt.Errorf("%w: Strict bindings that do not arm", enforcement.ErrNotHealable) - b.lastHeal = time.Time{} // past healRetry if r, err := b.Replace(ctx, privBinding(1), plan); err != nil || !r.Committed || len(e.instances) != 2 || i.stops != 1 { - t.Fatalf("reload once nothing is owed: %+v %v instances=%d", r, err, len(e.instances)) + t.Fatalf("reload: %+v %v instances=%d", r, err, len(e.instances)) } } From 4f5bde782490bd66c068773ae7ddb5d37ace1b72 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 09:55:40 +0100 Subject: [PATCH 13/21] fix(enforcement): a start move refused by a held ring keeps the pending entry When startup adopted a Strict pending entry but wanted a real Strict slot, a held io_uring ring made bind refuse the move and restore the pending entry, and the start recovery (keepUnrecorded) then installed the real slot anyway, dropping pending protection before credential coverage was confirmed. keepUnrecorded now applies only when the wanted binding is itself Strict pending; a refused move to another slot keeps the pending entry, unchecked and unconfirmed, and the start does not fail. The wanted binding is recorded and counted in RingUnconfirmed of its slot, so that slot is unhealthy while the move is outstanding; Heal and HealNode retry the move once the ring is gone. Any validated bind attempt for the cgroup replaces a record for another target (a newer refused move records the newer wish), and an unbind clears it. Addresses Copilot review on #1160 (comment 4797440472). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 61 +++++- .../common/enforcement/pending_test.go | 192 ++++++++++++++++++ pkg/ebpf/gadgets/common/enforcement/slots.go | 20 ++ .../gadgets/common/enforcement/slots_test.go | 7 +- 4 files changed, 272 insertions(+), 8 deletions(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index 714a98d1f0..d9902e1e43 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -260,6 +260,12 @@ type Bindings struct { // whose kernel entry may still carry bindingRingChecked (the write of // the unchecked value failed). Every heal writes it again (healArm). uncheckPending map[uint64]bool + // moves: the wanted binding of a cgroup whose move from an adopted + // Strict pending entry a held ring refused at start; the cgroup keeps a + // Strict pending binding (see start). The wanted slot counts it as + // unconfirmed (RingUnconfirmed) until a heal of that slot binds it, or + // any bind or unbind of the cgroup replaces it. + moves map[uint64]Binding // Long-lived instance (WritePolicy nil): see slots.go. slotState Map publish map[string]Map @@ -304,7 +310,7 @@ func New(config Config) (*Bindings, error) { return nil, fmt.Errorf("enforcement controller with a fault map requires the slot class") } b := &Bindings{config: config, desired: map[execpolicy.Container]Binding{}, active: map[uint64]Binding{}, unarmed: map[uint64]bool{}, armExisting: ArmExisting, - slots: map[uint32]*slotRecord{}, now: time.Now, classRetry: map[uint32]bool{}, adopted: map[uint64]bindingValue{}, listBindings: listPinnedBindings, ioUringAudit: map[uint64]bool{}, ringChecked: map[uint64]bool{}, ringUnconfirmed: map[uint64]bool{}, uncheckPending: map[uint64]bool{}} + slots: map[uint32]*slotRecord{}, now: time.Now, classRetry: map[uint32]bool{}, adopted: map[uint64]bindingValue{}, listBindings: listPinnedBindings, ioUringAudit: map[uint64]bool{}, ringChecked: map[uint64]bool{}, ringUnconfirmed: map[uint64]bool{}, uncheckPending: map[uint64]bool{}, moves: map[uint64]Binding{}} for _, c := range config.InitialBindings { if err := b.validate(c); err != nil { return nil, err @@ -512,6 +518,14 @@ func (b *Bindings) bind(c Binding) error { if bound && previous.Container != id { return fmt.Errorf("cgroup identity conflicts with active binding") } + // A bind attempt for a cgroup with a refused start move (moves) is the + // newer wish: the record goes, whatever the outcome. A refused move + // below records c instead (see the undo). retryMoves binds the + // recorded wish itself, which keeps it until it succeeds. + _, hadMove := b.moves[id.CgroupID] + if hadMove && b.moves[id.CgroupID] != c { + delete(b.moves, id.CgroupID) + } // A Strict binding that is unconfirmed binds again, so the walk can // confirm it (a refresh re-binds the same value). A SkipArming binding // that becomes one that arms binds again too: its tasks were never armed. @@ -612,6 +626,11 @@ func (b *Bindings) bind(c Binding) error { } // The previous entry is back as the state holds it. delete(b.uncheckPending, id.CgroupID) + if hadMove && errors.Is(err, ErrIoUringHeld) && c.Slot != PendingSlot { + // Still on the kept pending binding: c is the move a + // heal retries now (retryMoves), not the older wish. + b.moves[id.CgroupID] = c + } if uncheckPrevious { // A Strict pending previous binding is restored // unchecked and unconfirmed, also when it does not arm @@ -673,6 +692,7 @@ func (b *Bindings) bind(c Binding) error { } b.setRingChecked(id.CgroupID, checked) b.active[id.CgroupID] = c + delete(b.moves, id.CgroupID) // a bind replaces a refused move b.setCredActive() return nil } @@ -786,13 +806,19 @@ func countBindings(m Map) (int, error) { // RingUnconfirmed returns how many Strict bindings of a slot (adopted or // active) may run io_uring requests under credentials the record lacks // (ringUnconfirmed): their protection is unconfirmed until a bind walk finds -// no ring. It also counts a Strict pending binding kept at start or after a +// no ring. It also counts a move to the slot that a held ring refused at +// start (moves). And a Strict pending binding kept at start or after a // purge whose walk could not record every task (ErrCredUnrecorded) until a // walk records them all. func (b *Bindings) RingUnconfirmed(slot uint32) int { b.mu.Lock() defer b.mu.Unlock() n := 0 + for _, w := range b.moves { + if w.Slot == slot { + n++ // the cgroup is not on this slot yet + } + } for id := range b.ringUnconfirmed { if v, ok := b.adopted[id]; ok { if v.Slot == slot { @@ -831,6 +857,7 @@ func (b *Bindings) unbind(c ContainerIdentity) error { // forgetCreds drops the io_uring state of a cgroup that is no longer bound and // deletes its credential counter (when the section keeps a record). func (b *Bindings) forgetCreds(cgroup uint64) error { + delete(b.moves, cgroup) delete(b.uncheckPending, cgroup) delete(b.ioUringAudit, cgroup) delete(b.ringChecked, cgroup) @@ -1129,8 +1156,9 @@ func (b *Bindings) SlotFaults(slot uint32) (uint64, error) { // keepUnrecorded installs a startup binding whose walk armed its tasks but // could not record all their credentials (ErrCredUnrecorded, a Strict pending -// binding), or found a ring while taking over an adopted Strict pending entry -// (ErrIoUringHeld): one binding must not stop the start of the whole section, and +// binding), or the Strict pending binding kept when a take-over of an adopted +// Strict pending entry found a ring (ErrIoUringHeld): one binding must not +// stop the start of the whole section, and // dropping it would leave its cgroup unprotected. Its kernel entry is // written without bindingRingChecked (a Strict pending entry denies what it // judges), it is active, and it is unconfirmed (RingUnconfirmed), so a heal @@ -1214,12 +1242,31 @@ func (b *Bindings) start(policy Map, members BindingMap, armed Map, faults, witn v, adopted := b.adopted[c.Container.CgroupID] distrusted := adopted && v.Slot == PendingSlot && v.Flags&bindingStrict != 0 err := b.bind(c) - if errors.Is(err, ErrCredUnrecorded) || (distrusted && errors.Is(err, ErrIoUringHeld)) { + switch { + case errors.Is(err, ErrCredUnrecorded): + err = b.keepUnrecorded(c) + case distrusted && errors.Is(err, ErrIoUringHeld) && c.Slot == PendingSlot && c.Strict: // A take-over of a Strict pending entry whose check is not - // trusted (see bind) that finds a ring is kept too: a + // trusted (see bind) found a ring. Not a start failure: a // replacement must not be blocked (the instance it replaces - // may enforce nothing). + // may enforce nothing). c is Strict pending too: kept, + // unchecked and unconfirmed. err = b.keepUnrecorded(c) + case distrusted && errors.Is(err, ErrIoUringHeld): + // The same, for a move to another slot: the pending entry is + // kept, never moved before the check passes. It becomes an + // active Strict pending binding with the entry's flags under + // c's identity, unchecked and unconfirmed. c is recorded + // (moves): a heal of c's slot (or a node heal) binds c again + // once the ring is closed, which moves it (retryMoves); a + // bind or unbind of the cgroup by the owner replaces it. + err = b.keepUnrecorded(Binding{Container: c.Container, Slot: PendingSlot, Strict: true, + Subtree: v.Flags&bindingSubtree != 0, RuntimeHelpers: v.Flags&bindingRuntimeHelpers != 0}) + if err == nil { + // The owner records c on its slot: that slot is not + // healthy until a heal moves the cgroup there. + b.moves[c.Container.CgroupID] = c + } } if err != nil && !errors.Is(err, ErrContainerGone) { return b.recordError(err) diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index 6531b94b15..41bdd72794 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -954,3 +954,195 @@ func TestAdoptedRealSlotCheckIsTrusted(t *testing.T) { t.Fatalf("a checked real-slot entry is trusted: %v", err) } } + +// A startup take-over that moves an adopted Strict pending entry to a real +// Strict slot and finds a held ring is refused: the pending entry stays (no +// real slot before the ring check passes), unchecked, as an active Strict +// pending binding under the container's identity, unconfirmed, so a heal +// walks it and a later bind moves it. The start does not fail. +func TestStartRefusedMoveToRealSlotKeepsPending(t *testing.T) { + pending := ContainerIdentity{Runtime: "containerd", ID: "c9", CgroupID: 77, CgroupPath: "/workloads.slice/parent-uid-9"} + real := Binding{Container: pending, Slot: 1} + b, policy, members, _ := newFixture(t, func(Map) error { return nil }) + b.config.StrictSlot = func(uint32) bool { return true } + b.desired[selector(pending)] = real + b.armExisting = func(Map, string) error { return nil } + ring := true + b.recordCreds = func(cgroup uint64, _ string, _, _ uint32) (bool, error) { + return cgroup == pending.CgroupID && ring, nil + } + stale := bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers | bindingRingChecked} + members.data[pending.CgroupID] = stale + b.adopted[pending.CgroupID] = stale + if err := b.start(policy, members, &fakeMap{typ: ebpf.TaskStorage}, nil, fakeWitness{0: 2}); err != nil { + t.Fatalf("start: %v", err) + } + if v := members.data[pending.CgroupID].(bindingValue); v != (bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers}) { + t.Fatalf("the pending entry stays, unchecked: %+v", v) + } + kept := Binding{Container: pending, Slot: PendingSlot, Strict: true, Subtree: true, RuntimeHelpers: true} + if c := b.active[pending.CgroupID]; c != kept || b.RingUnconfirmed(PendingSlot) != 1 { + t.Fatalf("active %+v, unconfirmed %d", c, b.RingUnconfirmed(PendingSlot)) + } + if _, ok := b.adopted[pending.CgroupID]; ok { + t.Fatal("the entry is this run's binding now") + } + // The ring closes: a heal confirms the pending binding, then the move + // to the real slot binds. + ring = false + if err := b.Ready(nil); err != nil { + t.Fatal(err) + } + if err := b.HealNode(); err != nil || b.RingUnconfirmed(PendingSlot) != 0 { + t.Fatalf("heal: %v, unconfirmed %d", err, b.RingUnconfirmed(PendingSlot)) + } + if err := b.Bind(real); err != nil { + t.Fatal(err) + } + if v := members.data[pending.CgroupID].(bindingValue); v.Slot != 1 || v.Flags&bindingStrict == 0 { + t.Fatalf("moved entry %+v", v) + } +} + +// A live take-over of an adopted Strict pending entry refused by a held ring +// succeeds once the ring is closed. +func TestLiveTakeOverRefusedThenSucceeds(t *testing.T) { + id := parentIdentity.CgroupID + stale := bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers | bindingRingChecked} + f := newPublishFixtureWith(t, func(f *publishFixture) { f.members.data[id] = stale }) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + ring := true + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return ring, nil } + if err := f.b.Bind(pendingMark(true)); !errors.Is(err, ErrIoUringHeld) { + t.Fatalf("a held ring refuses the take-over: %v", err) + } + if _, ok := f.b.adopted[id]; !ok { + t.Fatal("the refused take-over keeps the adopted entry") + } + ring = false + if err := f.b.Bind(pendingMark(true)); err != nil { + t.Fatalf("take-over after the ring closed: %v", err) + } + v := f.members.data[id].(bindingValue) + if v.Flags&bindingRingChecked == 0 || f.b.RingUnconfirmed(PendingSlot) != 0 || f.b.active[id] != pendingMark(true) { + t.Fatalf("entry %+v, unconfirmed %d, active %+v", v, f.b.RingUnconfirmed(PendingSlot), f.b.active[id]) + } + if _, ok := f.b.adopted[id]; ok { + t.Fatal("taken over") + } +} + +// A move from an adopted Strict pending entry to a real Strict slot that a +// held ring refused at start is recorded: the slot counts it as unconfirmed +// (its health fails while the cgroup is not there), and a heal of the slot +// moves the cgroup once the ring is closed; the slot is then healthy. +func TestRefusedStartMoveIsRetriedByHeal(t *testing.T) { + c9 := ContainerIdentity{Runtime: "containerd", ID: "c9", CgroupID: 77, CgroupPath: "/workloads.slice/parent-uid-9"} + wanted := Binding{Container: c9, Slot: 1} + ring := true + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.members.data[c9.CgroupID] = bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers | bindingRingChecked} + f.b.config.InitialPublications = []Publication{f.publication(1, 10, true)} + f.b.desired[selector(c9)] = wanted + f.b.recordCreds = func(cgroup uint64, _ string, _, _ uint32) (bool, error) { return cgroup == c9.CgroupID && ring, nil } + f.armed = &fakeMap{typ: ebpf.TaskStorage} + }) + if !f.b.Strict(1) { + t.Fatal("fixture: slot 1 is Strict") + } + if v := f.members.data[c9.CgroupID].(bindingValue); v.Slot != PendingSlot { + t.Fatalf("the refused move keeps the pending entry: %+v", v) + } + if f.b.RingUnconfirmed(1) != 1 || f.b.moves[c9.CgroupID] != wanted { + t.Fatalf("slot 1 must not look healthy: unconfirmed %d, moves %+v", f.b.RingUnconfirmed(1), f.b.moves) + } + // Still held: the heal keeps the pending entry and the record. + if err := f.b.Heal(1); err != nil || f.b.RingUnconfirmed(1) != 1 { + t.Fatalf("heal with the ring held: %v, unconfirmed %d", err, f.b.RingUnconfirmed(1)) + } + ring = false + if err := f.b.Heal(1); err != nil { + t.Fatalf("heal: %v", err) + } + if v := f.members.data[c9.CgroupID].(bindingValue); v.Slot != 1 || v.Flags&bindingStrict == 0 || v.Flags&bindingRingChecked == 0 { + t.Fatalf("the heal moves the cgroup to slot 1: %+v", v) + } + if f.b.RingUnconfirmed(1) != 0 || f.b.RingUnconfirmed(PendingSlot) != 0 || len(f.b.moves) != 0 || f.b.active[c9.CgroupID] != wanted { + t.Fatalf("healthy: unconfirmed %d/%d, moves %+v, active %+v", f.b.RingUnconfirmed(1), f.b.RingUnconfirmed(PendingSlot), f.b.moves, f.b.active[c9.CgroupID]) + } +} + +// A bind or an unbind of the cgroup replaces a refused move. +func TestRefusedStartMoveClearedByBindOrUnbind(t *testing.T) { + c9 := ContainerIdentity{Runtime: "containerd", ID: "c9", CgroupID: 77, CgroupPath: "/workloads.slice/parent-uid-9"} + for _, unbind := range []bool{false, true} { + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.members.data[c9.CgroupID] = bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers | bindingRingChecked} + f.b.config.InitialPublications = []Publication{f.publication(1, 10, true)} + f.b.desired[selector(c9)] = Binding{Container: c9, Slot: 1} + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return true, nil } + f.armed = &fakeMap{typ: ebpf.TaskStorage} + }) + if len(f.b.moves) != 1 { + t.Fatal("fixture: a refused move") + } + var err error + if unbind { + err = f.b.Unbind(c9) + } else { + // The pending binding again (a refresh that walks it: unconfirmed). + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + err = f.b.Bind(f.b.active[c9.CgroupID]) + } + if err != nil || len(f.b.moves) != 0 || f.b.RingUnconfirmed(1) != 0 { + t.Fatalf("unbind %v: %v, moves %+v", unbind, err, f.b.moves) + } + } +} + +// Any bind attempt for a cgroup with a refused start move replaces the +// recorded wish: a same-value bind clears it, and a failed move to another +// slot that a held ring refuses records the newer wish, so a heal never +// moves the cgroup to the older one. +func TestBindAttemptReplacesRefusedMove(t *testing.T) { + c9 := ContainerIdentity{Runtime: "containerd", ID: "c9", CgroupID: 77, CgroupPath: "/workloads.slice/parent-uid-9"} + setup := func(ring *bool) func(*publishFixture) { + return func(f *publishFixture) { + f.members.data[c9.CgroupID] = bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers | bindingRingChecked} + 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, uint32, uint32) (bool, error) { return *ring, nil } + f.armed = &fakeMap{typ: ebpf.TaskStorage} + f.witness = fakeWitness{0: 2} + } + } + t.Run("failed move to another slot records the newer wish", func(t *testing.T) { + ring := true + f := newPublishFixtureWith(t, setup(&ring)) + newer := Binding{Container: c9, Slot: 2} + if err := f.b.Bind(newer); !errors.Is(err, ErrIoUringHeld) { + 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)) + } + ring = false + if err := f.b.HealNode(); err != nil { + t.Fatal(err) + } + if v := f.members.data[c9.CgroupID].(bindingValue); v.Slot != 2 { + t.Fatalf("the heal moves the cgroup to the newer wish: %+v", v) + } + }) + t.Run("same-value bind clears it", func(t *testing.T) { + ring := true + f := newPublishFixtureWith(t, setup(&ring)) + delete(f.b.ringUnconfirmed, c9.CgroupID) // the fast path + if err := f.b.Bind(f.b.active[c9.CgroupID]); err != nil { + t.Fatal(err) + } + if len(f.b.moves) != 0 || f.b.RingUnconfirmed(1) != 0 { + t.Fatalf("moves %+v", f.b.moves) + } + }) +} diff --git a/pkg/ebpf/gadgets/common/enforcement/slots.go b/pkg/ebpf/gadgets/common/enforcement/slots.go index 7bb79209a5..c9f89f5888 100644 --- a/pkg/ebpf/gadgets/common/enforcement/slots.go +++ b/pkg/ebpf/gadgets/common/enforcement/slots.go @@ -414,6 +414,7 @@ func (b *Bindings) Heal(slot uint32) error { errs = append(errs, err) } } + errs = append(errs, b.retryMoves(func(w Binding) bool { return w.Slot == slot })...) if len(errs) > 0 { return errors.Join(errs...) } @@ -474,6 +475,7 @@ func (b *Bindings) HealNode() error { errs = append(errs, err) } } + errs = append(errs, b.retryMoves(func(Binding) bool { return true })...) if len(errs) > 0 { return errors.Join(errs...) } @@ -484,6 +486,24 @@ func (b *Bindings) HealNode() error { return nil } +// retryMoves binds again the refused moves (moves) that match, after the +// heal walked their pending bindings: a pending binding the walk confirmed +// moves without a new ring check; one that still holds a ring is refused +// again (ErrIoUringHeld, not a heal failure: the slot stays unconfirmed). +// A success clears the move (bind). Called with mu held. +func (b *Bindings) retryMoves(match func(Binding) bool) []error { + var errs []error + for _, w := range b.moves { + if !match(w) { + continue + } + if err := b.bind(w); err != nil && !errors.Is(err, ErrIoUringHeld) && !errors.Is(err, ErrContainerGone) { + errs = append(errs, err) + } + } + return errs +} + // healArm arms a binding again in a heal. A Strict binding that is // unconfirmed is checked for io_uring rings too (for an unchanged plan the // owner heals the slot; it does not bind again): it is confirmed when the diff --git a/pkg/ebpf/gadgets/common/enforcement/slots_test.go b/pkg/ebpf/gadgets/common/enforcement/slots_test.go index 57afcd0ec5..d602b01919 100644 --- a/pkg/ebpf/gadgets/common/enforcement/slots_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/slots_test.go @@ -21,6 +21,10 @@ type publishFixture struct { policy *fakeMap members *fakeMap faults fakeFaults + // armed and witness are the arming and witness maps the start gets + // (nil unless a setup sets them). + armed Map + witness FaultMap clock time.Time // strictAt is the class ClassOf reads at a storage index. strictAt map[uint32]bool @@ -71,13 +75,14 @@ func newPublishFixtureWith(t *testing.T, setup func(*publishFixture)) *publishFi } b.now = func() time.Time { return f.clock } b.armExisting = func(Map, string) error { return nil } + f.b = b // a setup may prepare the controller (desired bindings, hooks) if setup != nil { setup(f) } if err := b.setPublishMaps(f.state, map[string]Map{"policy": f.policy}); err != nil { t.Fatal(err) } - if err := b.start(nil, f.members, nil, f.faults, nil); err != nil { + if err := b.start(nil, f.members, f.armed, f.faults, f.witness); err != nil { t.Fatal(err) } f.b = b From 031cc8966aa74fcaf644544e32a5196ffefda08f Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 10:08:07 +0100 Subject: [PATCH 14/21] fix(enforcement): keep the deferred-move record consistent with Free and Rebind - Free refused a bound slot but not one a refused startup move still targeted, so the slot could be retired and reused and the heal's retry would move the Strict pending cgroup onto an unrelated policy. Free now refuses such a slot too; any bind or unbind of the cgroup clears the record, after which Free succeeds. - A Rebind refused by a held ring restored the old identity but left the move record on the rejected identity, so every heal retried it and failed with an identity conflict. The rollback now restores the move record together with the identity. Addresses Copilot review on #1160 (comments 4797679424, 4797679532). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 9 ++- .../common/enforcement/pending_test.go | 62 +++++++++++++++++++ pkg/ebpf/gadgets/common/enforcement/slots.go | 9 +++ 3 files changed, 79 insertions(+), 1 deletion(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index d9902e1e43..b6c220bd4b 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -390,12 +390,19 @@ func (b *Bindings) rebind(old ContainerIdentity, next Binding) error { swapped := previous swapped.Container = id b.active[id.CgroupID] = swapped + move, moved := b.moves[id.CgroupID] err := b.bind(next) c, ok := b.active[id.CgroupID] switch { case ok && c == swapped && err != nil: - // The undo put the previous entry back: it is old's again. + // The undo put the previous entry back: it is old's again, with + // old's refused move (bind replaced it with next's wish). b.active[id.CgroupID] = previous + if moved { + b.moves[id.CgroupID] = move + } else { + delete(b.moves, id.CgroupID) + } case ok && c == swapped: // The kernel value did not change (bind returned early): record // next itself, so its other fields (SkipArming) are current. diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index 41bdd72794..9552022025 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -1146,3 +1146,65 @@ func TestBindAttemptReplacesRefusedMove(t *testing.T) { } }) } + +// refusedMoveFixture starts with a refused start move of c9 to slot 1 +// (Strict), slot 2 published too (Audit), and a held ring (*ring). +func refusedMoveFixture(t *testing.T, ring *bool) (*publishFixture, ContainerIdentity) { + t.Helper() + c9 := ContainerIdentity{Runtime: "containerd", ID: "c9", CgroupID: 77, CgroupPath: "/workloads.slice/parent-uid-9"} + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.members.data[c9.CgroupID] = bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers | bindingRingChecked} + f.b.config.InitialPublications = []Publication{f.publication(1, 10, true), f.publication(2, 20, false)} + f.b.desired[selector(c9)] = Binding{Container: c9, Slot: 1} + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return *ring, nil } + f.armed = &fakeMap{typ: ebpf.TaskStorage} + f.witness = fakeWitness{0: 2} + }) + if len(f.b.moves) != 1 { + t.Fatal("fixture: a refused move") + } + return f, c9 +} + +// Free refuses a slot that a refused move still targets: reused for another +// policy (an Audit one), the heal's retry would move the Strict pending +// cgroup there. Once the move record goes (an unbind), Free frees it. +func TestFreeRefusesSlotOfRefusedMove(t *testing.T) { + ring := true + f, c9 := refusedMoveFixture(t, &ring) + if err := f.b.Free(1); err == nil || !strings.Contains(err.Error(), "refused move") { + t.Fatalf("Free: %v", err) + } + if s := f.slotState(1); s.Generation() != 10 { + t.Fatalf("slot 1 must stay published: %+v", s) + } + if err := f.b.Unbind(c9); err != nil { + t.Fatal(err) + } + if err := f.b.Free(1); err != nil { + t.Fatalf("Free after the unbind: %v", err) + } +} + +// A Rebind refused by a held ring rolls back the move record with the +// identity: the old identity keeps its recorded move, so a heal moves it once +// the ring is closed (no identity conflict). +func TestRefusedRebindRestoresMoveRecord(t *testing.T) { + ring := true + f, c9 := refusedMoveFixture(t, &ring) + before := f.b.moves[c9.CgroupID] + next := Binding{Container: ContainerIdentity{Runtime: "containerd", ID: "c10", CgroupID: c9.CgroupID, CgroupPath: c9.CgroupPath}, Slot: 1} + if err := f.b.Rebind(c9, next); !errors.Is(err, ErrIoUringHeld) { + t.Fatalf("Rebind: %v", err) + } + if f.b.active[c9.CgroupID].Container != c9 || f.b.moves[c9.CgroupID] != before { + t.Fatalf("active %+v, moves %+v", f.b.active[c9.CgroupID], f.b.moves) + } + ring = false + if err := f.b.HealNode(); err != nil { + t.Fatalf("heal: %v", err) + } + if v := f.members.data[c9.CgroupID].(bindingValue); v.Slot != 1 || f.b.active[c9.CgroupID] != before || len(f.b.moves) != 0 { + t.Fatalf("entry %+v, active %+v, moves %+v", v, f.b.active[c9.CgroupID], f.b.moves) + } +} diff --git a/pkg/ebpf/gadgets/common/enforcement/slots.go b/pkg/ebpf/gadgets/common/enforcement/slots.go index c9f89f5888..9797e72d66 100644 --- a/pkg/ebpf/gadgets/common/enforcement/slots.go +++ b/pkg/ebpf/gadgets/common/enforcement/slots.go @@ -295,6 +295,15 @@ func (b *Bindings) Free(slot uint32) error { return fmt.Errorf("slot %d still has adopted bindings", slot) } } + for _, w := range b.moves { + if w.Slot == slot { + // The owner records that cgroup on this slot: as a bound slot, + // it is not freed (a reuse for another policy would receive + // the heal's move). The record goes with a bind or unbind of + // the cgroup, so the slot is never stranded. + return fmt.Errorf("slot %d is still the target of a refused move", slot) + } + } if err := b.slotState.Put(slot, SlotState{}); err != nil { return fmt.Errorf("clearing slot %d: %w", slot, err) } From e3fa03a8efdb54ab5674c070ae1730eeca670aa9 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 10:24:45 +0100 Subject: [PATCH 15/21] feat(enforcement): per-cgroup ring-check query for pending marks Add Bindings.CgroupRingUnconfirmed(cgroup), exposed on NodeInstance, so the node owner can tell whether a cgroup's Strict pending mark has passed its io_uring/credential check. It reports true for a refused move, an owed unchecked write, an adopted Strict pending entry (never trusted), a Strict binding still unconfirmed, and an unknown cgroup (unknown never reads as confirmed); false only for an Audit binding or a Strict binding whose check passed. Query only; no behaviour change in S1. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 27 +++++++ .../common/enforcement/pending_test.go | 72 +++++++++++++++++++ pkg/sandboxpolicy/igbackend/nodeowner.go | 5 ++ .../igbackend/privilege_native.go | 5 ++ pkg/sandboxpolicy/igbackend/privilege_test.go | 19 ++++- 5 files changed, 127 insertions(+), 1 deletion(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index b6c220bd4b..ec9d3778f1 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -838,6 +838,33 @@ func (b *Bindings) RingUnconfirmed(slot uint32) int { return n } +// CgroupRingUnconfirmed reports whether the protection of a cgroup's binding +// is not attested: true while its Strict binding (active or adopted) has not +// passed the io_uring check (ringUnconfirmed: a held ring, credentials the +// record lacks, a class change), while the write of its unchecked entry is +// owed (uncheckPending), while a held ring keeps it from its wanted slot +// (moves), and for an adopted Strict pending entry, whose check is never +// trusted (see bind). It is also true for a cgroup this instance does not +// bind (unknown): a caller must never read an absent binding as confirmed. +// It is false only for an active or adopted binding that is Audit (it claims +// no protection) or that passed the check. +func (b *Bindings) CgroupRingUnconfirmed(cgroup uint64) bool { + b.mu.Lock() + defer b.mu.Unlock() + if _, ok := b.moves[cgroup]; ok || b.uncheckPending[cgroup] { + return true + } + if v, ok := b.adopted[cgroup]; ok { + strict := v.Flags&bindingStrict != 0 + return strict && (v.Slot == PendingSlot || b.ringUnconfirmed[cgroup]) + } + c, ok := b.active[cgroup] + if !ok { + return true // unknown: not attested + } + return b.classOf(c) && b.ringUnconfirmed[cgroup] +} + func (b *Bindings) unbind(c ContainerIdentity) error { if b.desired[selector(c)].Container == c { delete(b.desired, selector(c)) diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index 9552022025..3427737a93 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -1208,3 +1208,75 @@ func TestRefusedRebindRestoresMoveRecord(t *testing.T) { t.Fatalf("entry %+v, active %+v, moves %+v", v, f.b.active[c9.CgroupID], f.b.moves) } } + +// CgroupRingUnconfirmed is false only for a binding that claims no +// protection (Audit) or whose Strict check passed; an unknown cgroup, an +// adopted Strict pending entry, an unconfirmed binding, an owed unchecked +// write and a refused move all read as not attested. +func TestCgroupRingUnconfirmed(t *testing.T) { + t.Run("active", func(t *testing.T) { + f := newPublishFixture(t) + if err := f.b.Publish(f.publication(1, 10, false)); err != nil { + t.Fatal(err) + } + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.witness = fakeWitness{0: 2} + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + id := parentIdentity.CgroupID + if !f.b.CgroupRingUnconfirmed(id) { + t.Fatal("an unknown cgroup is not attested") + } + if err := f.b.Bind(pendingMark(true)); err != nil { + t.Fatal(err) + } + if f.b.CgroupRingUnconfirmed(id) { + t.Fatal("a checked Strict pending binding is attested") + } + unrecordedAt(f.b, map[uint64]bool{id: true}) + _ = f.b.HealNode() + if !f.b.CgroupRingUnconfirmed(id) { + t.Fatal("unrecorded credentials: not attested") + } + f.b.ringUnconfirmed = map[uint64]bool{} // isolate the owed write + f.b.uncheckPending[id] = true + if !f.b.CgroupRingUnconfirmed(id) { + t.Fatal("an owed unchecked write: not attested") + } + delete(f.b.uncheckPending, id) + audit := ContainerIdentity{Runtime: "containerd", ID: "a1", CgroupID: 50, CgroupPath: "/workloads.slice/audit"} + if err := f.b.Bind(Binding{Container: audit, Slot: 1}); err != nil { + t.Fatal(err) + } + if f.b.CgroupRingUnconfirmed(audit.CgroupID) { + t.Fatal("an Audit binding claims no protection") + } + }) + t.Run("adopted", func(t *testing.T) { + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.members.data[uint64(60)] = bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingRingChecked} + f.members.data[uint64(61)] = bindingValue{Slot: 1, Flags: bindingStrict | bindingRingChecked} + f.members.data[uint64(62)] = bindingValue{Slot: PendingSlot} + }) + if !f.b.CgroupRingUnconfirmed(60) { + t.Fatal("an adopted Strict pending check is never trusted") + } + if f.b.CgroupRingUnconfirmed(61) { + t.Fatal("an adopted checked real-slot entry is trusted") + } + if f.b.CgroupRingUnconfirmed(62) { + t.Fatal("an adopted Audit pending entry claims no protection") + } + f.b.ringUnconfirmed[61] = true + if !f.b.CgroupRingUnconfirmed(61) { + t.Fatal("an unconfirmed adopted Strict entry is not attested") + } + }) + t.Run("refused move", func(t *testing.T) { + ring := true + f, c9 := refusedMoveFixture(t, &ring) + delete(f.b.ringUnconfirmed, c9.CgroupID) // the move alone + if !f.b.CgroupRingUnconfirmed(c9.CgroupID) { + t.Fatal("a refused move: not attested") + } + }) +} diff --git a/pkg/sandboxpolicy/igbackend/nodeowner.go b/pkg/sandboxpolicy/igbackend/nodeowner.go index 4d174b8a19..5a053396b0 100644 --- a/pkg/sandboxpolicy/igbackend/nodeowner.go +++ b/pkg/sandboxpolicy/igbackend/nodeowner.go @@ -51,6 +51,11 @@ type NodeInstance interface { // baseline, so the faults an earlier instance counted do not fail the // health of this one. ResetFaults() error + // CgroupRingUnconfirmed reports whether the protection of the cgroup's + // binding is not attested (enforcement.Bindings.CgroupRingUnconfirmed): + // true for a Strict binding that has not passed the io_uring check, and + // for a cgroup the instance does not bind (unknown). + CgroupRingUnconfirmed(cgroup uint64) bool } // NodeStats counts how container binds found their policy slot. diff --git a/pkg/sandboxpolicy/igbackend/privilege_native.go b/pkg/sandboxpolicy/igbackend/privilege_native.go index b122c5984e..887bd81392 100644 --- a/pkg/sandboxpolicy/igbackend/privilege_native.go +++ b/pkg/sandboxpolicy/igbackend/privilege_native.go @@ -459,6 +459,11 @@ func (i *nativeNodeInstance) SlotHealth(slot uint32) error { // IoUringHeld reports whether an Audit binding's tasks held io_uring rings // opened before it (enforcement.Bindings.IoUringHeld). +// CgroupRingUnconfirmed: unknown (no controller) reads as not attested. +func (i *nativeNodeInstance) CgroupRingUnconfirmed(cgroup uint64) bool { + return i.bindings == nil || i.bindings.CgroupRingUnconfirmed(cgroup) +} + func (i *nativeNodeInstance) IoUringHeld(cgroup uint64) bool { return i.bindings != nil && i.bindings.IoUringHeld(cgroup) } diff --git a/pkg/sandboxpolicy/igbackend/privilege_test.go b/pkg/sandboxpolicy/igbackend/privilege_test.go index e1a6f54f61..3031da5a27 100644 --- a/pkg/sandboxpolicy/igbackend/privilege_test.go +++ b/pkg/sandboxpolicy/igbackend/privilege_test.go @@ -29,7 +29,10 @@ type fakePrivilegeInstance struct { publishErr error freeErr error healErr error - heals int + // unconfirmed: the cgroups CgroupRingUnconfirmed reports (bound ones + // otherwise read as confirmed, unbound ones as unconfirmed). + unconfirmed map[uint64]bool + heals int // capacity > 0 limits the slots the instance has. capacity int // adopted counts the kernel bindings of a restored state per slot; @@ -144,6 +147,12 @@ func (i *fakePrivilegeInstance) AdoptedBindings() map[uint32]int { return out } func (i *fakePrivilegeInstance) ResetFaults() error { i.resets++; return nil } +func (i *fakePrivilegeInstance) CgroupRingUnconfirmed(cgroup uint64) bool { + if _, bound := i.bound[cgroup]; !bound { + return true + } + return i.unconfirmed[cgroup] +} func (i *fakePrivilegeInstance) Ready() error { return i.readyErr } func (i *fakePrivilegeInstance) SlotHealth(slot uint32) error { @@ -1425,3 +1434,11 @@ func TestPrivilegeInPlaceStartRetriesCarriedPod(t *testing.T) { }) } } + +// An instance without a binding controller reports every cgroup as not +// attested: unknown never reads as confirmed. +func TestNativeCgroupRingUnconfirmedUnknown(t *testing.T) { + if !(&nativeNodeInstance{}).CgroupRingUnconfirmed(42) { + t.Fatal("no controller: not attested") + } +} From cda2148b15b93cfd49b1132af41c20b225b01899 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 12:12:23 +0100 Subject: [PATCH 16/21] fix(enforcement): a check-only walk confirms an unconfirmed SkipArming Strict binding A SkipArming Strict pending mark could be left unconfirmed (an adopted entry flagged after a credential purge at start), and since a SkipArming bind never walks, nothing ever confirmed it again; the pod stayed Faulted. A same-value re-bind of such a binding, and Heal/HealNode in their skip branches, now run a check-only walk: record the tasks' credentials and scan for io_uring rings, without arming any task. The binding is marked checked only when no ring is held and every credential was recorded; otherwise it stays unconfirmed. Heals still return ErrNotHealable for it. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 39 +++++++++++++++ .../common/enforcement/pending_test.go | 49 +++++++++++++++++++ pkg/ebpf/gadgets/common/enforcement/slots.go | 9 ++++ .../igbackend/privilege_native.go | 4 +- 4 files changed, 99 insertions(+), 2 deletions(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index ec9d3778f1..5b6dc3ee93 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -533,6 +533,20 @@ func (b *Bindings) bind(c Binding) error { if hadMove && b.moves[id.CgroupID] != c { delete(b.moves, id.CgroupID) } + // A SkipArming Strict binding never arms, so the walk below never runs + // for it: a re-bind of the same value while it is unconfirmed checks it + // without arming (checkOnly). A held ring keeps it unconfirmed (not a + // failure, as a refresh below); a failed record too (the error). + if bound && b.value(previous) == b.value(c) && !b.unarmed[id.CgroupID] && + !b.uncheckPending[id.CgroupID] && c.SkipArming && + b.ringUnconfirmed[id.CgroupID] && b.classOf(c) && b.walksCreds() { + err := b.checkOnly(c) + if err != nil && !errors.Is(err, ErrIoUringHeld) { + return err + } + b.active[id.CgroupID] = c + return nil + } // A Strict binding that is unconfirmed binds again, so the walk can // confirm it (a refresh re-binds the same value). A SkipArming binding // that becomes one that arms binds again too: its tasks were never armed. @@ -941,6 +955,31 @@ func (b *Bindings) arm(c Binding, newStrict bool) error { return nil } +// checkOnly checks an unconfirmed SkipArming Strict binding without arming +// its tasks: it records their credentials and scans their io_uring rings. +// With no ring the binding is confirmed (bindingRingChecked); a ring +// (ErrIoUringHeld) or a failed record keeps it unconfirmed. Called with mu +// held. +func (b *Bindings) checkOnly(c Binding) error { + id := c.Container.CgroupID + record := b.recordCreds + if record == nil { + record = b.creds.record // walksCreds: one of them is set + } + v := b.value(c) + ring, err := record(id, c.Container.CgroupPath, v.Flags, v.Slot) + if err != nil { + return err + } + if ring { + return fmt.Errorf("%w (container %s, cgroup %d)", ErrIoUringHeld, c.Container.ID, id) + } + delete(b.ringUnconfirmed, id) + b.setRingChecked(id, true) + _ = b.members.Put(id, b.kernelValue(c, true)) // not retried: an adopter checks again + return nil +} + // Kept reports whether the kernel holds an entry for the cgroup (an active // or adopted binding), and whether that entry is Strict: a refused bind // (ErrIoUringHeld) leaves the previous entry in place, which enforces only diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index 3427737a93..295eefae09 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -1280,3 +1280,52 @@ func TestCgroupRingUnconfirmed(t *testing.T) { } }) } + +// A SkipArming Strict binding that is unconfirmed (an adopted entry flagged +// by the purge at start, taken over without a walk) is checked by a re-bind +// of the same value with a check-only walk: the credentials are recorded and +// the rings scanned, no task is armed. A held ring or a failed record keeps +// it unconfirmed; once the ring is closed the re-bind confirms it. A heal +// does the same check, and still reports the binding as not healable (its +// tasks are not armed). +func TestSkipArmingCheckOnlyWalk(t *testing.T) { + f := newPublishFixture(t) + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.witness = fakeWitness{0: 2} + arms, walks := 0, 0 + f.b.armExisting = func(Map, string) error { arms++; return nil } + ring := true + var recordErr error + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { walks++; return ring, recordErr } + id := parentIdentity.CgroupID + mark := pendingMark(true) + mark.SkipArming = true + if err := f.b.Bind(mark); err != nil || walks != 0 { + t.Fatalf("a SkipArming bind walks nothing: %v (walks %d)", err, walks) + } + f.b.ringUnconfirmed[id] = true // as after the purge at start + if err := f.b.Bind(mark); err != nil || walks != 1 || !f.b.CgroupRingUnconfirmed(id) { + t.Fatalf("held ring: %v, walks %d, unconfirmed %v", err, walks, f.b.CgroupRingUnconfirmed(id)) + } + recordErr = fmt.Errorf("%w: 1 tasks", ErrCredUnrecorded) + ring = false + if err := f.b.Bind(mark); !errors.Is(err, ErrCredUnrecorded) || !f.b.CgroupRingUnconfirmed(id) { + t.Fatalf("a failed record keeps it unconfirmed: %v", err) + } + recordErr = nil + if err := f.b.HealNode(); !errors.Is(err, ErrNotHealable) { + t.Fatalf("HealNode: %v", err) + } + if f.b.CgroupRingUnconfirmed(id) || f.members.data[id].(bindingValue).Flags&bindingRingChecked == 0 { + t.Fatalf("the heal's check confirms it: entry %+v", f.members.data[id]) + } + if arms != 0 { + t.Fatalf("no task is armed: %d", arms) + } + // And the re-bind path confirms it as well. + f.b.ringUnconfirmed[id] = true + f.b.setRingChecked(id, false) + if err := f.b.Bind(mark); err != nil || f.b.CgroupRingUnconfirmed(id) || arms != 0 { + t.Fatalf("re-bind with the ring closed: %v, unconfirmed %v, arms %d", err, f.b.CgroupRingUnconfirmed(id), arms) + } +} diff --git a/pkg/ebpf/gadgets/common/enforcement/slots.go b/pkg/ebpf/gadgets/common/enforcement/slots.go index 9797e72d66..0f94cff47e 100644 --- a/pkg/ebpf/gadgets/common/enforcement/slots.go +++ b/pkg/ebpf/gadgets/common/enforcement/slots.go @@ -406,6 +406,12 @@ func (b *Bindings) Heal(slot uint32) error { } if !armable(c) { skipped = true + if b.ringUnconfirmed[c.Container.CgroupID] && b.classOf(c) && b.walksCreds() && !b.uncheckPending[c.Container.CgroupID] { + // Not armed, but checked (checkOnly): confirmed once its + // ring is closed. A failure keeps it unconfirmed; the heal + // still reports it as not healable. + _ = b.checkOnly(c) + } if b.uncheckPending[c.Container.CgroupID] { // Not armed, but its owed unchecked entry is written. A // safeguard: no bind leaves a binding that does not arm @@ -469,6 +475,9 @@ func (b *Bindings) HealNode() error { if !armable(c) { // Node faults concern Strict slots only. skipped = skipped || b.classOf(c) + if b.ringUnconfirmed[c.Container.CgroupID] && b.classOf(c) && b.walksCreds() && !b.uncheckPending[c.Container.CgroupID] { + _ = b.checkOnly(c) // as in Heal + } if b.uncheckPending[c.Container.CgroupID] { // Not armed, but its owed unchecked entry is written. A // safeguard: no bind leaves a binding that does not arm diff --git a/pkg/sandboxpolicy/igbackend/privilege_native.go b/pkg/sandboxpolicy/igbackend/privilege_native.go index 887bd81392..367ed586a9 100644 --- a/pkg/sandboxpolicy/igbackend/privilege_native.go +++ b/pkg/sandboxpolicy/igbackend/privilege_native.go @@ -457,13 +457,13 @@ func (i *nativeNodeInstance) SlotHealth(slot uint32) error { return errors.Join(errs...) } -// IoUringHeld reports whether an Audit binding's tasks held io_uring rings -// opened before it (enforcement.Bindings.IoUringHeld). // CgroupRingUnconfirmed: unknown (no controller) reads as not attested. func (i *nativeNodeInstance) CgroupRingUnconfirmed(cgroup uint64) bool { return i.bindings == nil || i.bindings.CgroupRingUnconfirmed(cgroup) } +// IoUringHeld reports whether an Audit binding's tasks held io_uring rings +// opened before it (enforcement.Bindings.IoUringHeld). func (i *nativeNodeInstance) IoUringHeld(cgroup uint64) bool { return i.bindings != nil && i.bindings.IoUringHeld(cgroup) } From 8b1258e0de4b3c39196520e5cc443c9f015b43ad Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 12:35:53 +0100 Subject: [PATCH 17/21] fix(enforcement): an adopted Strict entry without a passed check is unconfirmed adopt() left ringUnconfirmed empty for an adopted Strict entry without bindingRingChecked (for example after an interrupted Audit->Strict rewrite), so CgroupRingUnconfirmed and SlotHealth reported it attested. In sections that walk credentials, every adopted Strict entry without the checked flag and every adopted Strict pending entry is now unconfirmed until a walk passes. When a held ring refuses a Strict binding c over a different unconfirmed Strict real-slot entry (active or adopted), keeping that entry could enforce a weaker policy than c; bind now installs c unchecked, active and unconfirmed instead (its slot reports it and a heal confirms it). An adopted entry equal to c, a Strict pending entry, and an Audit entry are restored as before (Audit->Strict needs a passed check; the bind error keeps status honest). Start keeps such a take-over instead of failing, so a replacement is never blocked. Addresses Copilot review on #1160 (comment 4799126761). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 87 +++++++-- .../common/enforcement/pending_test.go | 176 ++++++++++++++++++ pkg/ebpf/gadgets/common/enforcement/slots.go | 13 ++ 3 files changed, 256 insertions(+), 20 deletions(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index 5b6dc3ee93..e4380889ed 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -638,6 +638,42 @@ func (b *Bindings) bind(c Binding) error { b.active[id.CgroupID] = c return nil } + // A held ring refused c (Strict: on a real slot, or Strict + // pending) while the entry it replaces is a different + // unconfirmed Strict one on a real slot (active, or adopted and + // not trusted): keeping the old policy could be weaker than + // c's (a Strict pending c denies more than any policy), and + // the ring exposure is the same for both, so c is installed. + // Its entry (written above, unchecked) stays; it is active and + // unconfirmed, and a heal walks it and confirms it once the + // ring is closed (healArm for a real slot; HealNode or a + // re-bind for a pending one). Not a failure: the caller + // commits and reports ProtectionUnconfirmed. + // Restored below instead, with the error, as before: + // - an adopted entry equal to c's (a same-value active one is + // the refresh above); + // - a Strict pending entry: it denies more than c's policy; + // - an Audit entry: Audit to Strict needs a passed check, so + // c is not installed. Fail-closed at the owner level: the + // bind error makes the owner report the binding as not + // committed (unconfirmed) and retry it, so status never + // claims c's Strict protection while the cgroup runs the + // Audit entry. + unchecked := adopted + unchecked.Flags &^= bindingRingChecked + prevStrictReal := (bound && b.classOf(previous) && previous.Slot != PendingSlot) || + (wasAdopted && adopted.Flags&bindingStrict != 0 && adopted.Slot != PendingSlot && unchecked != b.value(c)) + if errors.Is(err, ErrIoUringHeld) && prevStrictReal && b.classOf(c) { + b.active[id.CgroupID] = c + delete(b.adopted, id.CgroupID) + delete(b.unarmed, id.CgroupID) + delete(b.ioUringAudit, id.CgroupID) + delete(b.moves, id.CgroupID) + b.setRingChecked(id.CgroupID, false) + b.ringUnconfirmed[id.CgroupID] = true + b.setCredActive() + return nil + } if bound && !errors.Is(err, ErrContainerGone) { // Undo the move, so a retry moves and arms again. prevChecked := b.ringChecked[id.CgroupID] && !uncheckPrevious @@ -1229,15 +1265,14 @@ func (b *Bindings) SlotFaults(slot uint32) (uint64, error) { // keepUnrecorded installs a startup binding whose walk armed its tasks but // could not record all their credentials (ErrCredUnrecorded, a Strict pending -// binding), or the Strict pending binding kept when a take-over of an adopted -// Strict pending entry found a ring (ErrIoUringHeld): one binding must not -// stop the start of the whole section, and -// dropping it would leave its cgroup unprotected. Its kernel entry is -// written without bindingRingChecked (a Strict pending entry denies what it -// judges), it is active, and it is unconfirmed (RingUnconfirmed), so a heal -// walks it again and confirms it once the record has room and no ring is -// held. A failed write -// fails the start. Called with mu held. +// binding), or the binding kept when a take-over of an adopted Strict entry +// whose check is not trusted found a ring (ErrIoUringHeld; c itself, or the +// pending entry's own flags, see start): one binding must not stop the start of the +// whole section, and dropping it would leave its cgroup unprotected. Its +// kernel entry is written without bindingRingChecked (a Strict entry denies +// what it judges), it is active, and it is unconfirmed (RingUnconfirmed), so +// a heal walks it again and confirms it once the record has room and no ring +// is held. A failed write fails the start. Called with mu held. func (b *Bindings) keepUnrecorded(c Binding) error { id := c.Container.CgroupID if err := b.members.Put(id, b.kernelValue(c, false)); err != nil { @@ -1313,29 +1348,41 @@ func (b *Bindings) start(policy Map, members BindingMap, armed Map, faults, witn } for _, c := range b.desired { v, adopted := b.adopted[c.Container.CgroupID] - distrusted := adopted && v.Slot == PendingSlot && v.Flags&bindingStrict != 0 + // An adopted Strict entry whose check is not trusted: a pending + // one (see bind), or one adopt found unconfirmed (no + // bindingRingChecked). Its take-over walks as a new Strict binding. + distrusted := adopted && v.Flags&bindingStrict != 0 && + (v.Slot == PendingSlot || b.ringUnconfirmed[c.Container.CgroupID]) err := b.bind(c) switch { case errors.Is(err, ErrCredUnrecorded): err = b.keepUnrecorded(c) case distrusted && errors.Is(err, ErrIoUringHeld) && c.Slot == PendingSlot && c.Strict: - // A take-over of a Strict pending entry whose check is not - // trusted (see bind) found a ring. Not a start failure: a + // The take-over found a ring. Not a start failure: a // replacement must not be blocked (the instance it replaces // may enforce nothing). c is Strict pending too: kept, // unchecked and unconfirmed. err = b.keepUnrecorded(c) + case distrusted && errors.Is(err, ErrIoUringHeld) && v.Slot != PendingSlot: + // The same for c equal to the adopted Strict real-slot entry + // (a different one is installed by bind itself): the entry is + // c's, kept as the kernel holds it, unchecked and unconfirmed; + // a heal of its slot walks it and confirms it. + err = b.keepUnrecorded(c) case distrusted && errors.Is(err, ErrIoUringHeld): - // The same, for a move to another slot: the pending entry is - // kept, never moved before the check passes. It becomes an + // The same for a move off an adopted Strict pending entry: + // the pending entry is kept as the kernel holds it, never + // moved before the check passes (it denies more than c's + // policy). It becomes an // active Strict pending binding with the entry's flags under - // c's identity, unchecked and unconfirmed. c is recorded + // c's identity, unchecked and unconfirmed, and c is recorded // (moves): a heal of c's slot (or a node heal) binds c again - // once the ring is closed, which moves it (retryMoves); a - // bind or unbind of the cgroup by the owner replaces it. - err = b.keepUnrecorded(Binding{Container: c.Container, Slot: PendingSlot, Strict: true, - Subtree: v.Flags&bindingSubtree != 0, RuntimeHelpers: v.Flags&bindingRuntimeHelpers != 0}) - if err == nil { + // once the ring is closed, which moves it (retryMoves); a bind + // or unbind of the cgroup by the owner replaces it. + kept := Binding{Container: c.Container, Slot: PendingSlot, Strict: true, + Subtree: v.Flags&bindingSubtree != 0, RuntimeHelpers: v.Flags&bindingRuntimeHelpers != 0} + err = b.keepUnrecorded(kept) + if err == nil && kept != c { // The owner records c on its slot: that slot is not // healthy until a heal moves the cgroup there. b.moves[c.Container.CgroupID] = c diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index 295eefae09..68da0f53ea 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -1329,3 +1329,179 @@ func TestSkipArmingCheckOnlyWalk(t *testing.T) { t.Fatalf("re-bind with the ring closed: %v, unconfirmed %v, arms %d", err, f.b.CgroupRingUnconfirmed(id), arms) } } + +// An adopted Strict entry without bindingRingChecked (a real slot too, for +// example after an interrupted Audit to Strict rewrite) has not passed the io_uring +// check: in a section that walks credentials it is unconfirmed from the +// adoption on (slot health and the per-cgroup query report it), and the +// take-over walk confirms it. A checked one, an Audit one, and any entry in +// a section that walks no credentials are not. +func TestAdoptedStrictWithoutCheckIsUnconfirmed(t *testing.T) { + seed := func(walks bool) func(*publishFixture) { + return func(f *publishFixture) { + f.state.data[uint32(1)] = slotState(0, 4) + f.strictAt[Storage(1, 0)] = true + f.members.data[uint64(70)] = bindingValue{Slot: 1, Flags: bindingStrict} // not checked + f.members.data[uint64(71)] = bindingValue{Slot: 1, Flags: bindingStrict | bindingRingChecked} // checked + if walks { + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + } + } + } + f := newPublishFixtureWith(t, seed(true)) + if !f.b.CgroupRingUnconfirmed(70) || f.b.CgroupRingUnconfirmed(71) || f.b.RingUnconfirmed(1) != 1 { + t.Fatalf("unchecked %v, checked %v, slot %d", f.b.CgroupRingUnconfirmed(70), f.b.CgroupRingUnconfirmed(71), f.b.RingUnconfirmed(1)) + } + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + c := Binding{Container: ContainerIdentity{Runtime: "containerd", ID: "c70", CgroupID: 70, CgroupPath: "/workloads.slice/c70"}, Slot: 1} + if err := f.b.Bind(c); err != nil { + t.Fatal(err) + } + if f.b.CgroupRingUnconfirmed(70) || f.b.RingUnconfirmed(1) != 0 { + t.Fatalf("the take-over walk confirms it: %d", f.b.RingUnconfirmed(1)) + } + // No credential walk in the section: nothing to confirm. + f = newPublishFixtureWith(t, seed(false)) + if f.b.RingUnconfirmed(1) != 0 { + t.Fatalf("a section without credential walks: %d", f.b.RingUnconfirmed(1)) + } +} + +// A startup take-over of an adopted unconfirmed Strict real-slot entry that a +// held ring refuses does not fail the start, and installs the wanted binding +// unconfirmed (a move to another real slot is never weaker than keeping the +// old policy: the ring exposure is the same): its slot reports it, and a heal +// of that slot confirms it once the ring is closed. +func TestStartKeepsUnconfirmedRealSlotTakeOverWithRing(t *testing.T) { + c70 := ContainerIdentity{Runtime: "containerd", ID: "c70", CgroupID: 70, CgroupPath: "/workloads.slice/c70"} + for _, slot := range []uint32{1, 2} { + t.Run(fmt.Sprintf("wanted slot %d", slot), func(t *testing.T) { + ring := true + wanted := Binding{Container: c70, Slot: slot} + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.state.data[uint32(1)] = slotState(0, 4) + f.state.data[uint32(2)] = slotState(0, 5) + f.strictAt[Storage(1, 0)] = true + f.strictAt[Storage(2, 0)] = true + f.members.data[c70.CgroupID] = bindingValue{Slot: 1, Flags: bindingStrict} + f.b.desired[selector(c70)] = wanted + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return ring, nil } + f.armed = &fakeMap{typ: ebpf.TaskStorage} + }) + if v := f.members.data[c70.CgroupID].(bindingValue); v != (bindingValue{Slot: slot, Flags: bindingStrict}) { + t.Fatalf("the wanted Strict entry, unchecked: %+v", v) + } + other := 3 - slot + if f.b.active[c70.CgroupID] != wanted || !f.b.CgroupRingUnconfirmed(c70.CgroupID) || f.b.RingUnconfirmed(slot) != 1 || f.b.RingUnconfirmed(other) != 0 || len(f.b.moves) != 0 { + t.Fatalf("active %+v, unconfirmed %v, slot %d: %d, moves %+v", f.b.active[c70.CgroupID], f.b.CgroupRingUnconfirmed(c70.CgroupID), slot, f.b.RingUnconfirmed(slot), f.b.moves) + } + ring = false + if err := f.b.Heal(slot); err != nil { + t.Fatalf("heal: %v", err) + } + if v := f.members.data[c70.CgroupID].(bindingValue); v != (bindingValue{Slot: slot, Flags: bindingStrict | bindingRingChecked}) || f.b.RingUnconfirmed(slot) != 0 { + t.Fatalf("confirmed: %+v", v) + } + }) + } +} + +// A live take-over or move from an unconfirmed Strict real-slot binding +// (adopted or active) to another Strict real slot that a held ring refuses +// installs the wanted binding unconfirmed (never weaker than the old policy); +// a heal confirms it. From an Audit binding the refusal keeps the Audit +// entry, as before; from a Strict pending one the pending entry stays. +func TestLiveRealSlotMoveWithRingInstallsUnconfirmed(t *testing.T) { + c70 := ContainerIdentity{Runtime: "containerd", ID: "c70", CgroupID: 70, CgroupPath: "/workloads.slice/c70"} + wanted := Binding{Container: c70, Slot: 2} + for _, tt := range []struct { + name string + adopted bindingValue + bound *Binding // an active previous binding instead + install bool + }{ + {name: "adopted Strict real slot", adopted: bindingValue{Slot: 1, Flags: bindingStrict}, install: true}, + {name: "active unconfirmed Strict real slot", bound: &Binding{Container: c70, Slot: 1}, install: true}, + {name: "adopted Audit real slot", adopted: bindingValue{Slot: 3}}, + {name: "adopted Strict pending", adopted: bindingValue{Slot: PendingSlot, Flags: bindingStrict}}, + } { + t.Run(tt.name, func(t *testing.T) { + ring := false + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.state.data[uint32(1)] = slotState(0, 4) + f.state.data[uint32(2)] = slotState(0, 5) + f.state.data[uint32(3)] = slotState(0, 6) + f.strictAt[Storage(1, 0)] = true + f.strictAt[Storage(2, 0)] = true + if tt.bound == nil { + f.members.data[c70.CgroupID] = tt.adopted + } + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return ring, nil } + f.armed = &fakeMap{typ: ebpf.TaskStorage} + }) + if tt.bound != nil { + if err := f.b.Bind(*tt.bound); err != nil { + t.Fatal(err) + } + f.b.ringUnconfirmed[c70.CgroupID] = true // as kept at start + f.b.setRingChecked(c70.CgroupID, false) + } + before := f.members.data[c70.CgroupID].(bindingValue) + ring = true + err := f.b.Bind(wanted) + v := f.members.data[c70.CgroupID].(bindingValue) + if !tt.install { + if !errors.Is(err, ErrIoUringHeld) || v.Slot != before.Slot || v.Flags&bindingStrict != before.Flags&bindingStrict { + t.Fatalf("refused, the entry stays: %v, %+v (was %+v)", err, v, before) + } + return + } + if err != nil || v != (bindingValue{Slot: 2, Flags: bindingStrict}) || f.b.active[c70.CgroupID] != wanted || f.b.RingUnconfirmed(2) != 1 { + t.Fatalf("installed unconfirmed: %v, %+v, active %+v, unconfirmed %d", err, v, f.b.active[c70.CgroupID], f.b.RingUnconfirmed(2)) + } + if _, adopted := f.b.adopted[c70.CgroupID]; adopted || len(f.b.moves) != 0 { + t.Fatalf("adopted %v, moves %+v", adopted, f.b.moves) + } + ring = false + if err := f.b.Heal(2); err != nil || f.b.RingUnconfirmed(2) != 0 || f.members.data[c70.CgroupID].(bindingValue).Flags&bindingRingChecked == 0 { + t.Fatalf("heal confirms: %v, unconfirmed %d", err, f.b.RingUnconfirmed(2)) + } + }) + } +} + +// A Strict pending c (it denies more than any policy) refused by a held ring +// over an unconfirmed Strict real-slot entry (adopted or active) is +// installed unchecked and unconfirmed, never the real-slot entry restored. +func TestPendingMarkOverRealSlotWithRingInstallsUnconfirmed(t *testing.T) { + c70 := ContainerIdentity{Runtime: "containerd", ID: "c70", CgroupID: 70, CgroupPath: "/workloads.slice/c70"} + mark := Binding{Container: c70, Slot: PendingSlot, Strict: true, Subtree: true, RuntimeHelpers: true} + for _, bound := range []bool{false, true} { + t.Run(fmt.Sprintf("active %v", bound), func(t *testing.T) { + ring := false + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.state.data[uint32(1)] = slotState(0, 4) + f.strictAt[Storage(1, 0)] = true + if !bound { + f.members.data[c70.CgroupID] = bindingValue{Slot: 1, Flags: bindingStrict} + } + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return ring, nil } + f.armed = &fakeMap{typ: ebpf.TaskStorage} + }) + if bound { + if err := f.b.Bind(Binding{Container: c70, Slot: 1}); err != nil { + t.Fatal(err) + } + f.b.ringUnconfirmed[c70.CgroupID] = true + f.b.setRingChecked(c70.CgroupID, false) + } + ring = true + err := f.b.Bind(mark) + v := f.members.data[c70.CgroupID].(bindingValue) + if err != nil || v != (bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers}) || + f.b.active[c70.CgroupID] != mark || !f.b.CgroupRingUnconfirmed(c70.CgroupID) || f.b.RingUnconfirmed(PendingSlot) != 1 { + t.Fatalf("installed unconfirmed: %v, entry %+v, active %+v", err, v, f.b.active[c70.CgroupID]) + } + }) + } +} diff --git a/pkg/ebpf/gadgets/common/enforcement/slots.go b/pkg/ebpf/gadgets/common/enforcement/slots.go index 0f94cff47e..86444d44dd 100644 --- a/pkg/ebpf/gadgets/common/enforcement/slots.go +++ b/pkg/ebpf/gadgets/common/enforcement/slots.go @@ -674,6 +674,19 @@ func (b *Bindings) adopt() error { } adopted[cgroup] = v } + if b.walksCreds() { + // A Strict entry that has not passed the io_uring check (no + // bindingRingChecked: an interrupted Audit to Strict rewrite, a + // failed check write), or a Strict pending one (its check is never + // trusted, see bind), is unconfirmed until a walk checks it: the + // take-over (bind), or recordAdopted after a purge. Not a start + // failure. + for cgroup, v := range adopted { + if v.Flags&bindingStrict != 0 && (v.Flags&bindingRingChecked == 0 || v.Slot == PendingSlot) { + b.ringUnconfirmed[cgroup] = true + } + } + } b.adopted = adopted return errors.Join(errs...) } From dc21ea97c80846a3a9b5372d7fc7713ea47c487c Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 12:56:28 +0100 Subject: [PATCH 18/21] fix(enforcement): class rewrites keep the ring-check marker; no reload for a ring-only SkipArming problem - rewriteClass changed an adopted entry's flags but not its ringUnconfirmed marker: Audit->Strict read as attested without a check, and unchecked Strict->Audit kept the slot unhealthy. An adopted entry made Strict in a credential-walking section is now unconfirmed, and one made Audit is cleared. - A Strict SkipArming binding is now ring-checked too: a fresh bind runs the check-only walk (records credentials, scans rings, arms nothing), so it is confirmed at once or bound but unconfirmed, never refused. - Heal and HealNode return ErrNotHealable for a non-arming binding only when there are slot tracking faults, an unknown fault count or new node faults (lost marks only a new instance can re-arm); a binding whose only problem is the ring check is check-only walked and stays unconfirmed, so the owner reports ProtectionUnconfirmed without reloading. Addresses Copilot review on #1160 (comments 4799346149, 4799126761). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 21 +++- .../common/enforcement/pending_test.go | 118 ++++++++++++++++-- pkg/ebpf/gadgets/common/enforcement/slots.go | 18 ++- .../gadgets/common/enforcement/slots_test.go | 10 +- pkg/sandboxpolicy/igbackend/privilege_test.go | 37 +++++- 5 files changed, 186 insertions(+), 18 deletions(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index e4380889ed..40b03fe152 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -742,9 +742,22 @@ func (b *Bindings) bind(c Binding) error { } } delete(b.unarmed, id.CgroupID) - if walked || !strict { + switch { + case strict && !checked && !walked && c.SkipArming && b.walksCreds(): + // A Strict binding that does not arm is checked without arming + // (checkOnly): confirmed when no task holds a ring and every + // credential is recorded; otherwise it binds unconfirmed (a + // re-bind or a heal checks it again). Never refused: the walk + // below would refuse an arming binding, but status reports this + // one as unconfirmed. + if b.checkOnly(c) == nil { + checked = true + } else { + b.ringUnconfirmed[id.CgroupID] = true + } + case walked || !strict: // The walk found no ring that refuses a Strict binding, or the - // binding is not Strict. A SkipArming bind walks nothing. + // binding is not Strict. delete(b.ringUnconfirmed, id.CgroupID) } b.setRingChecked(id.CgroupID, checked) @@ -795,7 +808,9 @@ func (b *Bindings) checkable(c Binding) bool { // tasks were not walked, so rings opened before it may run under credentials // the record lacks. The next bind walks it (see the early return in bind). func (b *Bindings) markUnchecked(cgroup uint64, c Binding, strictEntry, checked bool) { - if strictEntry && !checked && b.checkable(c) { + // A SkipArming binding too: its check-only walk (a re-bind, a heal) + // confirms it, and a heal does not reload for it (see Heal). + if strictEntry && !checked && b.walksCreds() { b.ringUnconfirmed[cgroup] = true } } diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index 68da0f53ea..610bca4583 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -456,9 +456,12 @@ func TestRebindFromSkipArmingArms(t *testing.T) { f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { walks++; return ring, nil } mark := pendingMark(true) mark.SkipArming = true - if err := f.b.Bind(mark); err != nil || len(armedPaths) != 0 || walks != 0 { + // A SkipArming mark arms nothing; its check-only walk records + // the credentials and scans the rings. + if err := f.b.Bind(mark); err != nil || len(armedPaths) != 0 || walks != 1 { t.Fatalf("a SkipArming mark arms nothing: %v %v %d", err, armedPaths, walks) } + walks = 0 next := pendingMark(true) next.Container = containerInParent if err := f.b.Rebind(parentIdentity, next); err != nil { @@ -495,9 +498,10 @@ func TestBindFromSkipArmingRingHeldHeals(t *testing.T) { f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { walks++; return ring, nil } mark := pendingMark(true) mark.SkipArming = true - if err := f.b.Bind(mark); err != nil { - t.Fatal(err) + if err := f.b.Bind(mark); err != nil || walks != 1 || f.b.RingUnconfirmed(PendingSlot) != 1 { + t.Fatalf("the check-only walk finds the ring: %v, walks %d", err, walks) } + walks = 0 next := pendingMark(true) if err := f.b.Bind(next); err != nil { t.Fatal(err) @@ -1300,11 +1304,12 @@ func TestSkipArmingCheckOnlyWalk(t *testing.T) { id := parentIdentity.CgroupID mark := pendingMark(true) mark.SkipArming = true - if err := f.b.Bind(mark); err != nil || walks != 0 { - t.Fatalf("a SkipArming bind walks nothing: %v (walks %d)", err, walks) - } - f.b.ringUnconfirmed[id] = true // as after the purge at start + // A fresh SkipArming bind checks without arming: the ring keeps it + // unconfirmed (never refused). if err := f.b.Bind(mark); err != nil || walks != 1 || !f.b.CgroupRingUnconfirmed(id) { + t.Fatalf("fresh bind, held ring: %v (walks %d)", err, walks) + } + if err := f.b.Bind(mark); err != nil || walks != 2 || !f.b.CgroupRingUnconfirmed(id) { t.Fatalf("held ring: %v, walks %d, unconfirmed %v", err, walks, f.b.CgroupRingUnconfirmed(id)) } recordErr = fmt.Errorf("%w: 1 tasks", ErrCredUnrecorded) @@ -1505,3 +1510,102 @@ func TestPendingMarkOverRealSlotWithRingInstallsUnconfirmed(t *testing.T) { }) } } + +// A class change of a slot keeps ringUnconfirmed in step with the adopted +// entries it rewrites, in a section that walks credentials: made Strict +// (written without bindingRingChecked), an entry is unconfirmed until a +// walk passes; made Audit, it claims no protection and its marker goes. +func TestRewriteClassKeepsRingUnconfirmed(t *testing.T) { + adoptedFixture := func(t *testing.T, flags uint32, strictSlot bool) *publishFixture { + return newPublishFixtureWith(t, func(f *publishFixture) { + f.state.data[uint32(1)] = slotState(0, 4) + f.strictAt[Storage(1, 0)] = strictSlot + f.members.data[uint64(70)] = bindingValue{Slot: 1, Flags: flags} + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + }) + } + t.Run("adopted Audit to Strict", func(t *testing.T) { + f := adoptedFixture(t, 0, false) + if f.b.RingUnconfirmed(1) != 0 { + t.Fatal("fixture: an Audit entry") + } + if err := f.b.Publish(f.publication(1, 10, true)); err != nil { + t.Fatal(err) + } + if v := f.members.data[uint64(70)].(bindingValue); v != (bindingValue{Slot: 1, Flags: bindingStrict}) { + t.Fatalf("entry %+v", v) + } + if !f.b.CgroupRingUnconfirmed(70) || f.b.RingUnconfirmed(1) != 1 { + t.Fatalf("made Strict without a check: unconfirmed %v, slot %d", f.b.CgroupRingUnconfirmed(70), f.b.RingUnconfirmed(1)) + } + }) + t.Run("adopted unchecked Strict to Audit", func(t *testing.T) { + f := adoptedFixture(t, bindingStrict, true) + if f.b.RingUnconfirmed(1) != 1 { + t.Fatal("fixture: an unconfirmed Strict entry") + } + if err := f.b.Publish(f.publication(1, 10, false)); err != nil { + t.Fatal(err) + } + if f.b.CgroupRingUnconfirmed(70) || f.b.RingUnconfirmed(1) != 0 { + t.Fatalf("made Audit: unconfirmed %v, slot %d", f.b.CgroupRingUnconfirmed(70), f.b.RingUnconfirmed(1)) + } + }) +} + +// A Strict SkipArming binding (a parent cgroup binding) whose only problem is the ring +// check does not make a heal return ErrNotHealable (no reload): the heal's +// check-only walk keeps it unconfirmed while a task holds a ring (the slot +// stays unhealthy) and confirms it once the ring is closed. With tracking +// faults in the slot (lost marks a heal cannot re-arm under it) the heal +// still returns ErrNotHealable; HealNode the same with new node faults. +func TestHealSkipArmingRingOnlyIsNotUnhealable(t *testing.T) { + group := ContainerIdentity{Runtime: "parent", ID: "uid-5", CgroupID: 80, CgroupPath: "/workloads.slice/parent-uid-5"} + setup := func(t *testing.T, ring *bool) *publishFixture { + f := newPublishFixture(t) + if err := f.b.Publish(f.publication(1, 10, true)); err != nil { + t.Fatal(err) + } + f.b.armed = &fakeMap{typ: ebpf.TaskStorage} + f.b.witness = fakeWitness{0: 0} + arms := 0 + f.b.armExisting = func(Map, string) error { arms++; return nil } + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return *ring, nil } + if err := f.b.Bind(Binding{Container: group, Slot: 1, Subtree: true, SkipArming: true}); err != nil { + t.Fatal(err) + } + if arms != 0 { + t.Fatal("a parent cgroup binding arms nothing") + } + return f + } + t.Run("ring only", func(t *testing.T) { + ring := true + f := setup(t, &ring) + if f.b.RingUnconfirmed(1) != 1 || !f.b.CgroupRingUnconfirmed(group.CgroupID) { + t.Fatal("a held ring: unconfirmed") + } + if err := f.b.Heal(1); err != nil || f.b.RingUnconfirmed(1) != 1 { + t.Fatalf("no reload, still unconfirmed: %v, %d", err, f.b.RingUnconfirmed(1)) + } + if err := f.b.HealNode(); err != nil { + t.Fatalf("HealNode without node faults: %v", err) + } + ring = false + if err := f.b.Heal(1); err != nil || f.b.RingUnconfirmed(1) != 0 || f.b.CgroupRingUnconfirmed(group.CgroupID) { + t.Fatalf("the check-only walk confirms it: %v, %d", err, f.b.RingUnconfirmed(1)) + } + }) + t.Run("tracking faults", func(t *testing.T) { + ring := false + f := setup(t, &ring) + f.faults[1] = 3 + if err := f.b.Heal(1); !errors.Is(err, ErrNotHealable) { + t.Fatalf("lost marks under a parent cgroup binding: %v", err) + } + f.b.witness = fakeWitness{0: 2} + if err := f.b.HealNode(); !errors.Is(err, ErrNotHealable) { + t.Fatalf("node faults with a Strict parent cgroup binding: %v", err) + } + }) +} diff --git a/pkg/ebpf/gadgets/common/enforcement/slots.go b/pkg/ebpf/gadgets/common/enforcement/slots.go index 86444d44dd..20832996a6 100644 --- a/pkg/ebpf/gadgets/common/enforcement/slots.go +++ b/pkg/ebpf/gadgets/common/enforcement/slots.go @@ -269,6 +269,14 @@ func (b *Bindings) rewriteClass(slot uint32, strict bool) error { continue } b.adopted[cgroup] = v + // Written without bindingRingChecked: a Strict entry is + // unconfirmed until a walk checks it (adopt's rule); an Audit one + // claims no protection. + if strict && b.walksCreds() { + b.ringUnconfirmed[cgroup] = true + } else { + delete(b.ringUnconfirmed, cgroup) + } } return errors.Join(errs...) } @@ -433,9 +441,12 @@ func (b *Bindings) Heal(slot uint32) error { if len(errs) > 0 { return errors.Join(errs...) } - if skipped { + if skipped && (count != r.faultBase || r.faultUnknown) { // A binding that never arms covers tasks this heal did not mark: - // the faults stay counted. + // the faults stay counted. Without a fault to heal (the slot is + // unhealthy only because a binding is unconfirmed) a binding that + // does not arm needs no reload: its check-only walk above checks + // it, and it stays unconfirmed until that passes. return fmt.Errorf("%w: slot %d has bindings that do not arm", ErrNotHealable, slot) } r.faultBase, r.faultUnknown = count, false @@ -497,7 +508,8 @@ func (b *Bindings) HealNode() error { if len(errs) > 0 { return errors.Join(errs...) } - if skipped { + if skipped && count != b.nodeFaultBase { + // As in Heal: only node faults need the tasks re-armed. return fmt.Errorf("%w: Strict bindings that do not arm", ErrNotHealable) } b.nodeFaultBase = count diff --git a/pkg/ebpf/gadgets/common/enforcement/slots_test.go b/pkg/ebpf/gadgets/common/enforcement/slots_test.go index d602b01919..3a63a60d14 100644 --- a/pkg/ebpf/gadgets/common/enforcement/slots_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/slots_test.go @@ -955,17 +955,19 @@ func TestAdoptedEntryIsReadAtBind(t *testing.T) { } } -// A SkipArming bind (a parent cgroup binding) walks nothing, so it keeps an unconfirmed -// binding unconfirmed; an unbind clears it. +// A SkipArming bind (a parent cgroup binding) arms nothing; its check-only +// walk keeps an unconfirmed binding unconfirmed while a task holds a ring; +// an unbind clears it. func TestSkipArmingBindKeepsRingUnconfirmed(t *testing.T) { adopted := bindingValue{Slot: 1, Flags: bindingStrict | bindingSubtree} - f, _ := strictRingFixture(t, &adopted) + f, ring := strictRingFixture(t, &adopted) + *ring = true f.b.ringUnconfirmed[identity.CgroupID] = true // as recordAdopted after a purge if err := f.b.Bind(Binding{Container: identity, Slot: 1, Subtree: true, SkipArming: true}); err != nil { t.Fatal(err) } if n := f.b.RingUnconfirmed(1); n != 1 { - t.Fatalf("a bind that walked nothing keeps it unconfirmed: %d", n) + t.Fatalf("a held ring keeps it unconfirmed: %d", n) } if err := f.b.Unbind(identity); err != nil { t.Fatal(err) diff --git a/pkg/sandboxpolicy/igbackend/privilege_test.go b/pkg/sandboxpolicy/igbackend/privilege_test.go index 3031da5a27..b487322fef 100644 --- a/pkg/sandboxpolicy/igbackend/privilege_test.go +++ b/pkg/sandboxpolicy/igbackend/privilege_test.go @@ -29,6 +29,9 @@ type fakePrivilegeInstance struct { publishErr error freeErr error healErr error + // healKeeps: a heal succeeds but leaves slotHealthErr (a binding + // that stays unconfirmed while a task holds a ring). + healKeeps bool // unconfirmed: the cgroups CgroupRingUnconfirmed reports (bound ones // otherwise read as confirmed, unbound ones as unconfirmed). unconfirmed map[uint64]bool @@ -102,7 +105,9 @@ func (i *fakePrivilegeInstance) Heal(slot uint32) error { } i.heals++ delete(i.faults, slot) - i.slotHealthErr = nil + if !i.healKeeps { + i.slotHealthErr = nil + } return nil } func (i *fakePrivilegeInstance) Collect() error { return nil } @@ -1442,3 +1447,33 @@ func TestNativeCgroupRingUnconfirmedUnknown(t *testing.T) { t.Fatal("no controller: not attested") } } + +// A heal that succeeds but leaves the slot unhealthy (a Strict pod binding +// that stays unconfirmed while a task holds a ring: no ErrNotHealable) does +// not reload: the result reports the health error (protection unconfirmed), +// and the next heal waits +// healRetry (no spin). Once the ring is closed a heal confirms it. +func TestPrivilegeHealUnconfirmedRingNoReloadNoSpin(t *testing.T) { + e := &fakePrivilegeEngine{} + b, _ := NewPrivilege(e, nil, "n") + ctx := context.Background() + plan := privPlan("r1", privPolicy("p1", api.ActionAllow, denyMount)) + if _, err := b.Replace(ctx, privBinding(1), plan); err != nil { + t.Fatal(err) + } + i := e.instances[0] + i.slotHealthErr = errors.New("1 Strict bindings have not passed the io_uring check") + i.healKeeps = true + r, err := b.Replace(ctx, privBinding(1), plan) + if err == nil || len(e.instances) != 1 || i.stops != 0 || i.heals != 1 || !r.ProtectionUnconfirmed { + t.Fatalf("no reload: %+v %v instances=%d heals=%d", r, err, len(e.instances), i.heals) + } + if _, err := b.Replace(ctx, privBinding(1), plan); err == nil || i.heals != 1 || len(e.instances) != 1 { + t.Fatalf("rate limited: %v heals=%d", err, i.heals) + } + i.healKeeps = false // the ring is closed + b.lastHeal = time.Time{} + if r, err := b.Replace(ctx, privBinding(1), plan); err != nil || !r.Committed || i.heals != 2 || len(e.instances) != 1 { + t.Fatalf("confirmed: %+v %v heals=%d", r, err, i.heals) + } +} From 95069da736c0cab68ff5ceed76303ae52e52e2e4 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 13:56:54 +0100 Subject: [PATCH 19/21] fix(enforcement): a move from a Strict pending entry checks before it publishes When an unchecked Strict pending entry moved to a real Strict slot, bind wrote the real-slot entry before arming and the io_uring check, so tasks could use the real policy's permissions during a walk that then failed. For that transition (an active or adopted Strict pending entry to a Strict real slot) bind now arms and checks first, while the pending entry still denies; on failure nothing is published and the pending entry stays unconfirmed (and becomes the heal-retried move if one was deferred), on success the checked entry is written once. Other transitions keep their order. keepFailed also clears any deferred move for the cgroup it keeps. Addresses Copilot review on #1160 (comments 4800029861, 4800029921). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 45 +++++++- .../common/enforcement/pending_test.go | 105 ++++++++++++++++++ 2 files changed, 148 insertions(+), 2 deletions(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index 40b03fe152..5c14f47196 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -591,16 +591,56 @@ func (b *Bindings) bind(c Binding) error { (wasAdopted && adopted.Flags&bindingStrict != 0 && adopted.Flags&bindingRingChecked != 0 && !b.credsPurged) strict := b.classOf(c) checked := wasChecked && strict + walked := false + // A move off a Strict pending entry (it denies what it judges) to a + // Strict real slot walks first, with the pending entry still installed: + // the real policy is written only once the check passed, so no task + // runs under it while the check can still refuse it. Arming marks tasks + // (armed_tasks, one mark per task, whatever the slot) and the record + // keys credentials by cgroup, so the walk is the same under either + // entry. A refused walk writes nothing: the pending entry stays. + prevPending := (bound && previous.Slot == PendingSlot && b.classOf(previous)) || + (wasAdopted && adopted.Slot == PendingSlot && adopted.Flags&bindingStrict != 0) + prechecked := prevPending && c.Slot != PendingSlot && strict && b.armed != nil && !c.SkipArming + if prechecked { + newStrict := !wasChecked + if err := b.arm(c, newStrict); err != nil { + if errors.Is(err, ErrContainerGone) { + // Gone: nothing to protect; drop it as a failed fresh bind. + if derr := b.members.Delete(id.CgroupID); derr != nil && !errors.Is(derr, ebpf.ErrKeyNotExist) { + return errors.Join(err, derr) + } + delete(b.adopted, id.CgroupID) + delete(b.active, id.CgroupID) + delete(b.unarmed, id.CgroupID) + return errors.Join(err, b.forgetCreds(id.CgroupID)) + } + // Nothing was published: the pending entry is as it was, now + // unconfirmed (it walked, the walk refused c or failed), with + // c as the move a heal retries when a move was deferred. + if hadMove && errors.Is(err, ErrIoUringHeld) { + b.moves[id.CgroupID] = c + } + b.setRingChecked(id.CgroupID, false) + if b.walksCreds() { + b.ringUnconfirmed[id.CgroupID] = true + } + return err + } + walked = b.walksCreds() + if newStrict && walked { + checked = true + } + } if err := b.members.Put(id.CgroupID, b.kernelValue(c, checked)); err != nil { return fmt.Errorf("writing container binding: %w", err) } delete(b.uncheckPending, id.CgroupID) // the entry is written as the state holds it delete(b.adopted, id.CgroupID) // this run owns the entry now - walked := false // A slot move arms again too: a task that the old slot left unarmed (an // audit slot allows a fork whose child mark failed) must not escape the // new slot. A SkipArming binding never arms. - if b.armed != nil && !c.SkipArming { + if b.armed != nil && !c.SkipArming && !prechecked { newStrict := strict && !wasChecked if err := b.arm(c, newStrict); err != nil { // The walk of this cgroup found tasks whose credentials the @@ -791,6 +831,7 @@ func (b *Bindings) setRingChecked(cgroup uint64, checked bool) { // retry or an adopter checks again, and it is unconfirmed until then. func (b *Bindings) keepFailed(c Binding, checked bool) { id := c.Container.CgroupID + delete(b.moves, id) // the kernel keeps c's entry: a deferred move is moot b.active[id] = c b.unarmed[id] = true b.setRingChecked(id, checked) diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index 610bca4583..7a3e540c30 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -1609,3 +1609,108 @@ func TestHealSkipArmingRingOnlyIsNotUnhealable(t *testing.T) { } }) } + +// A move from a Strict pending entry (it denies more) to a real Strict slot +// walks while the pending entry stays installed: the real-slot entry is +// written only after the check passed, and a refused move writes nothing. +func TestPendingToRealSlotChecksBeforeWriting(t *testing.T) { + c70 := ContainerIdentity{Runtime: "containerd", ID: "c70", CgroupID: 70, CgroupPath: "/workloads.slice/c70"} + pendingValue := bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers} + for _, tt := range []struct { + name string + adopted bool + ring bool + }{ + {"active, ring held", false, true}, + {"active, no ring", false, false}, + {"adopted, ring held", true, true}, + {"adopted, no ring", true, false}, + } { + t.Run(tt.name, func(t *testing.T) { + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.state.data[uint32(1)] = slotState(0, 4) + f.strictAt[Storage(1, 0)] = true + if tt.adopted { + f.members.data[c70.CgroupID] = pendingValue + } + f.armed = &fakeMap{typ: ebpf.TaskStorage} + }) + if !tt.adopted { + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + if err := f.b.Bind(Binding{Container: c70, Slot: PendingSlot, Strict: true, Subtree: true, RuntimeHelpers: true}); err != nil { + t.Fatal(err) + } + // Unconfirmed, as after a purge or a failed check. + f.members.data[c70.CgroupID] = pendingValue + f.b.setRingChecked(c70.CgroupID, false) + f.b.ringUnconfirmed[c70.CgroupID] = true + } + var during []bindingValue + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { + during = append(during, f.members.data[c70.CgroupID].(bindingValue)) + return tt.ring, nil + } + before := puts(*f.members.log) + err := f.b.Bind(Binding{Container: c70, Slot: 1}) + if len(during) != 1 || during[0] != pendingValue { + t.Fatalf("the pending entry stays during the walk: %+v", during) + } + v := f.members.data[c70.CgroupID].(bindingValue) + if tt.ring { + if !errors.Is(err, ErrIoUringHeld) || v != pendingValue || puts(*f.members.log) != before { + t.Fatalf("refused, nothing written: %v, %+v, puts %d", err, v, puts(*f.members.log)-before) + } + if !f.b.CgroupRingUnconfirmed(c70.CgroupID) { + t.Fatal("the pending binding stays unconfirmed") + } + return + } + if err != nil || v != (bindingValue{Slot: 1, Flags: bindingStrict | bindingRingChecked}) || puts(*f.members.log)-before != 1 { + t.Fatalf("moved after the check, one write: %v, %+v, puts %d", err, v, puts(*f.members.log)-before) + } + if f.b.CgroupRingUnconfirmed(c70.CgroupID) { + t.Fatal("confirmed") + } + }) + } +} + +// A refused startup move retried while its write fails (round 15): the +// deferred move never leaves a binding the heal cannot clear. Once the ring +// is closed, a heal of the slot moves the cgroup and the slot is healthy. +func TestRefusedMoveRetryWithFailedWriteClears(t *testing.T) { + ring := true + f, c9 := refusedMoveFixture(t, &ring) + f.b.members = &failNthPut{fakeMap: f.members, n: 2} + if err := f.b.Heal(1); err != nil { + t.Fatalf("heal with the ring held: %v", err) + } + if err := f.b.Heal(1); err != nil { + t.Fatalf("heal again: %v", err) + } + ring = false + if err := f.b.Heal(1); err != nil { + t.Fatalf("heal after the ring closed: %v", err) + } + if err := f.b.Heal(1); err != nil { + t.Fatal(err) + } + if n := f.b.RingUnconfirmed(1); n != 0 || len(f.b.moves) != 0 { + t.Fatalf("slot 1 healthy: %d, moves %+v", n, f.b.moves) + } + if v := f.members.data[c9.CgroupID].(bindingValue); v.Slot != 1 { + t.Fatalf("moved to slot 1: %+v", v) + } +} + +// keepFailed keeps the new binding's entry: a deferred move of the cgroup is +// moot and goes. +func TestKeepFailedClearsDeferredMove(t *testing.T) { + ring := true + f, c9 := refusedMoveFixture(t, &ring) + w := f.b.moves[c9.CgroupID] + f.b.keepFailed(w, false) + if len(f.b.moves) != 0 { + t.Fatalf("moves %+v", f.b.moves) + } +} From 3a8d720896d6652ffec1c263b52aa2defaab86a1 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 14:09:13 +0100 Subject: [PATCH 20/21] fix(enforcement): a SkipArming move off a Strict pending entry also checks before it publishes The round-15 check-before-write covered only arming bindings. A SkipArming binding (the pod hand-over) moving from an unchecked Strict pending entry to a Strict real slot still wrote the real-slot entry before checkOnly, and a held io_uring ring left the real policy in place. bind now runs a side-effect-free scan (record credentials, scan rings, no arming) first while the pending entry stays installed; on failure nothing is written, the pending entry stays unconfirmed and Bind returns ErrIoUringHeld (the owner keeps the pending mark, reports it Faulted and retries); on success the checked entry is written once. Addresses Copilot review on #1160 (comment 4800173157). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 32 +++++++--- .../common/enforcement/pending_test.go | 63 +++++++++++++++++++ 2 files changed, 88 insertions(+), 7 deletions(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index 5c14f47196..54bd59cace 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -601,10 +601,18 @@ func (b *Bindings) bind(c Binding) error { // entry. A refused walk writes nothing: the pending entry stays. prevPending := (bound && previous.Slot == PendingSlot && b.classOf(previous)) || (wasAdopted && adopted.Slot == PendingSlot && adopted.Flags&bindingStrict != 0) - prechecked := prevPending && c.Slot != PendingSlot && strict && b.armed != nil && !c.SkipArming + // A SkipArming c (a parent cgroup binding) gets the same preflight without + // arming: its check-only scan (scan), unless the pending binding's check + // holds already (wasChecked, as an arming c is not refused then). + prechecked := prevPending && c.Slot != PendingSlot && strict && + ((b.armed != nil && !c.SkipArming) || (c.SkipArming && !wasChecked && b.walksCreds())) if prechecked { newStrict := !wasChecked - if err := b.arm(c, newStrict); err != nil { + check := func() error { return b.arm(c, newStrict) } + if c.SkipArming { + check = func() error { return b.scan(c) } + } + if err := check(); err != nil { if errors.Is(err, ErrContainerGone) { // Gone: nothing to protect; drop it as a failed fresh bind. if derr := b.members.Delete(id.CgroupID); derr != nil && !errors.Is(derr, ebpf.ErrKeyNotExist) { @@ -1053,22 +1061,32 @@ func (b *Bindings) arm(c Binding, newStrict bool) error { // (ErrIoUringHeld) or a failed record keeps it unconfirmed. Called with mu // held. func (b *Bindings) checkOnly(c Binding) error { + if err := b.scan(c); err != nil { + return err + } id := c.Container.CgroupID + delete(b.ringUnconfirmed, id) + b.setRingChecked(id, true) + _ = b.members.Put(id, b.kernelValue(c, true)) // not retried: an adopter checks again + return nil +} + +// scan records the credentials of c's tasks and scans their io_uring rings, +// without arming them and without changing any state: ErrIoUringHeld when a +// task holds a ring, the record's error when it fails. Called with mu held. +func (b *Bindings) scan(c Binding) error { record := b.recordCreds if record == nil { record = b.creds.record // walksCreds: one of them is set } v := b.value(c) - ring, err := record(id, c.Container.CgroupPath, v.Flags, v.Slot) + ring, err := record(c.Container.CgroupID, c.Container.CgroupPath, v.Flags, v.Slot) if err != nil { return err } if ring { - return fmt.Errorf("%w (container %s, cgroup %d)", ErrIoUringHeld, c.Container.ID, id) + return fmt.Errorf("%w (container %s, cgroup %d)", ErrIoUringHeld, c.Container.ID, c.Container.CgroupID) } - delete(b.ringUnconfirmed, id) - b.setRingChecked(id, true) - _ = b.members.Put(id, b.kernelValue(c, true)) // not retried: an adopter checks again return nil } diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index 7a3e540c30..0c1162d30a 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -1714,3 +1714,66 @@ func TestKeepFailedClearsDeferredMove(t *testing.T) { t.Fatalf("moves %+v", f.b.moves) } } + +// The same check-before-write for a SkipArming c (a parent cgroup binding taking over +// a Strict pending mark): a check-only preflight (credentials recorded, rings +// scanned, no task armed) runs with the pending entry still installed; a held +// ring refuses the move and nothing is written. +func TestPendingToRealSlotSkipArmingChecksBeforeWriting(t *testing.T) { + c70 := ContainerIdentity{Runtime: "containerd", ID: "c70", CgroupID: 70, CgroupPath: "/workloads.slice/c70"} + pendingValue := bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers} + want := Binding{Container: c70, Slot: 1, Subtree: true, SkipArming: true} + for _, tt := range []struct { + name string + adopted bool + ring bool + }{ + {"active, ring held", false, true}, + {"active, no ring", false, false}, + {"adopted, ring held", true, true}, + {"adopted, no ring", true, false}, + } { + t.Run(tt.name, func(t *testing.T) { + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.state.data[uint32(1)] = slotState(0, 4) + f.strictAt[Storage(1, 0)] = true + if tt.adopted { + f.members.data[c70.CgroupID] = pendingValue + } + f.armed = &fakeMap{typ: ebpf.TaskStorage} + }) + arms := 0 + f.b.armExisting = func(Map, string) error { arms++; return nil } + if !tt.adopted { + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return false, nil } + if err := f.b.Bind(Binding{Container: c70, Slot: PendingSlot, Strict: true, Subtree: true, RuntimeHelpers: true, SkipArming: true}); err != nil { + t.Fatal(err) + } + f.members.data[c70.CgroupID] = pendingValue // unconfirmed + f.b.setRingChecked(c70.CgroupID, false) + f.b.ringUnconfirmed[c70.CgroupID] = true + } + var during []bindingValue + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { + during = append(during, f.members.data[c70.CgroupID].(bindingValue)) + return tt.ring, nil + } + before := puts(*f.members.log) + err := f.b.Bind(want) + if len(during) != 1 || during[0] != pendingValue || arms != 0 { + t.Fatalf("the pending entry stays during the check, nothing armed: %+v, arms %d", during, arms) + } + v := f.members.data[c70.CgroupID].(bindingValue) + if tt.ring { + if !errors.Is(err, ErrIoUringHeld) || v != pendingValue || puts(*f.members.log) != before || !f.b.CgroupRingUnconfirmed(c70.CgroupID) { + t.Fatalf("refused, nothing written: %v, %+v, puts %d", err, v, puts(*f.members.log)-before) + } + return + } + if err != nil || v != (bindingValue{Slot: 1, Flags: bindingStrict | bindingSubtree | bindingRingChecked}) || + puts(*f.members.log)-before != 1 || f.b.CgroupRingUnconfirmed(c70.CgroupID) || f.b.active[c70.CgroupID] != want { + t.Fatalf("moved after the check: %v, %+v, puts %d", err, v, puts(*f.members.log)-before) + } + }) + } +} From 7f9d771815198a0b25985dc06b81d5d3fcb8ce92 Mon Sep 17 00:00:00 2001 From: Matthias Bertschy Date: Fri, 4 Dec 2026 14:20:14 +0100 Subject: [PATCH 21/21] fix(enforcement): a refused startup move keeps the wanted binding's SkipArming When a held ring refused a startup move off an adopted Strict pending entry, start rebuilt the kept pending binding field by field and dropped SkipArming, so the next HealNode armed a pod or parent binding's tasks, runtime helpers included, instead of running the check-only walk. The kept binding now takes its kernel flags from the adopted entry and its identity and SkipArming from the wanted binding. Addresses Copilot review on #1160 (comment 4800306772). Co-Authored-By: Claude Opus 5.5 Signed-off-by: Matthias Bertschy --- .../gadgets/common/enforcement/bindings.go | 7 +++- .../common/enforcement/pending_test.go | 38 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/pkg/ebpf/gadgets/common/enforcement/bindings.go b/pkg/ebpf/gadgets/common/enforcement/bindings.go index 54bd59cace..e858f0bc6b 100644 --- a/pkg/ebpf/gadgets/common/enforcement/bindings.go +++ b/pkg/ebpf/gadgets/common/enforcement/bindings.go @@ -1453,7 +1453,12 @@ func (b *Bindings) start(policy Map, members BindingMap, armed Map, faults, witn // (moves): a heal of c's slot (or a node heal) binds c again // once the ring is closed, which moves it (retryMoves); a bind // or unbind of the cgroup by the owner replaces it. - kept := Binding{Container: c.Container, Slot: PendingSlot, Strict: true, + // The kernel's flags come from the entry (what it enforces); + // the identity and SkipArming, which the kernel does not hold, + // from c: a binding that must not arm (a parent cgroup binding, + // its runtime helpers exempt) stays one, so a heal takes the + // check-only path for it, never healArm. + kept := Binding{Container: c.Container, Slot: PendingSlot, Strict: true, SkipArming: c.SkipArming, Subtree: v.Flags&bindingSubtree != 0, RuntimeHelpers: v.Flags&bindingRuntimeHelpers != 0} err = b.keepUnrecorded(kept) if err == nil && kept != c { diff --git a/pkg/ebpf/gadgets/common/enforcement/pending_test.go b/pkg/ebpf/gadgets/common/enforcement/pending_test.go index 0c1162d30a..001fee1384 100644 --- a/pkg/ebpf/gadgets/common/enforcement/pending_test.go +++ b/pkg/ebpf/gadgets/common/enforcement/pending_test.go @@ -1777,3 +1777,41 @@ func TestPendingToRealSlotSkipArmingChecksBeforeWriting(t *testing.T) { }) } } + +// A startup move of a SkipArming binding (a parent cgroup binding) off an +// adopted Strict pending entry that a held ring refuses keeps the pending +// entry as a binding that does not arm either: the heal then takes the +// check-only path and arms nothing (runtime helpers stay exempt), and moves +// the cgroup once the ring is closed. +func TestRefusedStartMoveKeepsSkipArming(t *testing.T) { + c9 := ContainerIdentity{Runtime: "parent", ID: "uid-9", CgroupID: 77, CgroupPath: "/workloads.slice/parent-uid-9"} + wanted := Binding{Container: c9, Slot: 1, Subtree: true, RuntimeHelpers: true, SkipArming: true} + ring := true + arms := 0 + f := newPublishFixtureWith(t, func(f *publishFixture) { + f.members.data[c9.CgroupID] = bindingValue{Slot: PendingSlot, Flags: bindingStrict | bindingSubtree | bindingRuntimeHelpers} + f.b.config.InitialPublications = []Publication{f.publication(1, 10, true)} + f.b.desired[selector(c9)] = wanted + f.b.armExisting = func(Map, string) error { arms++; return nil } + f.b.recordCreds = func(uint64, string, uint32, uint32) (bool, error) { return ring, nil } + f.armed = &fakeMap{typ: ebpf.TaskStorage} + f.witness = fakeWitness{0: 0} + }) + kept := f.b.active[c9.CgroupID] + if kept.Slot != PendingSlot || !kept.SkipArming || f.b.moves[c9.CgroupID] != wanted { + t.Fatalf("kept %+v, moves %+v", kept, f.b.moves) + } + if err := f.b.HealNode(); err != nil { + t.Fatalf("heal with the ring held: %v", err) + } + ring = false + if err := f.b.HealNode(); err != nil { + t.Fatalf("heal: %v", err) + } + if arms != 0 { + t.Fatalf("nothing is armed: %d", arms) + } + if v := f.members.data[c9.CgroupID].(bindingValue); v.Slot != 1 || f.b.active[c9.CgroupID] != wanted || len(f.b.moves) != 0 || f.b.RingUnconfirmed(1) != 0 { + t.Fatalf("moved: %+v, active %+v, moves %+v", v, f.b.active[c9.CgroupID], f.b.moves) + } +}