From cc09718211774b2a8b877190dd195bd58740fbac Mon Sep 17 00:00:00 2001 From: Abdullah Hanif <318923962+abdullahhanif-001@users.noreply.github.com> Date: Sat, 24 Oct 2026 09:14:43 +0500 Subject: [PATCH 1/4] mbset: treat missing map keys as already removed on duplicate paths When the same binary path shows up twice in one matchBinaries selector, RemoveID deletes the mbset entry on the first copy. The second Lookup then returns ErrKeyNotExist. That used to abort the whole RemoveID and leave the ID allocated, which burns a slot under the 64-bit followChildren cap. Treat ErrKeyNotExist as already-removed and keep walking the path list so the ID still gets released. Signed-off-by: Abdullah Hanif <318923962+abdullahhanif-001@users.noreply.github.com> --- pkg/mbset/mbset.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pkg/mbset/mbset.go b/pkg/mbset/mbset.go index 38780510b80..581fc55a9c0 100644 --- a/pkg/mbset/mbset.go +++ b/pkg/mbset/mbset.go @@ -104,6 +104,11 @@ func (s *state) RemoveID(id uint32, paths [][processapi.BINARY_PATH_MAX_LEN]byte err := mbsetMap.Lookup(path, &val) if err != nil { + // Duplicate paths in one selector hit Delete on the first copy; + // a second Lookup returns ErrKeyNotExist — continue, do not leak ID. + if errors.Is(err, ebpf.ErrKeyNotExist) { + continue + } return fmt.Errorf("failed to lookup mbset map: %w", err) } From 1039f2375bf2fca33e3fa9d69f565f422e36e502 Mon Sep 17 00:00:00 2001 From: Abdullah Hanif <318923962+abdullahhanif-001@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:50:44 +0000 Subject: [PATCH 2/4] mbset: don't hand out IDs that running processes still carry RemoveID used to bail out early when there's no execve_map updater (small programs), and the previous version of this series turned that into "just release the ID". That is wrong: the bit stays set in tg_mbset_map and in the execve_map entries of running processes, so the next followChildren selector that gets the ID matches the removed policy's binaries and their children. With a Sigkill action that kills unrelated stuff. Drop the early return so tg_mbset_map is always cleaned up. Without an updater we can't clear the bit from execve_map, so just check that no process has it and fail otherwise. Same goes for the updater path when the retries run out, and also if iterating execve_map fails (that used to look like "no pids found" and released the ID). When RemoveID fails after tg_mbset_map is clean, keep the ID allocated and remember it as stale. Once AllocID runs out of free IDs it scans execve_map once and releases the stale IDs nobody carries anymore. A bit can only be inherited from a parent at that point, so if no process has it, no new process will get it either. Map opening goes through state.openMap so the tests can use private maps. The tests create BPF maps, so they need to run privileged like the rest of `make test`. Signed-off-by: Abdullah Hanif <318923962+abdullahhanif-001@users.noreply.github.com> --- pkg/mbset/mbset.go | 116 +++++++++++++++++---- pkg/mbset/mbset_removeid_test.go | 174 +++++++++++++++++++++++++++++++ 2 files changed, 271 insertions(+), 19 deletions(-) create mode 100644 pkg/mbset/mbset_removeid_test.go diff --git a/pkg/mbset/mbset.go b/pkg/mbset/mbset.go index 581fc55a9c0..18d7b34f011 100644 --- a/pkg/mbset/mbset.go +++ b/pkg/mbset/mbset.go @@ -44,38 +44,97 @@ type state struct { mu sync.Mutex // map of used IDs for mbset bits [0..MaxIDs] ids map[uint32]struct{} + // IDs whose policy is gone, but whose bit might still be set in the + // execve_map entries of running processes. They stay in ids (so nobody + // else gets them) until reclaimStale sees that no process carries the + // bit anymore. + stale map[uint32]struct{} // generation value aka last mbset filter timestamp gen uint64 + // openMap opens a pinned map by name, tests replace it + openMap func(name string) (*ebpf.Map, error) } func newState() (*state, error) { return &state{ - ids: make(map[uint32]struct{}), + ids: make(map[uint32]struct{}), + stale: make(map[uint32]struct{}), + openMap: openMap, }, nil } +// freeID returns the first unused ID, s.mu must be held +func (s *state) freeID() (uint32, bool) { + for id := range uint32(MaxIDs) { + if _, ok := s.ids[id]; !ok { + return id, true + } + } + return InvalidID, false +} + // AllocID allocates a new ID func (s *state) AllocID() (uint32, error) { s.mu.Lock() defer s.mu.Unlock() - for id := range uint32(MaxIDs) { - if _, ok := s.ids[id]; !ok { - s.ids[id] = struct{}{} - return id, nil + id, ok := s.freeID() + if !ok && len(s.stale) != 0 { + // We ran out of IDs, but some of them are only held back because + // processes still had their bit set when the policy was removed. + // Check if those processes are gone by now. + if err := s.reclaimStale(); err != nil { + return InvalidID, fmt.Errorf("cannot allocate new id: %w", err) + } + id, ok = s.freeID() + } + if !ok { + return InvalidID, errors.New("cannot allocate new id") + } + s.ids[id] = struct{}{} + return id, nil +} + +// reclaimStale releases stale IDs whose bit is not set in any execve_map +// entry anymore, s.mu must be held. +// +// Once the bit is gone from tg_mbset_map (RemoveID takes care of that before +// marking the ID as stale) it can only be inherited from a parent that still +// has it, so if no process has the bit, no new one will get it. +func (s *state) reclaimStale() error { + hash, err := s.openMap(ExecveMapName) + if err != nil { + return fmt.Errorf("failed to open execve_map hash map: %w", err) + } + defer hash.Close() + + var ( + key execvemap.ExecveKey + val execvemap.ExecveValue + inUse bitSet + ) + + iter := hash.Iterate() + for iter.Next(&key, &val) { + inUse |= val.Binary.MBSet + } + if err := iter.Err(); err != nil { + return fmt.Errorf("failed to iterate execve_map: %w", err) + } + + for id := range s.stale { + if inUse&(bitSet(1)< Date: Fri, 20 Nov 2026 14:50:59 +0000 Subject: [PATCH 3/4] selectors: dedupe matchBinaries paths in ParseMatchBinary When the same binary path shows up more than once in a matchBinaries selector it ends up multiple times in matchBinariesPaths, and RemoveID then hits the same mbset key twice (see previous commit). Skip duplicates while walking the In/NotIn values. Doing it there with a map keeps it linear, instead of searching the already written paths for every new one in WriteMatchBinariesPath. Signed-off-by: Abdullah Hanif <318923962+abdullahhanif-001@users.noreply.github.com> --- pkg/selectors/kernel.go | 7 ++++++ pkg/selectors/matchbinaries_paths_test.go | 29 +++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 pkg/selectors/matchbinaries_paths_test.go diff --git a/pkg/selectors/kernel.go b/pkg/selectors/kernel.go index 1259331e31b..658755bd9a3 100644 --- a/pkg/selectors/kernel.go +++ b/pkg/selectors/kernel.go @@ -1871,10 +1871,17 @@ func ParseMatchBinary(k *KernelSelectorState, b *v1alpha1.BinarySelector, selIdx switch op { case SelectorOpIn, SelectorOpNotIn: + // Skip duplicates, otherwise the same path ends up multiple times + // in matchBinariesPaths and mbset.RemoveID walks it more than once. + seen := make(map[string]struct{}, len(b.Values)) for _, s := range b.Values { if len(s) > processapi.BINARY_PATH_MAX_LEN-1 { return fmt.Errorf("%s error: Binary names > %d chars not supported", selectorType, processapi.BINARY_PATH_MAX_LEN-1) } + if _, ok := seen[s]; ok { + continue + } + seen[s] = struct{}{} k.WriteMatchBinariesPath(selectorType.keyFromSelectorID(selIdx), s) } case SelectorOpPrefix, SelectorOpNotPrefix: diff --git a/pkg/selectors/matchbinaries_paths_test.go b/pkg/selectors/matchbinaries_paths_test.go new file mode 100644 index 00000000000..d987f7b339e --- /dev/null +++ b/pkg/selectors/matchbinaries_paths_test.go @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: Apache-2.0 +// Copyright Authors of Tetragon + +//go:build !windows + +package selectors + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/cilium/tetragon/pkg/k8s/apis/cilium.io/v1alpha1" +) + +func TestParseMatchBinaryDedupesPaths(t *testing.T) { + k := NewKernelSelectorState(nil, nil, false, 0, nil, nil) + b := &v1alpha1.BinarySelector{ + Operator: "In", + Values: []string{"/usr/bin/cat", "/usr/bin/cat", "/usr/bin/echo", "/usr/bin/cat"}, + } + require.NoError(t, ParseMatchBinary(k, b, 0, matchBinaries)) + + paths := k.MatchBinariesPaths()[0] + require.Len(t, paths, 2) + require.Equal(t, "/usr/bin/cat", strings.TrimRight(string(paths[0][:]), "\x00")) + require.Equal(t, "/usr/bin/echo", strings.TrimRight(string(paths[1][:]), "\x00")) +} From bb5fe560e1e771ff3833218c9a113fcb70ed6319 Mon Sep 17 00:00:00 2001 From: Abdullah Hanif <318923962+abdullahhanif-001@users.noreply.github.com> Date: Fri, 20 Nov 2026 14:51:13 +0000 Subject: [PATCH 4/4] selectors: give back followChildren IDs when parsing fails ParseMatchBinary allocates the mbset ID before it looks at the values, and the selector is only stored in the state at the very end. So if a path is too long the ID is gone for good, CleanupKernelSelectorState never sees it. Same thing one level up: createKernelSelectorState drops the whole state when a later selector fails, together with the IDs the earlier ones already took. With only 64 IDs, a few broken policies are enough to make every followChildren policy fail to load until restart. Add mbset.ReleaseID for IDs that never made it to the mbset map and use it in both error paths. Signed-off-by: Abdullah Hanif <318923962+abdullahhanif-001@users.noreply.github.com> --- pkg/mbset/mbset.go | 17 ++++++++ pkg/mbset/mbset_removeid_test.go | 13 ++++++ pkg/selectors/kernel.go | 23 +++++++++- pkg/selectors/matchbinaries_paths_test.go | 51 +++++++++++++++++++++++ 4 files changed, 103 insertions(+), 1 deletion(-) diff --git a/pkg/mbset/mbset.go b/pkg/mbset/mbset.go index 18d7b34f011..e1bad16e5d2 100644 --- a/pkg/mbset/mbset.go +++ b/pkg/mbset/mbset.go @@ -95,6 +95,15 @@ func (s *state) AllocID() (uint32, error) { return id, nil } +// ReleaseID gives back an ID that was allocated but never written to the +// mbset map (i.e. UpdateMap was not called for it), for example because the +// rest of the policy failed to parse. Use RemoveID for everything else. +func (s *state) ReleaseID(id uint32) { + s.mu.Lock() + defer s.mu.Unlock() + delete(s.ids, id) +} + // reclaimStale releases stale IDs whose bit is not set in any execve_map // entry anymore, s.mu must be held. // @@ -335,6 +344,14 @@ func RemoveID(id uint32, paths [][processapi.BINARY_PATH_MAX_LEN]byte) error { return s.RemoveID(id, paths) } +func ReleaseID(id uint32) { + s, err := getState() + if err != nil { + return + } + s.ReleaseID(id) +} + func UpdateMap(id uint32, paths [][processapi.BINARY_PATH_MAX_LEN]byte) error { s, err := getState() if err != nil { diff --git a/pkg/mbset/mbset_removeid_test.go b/pkg/mbset/mbset_removeid_test.go index 29f31e004ef..0bfbed9fd0f 100644 --- a/pkg/mbset/mbset_removeid_test.go +++ b/pkg/mbset/mbset_removeid_test.go @@ -172,3 +172,16 @@ func TestAllocIDReclaimsOnlyUnusedStaleIDs(t *testing.T) { _, err = s.AllocID() require.Error(t, err) } + +func TestReleaseID(t *testing.T) { + s, err := newState() + require.NoError(t, err) + + id, err := s.AllocID() + require.NoError(t, err) + s.ReleaseID(id) + + id2, err := s.AllocID() + require.NoError(t, err) + require.Equal(t, id, id2) +} diff --git a/pkg/selectors/kernel.go b/pkg/selectors/kernel.go index 658755bd9a3..b7e333baabf 100644 --- a/pkg/selectors/kernel.go +++ b/pkg/selectors/kernel.go @@ -1839,7 +1839,7 @@ func (s genericMatchBinariesSelector) keyFromSelectorID(selectorID int) int { return selectorID + offset } -func ParseMatchBinary(k *KernelSelectorState, b *v1alpha1.BinarySelector, selIdx int, selectorType genericMatchBinariesSelector) error { +func ParseMatchBinary(k *KernelSelectorState, b *v1alpha1.BinarySelector, selIdx int, selectorType genericMatchBinariesSelector) (retErr error) { if selectorType != matchBinaries && selectorType != matchParentBinaries { return errors.New("selector must be either matchBinaries or matchParentBinaries") } @@ -1867,6 +1867,13 @@ func ParseMatchBinary(k *KernelSelectorState, b *v1alpha1.BinarySelector, selIdx if err != nil { return fmt.Errorf("%s followChildren: failed to allocate ID: %w", selectorType, err) } + // The selector is not stored in k until the very end, so + // CleanupKernelSelectorState can't see the ID if we bail out. + defer func() { + if retErr != nil { + mbset.ReleaseID(sel.MBSetID) + } + }() } switch op { @@ -2029,16 +2036,30 @@ func createKernelSelectorState( WriteSelectorLength(&state.data, soff[i]) loff := AdvanceSelectorLength(&state.data) if err := parseSelector(state, &s, i); err != nil { + releaseMBSetIDs(state) return nil, err } WriteSelectorLength(&state.data, loff) } if len(state.data.e) > KernelBufferSize { + releaseMBSetIDs(state) return nil, fmt.Errorf("selector encoding overflow: %d bytes exceeds %d byte buffer", len(state.data.e), KernelBufferSize) } return state, nil } +// releaseMBSetIDs gives back the followChildren IDs of a state that is thrown +// away before it was loaded. Nothing has been written to the mbset map for +// them at this point (that happens at load time), so there is nothing else to +// clean up. +func releaseMBSetIDs(state *KernelSelectorState) { + for _, sel := range state.MatchBinaries() { + if sel.MBSetID != mbset.InvalidID { + mbset.ReleaseID(sel.MBSetID) + } + } +} + func InitKernelSelectorState(args *KernelSelectorArgs) (*KernelSelectorState, error) { parse := func(k *KernelSelectorState, selector *v1alpha1.KProbeSelector, selIdx int) error { if err := ParseMatchPids(k, selector.MatchPIDs); err != nil { diff --git a/pkg/selectors/matchbinaries_paths_test.go b/pkg/selectors/matchbinaries_paths_test.go index d987f7b339e..798cd49494d 100644 --- a/pkg/selectors/matchbinaries_paths_test.go +++ b/pkg/selectors/matchbinaries_paths_test.go @@ -11,7 +11,9 @@ import ( "github.com/stretchr/testify/require" + "github.com/cilium/tetragon/pkg/api/processapi" "github.com/cilium/tetragon/pkg/k8s/apis/cilium.io/v1alpha1" + "github.com/cilium/tetragon/pkg/mbset" ) func TestParseMatchBinaryDedupesPaths(t *testing.T) { @@ -27,3 +29,52 @@ func TestParseMatchBinaryDedupesPaths(t *testing.T) { require.Equal(t, "/usr/bin/cat", strings.TrimRight(string(paths[0][:]), "\x00")) require.Equal(t, "/usr/bin/echo", strings.TrimRight(string(paths[1][:]), "\x00")) } + +// nextMBSetID returns the ID the next mbset.AllocID call would hand out +func nextMBSetID(t *testing.T) uint32 { + t.Helper() + id, err := mbset.AllocID() + require.NoError(t, err) + mbset.ReleaseID(id) + return id +} + +func TestParseMatchBinaryReleasesIDOnError(t *testing.T) { + want := nextMBSetID(t) + + k := NewKernelSelectorState(nil, nil, false, 0, nil, nil) + b := &v1alpha1.BinarySelector{ + Operator: "In", + Values: []string{"/usr/bin/cat", strings.Repeat("a", processapi.BINARY_PATH_MAX_LEN)}, + FollowChildren: true, + } + require.Error(t, ParseMatchBinary(k, b, 0, matchBinaries)) + require.Equal(t, want, nextMBSetID(t)) +} + +func TestCreateKernelSelectorStateReleasesIDsOnError(t *testing.T) { + want := nextMBSetID(t) + + selectors := []v1alpha1.KProbeSelector{ + { + MatchBinaries: []v1alpha1.BinarySelector{{ + Operator: "In", + Values: []string{"/usr/bin/cat"}, + FollowChildren: true, + }}, + }, + { + MatchBinaries: []v1alpha1.BinarySelector{{ + Operator: "In", + Values: []string{strings.Repeat("a", processapi.BINARY_PATH_MAX_LEN)}, + FollowChildren: true, + }}, + }, + } + parse := func(k *KernelSelectorState, s *v1alpha1.KProbeSelector, selIdx int) error { + return ParseMatchBinaries(k, s.MatchBinaries, selIdx, matchBinaries) + } + _, err := createKernelSelectorState(selectors, nil, nil, false, 0, nil, nil, parse) + require.Error(t, err) + require.Equal(t, want, nextMBSetID(t)) +}