-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcheck.go
More file actions
375 lines (353 loc) · 13.2 KB
/
check.go
File metadata and controls
375 lines (353 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
//go:build linux
package kfeatures
import (
"errors"
"fmt"
"github.com/cilium/ebpf"
"github.com/cilium/ebpf/features"
"golang.org/x/sys/unix"
)
// Check validates the specified requirements and returns a *[FeatureError]
// for the first unsatisfied requirement, or nil if all are met.
//
// Accepted requirement kinds:
// - [Feature] (stable boolean gates)
// - [FeatureGroup] (reusable requirement presets)
// - [ProgramTypeRequirement], [MapTypeRequirement], [ProgramHelperRequirement]
// - [MountRequirement] (filesystem-mounted-with-magic gate)
//
// Check is the only gate entrypoint. Keep ProbeWith/WithX for diagnostics-only
// data collection, not for expressing required readiness conditions.
// Kernel config is always probed to provide actionable diagnostics.
func Check(required ...Requirement) error {
rs := normalizeRequirements(required)
opts := probeOptionsFor(rs.features)
opts = append(opts, WithKernelConfig())
sf, err := ProbeWith(opts...)
if err != nil {
return fmt.Errorf("probe features: %w", err)
}
for _, f := range rs.features {
result, known := sf.Result(f)
if !known {
return &FeatureError{Feature: f.String(), Reason: "unknown feature"}
}
if !result.Supported {
return &FeatureError{
Feature: f.String(),
Reason: sf.Diagnose(f),
Err: result.Error,
}
}
}
for _, pt := range rs.programTypes {
err := features.HaveProgramType(pt)
if err == nil {
continue
}
return &FeatureError{
Feature: fmt.Sprintf("program type %s", pt),
Reason: reasonForProgramTypeError(pt, err),
Err: err,
}
}
for _, mt := range rs.mapTypes {
err := features.HaveMapType(mt)
if err == nil {
continue
}
return &FeatureError{
Feature: fmt.Sprintf("map type %s", mt),
Reason: reasonForMapTypeError(mt, err),
Err: err,
}
}
for _, req := range rs.programHelpers {
err := features.HaveProgramHelper(req.ProgramType, req.Helper)
if err == nil {
continue
}
return &FeatureError{
Feature: fmt.Sprintf("helper %s for program type %s", req.Helper, req.ProgramType),
Reason: reasonForProgramHelperError(req, err),
Err: err,
}
}
for _, m := range rs.mounts {
if err := checkMount(m.Path, m.Magic); err != nil {
return &FeatureError{
Feature: fmt.Sprintf("mount %s (magic 0x%x)", m.Path, m.Magic),
Reason: err.Error(),
Err: err,
}
}
}
for _, mk := range rs.minKernels {
if err := mk.satisfiedBy(sf.KernelVersion); err != nil {
return &FeatureError{
Feature: mk.String(),
Reason: err.Error(),
Err: err,
}
}
}
return nil
}
// Result maps a [Feature] to its corresponding [ProbeResult] in SystemFeatures.
// Returns false as the second value if the feature is unknown.
func (sf *SystemFeatures) Result(f Feature) (ProbeResult, bool) {
switch f {
case FeatureBPFLSM:
// Composite: LSM program type must be loadable AND "bpf" must be in active LSM list.
// Check program type loadability first (the most fundamental requirement).
if !sf.LSMProgramType.Supported {
return sf.LSMProgramType, true
}
return sf.BPFLSMEnabled, true
case FeatureBTF:
return sf.BTF, true
case FeatureIMA:
return sf.IMAEnabled, true
case FeatureIMAAnyMeasurementActive:
return sf.IMAAnyMeasurementActive, true
case FeatureKprobe:
return sf.Kprobe, true
case FeatureKprobeMulti:
return sf.KprobeMulti, true
case FeatureFentry:
return sf.Fentry, true
case FeatureTracepoint:
return sf.Tracepoint, true
case FeatureCapBPF:
return sf.HasCapBPF, true
case FeatureCapSysAdmin:
return sf.HasCapSysAdmin, true
case FeatureCapPerfmon:
return sf.HasCapPerfmon, true
case FeatureJITEnabled:
return sf.JITEnabled, true
case FeatureJITHardened:
return sf.JITHardened, true
case FeatureBPFSyscall:
return sf.BPFSyscall, true
case FeaturePerfEventOpen:
return sf.PerfEventOpen, true
case FeatureSleepableBPF:
return ProbeResult{Supported: sf.PreemptMode.SupportsSleepable()}, true
case FeatureTraceFS:
return sf.TraceFS, true
case FeatureBPFFS:
return sf.BPFFS, true
case FeatureInitUserNS:
return sf.InInitUserNS, true
case FeatureUnprivilegedBPFDisabled:
return sf.UnprivilegedBPFDisabled, true
case FeatureBPFStatsEnabled:
return sf.BPFStatsEnabled, true
default:
return ProbeResult{}, false
}
}
// Diagnose returns an enriched reason string explaining why a feature
// is not supported and what the operator can do to fix it.
func (sf *SystemFeatures) Diagnose(f Feature) string {
kc := sf.KernelConfig // may be nil
switch f {
case FeatureBPFLSM:
// Check program type loadability first (the most fundamental requirement).
if !sf.LSMProgramType.Supported {
if sf.LSMProgramType.Error != nil {
return fmt.Sprintf("cannot probe LSM program type: %v; run as root or add CAP_BPF/CAP_SYS_ADMIN", sf.LSMProgramType.Error)
}
return "LSM program type not supported; use a kernel with BPF LSM support (CONFIG_BPF_LSM=y)"
}
// Program type is loadable: check sysfs and config signals.
if sf.BPFLSMEnabled.Error != nil {
return "unable to read active LSM list (/sys/kernel/security/lsm); ensure securityfs is mounted and readable"
}
if kc != nil && !kc.BPFLSM.IsEnabled() {
return "CONFIG_BPF_LSM not set; rebuild kernel with CONFIG_BPF_LSM=y"
}
if kc != nil && kc.BPFLSM.IsEnabled() && !sf.BPFLSMEnabled.Supported {
return "CONFIG_BPF_LSM=y but 'bpf' not in active LSM list; add lsm=...,bpf to kernel boot params"
}
case FeatureBTF:
if kc != nil && !kc.BTF.IsEnabled() {
return "CONFIG_DEBUG_INFO_BTF not set; rebuild kernel with CONFIG_DEBUG_INFO_BTF=y"
}
case FeatureKprobeMulti:
if kc != nil && !kc.KprobeMulti.IsEnabled() {
return "CONFIG_FPROBE not set; requires kernel 5.18+ with CONFIG_FPROBE=y"
}
case FeatureKprobe:
return "kprobe program type not supported; use a kernel with BPF kprobe support or switch to a supported attach type"
case FeatureFentry:
return "fentry/fexit program type not supported; use a kernel with BPF trampoline support (and BTF) or switch attach strategy"
case FeatureTracepoint:
return "tracepoint program type not supported; ensure perf events are enabled and use a kernel with tracepoint BPF support"
case FeatureIMA:
if sf.IMAEnabled.Error != nil {
return "unable to read active LSM list (/sys/kernel/security/lsm); ensure securityfs is mounted and readable to verify IMA state"
}
if kc != nil && !kc.IMA.IsEnabled() {
return "CONFIG_IMA not set; rebuild kernel with CONFIG_IMA=y"
}
case FeatureIMAAnyMeasurementActive:
if sf.IMAAnyMeasurementActive.Error != nil {
return fmt.Sprintf("unable to read IMA measurement count from %s: %v", imaMeasurementCountPath, sf.IMAAnyMeasurementActive.Error)
}
if !sf.IMAEnabled.Supported {
return "IMA is not in the active LSM list; enable IMA first (lsm=...,ima in kernel boot params)"
}
return "no IMA measurement has occurred; write a measurement rule (e.g., 'measure func=BPRM_CHECK') to /sys/kernel/security/ima/policy"
case FeatureCapBPF:
return "missing CAP_BPF; run with CAP_BPF or as root"
case FeatureCapSysAdmin:
return "missing CAP_SYS_ADMIN; run as root or add CAP_SYS_ADMIN"
case FeatureCapPerfmon:
return "missing CAP_PERFMON; run with CAP_PERFMON or as root"
case FeatureJITEnabled:
return "BPF JIT disabled; set /proc/sys/net/core/bpf_jit_enable to 1"
case FeatureJITHardened:
return "BPF JIT hardening disabled; set /proc/sys/net/core/bpf_jit_harden to 1 or 2"
case FeatureBPFSyscall:
return "bpf() syscall not available; kernel too old or CONFIG_BPF not enabled"
case FeaturePerfEventOpen:
return "perf_event_open() syscall not available; kernel too old or CONFIG_PERF_EVENTS not enabled"
case FeatureSleepableBPF:
if kc != nil {
return fmt.Sprintf("kernel preemption model is %s; sleepable BPF (BPF_F_SLEEPABLE) requires CONFIG_PREEMPT or CONFIG_PREEMPT_DYNAMIC", kc.Preempt)
}
return "cannot determine preemption model; kernel config not available"
case FeatureTraceFS:
return "tracefs not mounted; mount tracefs at /sys/kernel/tracing (or /sys/kernel/debug/tracing on older kernels)"
case FeatureBPFFS:
return "bpffs not mounted; mount bpffs at /sys/fs/bpf"
case FeatureInitUserNS:
return "process not in initial user namespace; run in host user namespace or adjust container runtime settings"
case FeatureUnprivilegedBPFDisabled:
return "unprivileged BPF is enabled; set /proc/sys/kernel/unprivileged_bpf_disabled to 1 or 2"
case FeatureBPFStatsEnabled:
return "BPF runtime stats are disabled; set /proc/sys/kernel/bpf_stats_enabled to 1"
}
// Fallback: use the probe error if available.
result, known := sf.Result(f)
if known && result.Error != nil {
return result.Error.Error()
}
return "not supported"
}
// probeOptionsFor determines which [ProbeOption] functions are needed
// for the given feature requirements.
//
// Classification rule for future additions:
// promote to [Feature] only when the signal can be expressed as a deterministic
// requirement with actionable remediation text in Diagnose. Keep descriptive
// context-only signals probe-only behind WithX options.
func probeOptionsFor(reqs []Feature) []ProbeOption {
var needSecurity bool
var needKernelConfig bool
var needCapabilities bool
var needJIT bool
var needSyscalls bool
var needFilesystems bool
var needNamespaces bool
var programTypes []ebpf.ProgramType
// Phase-B classification decisions:
// - DebugFS stays diagnostics-only because TraceFS is the primary readiness gate
// and DebugFS is a legacy/fallback mount signal.
// - SecurityFS stays diagnostics-only because BPFLSM/IMA checks already validate
// functional readiness via active LSM state, not only mount presence.
// - InInitPIDNS stays diagnostics-only because PID namespace context affects helper
// semantics, but is not a universal run/block condition.
for _, f := range reqs {
switch f {
case FeatureBPFLSM:
needSecurity = true
programTypes = append(programTypes, ebpf.LSM)
case FeatureIMA, FeatureIMAAnyMeasurementActive:
needSecurity = true
case FeatureKprobe:
programTypes = append(programTypes, ebpf.Kprobe)
case FeatureKprobeMulti:
programTypes = append(programTypes, ebpf.Kprobe)
needKernelConfig = true // kprobe.multi requires CONFIG_FPROBE check
case FeatureFentry:
programTypes = append(programTypes, ebpf.Tracing)
case FeatureTracepoint:
programTypes = append(programTypes, ebpf.TracePoint)
case FeatureCapBPF, FeatureCapSysAdmin, FeatureCapPerfmon:
needCapabilities = true
case FeatureJITEnabled, FeatureJITHardened:
needJIT = true
case FeatureBPFSyscall, FeaturePerfEventOpen:
needSyscalls = true
case FeatureSleepableBPF:
needKernelConfig = true
case FeatureTraceFS, FeatureBPFFS:
needFilesystems = true
case FeatureInitUserNS:
needNamespaces = true
case FeatureUnprivilegedBPFDisabled:
needCapabilities = true
case FeatureBPFStatsEnabled:
needCapabilities = true
}
}
var opts []ProbeOption
if needSyscalls {
opts = append(opts, WithSyscalls())
}
if needSecurity {
opts = append(opts, WithSecuritySubsystems())
}
if len(programTypes) > 0 {
opts = append(opts, WithProgramTypes(programTypes...))
}
if needKernelConfig {
opts = append(opts, WithKernelConfig())
}
if needCapabilities {
opts = append(opts, WithCapabilities())
}
if needJIT {
opts = append(opts, WithJIT())
}
if needFilesystems {
opts = append(opts, WithFilesystems())
}
if needNamespaces {
opts = append(opts, WithNamespaces())
}
return opts
}
func reasonForProgramTypeError(pt ebpf.ProgramType, err error) string {
switch {
case errors.Is(err, ebpf.ErrNotSupported):
return fmt.Sprintf("program type %s is unavailable on this kernel; use a kernel/workload combination that supports it", pt)
case errors.Is(err, unix.EPERM), errors.Is(err, unix.EACCES):
return fmt.Sprintf("cannot probe program type %s due to insufficient privileges; run as root or add CAP_BPF/CAP_SYS_ADMIN", pt)
default:
return fmt.Sprintf("unable to validate program type %s support; verify kernel BPF support and required privileges (CAP_BPF/CAP_SYS_ADMIN)", pt)
}
}
func reasonForMapTypeError(mt ebpf.MapType, err error) string {
switch {
case errors.Is(err, ebpf.ErrNotSupported):
return fmt.Sprintf("map type %s is unavailable on this kernel; use a supported map type or a newer kernel", mt)
case errors.Is(err, unix.EPERM), errors.Is(err, unix.EACCES):
return fmt.Sprintf("cannot probe map type %s due to insufficient privileges; run as root or add CAP_BPF/CAP_SYS_ADMIN", mt)
default:
return fmt.Sprintf("unable to validate map type %s support; verify kernel BPF support and required privileges (CAP_BPF/CAP_SYS_ADMIN)", mt)
}
}
func reasonForProgramHelperError(req ProgramHelperRequirement, err error) string {
switch {
case errors.Is(err, ebpf.ErrNotSupported):
return fmt.Sprintf("helper %s is unavailable for program type %s; choose a compatible helper/program combination or newer kernel", req.Helper, req.ProgramType)
case errors.Is(err, unix.EPERM), errors.Is(err, unix.EACCES):
return fmt.Sprintf("cannot probe helper %s for program type %s due to insufficient privileges; run as root or add CAP_BPF/CAP_SYS_ADMIN", req.Helper, req.ProgramType)
default:
return fmt.Sprintf("unable to validate helper %s for program type %s; verify kernel support and required privileges (CAP_BPF/CAP_SYS_ADMIN)", req.Helper, req.ProgramType)
}
}