sandboxpolicy

package
v0.3.336 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 19, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package sandboxpolicy selects and compiles Kubernetes sandbox policies. It does not attach programs: Backend owns kernel capability validation and lifecycle.

Index

Constants

View Source
const AgentStoppingReason = "AgentStopping"

AgentStoppingReason is the Ready reason of every exec policy's last report before a graceful agent stop withdraws enforcement.

View Source
const AgentStoppingTimeout = 2500 * time.Millisecond

AgentStoppingTimeout bounds the AgentStopping writes once they start.

View Source
const MaxPathsPerRule = 256
View Source
const MaxPoliciesPerBinding = 64

Limits are deliberately bounded before handing work to the kernel backend, which may impose stricter supported-environment limits.

View Source
const MaxRulesPerPolicy = 256
View Source
const MaxVerdictQueueCapacity = 65536
View Source
const VerdictDrainTimeout = 2 * time.Second

VerdictDrainTimeout bounds the drain after Run's ctx is cancelled (Stop bounds it by its own ctx instead).

Variables

View Source
var ClassesGVR = api.SchemeGroupVersion.WithResource("sandboxpolicyclasses")
View Source
var ClusterPolicyGVR = api.SchemeGroupVersion.WithResource("clustersandboxpolicies")
View Source
var ErrVerdictExporterStopped = errors.New("sandbox verdict exporter is stopped")
View Source
var ErrVerdictQueueFull = errors.New("sandbox verdict reporting queue is full")
View Source
var NodeStatusGVR = api.SchemeGroupVersion.WithResource("sandboxpolicynodestatuses")
View Source
var PolicyGVR = api.SchemeGroupVersion.WithResource("sandboxpolicies")

Functions

func BoundCondition

func BoundCondition(c *metav1.Condition) bool

BoundCondition fits c's reason and message into the storage schema (api.MaxStatusConditionKeyLength, api.MaxStatusDiagnosticLength); an out-of-schema status update would be rejected and leave the previous status (perhaps Ready True) in place. It reports whether anything was cut.

func BoundConditionReason

func BoundConditionReason(reason string) (bounded string, cut bool)

BoundConditionReason fits a comma-joined reason list into api.MaxStatusConditionKeyLength. It drops empty and malformed items and, when the list is too long, whole trailing items (never half of one), appending ",More" ("More" alone if not even the first item fits beside it). The result always matches the condition reason syntax ("Unknown" if no item is usable). cut reports any change.

func PolicyExecFrom

func PolicyExecFrom(ctx context.Context) (hasExec, known bool)

PolicyExecFrom returns what WithPolicyExec recorded; known is false when the caller did not say, and a writer must then treat the policy as an exec policy (fail-closed).

func WithPolicyExec

func WithPolicyExec(ctx context.Context, hasExec bool) context.Context

WithPolicyExec tells a StatusWriter whether the policy whose report it writes carries exec rules (an exec section or ContainerProfile sources). The controller sets it on every WriteStatus; exec-only node health (the shared exec engine's) applies only to such policies.

Types

type Backend

type Backend interface {
	Replace(context.Context, Binding, Plan) (ReplaceResult, error)
	Withdraw(context.Context, Binding) (WithdrawResult, error)
}

Backend owns candidate readiness, immutable replacement and cleanup. Before commit, failure MUST leave the previous plan enforced and clean up the candidate. After commit, return Committed=true even if retiring old instances fails; the new plan is active but reconciliation remains NotReady until cleanup succeeds. Same-plan Replace retries must safely finish cleanup without resetting roles or creating gaps. Success requires Committed=true and ActiveRevision=Plan.Revision. Temporary overlap may overblock, but never introduce an enforcement gap. Unsupported predicates, limits and incomplete identities must return errors. Withdraw is idempotent and removes only this exact container/cgroup identity; stale deletion must never remove a newer registration. Before commit, errors retain enforcement; after commit, errors MUST return Committed=true. Repeated calls after removal finish cleanup without touching newer runtime identities.

type Binding

type Binding struct {
	Runtime        string
	CgroupPath     string
	PID            uint32
	MountNamespace uint64
	ContainerID    string
	CgroupID       uint64
	PodUID         types.UID
	Namespace      string
	PodName        string
	ContainerName  string
	// Kind is regular, init, or ephemeral. Wildcard policy selectors match regular only.
	Kind            string
	PodLabels       map[string]string
	NamespaceLabels map[string]string
}

Binding is an immutable runtime identity. CgroupID must be verified by the backend against the live container, not inferred from pod metadata.

type BindingPendingError

type BindingPendingError struct {
	// Containers counts the selected, uncorrelated live containers on the node.
	Containers int
}

BindingPendingError accompanies a selected runtime snapshot while live Kubernetes containers that a policy selects, or may select, are not yet correlated with a running node pod (kubelet has not reported them Running). Returned together with the correlated bindings, it is non-fatal: Refresh binds those as usual, and every policy reports Ready False with reason BindingPending until a snapshot has no pending container. Returned without bindings, it is an ordinary failed snapshot.

func (*BindingPendingError) Error

func (e *BindingPendingError) Error() string

type CompiledPolicy

type CompiledPolicy struct {
	Identity PolicyIdentity  `json:"identity"`
	Revision string          `json:"revision"`
	Mode     api.PolicyMode  `json:"mode"`
	RootRole string          `json:"rootRole"`
	Exec     api.ExecSection `json:"exec"`
}

CompiledPolicy keeps policy-local role namespaces, mode overrides and defaults separate. Backends must implement deny-wins across policies, not first-match.

func Compile

func Compile(ctx context.Context, identity PolicyIdentity, spec api.PolicySpec, classes api.PolicyClasses, binding Binding, resolver SourceResolver) (CompiledPolicy, error)

Compile resolves a single policy without mutating its source objects. A missing class/profile is an error, never a wildcard or a silently omitted rule.

type Controller

type Controller struct {
	// contains filtered or unexported fields
}

func NewController

func NewController(client dynamic.Interface, backend Backend, resolver SourceResolver, writer StatusWriter, options Options) (*Controller, error)

func (*Controller) AddHandler

func (c *Controller) AddHandler(ctx context.Context, obj runtime.Object)

func (*Controller) BindingSelector

func (c *Controller) BindingSelector() func(Binding) bool

BindingSelector snapshots the last coherently loaded policy selectors. It performs no I/O and holds no controller lock when invoked. Discovery uses it only to determine which authoritative pod/container metadata REQUIRE runtime identity: it is not permission to guess an identity or exempt observer-ignored workloads. Invalid policies conservatively require every container in their owning namespace (or every namespace for cluster policies), retaining last-good selection until the invalid revision is repaired or intentionally deleted.

func (*Controller) DeleteHandler

func (c *Controller) DeleteHandler(ctx context.Context, obj runtime.Object)

func (*Controller) HasConfigurationVersion

func (c *Controller) HasConfigurationVersion(uid types.UID, resourceVersion string) bool

HasConfigurationVersion reports whether Refresh has already listed this exact object revision. Both identity fields must come from the API server.

func (*Controller) InitialSync

func (c *Controller) InitialSync(ctx context.Context) error

InitialSync is also the reconnect/relist recovery path. A failed list never commits a partial snapshot or withdraws last-good enforcement.

func (*Controller) LastError

func (c *Controller) LastError() error

func (*Controller) ModifyHandler

func (c *Controller) ModifyHandler(ctx context.Context, obj runtime.Object)

func (*Controller) Reconcile

func (c *Controller) Reconcile(ctx context.Context) error

Reconcile retries failed backends/status writes and refreshes source imports. Invoke on referenced profile updates and periodically for status heartbeats.

func (*Controller) Refresh

func (c *Controller) Refresh(ctx context.Context, snapshot func(context.Context, func(Binding) bool) ([]Binding, error)) error

Refresh is the integrated configuration/selection readiness barrier. It reads all policy inputs, selects from that candidate configuration, then obtains the matching authoritative runtime snapshot BEFORE any installation or Ready report. The callback executes under the reconciliation lock and must not call Controller methods other than the lock-free HasConfigurationVersion. It must reject incomplete discovery and concurrent churn, not return an inferred empty snapshot. The caller remains responsible for subscribe/replay. On snapshot failure the fetched config is retained for truthful new-policy NotReady reports, while last-good binding state is preserved. Valid explicit off/deletion may withdraw previously owned policies; no new plan is installed.

func (*Controller) ReportBindingFailure

func (c *Controller) ReportBindingFailure(ctx context.Context, failure error) error

ReportBindingFailure retains the last authoritative snapshot and publishes NotReady when discovery or Kubernetes metadata cannot produce a complete one. Only a subsequent successful binding snapshot (SetBindings or Refresh) clears it.

func (*Controller) SetBindings

func (c *Controller) SetBindings(ctx context.Context, bindings []Binding) error

SetBindings replaces an authoritative container snapshot. Call it on container, pod-label or namespace-label changes; absent entries are explicitly withdrawn. Snapshot subscriptions and live cgroup identity verification belong to the caller and Backend respectively. The controller never infers a binding from selectors.

func (*Controller) StopReporting

func (c *Controller) StopReporting(ctx context.Context) error

StopReporting ends status reporting before a graceful stop withdraws enforcement: it writes Ready False (AgentStopping) for every exec policy this node reports, and no status afterwards. Policies without exec rules are not written. It returns when ctx ends, whatever a writer does. The AgentStopping writes wait for an in-flight reconciliation (the controller lock) and then run on their own context, bounded by AgentStoppingTimeout and not cancelled with ctx: when the caller stopped waiting for a slow reconciliation, AgentStopping still lands after its last write.

func (*Controller) WatchResources

func (*Controller) WatchResources() []watcher.WatchResource

type DynamicStatusWriter

type DynamicStatusWriter struct{ Client dynamic.Interface }

DynamicStatusWriter only creates the UID-scoped report and writes its status subresource. It never edits policy parent aggregates. Conflicts are returned so the controller's periodic reconciliation can retry without hiding write loss.

func (DynamicStatusWriter) WriteStatus

type ExecVerdictEvent

type ExecVerdictEvent struct {
	Verdict Verdict
	Binding Binding
	// contains filtered or unexported fields
}

ExecVerdictEvent is an exec authorization attempt, NOT an observed process creation. It deliberately does not implement utils.ExecEvent. The raw Verdict retains policy/rule provenance and audit/deny semantics even after optional enrichment. Unknown enrichment fields are absent (FieldPresent=false), not fabricated from the target executable. In particular GetError's zero means unavailable, not a successful exec syscall: this event describes an LSM decision, not syscall exit. Keep this event exec-specific. When a second enforce gadget is added, give its operation facts a distinct event and dispatch key; extract only metadata proven common to both. See docs/features/sandbox-policy.md#adding-a-second-enforcement-gadget.

func NewExecVerdictEvent

func NewExecVerdictEvent(verdict Verdict, binding Binding) *ExecVerdictEvent

func (*ExecVerdictEvent) FieldPresent

func (e *ExecVerdictEvent) FieldPresent(name string) bool

func (*ExecVerdictEvent) GetComm

func (*ExecVerdictEvent) GetComm() string

func (*ExecVerdictEvent) GetContainer

func (e *ExecVerdictEvent) GetContainer() string

func (*ExecVerdictEvent) GetContainerID

func (e *ExecVerdictEvent) GetContainerID() string

func (*ExecVerdictEvent) GetContainerImage

func (*ExecVerdictEvent) GetContainerImage() string

func (*ExecVerdictEvent) GetContainerImageDigest

func (*ExecVerdictEvent) GetContainerImageDigest() string

func (*ExecVerdictEvent) GetEcsAvailabilityZone

func (*ExecVerdictEvent) GetEcsAvailabilityZone() string

func (*ExecVerdictEvent) GetEcsClusterARN

func (*ExecVerdictEvent) GetEcsClusterARN() string

func (*ExecVerdictEvent) GetEcsClusterName

func (*ExecVerdictEvent) GetEcsClusterName() string

func (*ExecVerdictEvent) GetEcsContainerARN

func (*ExecVerdictEvent) GetEcsContainerARN() string

func (*ExecVerdictEvent) GetEcsContainerInstance

func (*ExecVerdictEvent) GetEcsContainerInstance() string

func (*ExecVerdictEvent) GetEcsContainerName

func (*ExecVerdictEvent) GetEcsContainerName() string

func (*ExecVerdictEvent) GetEcsLaunchType

func (*ExecVerdictEvent) GetEcsLaunchType() string

func (*ExecVerdictEvent) GetEcsServiceName

func (*ExecVerdictEvent) GetEcsServiceName() string

func (*ExecVerdictEvent) GetEcsTaskARN

func (*ExecVerdictEvent) GetEcsTaskARN() string

func (*ExecVerdictEvent) GetEcsTaskDefinitionARN

func (*ExecVerdictEvent) GetEcsTaskDefinitionARN() string

func (*ExecVerdictEvent) GetEcsTaskFamily

func (*ExecVerdictEvent) GetEcsTaskFamily() string

func (*ExecVerdictEvent) GetError

func (*ExecVerdictEvent) GetError() int64

func (*ExecVerdictEvent) GetEventType

func (*ExecVerdictEvent) GetEventType() utils.EventType

func (*ExecVerdictEvent) GetExtra

func (e *ExecVerdictEvent) GetExtra() any

func (*ExecVerdictEvent) GetGid

func (*ExecVerdictEvent) GetGid() *uint32

func (*ExecVerdictEvent) GetHostNetwork

func (*ExecVerdictEvent) GetHostNetwork() bool

func (*ExecVerdictEvent) GetMountNsID

func (e *ExecVerdictEvent) GetMountNsID() uint64

func (*ExecVerdictEvent) GetNamespace

func (e *ExecVerdictEvent) GetNamespace() string

func (*ExecVerdictEvent) GetPID

func (e *ExecVerdictEvent) GetPID() uint32

func (*ExecVerdictEvent) GetPID64

func (e *ExecVerdictEvent) GetPID64() uint64

func (*ExecVerdictEvent) GetPcomm

func (*ExecVerdictEvent) GetPcomm() string

func (*ExecVerdictEvent) GetPod

func (e *ExecVerdictEvent) GetPod() string

func (*ExecVerdictEvent) GetPodLabels

func (e *ExecVerdictEvent) GetPodLabels() map[string]string

func (*ExecVerdictEvent) GetPpid

func (e *ExecVerdictEvent) GetPpid() uint32

func (*ExecVerdictEvent) GetTimestamp

func (e *ExecVerdictEvent) GetTimestamp() gadgettypes.Time

func (*ExecVerdictEvent) GetUid

func (e *ExecVerdictEvent) GetUid() *uint32

func (*ExecVerdictEvent) HasDroppedEvents

func (*ExecVerdictEvent) HasDroppedEvents() bool

func (*ExecVerdictEvent) Release

func (*ExecVerdictEvent) Release()

func (*ExecVerdictEvent) SetExtra

func (e *ExecVerdictEvent) SetExtra(extra any)

type ExporterOptions

type ExporterOptions struct {
	Capacity  int
	Receivers *maps.SafeMap[utils.EventType, mapset.Set[containerwatcher.GenericEventReceiver]]
	Enricher  containerwatcher.TaskBasedEnricher
	// ResolveBinding must be a nonblocking cache lookup. Only return identities
	// verified for this event's full container ID and cgroup ID, never a current
	// container reusing the same short ID. A missing result leaves metadata absent.
	ResolveBinding func(Verdict) (Binding, bool)
}

type ExporterStats

type ExporterStats struct {
	Enqueued         uint64
	Delivered        uint64 // successful receiver invocations, not kernel decisions
	Dropped          uint64 // full queue, stopped exporter, or still queued at the drain deadline
	ReceiverErrors   uint64
	EnrichmentErrors uint64
}

type Options

type Options struct {
	Node           api.NodeReference
	AgentNamespace string
}

Options identifies this node and the namespace for cluster-policy reports.

type Plan

type Plan struct {
	Revision string           `json:"revision"`
	Policies []CompiledPolicy `json:"policies"`
}

type PolicyIdentity

type PolicyIdentity struct {
	Kind       string    `json:"kind"`
	Namespace  string    `json:"namespace,omitempty"`
	Name       string    `json:"name"`
	UID        types.UID `json:"uid"`
	Generation int64     `json:"generation"`
}

type PolicyRevision

type PolicyRevision struct {
	Policy   PolicyIdentity
	Revision string
}

PolicyRevision identifies one immutable policy applied to a decision.

type ProtectionAttester

type ProtectionAttester interface {
	Attest(context.Context, Binding, string) error
}

ProtectionAttester optionally verifies an already-owned exact binding/revision. It must not install, update, resume, abort or publish any policy. Unsupported attestation leaves ownership retained but protection unconfirmed during discovery uncertainty; only an authoritative snapshot may authorize reconciliation again.

type ReplaceResult

type ReplaceResult struct {
	Committed      bool
	ActiveRevision string
	// ProtectionUnconfirmed indicates externally lost/uncertain health or identity
	// of owned enforcement, not an ordinary rejected candidate. Ownership remains
	// for cleanup, but callers MUST NOT claim active or last-good protection. This
	// flag does not relax the requirement to preserve healthy old enforcement when
	// a candidate fails. A confirmed candidate/re-attestation clears it.
	ProtectionUnconfirmed bool
}

ReplaceResult distinguishes a failed candidate from a committed candidate whose old-instance cleanup failed. Committed results MUST identify the desired plan's exact revision. An error does not imply rollback after the commit boundary.

type RuleMatch

type RuleMatch struct {
	Policy   PolicyIdentity
	Revision string
	Name     string
	Origin   string   // Legacy scalar; use Origins for presence-aware provenance.
	Origins  []string `json:"origins"`
	Action   api.Action
	Mode     api.RuleMode
}

RuleMatch records a reported match, not necessarily a decisive rule.

type SourceResolver

type SourceResolver interface {
	ResolveExecs(context.Context, string, string, string) ([]api.ExecRule, error)
}

SourceResolver reads ContainerProfile execs in the selected pod's namespace. It must return an error for missing/incomplete profiles; empty successful results mean a known complete profile with no execs. Rules retain their predicates. The caller invokes Controller.Reconcile when referenced profile content changes.

type StatusWriter

type StatusWriter interface {
	WriteStatus(context.Context, *api.SandboxPolicyNodeStatus) error
}

type Verdict

type Verdict struct {
	// PolicySet contains every applied policy; Policy/Rule below are singular
	// only when attribution is unambiguous. Matches may be partial on faults.
	PolicySet []PolicyRevision
	Matches   []RuleMatch
	// MatchesComplete is false for legacy events and operational failures.
	MatchesComplete bool
	Time            time.Time
	Policy          PolicyIdentity
	// Revision is always the aggregate Plan.Revision, independent of singular
	// attribution. Policy-specific revisions belong to PolicySet and Matches.
	Revision       string
	Rule           string
	Origin         string   // Legacy scalar; use Origins for presence-aware provenance.
	Origins        []string `json:"origins"`
	Mode           api.RuleMode
	Verdict        api.Action
	WouldDeny      bool
	Reason         string
	ContainerID    string
	PodUID         types.UID
	BindingPID     uint32
	MountNamespace uint64
	CgroupID       uint64
	PID            uint32
	ParentPID      uint32
	UID            *uint32
	ActorPath      string
	TargetPath     string
	Argv           []string
	FromImage      *bool
	// Pass, ExecID, TaskCookie and LoadEpoch are present only on
	// shared-engine events (additive event ABI). Pass is the evaluated bprm
	// pass (absent for a fault); one exec's passes share ExecID, and
	// (LoadEpoch, TaskCookie, ExecID) is node-unique when TaskCookie is
	// present. LoadEpoch is the nonzero per-collection-load epoch: TaskCookie
	// restarts on every load, so it is never a key without LoadEpoch.
	Pass       *uint32
	ExecID     *uint64
	TaskCookie *uint64
	LoadEpoch  *uint64
	// ExecClass (1 Audit, 2 Strict), Scope (the route scope), Uncertain and
	// FactsUnknown (the unknown-fact bitmap) are also present only on
	// shared-engine events, so uncertain verdicts stay visible downstream.
	ExecClass    *uint32
	Scope        *uint64
	Uncertain    *bool
	FactsUnknown *uint32
}

Verdict is independent of observer trace_exec: denied attempts are not process creation events. Optional fields remain absent when the backend cannot know them.

type VerdictExporter

type VerdictExporter struct {
	// contains filtered or unexported fields
}

VerdictExporter separates bounded, best-effort telemetry from kernel decisions. ReportVerdict never calls receivers/enrichers and never changes enforcement. Start exactly one Run goroutine; register receivers under the distinct verdict event type, not ExecveEventType. Void receiver/enricher APIs cannot be cancelled mid-call, so implementations must return promptly; a slow consumer fills this queue and drops telemetry rather than blocking the enforcement producer.

func NewVerdictExporter

func NewVerdictExporter(options ExporterOptions) (*VerdictExporter, error)

func (*VerdictExporter) ReportVerdict

func (e *VerdictExporter) ReportVerdict(ctx context.Context, verdict Verdict) error

func (*VerdictExporter) Run

func (e *VerdictExporter) Run(ctx context.Context) error

Run delivers queued verdicts until Stop or ctx cancellation, then drains: already-queued verdicts are still delivered until the drain deadline (Stop's ctx, or VerdictDrainTimeout after ctx cancellation). Only what is still queued at the deadline is counted as dropped. Run returns nil after Stop; Stop reports whether the drain lost verdicts.

func (*VerdictExporter) Started

func (e *VerdictExporter) Started() <-chan struct{}

Started is closed once Run has claimed the start. A caller that launches Run on a goroutine waits on it so a later Stop drains rather than finding the exporter never started and dropping its queue.

func (*VerdictExporter) Stats

func (e *VerdictExporter) Stats() ExporterStats

func (*VerdictExporter) Stop

func (e *VerdictExporter) Stop(ctx context.Context) error

Stop refuses new verdicts at once, lets Run deliver those already queued until ctx ends, and waits for Run to return, at most until ctx ends. It returns nil only for a clean drain, and the deadline error when verdicts were lost to it or when Run is still delivering at the deadline (concurrent Stop callers may briefly observe different outcomes). At the first Stop's deadline whatever is still queued is counted as dropped, also when Run is stuck in a receiver that never returns (that in-flight event is counted when, if ever, it returns). If Run never started, queued verdicts are counted as dropped at once. Stop is idempotent; only the first call's ctx bounds Run's drain, and a later call only waits.

type VerdictReceiver

type VerdictReceiver interface {
	ReportVerdict(context.Context, Verdict) error
}

type WithdrawResult

type WithdrawResult struct {
	Committed bool
	// A failed drain/retirement may leave membership present without healthy
	// admission. Do not report that retained owner as confirmed last-good.
	ProtectionUnconfirmed bool
}

WithdrawResult records the point after which this binding is no longer protected. Committed=true is required on success and after removal even if subsequent resource cleanup fails.

Directories

Path Synopsis
Package igbackend owns strict execution-policy gadgets.
Package igbackend owns strict execution-policy gadgets.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL